feat: export one source-bound session result as a static ZIP

This commit is contained in:
cflmy committed 2026-11-24 13:43:27 +08:00
1 parent 3081581b0b
commit aa2a2b3ce4
23 files changed
+1816 -114

No files matched your search

+1 -59
View File
@@ -150,65 +150,7 @@ pub struct RunOutput {
pub trace_sha256: Option<String>,
}
/// A private temporary directory for Core artifacts.
pub struct ScratchDir {
path: PathBuf,
}
impl ScratchDir {
pub fn create(label: &str) -> ViewResult<Self> {
let base = std::env::temp_dir();
let unique = format!(
"marqdo-view-{}-{}-{}",
std::process::id(),
unique_counter(),
sanitize_label(label)
);
let path = base.join(unique);
std::fs::create_dir_all(&path)
.map_err(|err| ViewError::io(&format!("create scratch {}", path.display()), err))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))
.map_err(|err| ViewError::io(&format!("chmod scratch {}", path.display()), err))?;
}
Ok(Self { path })
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn file(&self, name: &str) -> PathBuf {
self.path.join(name)
}
}
impl Drop for ScratchDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn unique_counter() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
seq ^ nanos.rotate_left(17)
}
fn sanitize_label(label: &str) -> String {
label
.chars()
.map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' })
.take(32)
.collect()
}
pub use crate::scratch::ScratchDir;
/// Negotiated public-client for one frozen core binary.
#[derive(Debug, Clone)]
+94 -25
View File
@@ -17,55 +17,115 @@ pub enum ExitClass {
#[derive(Debug)]
pub enum ViewError {
/// `MARQDO_BIN` unset, missing, or not executable.
CoreMissing { detail: String },
CoreMissing {
detail: String,
},
/// Tool/Analysis/Trace protocol or product range mismatch.
ProtocolIncompatible { detail: String },
ProtocolIncompatible {
detail: String,
},
/// Core `check` failed; prose stays readable but semantics are unusable.
AnalysisFailed { detail: String },
AnalysisFailed {
detail: String,
},
/// Analysis `source_digest` does not match the current source bytes.
SourceMismatch { expected: String, actual: String },
SourceMismatch {
expected: String,
actual: String,
},
/// A Core byte span is out of range or not on a UTF-8 boundary.
SourceSpanInvalid { detail: String },
SourceSpanInvalid {
detail: String,
},
/// Trace does not bind to the current Analysis bytes.
TraceStale { detail: String },
TraceStale {
detail: String,
},
/// The user did not confirm, or the requested mode/grants are not allowed.
RunDenied { detail: String },
RunDenied {
detail: String,
},
/// Path escapes the allowed project root or is otherwise forbidden.
PathForbidden { detail: String },
PathForbidden {
detail: String,
},
/// Refused a bind address that is not explicitly allowed.
BindDenied { detail: String },
BindDenied {
detail: String,
},
/// Embedded asset digest mismatch (build/package integrity).
AssetIntegrity { detail: String },
AssetIntegrity {
detail: String,
},
/// Export target is unsafe or the write failed.
ExportFailed { detail: String },
ExportFailed {
detail: String,
},
ExportInvalid {
detail: String,
},
ExportUnavailable {
detail: String,
},
ExportSourceChanged {
detail: String,
},
/// A configured resource limit was exceeded.
ResourceLimit { detail: String },
ResourceLimit {
detail: String,
},
/// Core subprocess could not be spawned.
CoreSpawn { detail: String },
CoreSpawn {
detail: String,
},
/// The submitted run request failed schema/target/parameter validation.
RunInvalid { detail: String },
RunInvalid {
detail: String,
},
/// The entry document has no resolvable `main`; View never substitutes one.
NoEntryFunction { detail: String },
NoEntryFunction {
detail: String,
},
/// A page/SSE/POST requires a valid local session cookie.
SessionRequired { detail: String },
SessionRequired {
detail: String,
},
/// Another explicit run is already active; View allows one at a time.
RunBusy { detail: String },
RunBusy {
detail: String,
},
/// The same client request id was reused with a different payload.
RunConflict { detail: String },
RunConflict {
detail: String,
},
/// The requested run id is unknown, expired or belongs to another session.
RunNotFound { detail: String },
RunNotFound {
detail: String,
},
/// Bounded capture of CLI stdout/stderr/JSON/trace exceeded the budget.
OutputLimit { detail: String },
OutputLimit {
detail: String,
},
/// The CLI exited but its `--json` document was missing or invalid.
CoreProtocol { detail: String },
CoreProtocol {
detail: String,
},
/// More than two concurrent SSE observers for one job.
SseBusy { detail: String },
SseBusy {
detail: String,
},
/// Core subprocess exceeded the View-level timeout and was killed.
CoreTimeout { detail: String },
CoreTimeout {
detail: String,
},
/// Local file system / HTTP I/O failure.
Io { detail: String },
Io {
detail: String,
},
/// Feature intentionally not implemented in this build (honest status).
Unsupported { detail: String },
Unsupported {
detail: String,
},
}
impl ViewError {
@@ -82,6 +142,9 @@ impl ViewError {
ViewError::BindDenied { .. } => "view.bind_denied",
ViewError::AssetIntegrity { .. } => "view.asset_integrity",
ViewError::ExportFailed { .. } => "view.export_failed",
ViewError::ExportInvalid { .. } => "view.export_invalid",
ViewError::ExportUnavailable { .. } => "view.export_unavailable",
ViewError::ExportSourceChanged { .. } => "view.export_source_changed",
ViewError::ResourceLimit { .. } => "view.resource_limit",
ViewError::CoreSpawn { .. } => "view.core_spawn",
ViewError::CoreTimeout { .. } => "view.core_timeout",
@@ -151,6 +214,9 @@ impl ViewError {
"view.bind_denied" => "拒绝绑定该网络地址。",
"view.asset_integrity" => "内嵌资源摘要不一致。",
"view.export_failed" => "静态导出失败(输出目录不安全或写入失败)。",
"view.export_invalid" => "导出范围或隐私确认无效。",
"view.export_unavailable" => "本次执行尚无可导出的已验证终态。",
"view.export_source_changed" => "文档、依赖或图片已变更。请刷新并重新运行后再导出。",
"view.resource_limit" => "超过配置的资源上限。",
"view.core_spawn" => "无法启动冻结核心。",
"view.core_timeout" => "冻结核心执行超时,已终止。",
@@ -204,6 +270,9 @@ impl ViewError {
| ViewError::BindDenied { detail }
| ViewError::AssetIntegrity { detail }
| ViewError::ExportFailed { detail }
| ViewError::ExportInvalid { detail }
| ViewError::ExportUnavailable { detail }
| ViewError::ExportSourceChanged { detail }
| ViewError::ResourceLimit { detail }
| ViewError::CoreSpawn { detail }
| ViewError::CoreTimeout { detail }
+40 -5
View File
@@ -8,6 +8,7 @@
use crate::core_client::{build_call_args, build_run_args, RunOptions, SandboxMode, ScratchDir};
use crate::error::{ViewError, ViewResult};
use crate::execution::events::{EventLog, RunEvent, RunState, Subscription};
use crate::execution::export_candidate::TerminalExportCandidate;
use crate::execution::process::{
run_bounded_with_hook, Captured, ProcessBudget, ProcessHooks, ProcessOutcome,
};
@@ -126,6 +127,7 @@ pub struct Job {
struct JobInner {
log: EventLog,
terminal_at: Option<Instant>,
export_candidate: Option<Arc<TerminalExportCandidate>>,
connections: usize,
}
@@ -140,6 +142,7 @@ impl Job {
inner: Mutex::new(JobInner {
log: EventLog::new(),
terminal_at: None,
export_candidate: None,
connections: 0,
}),
}
@@ -308,6 +311,16 @@ impl ExecutionController {
let (state, result, trace, trace_status, error_code, error_message) = terminal;
let mut result = result;
result["trace_status"] = serde_json::json!(trace_status.clone());
if let Some(candidate) = TerminalExportCandidate::from_terminal(
state,
&plan,
&static_doc,
&result,
trace.as_ref(),
) {
result["export_preview"] = candidate.preview();
inner.export_candidate = Some(Arc::new(candidate));
}
match state {
RunState::Succeeded => {
inner.log.publish_complete(result, trace);
@@ -633,9 +646,13 @@ impl ExecutionController {
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")));
result["output_complete"] = serde_json::json!(
std::str::from_utf8(&stream.stdout).is_ok()
&& std::str::from_utf8(&stream.stderr).is_ok()
&& !json["error"]["code"]
.as_str()
.is_some_and(|code| code.contains("output_limit"))
);
if trace_status == "verified"
&& trace
.as_ref()
@@ -731,10 +748,28 @@ impl ExecutionController {
Ok(self.lookup(session_id, run_id)?.state())
}
pub fn get_export_candidate(
&self,
session_id: &str,
run_id: &str,
) -> ViewResult<Arc<TerminalExportCandidate>> {
let job = self.lookup(session_id, run_id)?;
let inner = job.inner.lock().map_err(|_| ViewError::Io {
detail: "job lock poisoned".into(),
})?;
inner
.export_candidate
.clone()
.ok_or_else(|| ViewError::ExportUnavailable {
detail: "job has no verified exportable terminal observation".into(),
})
}
fn lookup(&self, session_id: &str, run_id: &str) -> ViewResult<Arc<Job>> {
let state = self.state.lock().map_err(|_| ViewError::Io {
let mut state = self.state.lock().map_err(|_| ViewError::Io {
detail: "execution controller lock poisoned".to_string(),
})?;
self.purge_locked(&mut state);
let job = state
.jobs
.get(run_id)
@@ -744,7 +779,7 @@ impl ExecutionController {
})?;
if job.session_id != session_id {
return Err(ViewError::RunNotFound {
detail: "运行任务不属于当前会话".to_string(),
detail: "运行任务不存在或已过期".to_string(),
});
}
Ok(job)
+148
View File
@@ -0,0 +1,148 @@
//! A bounded projection retained only inside an existing terminal Job.
use crate::execution::events::RunState;
use crate::execution::request::ExecutionPlan;
use crate::reader::assemble::StaticDocument;
use serde_json::{json, Value};
use std::collections::BTreeMap;
const MAX_TEXT: usize = 128 * 1024;
#[derive(Debug)]
pub struct TerminalExportCandidate {
pub document: String,
pub function_id: String,
pub label: String,
pub project_root_id: String,
pub module_id: String,
pub analysis_digest: String,
pub analysis_version: u32,
pub source_sha256: String,
pub lock_digest: String,
pub media: BTreeMap<String, String>,
pub core_run_id: String,
pub core_version: String,
pub mode: String,
pub terminal_at: String,
pub state: RunState,
pub value: Option<String>,
pub value_is_public_scalar: bool,
pub stdout: String,
pub stderr: String,
pub arguments: Vec<(String, String)>,
pub trace_status: String,
pub trace_counts: Option<BTreeMap<String, u64>>,
pub output_complete: bool,
pub result_complete: bool,
pub observation_truncated: bool,
}
impl TerminalExportCandidate {
pub(super) fn from_terminal(
state: RunState,
plan: &ExecutionPlan,
document: &StaticDocument,
result: &Value,
trace: Option<&Value>,
) -> Option<Self> {
if !matches!(state, RunState::Succeeded | RunState::Failed)
|| result.get("source_verified").and_then(Value::as_bool) != Some(true)
|| result.get("event_protocol").and_then(Value::as_u64) != Some(1)
{
return None;
}
let projection = &document.verified.projection;
let function = projection
.functions
.iter()
.find(|function| function.id == plan.function_id)?;
let (stdout, stdout_complete) = bounded_text(&result["stdout"]);
let (stderr, stderr_complete) = bounded_text(&result["stderr"]);
let (value, value_complete) = bounded_text(&result["value_text"]);
let trace_status = match &result["trace_status"] {
Value::String(status) if status == "verified" => {
if trace.is_some_and(|trace| !trace["truncated"].is_null()) {
"truncated"
} else {
"verified"
}
}
Value::String(status) if status == "invalid" => "invalid",
_ => "unavailable",
};
let trace_counts = trace
.filter(|trace| trace["status"] == "verified")
.and_then(|trace| trace["counts"].as_object())
.map(|counts| {
counts
.iter()
.filter_map(|(kind, count)| Some((kind.clone(), count.as_u64()?)))
.collect()
});
let value_is_public_scalar = matches!(
result["value"]["type"].as_str(),
Some("int" | "float" | "bool" | "unit")
);
let value = if state == RunState::Succeeded && !value.is_empty() {
Some(value)
} else {
None
};
Some(Self {
document: plan.document.to_string(),
function_id: function.id.clone(),
label: function.local_name.clone(),
project_root_id: projection.project_root_id.clone(),
module_id: projection.module_id.clone(),
analysis_digest: document.analysis_digest.clone(),
analysis_version: projection.schema_version,
source_sha256: document.source_sha256.clone(),
lock_digest: projection.lock_digest.clone(),
media: document.media_digests.clone(),
core_run_id: result["core_run_id"].as_str()?.to_string(),
core_version: projection.producer_version.clone(),
mode: plan.mode.as_str().to_string(),
terminal_at: crate::execution::events::utc_now(),
state,
value,
value_is_public_scalar,
stdout,
stderr,
arguments: plan.arguments.clone(),
trace_status: trace_status.to_string(),
trace_counts,
output_complete: result["output_complete"].as_bool() == Some(true)
&& stdout_complete
&& stderr_complete,
result_complete: state == RunState::Succeeded && value_complete,
observation_truncated: result["observation_truncated"].as_bool().unwrap_or(false),
})
}
pub(super) fn preview(&self) -> Value {
json!({
"label": self.label,
"value_bytes": self.value.as_ref().map(String::len),
"value_is_public_scalar": self.value_is_public_scalar,
"stdout_bytes": self.stdout.len(),
"stderr_bytes": self.stderr.len(),
"arguments_count": self.arguments.len(),
"trace_summary": self.trace_counts.is_some(),
"trace_status": self.trace_status,
"observation_truncated": self.observation_truncated,
"output_complete": self.output_complete,
"result_complete": self.result_complete,
})
}
}
fn bounded_text(value: &Value) -> (String, bool) {
let Some(text) = value.as_str() else {
return (String::new(), true);
};
let mut end = text.len().min(MAX_TEXT);
while !text.is_char_boundary(end) {
end -= 1;
}
(text[..end].to_string(), end == text.len())
}
+1
View File
@@ -11,5 +11,6 @@
pub mod controller;
pub mod events;
pub mod export_candidate;
pub mod process;
pub mod request;
+84 -4
View File
@@ -8,9 +8,12 @@ use crate::error::{ViewError, ViewResult};
use crate::reader::assemble::DocumentService;
use crate::reader::assets::AssetBundle;
use crate::reader::render::ReaderRenderer;
use crate::reader::snapshot::ExportResultOverlay;
use crate::reader::source::sha256_hex;
use crate::reader::source::SafeRelativePath;
use crate::scratch::ScratchDir;
use std::path::{Path, PathBuf};
use std::sync::Arc;
const MANIFEST_SCHEMA: &str = "marqdo.view-export";
@@ -45,7 +48,7 @@ pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<
let staging = staging_dir(&out)?;
let result = (|| {
let entry = context.load(&context.project().entry().relative)?;
let site = build_site(context, &entry, &staging, !options.no_annotations)?;
let site = build_site(context, &entry, &staging, !options.no_annotations, None)?;
publish(&staging, &out)?;
Ok(ExportSummary {
out,
@@ -113,6 +116,7 @@ fn build_site(
entry_model: &crate::reader::model::PresentationModel,
staging: &Path,
annotations: bool,
overlay: Option<Arc<ExportResultOverlay>>,
) -> ViewResult<Site> {
let documents = context.project().list_documents()?;
let entry = SafeRelativePath::parse(&entry_model.document.identity.relative_path)?;
@@ -130,6 +134,9 @@ fn build_site(
let renderer = ReaderRenderer::new();
let mut assets = Vec::new();
for asset in bundle.all() {
if overlay.is_some() && asset.extension == "js" {
continue;
}
let (name, bytes) = if asset.name == "reader" && asset.extension == "css" {
(bundle.hashed_css_name(), bundle.css_bytes())
} else {
@@ -158,7 +165,13 @@ fn build_site(
}
}
let depth = relative.as_str().split('/').count();
let settings = crate::reader::render::RenderContext::static_export(depth, annotations);
let mut settings = crate::reader::render::RenderContext::static_export(depth, annotations);
settings.snapshot_package = overlay.is_some();
settings.overlay = if *relative == entry {
overlay.clone()
} else {
None
};
let page = renderer.render(model, &settings);
let path = format!("pages/{}.html", relative.as_str());
let file = writer.write(&path, page.html.as_bytes())?;
@@ -176,13 +189,15 @@ fn build_site(
}
files.extend(media_files.values().cloned());
let index_context = crate::reader::render::RenderContext::static_export(0, annotations);
let mut index_context = crate::reader::render::RenderContext::static_export(0, annotations);
index_context.snapshot_package = overlay.is_some();
index_context.overlay = overlay.clone();
let index_page = renderer.render(entry_model, &index_context);
let index_file = writer.write("index.html", index_page.html.as_bytes())?;
let index_sha = index_file["sha256"].clone();
files.push(index_file);
files.sort_by(|a, b| a["path"].as_str().cmp(&b["path"].as_str()));
let manifest = serde_json::json!({
let mut manifest = serde_json::json!({
"schema": MANIFEST_SCHEMA,
"schema_version": 1,
"view": {"name": "marqdo-view", "version": env!("CARGO_PKG_VERSION")},
@@ -202,6 +217,17 @@ fn build_site(
"executed": false,
"note": "Static export only; reading or exporting never executes the document.",
});
if let Some(overlay) = overlay {
manifest["schema_version"] = serde_json::json!(2);
manifest["source"] = serde_json::json!(overlay.source);
manifest["execution"] = serde_json::json!(overlay.execution);
manifest["scope"] = serde_json::json!("document");
manifest["executed_during_export"] = serde_json::json!(false);
if let Some(fields) = manifest.as_object_mut() {
fields.remove("executed");
fields.remove("note");
}
}
let manifest_bytes =
serde_json::to_vec_pretty(&manifest).map_err(|err| ViewError::ExportFailed {
detail: format!("serialize export manifest: {err}"),
@@ -214,6 +240,60 @@ fn build_site(
})
}
pub struct SnapshotArchive {
pub file: std::fs::File,
pub len: usize,
_scratch: ScratchDir,
}
pub fn snapshot(
context: &DocumentService,
model: &crate::reader::model::PresentationModel,
overlay: ExportResultOverlay,
) -> ViewResult<SnapshotArchive> {
let temp = std::env::temp_dir()
.canonicalize()
.map_err(|err| ViewError::io("resolve temporary location", err))?;
if temp.starts_with(context.project().root()) {
return Err(ViewError::ExportFailed {
detail: "temporary location is inside the project".into(),
});
}
let scratch = ScratchDir::create("snapshot")?;
let staging = scratch.file("site");
std::fs::create_dir(&staging)
.map_err(|err| ViewError::io("create private snapshot site", err))?;
let site = build_site(context, model, &staging, true, Some(Arc::new(overlay)))?;
let path = scratch.file("snapshot.zip");
let archive =
std::fs::File::create(&path).map_err(|err| ViewError::io("create snapshot ZIP", err))?;
let mut archive = zip::ZipWriter::new(archive);
let zip_error = |err: zip::result::ZipError| ViewError::ExportFailed {
detail: format!("package snapshot ZIP: {err}"),
};
let options = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.unix_permissions(0o644);
for name in site.entries {
archive.start_file(&name, options).map_err(zip_error)?;
let mut file = std::fs::File::open(staging.join(name))
.map_err(|err| ViewError::io("open static snapshot file", err))?;
std::io::copy(&mut file, &mut archive)
.map_err(|err| ViewError::io("write snapshot file into ZIP", err))?;
}
archive.finish().map_err(zip_error)?;
let file = std::fs::File::open(path).map_err(|err| ViewError::io("open snapshot ZIP", err))?;
let len = file
.metadata()
.map_err(|err| ViewError::io("stat snapshot ZIP", err))?
.len() as usize;
Ok(SnapshotArchive {
file,
len,
_scratch: scratch,
})
}
fn absolute_export_target(raw: &Path) -> ViewResult<PathBuf> {
let absolute = if raw.is_absolute() {
raw.to_path_buf()
+188
View File
@@ -0,0 +1,188 @@
//! Validate the selected session result against a freshly loaded document.
//! The output is an owned reader projection, independent of the job.
use crate::{
execution::{events::RunState, export_candidate::TerminalExportCandidate},
reader::{
assemble::DocumentService,
media,
model::PresentationModel,
snapshot::{ExportResultOverlay, SnapshotExecution, SnapshotProtocols, SnapshotSource},
source::{sha256_hex, SafeRelativePath},
},
ViewError, ViewResult,
};
use serde::Deserialize;
pub const MAX_EXPORT_REQUEST: usize = 8 * 1024;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExportSelection {
schema: String,
schema_version: u32,
pub run_id: String,
document: String,
analysis_digest: String,
scope: Scope,
include: Include,
confirm_sensitive_output: bool,
#[serde(default)]
confirm_partial: bool,
client_export_request_id: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum Scope {
Document,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Include {
result_value: bool,
stdout: bool,
stderr: bool,
trace_summary: bool,
arguments: bool,
}
impl ExportSelection {
pub fn parse(body: &[u8]) -> ViewResult<Self> {
let invalid = || ViewError::ExportInvalid {
detail: "invalid v1 static export request".into(),
};
let selection: Self = serde_json::from_slice(body).map_err(|_| invalid())?;
let valid_token = |value: &str| {
!value.is_empty()
&& value.len() <= 128
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
};
let path = SafeRelativePath::parse(&selection.document).map_err(|_| invalid())?;
let digest = selection
.analysis_digest
.strip_prefix("sha256:")
.ok_or_else(invalid)?;
if selection.schema != "marqdo.view-static-export-request"
|| selection.schema_version != 1
|| !matches!(selection.scope, Scope::Document)
|| selection.document.len() > 1024
|| path.as_str() != selection.document
|| !selection.document.ends_with(".mq.md")
|| digest.len() != 64
|| !digest
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|| !valid_token(&selection.run_id)
|| !valid_token(&selection.client_export_request_id)
{
return Err(invalid());
}
Ok(selection)
}
pub fn prepare(
&self,
service: &DocumentService,
candidate: &TerminalExportCandidate,
) -> ViewResult<(PresentationModel, ExportResultOverlay)> {
let changed = || ViewError::ExportSourceChanged {
detail: "selected execution no longer matches the document".into(),
};
let invalid = || ViewError::ExportInvalid {
detail: "missing confirmation for selected fields or partial result".into(),
};
if self.document != candidate.document || self.analysis_digest != candidate.analysis_digest
{
return Err(changed());
}
if (self.include.stdout
|| self.include.stderr
|| self.include.arguments
|| self.include.result_value
&& candidate.value.is_some()
&& !candidate.value_is_public_scalar)
&& !self.confirm_sensitive_output
{
return Err(invalid());
}
if (candidate.state != RunState::Succeeded
|| !candidate.output_complete
|| candidate.observation_truncated
|| candidate.trace_status == "truncated")
&& !self.confirm_partial
{
return Err(invalid());
}
let document = SafeRelativePath::parse(&self.document)?;
let model = service.load(&document).map_err(|_| changed())?;
let analysis = model.semantic.as_ref().ok_or_else(changed)?;
if analysis.analysis_digest != candidate.analysis_digest
|| analysis.schema_version != candidate.analysis_version
|| analysis.project_root_id != candidate.project_root_id
|| analysis.module_id != candidate.module_id
|| analysis.lock_digest != candidate.lock_digest
|| sha256_hex(model.document.source.as_bytes()) != candidate.source_sha256
|| media::digests(&model.media) != candidate.media
|| !analysis
.functions
.iter()
.any(|function| function.id == candidate.function_id)
{
return Err(changed());
}
let overlay = ExportResultOverlay {
source: SnapshotSource {
project_root_id: candidate.project_root_id.clone(),
document: candidate.document.clone(),
module_id: candidate.module_id.clone(),
source_sha256: candidate.source_sha256.clone(),
analysis_digest: candidate.analysis_digest.clone(),
lock_digest: (!candidate.lock_digest.is_empty())
.then(|| candidate.lock_digest.clone()),
},
execution: SnapshotExecution {
included: true,
core_run_id: candidate.core_run_id.clone(),
target: candidate.function_id.clone(),
core_version: candidate.core_version.clone(),
status: candidate.state.data_value(),
terminal_at: candidate.terminal_at.clone(),
source_verified: true,
trace_status: candidate.trace_status.clone(),
result_complete: candidate.result_complete,
output_complete: candidate.output_complete,
observation_truncated: candidate.observation_truncated,
parameters: if self.include.arguments {
"included"
} else {
"omitted"
},
mode: candidate.mode.clone(),
core_protocol: SnapshotProtocols {
analysis: candidate.analysis_version,
trace: 2,
events: 1,
},
},
label: candidate.label.clone(),
value: self
.include
.result_value
.then(|| candidate.value.clone())
.flatten(),
stdout: self.include.stdout.then(|| candidate.stdout.clone()),
stderr: self.include.stderr.then(|| candidate.stderr.clone()),
trace_counts: self
.include
.trace_summary
.then(|| candidate.trace_counts.clone())
.flatten(),
arguments: self.include.arguments.then(|| candidate.arguments.clone()),
};
Ok((model, overlay))
}
}
+2
View File
@@ -12,8 +12,10 @@ pub mod core_client;
pub mod error;
pub mod execution;
pub mod export;
pub mod export_result;
pub mod protocol;
pub mod reader;
mod scratch;
pub mod server;
pub use cli::Cli;
+6
View File
@@ -382,6 +382,7 @@ pub struct StaticDocument {
pub source_sha256: String,
/// Exact bytes written by `marqdo check --emit`.
pub analysis_bytes: Vec<u8>,
pub media_digests: std::collections::BTreeMap<String, String>,
pub analysis_digest: String,
pub verified: crate::protocol::analysis_v2::VerifiedAnalysis,
}
@@ -443,6 +444,10 @@ impl DocumentService {
&source_index,
relative.as_str(),
)?;
let document =
DocumentModel::parse(source.clone(), DocumentIdentity::placeholder(relative));
let media = super::media::collect(&self.project, relative, &document.blocks);
let media_digests = super::media::digests(&media);
Ok(StaticDocument {
relative: relative.clone(),
source,
@@ -450,6 +455,7 @@ impl DocumentService {
source_sha256,
analysis_digest: check.analysis_digest,
analysis_bytes: check.analysis_bytes,
media_digests,
verified,
})
}
+7
View File
@@ -63,6 +63,13 @@ pub fn collect(
result
}
pub fn digests(media: &BTreeMap<String, Arc<Media>>) -> BTreeMap<String, String> {
media
.values()
.map(|item| (item.path.to_string(), item.digest.clone()))
.collect()
}
fn scan_blocks<'a>(blocks: &'a [DocBlock], urls: &mut BTreeSet<&'a str>) {
for block in blocks {
match block {
+1
View File
@@ -12,4 +12,5 @@ pub mod math;
pub mod media;
pub mod model;
pub mod render;
pub mod snapshot;
pub mod source;
+114 -19
View File
@@ -77,7 +77,7 @@ impl LinkPolicy {
}
/// Everything the renderer needs beyond the model.
#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct RenderContext {
pub links: LinkPolicy,
pub live: bool,
@@ -91,6 +91,8 @@ pub struct RenderContext {
pub run_timeout_secs: u64,
/// Whether a frozen Core was negotiated (an explicit run form can exist).
pub core_available: bool,
pub snapshot_package: bool,
pub overlay: Option<std::sync::Arc<super::snapshot::ExportResultOverlay>>,
}
impl RenderContext {
@@ -103,6 +105,8 @@ impl RenderContext {
annotations: true,
run_timeout_secs: 30,
core_available: false,
snapshot_package: false,
overlay: None,
}
}
@@ -115,6 +119,8 @@ impl RenderContext {
annotations: true,
run_timeout_secs: 0,
core_available: false,
snapshot_package: false,
overlay: None,
}
}
@@ -153,12 +159,14 @@ impl ReaderRenderer {
let logo_uri = self.assets.logo().data_uri();
let navigation = &model.navigation;
let document_href = format!(
"{prefix}reader.{hash}.css",
prefix = asset_prefix,
hash = &self.assets.css_served_sha256()[..16]
);
let _ = document_href;
let script = if ctx.snapshot_package {
String::new()
} else {
format!(
"<script defer src=\"{}\"></script>",
escape_attr(&format!("{asset_prefix}{js_name}"))
)
};
let mut html = String::with_capacity(16 * 1024 + model.document.source.len());
let relative_path = model.document.identity.relative_path.clone();
let analysis_digest = model
@@ -185,18 +193,17 @@ impl ReaderRenderer {
<title>{title}</title>
<link rel="icon" type="image/svg+xml" href="{logo}"/>
<link rel="stylesheet" href="{css}"/>
<script defer src="{js}"></script>
{script}
</head>
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}">
<a class="mq-skip" href="#mq-main">跳到正文</a>
"##,
presentation_version = model.version,
view_version = env!("CARGO_PKG_VERSION"),
csp = csp_policy(),
csp = csp_policy(ctx.snapshot_package),
title = escape_text(&page_title),
logo = escape_attr(&logo_uri),
css = escape_attr(&format!("{asset_prefix}{css_name}")),
js = escape_attr(&format!("{asset_prefix}{js_name}")),
status = model.source_status.data_value(),
annotations = if ctx.annotations { "on" } else { "off" },
run_state = model.run_state().data_value(),
@@ -217,6 +224,13 @@ impl ReaderRenderer {
self.render_welcome(&mut html, navigation);
}
self.render_document_meta(&mut html, model);
if ctx.overlay.is_some() {
let prefix = match ctx.links {
LinkPolicy::StaticRelative { page_depth } => "../".repeat(page_depth),
LinkPolicy::LocalServer => String::new(),
};
let _ = write!(html, "<p class=\"mq-snapshot-notice\">此文档包含一次执行快照。来源摘要见 <a href=\"{prefix}manifest.json\">manifest.json</a>。</p>");
}
self.render_diagnostics(&mut html, model);
self.render_functions(&mut html, model, ctx);
self.render_document(&mut html, model, ctx);
@@ -225,18 +239,30 @@ impl ReaderRenderer {
} else {
self.render_run_panel(&mut html, model, ctx);
}
self.render_source_pane(&mut html, model, ctx);
if ctx.snapshot_package {
let _ = write!(html, "<details class=\"mq-static-source\"><summary>原始源码</summary><pre>{}</pre></details>",
escape_text(&model.document.source));
html.push_str(&self.render_file_list(model, ctx));
} else {
self.render_source_pane(&mut html, model, ctx);
}
self.render_footer(&mut html, model);
let _ = write!(html, "</main>\n");
self.render_dock(&mut html, ctx);
self.render_toast(&mut html);
self.render_dialogs(&mut html, model, ctx);
if !ctx.snapshot_package {
self.render_dock(&mut html, ctx);
self.render_toast(&mut html);
self.render_dialogs(&mut html, model, ctx);
}
html.push_str("</body>\n</html>\n");
RenderedPage {
html,
assets_used: vec![css_name, js_name],
assets_used: if ctx.snapshot_package {
vec![css_name]
} else {
vec![css_name, js_name]
},
}
}
@@ -247,6 +273,11 @@ impl ReaderRenderer {
ctx: &RenderContext,
navigation: &crate::reader::model::Navigation,
) {
if ctx.snapshot_package {
let _ = write!(html, "<header class=\"mq-topbar\"><a class=\"mq-brand\" href=\"#mq-main\"><img class=\"mq-brand-logo\" src=\"{}\" width=\"44\" height=\"44\" alt=\"\"><span class=\"mq-brand-word\">{}</span></a></header>",
escape_attr(&self.assets.logo().data_uri()), escape_text(&navigation.site_title));
return;
}
let active = model
.navigation
.active
@@ -450,6 +481,9 @@ impl ReaderRenderer {
if ctx.live {
let _ = write!(html, "<div class=\"mq-result-slot\" data-result-for=\"{}\"></div>", escape_attr(&function.id));
}
if let Some(overlay) = ctx.overlay.as_deref().filter(|overlay| overlay.execution.target == function.id) {
render_snapshot(html, overlay);
}
};
for block in &model.document.blocks {
if let DocBlock::Heading {
@@ -1373,10 +1407,71 @@ fn escape_attr(raw: &str) -> String {
escape_text(raw)
}
fn csp_policy() -> &'static str {
// `frame-ancestors` is ignored in <meta>; the HTTP header (server.rs) adds
// the framing restrictions. Keep the meta policy identical otherwise.
"default-src 'none'; style-src 'self'; script-src 'self' file:; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; object-src 'none'"
fn csp_policy(snapshot_package: bool) -> &'static str {
if snapshot_package {
"default-src 'none'; style-src 'self' file:; img-src 'self' file: data:; font-src 'self' file:; base-uri 'none'; form-action 'none'; object-src 'none'"
} else {
"default-src 'none'; style-src 'self'; script-src 'self' file:; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; object-src 'none'"
}
}
fn render_snapshot(html: &mut String, overlay: &super::snapshot::ExportResultOverlay) {
let execution = &overlay.execution;
let status = if execution.status == "succeeded" {
"成功"
} else {
"失败 · 部分观察"
};
let _ = write!(html, "<details class=\"mq-snapshot\" data-run-state=\"{}\" open><summary>本次执行快照 · {} · {status}</summary><p class=\"mq-colophon\">Core {} · {} · <time datetime=\"{}\">{}</time></p>",
escape_attr(execution.status), escape_text(&overlay.label), escape_text(&execution.core_version),
escape_text(&execution.mode), escape_attr(&execution.terminal_at), escape_text(&execution.terminal_at));
for (label, value) in [
("返回值", &overlay.value),
("stdout", &overlay.stdout),
("stderr", &overlay.stderr),
] {
if let Some(value) = value {
let _ = write!(
html,
"<p>{label}</p><pre aria-label=\"{label}\">{}</pre>",
escape_text(value)
);
}
}
if let Some(arguments) = &overlay.arguments {
html.push_str("<p>提交的参数表达式</p><dl>");
for (name, expression) in arguments {
let _ = write!(
html,
"<dt>{}</dt><dd><code>{}</code></dd>",
escape_text(name),
escape_text(expression)
);
}
html.push_str("</dl>");
} else {
html.push_str("<p class=\"mq-colophon\">参数未包含</p>");
}
let trace_status = match execution.trace_status.as_str() {
"verified" => "已验证",
"truncated" => "已验证,轨迹截断",
"invalid" => "无效",
_ => "不可用",
};
let _ = write!(html, "<p class=\"mq-colophon\">Trace v2 {trace_status}</p>");
if let Some(counts) = &overlay.trace_counts {
html.push_str("<dl class=\"mq-snapshot-counts\">");
for (kind, count) in counts {
let _ = write!(html, "<dt>{}</dt><dd>{count}</dd>", escape_text(kind));
}
html.push_str("</dl>");
}
if !execution.output_complete || !execution.result_complete || execution.observation_truncated {
html.push_str(
"<p class=\"mq-run-warning\">部分结果、输出或事件超过显示上限,或未完成。</p>",
);
}
html.push_str("</details>");
}
fn percent_encode_path(raw: &str) -> String {
+50
View File
@@ -0,0 +1,50 @@
//! Renderer input for one explicitly selected, already verified terminal result.
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Serialize)]
pub struct SnapshotSource {
pub project_root_id: String,
pub document: String,
pub module_id: String,
pub source_sha256: String,
pub analysis_digest: String,
pub lock_digest: Option<String>,
}
#[derive(Serialize)]
pub struct SnapshotProtocols {
pub analysis: u32,
pub trace: u32,
pub events: u32,
}
#[derive(Serialize)]
pub struct SnapshotExecution {
pub included: bool,
pub core_run_id: String,
pub core_version: String,
pub target: String,
pub status: &'static str,
pub terminal_at: String,
pub source_verified: bool,
pub trace_status: String,
pub result_complete: bool,
pub output_complete: bool,
pub observation_truncated: bool,
pub parameters: &'static str,
pub mode: String,
pub core_protocol: SnapshotProtocols,
}
pub struct ExportResultOverlay {
pub source: SnapshotSource,
pub execution: SnapshotExecution,
pub label: String,
pub value: Option<String>,
pub stdout: Option<String>,
pub stderr: Option<String>,
pub trace_counts: Option<BTreeMap<String, u64>>,
pub arguments: Option<Vec<(String, String)>>,
}
+63
View File
@@ -0,0 +1,63 @@
use crate::{ViewError, ViewResult};
use std::path::{Path, PathBuf};
/// A private temporary directory for transient artifacts.
pub struct ScratchDir {
path: PathBuf,
}
impl ScratchDir {
pub fn create(label: &str) -> ViewResult<Self> {
let base = std::env::temp_dir();
let unique = format!(
"marqdo-view-{}-{}-{}",
std::process::id(),
unique_counter(),
sanitize_label(label)
);
let path = base.join(unique);
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder
.create(&path)
.map_err(|err| ViewError::io("create private scratch directory", err))?;
Ok(Self { path })
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn file(&self, name: &str) -> PathBuf {
self.path.join(name)
}
}
impl Drop for ScratchDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn unique_counter() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
seq ^ nanos.rotate_left(17)
}
fn sanitize_label(label: &str) -> String {
label
.chars()
.map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' })
.take(32)
.collect()
}
+1
View File
@@ -48,6 +48,7 @@ pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult<i32> {
cache: Mutex::new(HashMap::new()),
security: crate::server::security::SecurityState::new(port),
active_requests: AtomicUsize::new(0),
snapshot_export: Mutex::new(()),
});
eprintln!("marqdo view: {url}");
+63 -2
View File
@@ -6,6 +6,8 @@
//! | `GET /file?path=...` | no |
//! | `GET /assets/...` | no |
//! | `GET /api/documents` | no |
//! | `GET /media/...` | no |
//! | `POST /api/exports` | no (static snapshot) |
//! | `POST /api/runs` | **yes — the only execution entry** |
//! | `GET /api/runs/{id}/events` | no (observe only) |
//! | `POST /api/runs/{id}/cancel` | no (control of an existing job) |
@@ -37,6 +39,7 @@ pub struct ServerState {
pub cache: Mutex<HashMap<String, CacheEntry>>,
pub security: SecurityState,
pub active_requests: AtomicUsize,
pub snapshot_export: Mutex<()>,
}
#[derive(Clone)]
@@ -129,6 +132,9 @@ pub fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
}
if method == Method::Post {
if path == "/api/exports" {
return submit_export(state, request);
}
if path == "/api/runs" {
return submit_run(state, request);
}
@@ -188,6 +194,8 @@ fn serve_page(
annotations: true,
run_timeout_secs: state.controller.config().run_timeout_secs(),
core_available: state.service.core().is_some(),
snapshot_package: false,
overlay: None,
};
let page = state.renderer.render(&model, &ctx);
let mut headers = Vec::new();
@@ -326,6 +334,56 @@ fn serve_documents(state: &ServerState, request: Request, query: &str) -> ViewRe
}
/// The only execution entry in the whole product.
fn submit_export(state: &ServerState, mut request: Request) -> ViewResult<()> {
use crate::export_result::{ExportSelection, MAX_EXPORT_REQUEST};
let result = (|| {
let session = state.security.authenticate_post(&request)?;
let selection = ExportSelection::parse(&read_body(&mut request, MAX_EXPORT_REQUEST)?)?;
let candidate = state
.controller
.get_export_candidate(&session.id, &selection.run_id)?;
let guard = state
.snapshot_export
.try_lock()
.map_err(|_| ViewError::ResourceLimit {
detail: "a snapshot download is already being prepared or sent".into(),
})?;
let (model, overlay) = selection.prepare(&state.service, &candidate)?;
let archive = crate::export::snapshot(&state.service, &model, overlay)?;
Ok((guard, archive))
})();
let (_guard, archive) = match result {
Ok(result) => result,
Err(err) => return respond_error(request, status_for(&err), &err),
};
let mut headers = crate::server::security::security_headers();
headers.retain(|(name, _)| *name != "Content-Security-Policy");
headers.extend([
("Content-Type", "application/zip"),
(
"Content-Disposition",
"attachment; filename=marqdo-execution-snapshot.zip",
),
("Content-Security-Policy", "default-src 'none'; sandbox"),
]);
let headers = headers
.into_iter()
.map(|(name, value)| {
Header::from_bytes(name, value).expect("valid snapshot download header")
})
.collect();
let response = Response::new(
StatusCode(200),
headers,
archive.file,
Some(archive.len),
None,
);
request
.respond(response)
.map_err(|err| ViewError::io("send snapshot ZIP", err))
}
fn submit_run(state: &ServerState, mut request: Request) -> ViewResult<()> {
let session = match state.security.authenticate_post(&request) {
Ok(session) => session,
@@ -478,8 +536,11 @@ fn status_for(err: &ViewError) -> StatusCode {
match err.code() {
"view.session_required" => StatusCode(401),
"view.run_denied" => StatusCode(403),
"view.run_invalid" | "view.no_entry_function" => StatusCode(400),
"view.run_busy" | "view.run_conflict" => StatusCode(409),
"view.run_invalid" | "view.no_entry_function" | "view.export_invalid" => StatusCode(400),
"view.run_busy"
| "view.run_conflict"
| "view.export_unavailable"
| "view.export_source_changed" => StatusCode(409),
"view.run_not_found" => StatusCode(404),
"view.sse_busy" | "view.resource_limit" => StatusCode(429),
"view.output_limit" => StatusCode(413),