From aa2a2b3ce49da440d78cfd51c706c7b8bd25c71b Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 13:43:27 +0800 Subject: [PATCH] feat: export one source-bound session result as a static ZIP --- Cargo.lock | 55 +++ Cargo.toml | 1 + assets/reader.css | 33 ++ docs/schema/export-manifest-v2.schema.json | 371 +++++++++++++++++++++ docs/schema/export-overlay-v1.schema.json | 216 ++++++++++++ docs/schema/export-request-v1.schema.json | 85 +++++ scripts/test-complete-reader.py | 192 +++++++++++ src/core_client.rs | 60 +--- src/error.rs | 119 +++++-- src/execution/controller.rs | 45 ++- src/execution/export_candidate.rs | 148 ++++++++ src/execution/mod.rs | 1 + src/export.rs | 88 ++++- src/export_result.rs | 188 +++++++++++ src/lib.rs | 2 + src/reader/assemble.rs | 6 + src/reader/media.rs | 7 + src/reader/mod.rs | 1 + src/reader/render.rs | 133 ++++++-- src/reader/snapshot.rs | 50 +++ src/scratch.rs | 63 ++++ src/server/mod.rs | 1 + src/server/routes.rs | 65 +++- 23 files changed, 1816 insertions(+), 114 deletions(-) create mode 100644 docs/schema/export-manifest-v2.schema.json create mode 100644 docs/schema/export-overlay-v1.schema.json create mode 100644 docs/schema/export-request-v1.schema.json create mode 100755 scripts/test-complete-reader.py create mode 100644 src/execution/export_candidate.rs create mode 100644 src/export_result.rs create mode 100644 src/reader/snapshot.rs create mode 100644 src/scratch.rs diff --git a/Cargo.lock b/Cargo.lock index fa739ce..99db59f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -58,6 +58,15 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + [[package]] name = "ascii" version = "1.1.0" @@ -227,6 +236,17 @@ dependencies = [ "typenum", ] +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "digest" version = "0.10.7" @@ -243,6 +263,12 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca" +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "fastrand" version = "2.5.0" @@ -312,6 +338,12 @@ dependencies = [ "weezl", ] +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + [[package]] name = "heck" version = "0.5.0" @@ -352,6 +384,16 @@ dependencies = [ "quick-error", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -392,6 +434,7 @@ dependencies = [ "serde_json", "sha2", "tiny_http", + "zip", ] [[package]] @@ -734,6 +777,18 @@ dependencies = [ "windows-link", ] +[[package]] +name = "zip" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" +dependencies = [ + "arbitrary", + "crc32fast", + "indexmap", + "memchr", +] + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/Cargo.toml b/Cargo.toml index 45b4e71..caea055 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,7 @@ sha2 = "0.10" comrak = { version = "=1.0.0", default-features = false } semver = "1" tiny_http = "0.12" +zip = { version = "=4.6.1", default-features = false } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/assets/reader.css b/assets/reader.css index a11920e..0117fad 100644 --- a/assets/reader.css +++ b/assets/reader.css @@ -1408,3 +1408,36 @@ .mq-run-panel[hidden] { display: none; } } + +@layer semantics { + .mq-snapshot, .mq-snapshot-notice, .mq-static-source { + background: var(--mq-surface); + border: 1px solid var(--mq-line); + border-radius: .65rem; + padding: .9rem 1rem; + margin-block: 1.25rem; + } + + .mq-snapshot { + border-color: var(--mq-olive); + overflow-wrap: anywhere; + } + + .mq-snapshot > summary, .mq-static-source > summary { + font-weight: 650; + cursor: pointer; + } + + .mq-snapshot pre, .mq-static-source pre { + white-space: pre-wrap; + overflow-wrap: anywhere; + font: .9rem/1.55 var(--mq-mono); + } + + .mq-snapshot-counts { + display: grid; + grid-template-columns: minmax(0, 2fr) 1fr; + } + + .mq-snapshot-counts dd { margin: 0; } +} diff --git a/docs/schema/export-manifest-v2.schema.json b/docs/schema/export-manifest-v2.schema.json new file mode 100644 index 0000000..672987c --- /dev/null +++ b/docs/schema/export-manifest-v2.schema.json @@ -0,0 +1,371 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://git.cflmy.cn/cflmy/marqdo-view/raw/branch/master/docs/schema/export-manifest-v2.schema.json", + "title": "View Static Result Export Manifest v2", + "type": "object", + "properties": { + "schema": { + "const": "marqdo.view-export" + }, + "schema_version": { + "const": 2 + }, + "view": { + "type": "object", + "properties": { + "name": { + "const": "marqdo-view" + }, + "version": { + "type": "string" + } + }, + "required": [ + "name", + "version" + ], + "additionalProperties": false + }, + "compatibility": { + "type": "object", + "properties": { + "marqdo": { + "type": "string" + }, + "tool_protocol": { + "const": 1 + }, + "analysis": { + "const": 2 + }, + "analysis_supported": { + "const": [ + 2, + 3 + ] + }, + "trace": { + "const": 2 + }, + "markdown_profile": { + "const": "marqdo.md.v1" + } + }, + "required": [ + "marqdo", + "tool_protocol", + "analysis", + "analysis_supported", + "trace", + "markdown_profile" + ], + "additionalProperties": false + }, + "core_version": { + "type": "string" + }, + "entry": { + "type": "object", + "properties": { + "relative_path": { + "type": "string", + "pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$" + }, + "file": { + "const": "index.html" + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } + }, + "required": [ + "relative_path", + "file", + "sha256" + ], + "additionalProperties": false + }, + "pages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "relative_path": { + "type": "string", + "pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$" + }, + "module_id": { + "type": "string" + }, + "source_sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "source_status": { + "type": "string" + }, + "analysis_digest": { + "anyOf": [ + { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + { + "type": "null" + } + ] + }, + "file": { + "type": "string", + "pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$" + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "annotations": { + "type": "boolean" + } + }, + "required": [ + "relative_path", + "module_id", + "source_sha256", + "source_status", + "analysis_digest", + "file", + "sha256", + "annotations" + ], + "additionalProperties": false + } + }, + "assets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$" + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "size": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "path", + "sha256", + "size" + ], + "additionalProperties": false + } + }, + "files": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$" + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "size": { + "type": "integer", + "minimum": 0 + }, + "mime": { + "enum": [ + "image/png", + "image/jpeg", + "image/gif", + "image/webp", + "image/svg+xml" + ] + } + }, + "required": [ + "path", + "sha256", + "size" + ], + "additionalProperties": false + } + }, + "scope": { + "const": "document" + }, + "source": { + "type": "object", + "properties": { + "project_root_id": { + "type": "string" + }, + "document": { + "type": "string", + "pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$" + }, + "module_id": { + "type": "string" + }, + "source_sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "analysis_digest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + "lock_digest": { + "anyOf": [ + { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "project_root_id", + "document", + "module_id", + "source_sha256", + "analysis_digest", + "lock_digest" + ], + "additionalProperties": false + }, + "execution": { + "type": "object", + "properties": { + "included": { + "const": true + }, + "core_run_id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,128}$" + }, + "core_version": { + "type": "string" + }, + "target": { + "type": "string" + }, + "status": { + "enum": [ + "succeeded", + "failed" + ] + }, + "terminal_at": { + "type": "string", + "format": "date-time" + }, + "source_verified": { + "const": true + }, + "trace_status": { + "enum": [ + "verified", + "invalid", + "unavailable", + "truncated" + ] + }, + "result_complete": { + "type": "boolean" + }, + "output_complete": { + "type": "boolean" + }, + "observation_truncated": { + "type": "boolean" + }, + "parameters": { + "enum": [ + "omitted", + "included" + ] + }, + "mode": { + "enum": [ + "pure", + "project" + ] + }, + "core_protocol": { + "type": "object", + "properties": { + "analysis": { + "enum": [ + 2, + 3 + ] + }, + "trace": { + "const": 2 + }, + "events": { + "const": 1 + } + }, + "required": [ + "analysis", + "trace", + "events" + ], + "additionalProperties": false + } + }, + "required": [ + "included", + "core_run_id", + "core_version", + "target", + "status", + "terminal_at", + "source_verified", + "trace_status", + "result_complete", + "output_complete", + "observation_truncated", + "parameters", + "mode", + "core_protocol" + ], + "additionalProperties": false + }, + "executed_during_export": { + "const": false + } + }, + "required": [ + "schema", + "schema_version", + "view", + "compatibility", + "core_version", + "entry", + "pages", + "assets", + "files", + "scope", + "source", + "execution", + "executed_during_export" + ], + "additionalProperties": false +} diff --git a/docs/schema/export-overlay-v1.schema.json b/docs/schema/export-overlay-v1.schema.json new file mode 100644 index 0000000..59fb489 --- /dev/null +++ b/docs/schema/export-overlay-v1.schema.json @@ -0,0 +1,216 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://git.cflmy.cn/cflmy/marqdo-view/raw/branch/master/docs/schema/export-overlay-v1.schema.json", + "title": "View internal renderer result projection v1", + "type": "object", + "properties": { + "source": { + "type": "object", + "properties": { + "project_root_id": { + "type": "string" + }, + "document": { + "type": "string", + "pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$" + }, + "module_id": { + "type": "string" + }, + "source_sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "analysis_digest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + "lock_digest": { + "anyOf": [ + { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "project_root_id", + "document", + "module_id", + "source_sha256", + "analysis_digest", + "lock_digest" + ], + "additionalProperties": false + }, + "execution": { + "type": "object", + "properties": { + "included": { + "const": true + }, + "core_run_id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,128}$" + }, + "core_version": { + "type": "string" + }, + "target": { + "type": "string" + }, + "status": { + "enum": [ + "succeeded", + "failed" + ] + }, + "terminal_at": { + "type": "string", + "format": "date-time" + }, + "source_verified": { + "const": true + }, + "trace_status": { + "enum": [ + "verified", + "invalid", + "unavailable", + "truncated" + ] + }, + "result_complete": { + "type": "boolean" + }, + "output_complete": { + "type": "boolean" + }, + "observation_truncated": { + "type": "boolean" + }, + "parameters": { + "enum": [ + "omitted", + "included" + ] + }, + "mode": { + "enum": [ + "pure", + "project" + ] + }, + "core_protocol": { + "type": "object", + "properties": { + "analysis": { + "enum": [ + 2, + 3 + ] + }, + "trace": { + "const": 2 + }, + "events": { + "const": 1 + } + }, + "required": [ + "analysis", + "trace", + "events" + ], + "additionalProperties": false + } + }, + "required": [ + "included", + "core_run_id", + "core_version", + "target", + "status", + "terminal_at", + "source_verified", + "trace_status", + "result_complete", + "output_complete", + "observation_truncated", + "parameters", + "mode", + "core_protocol" + ], + "additionalProperties": false + }, + "label": { + "type": "string" + }, + "value": { + "type": [ + "string", + "null" + ], + "maxLength": 131072 + }, + "stdout": { + "type": [ + "string", + "null" + ], + "maxLength": 131072 + }, + "stderr": { + "type": [ + "string", + "null" + ], + "maxLength": 131072 + }, + "trace_counts": { + "type": [ + "object", + "null" + ], + "additionalProperties": { + "type": "integer", + "minimum": 0 + } + }, + "arguments": { + "type": [ + "array", + "null" + ], + "maxItems": 32, + "items": { + "type": "array", + "prefixItems": [ + { + "type": "string" + }, + { + "type": "string" + } + ], + "items": false, + "minItems": 2 + } + } + }, + "required": [ + "source", + "execution", + "label", + "value", + "stdout", + "stderr", + "trace_counts", + "arguments" + ], + "additionalProperties": false +} diff --git a/docs/schema/export-request-v1.schema.json b/docs/schema/export-request-v1.schema.json new file mode 100644 index 0000000..b773fe1 --- /dev/null +++ b/docs/schema/export-request-v1.schema.json @@ -0,0 +1,85 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://git.cflmy.cn/cflmy/marqdo-view/raw/branch/master/docs/schema/export-request-v1.schema.json", + "title": "View Static Export Request v1", + "type": "object", + "properties": { + "schema": { + "const": "marqdo.view-static-export-request" + }, + "schema_version": { + "const": 1 + }, + "run_id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,128}$" + }, + "document": { + "type": "string", + "pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$", + "maxLength": 1024, + "allOf": [ + { + "pattern": "\\.mq\\.md$" + } + ] + }, + "analysis_digest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + "scope": { + "const": "document" + }, + "include": { + "type": "object", + "properties": { + "result_value": { + "type": "boolean" + }, + "stdout": { + "type": "boolean" + }, + "stderr": { + "type": "boolean" + }, + "trace_summary": { + "type": "boolean" + }, + "arguments": { + "type": "boolean" + } + }, + "required": [ + "result_value", + "stdout", + "stderr", + "trace_summary", + "arguments" + ], + "additionalProperties": false + }, + "confirm_sensitive_output": { + "type": "boolean" + }, + "confirm_partial": { + "type": "boolean" + }, + "client_export_request_id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,128}$" + } + }, + "required": [ + "schema", + "schema_version", + "run_id", + "document", + "analysis_digest", + "scope", + "include", + "confirm_sensitive_output", + "client_export_request_id" + ], + "additionalProperties": false +} diff --git a/scripts/test-complete-reader.py b/scripts/test-complete-reader.py new file mode 100755 index 0000000..d74066e --- /dev/null +++ b/scripts/test-complete-reader.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""HTTP and ZIP acceptance against an unmodified RC.2 release binary.""" + +import hashlib +import http.cookiejar +import io +import json +import os +from pathlib import Path, PurePosixPath +import re +import shutil +import subprocess +import tempfile +import urllib.error +import urllib.request +import zipfile + +ROOT = Path(__file__).resolve().parents[1] +CORE = Path(os.environ["MARQDO_BIN"]).resolve(strict=True) +VIEW = Path(os.environ.get("VIEW_BIN", ROOT / "target/debug/marqdo-view")).resolve(strict=True) + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def session(base): + browser = urllib.request.build_opener( + urllib.request.ProxyHandler({}), + urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()), + ) + html = browser.open(base, timeout=10).read().decode() + token = re.search(r'name="mq-csrf-token" content="([a-f0-9]+)"', html)[1] + digest = re.search(r'data-analysis-digest="([^"]+)"', html)[1] + return browser, token, digest, html + + +def post(browser, base, route, token, body, status=200, origin=None): + headers = {"Content-Type": "application/json", "Origin": origin or base} + if token is not None: + headers["X-View-CSRF"] = token + request = urllib.request.Request(base + route, json.dumps(body).encode(), headers) + try: + with browser.open(request, timeout=20) as response: + assert response.status == status, (route, response.status, status) + return response.read(), response.headers + except urllib.error.HTTPError as error: + assert error.code == status, (route, error.code, status, error.read()) + return error.read(), error.headers + + +def verify_zip(payload, destination): + with zipfile.ZipFile(io.BytesIO(payload)) as archive: + names = archive.namelist() + assert len(names) == len(set(names)) + for item in archive.infolist(): + path = PurePosixPath(item.filename) + assert not path.is_absolute() and ".." not in path.parts + assert item.compress_type == zipfile.ZIP_STORED and item.file_size <= 16 * 1024 ** 2 + manifest = json.loads(archive.read("manifest.json")) + assert manifest["schema_version"] == 2 and not manifest["executed_during_export"] + assert manifest["execution"]["source_verified"] and manifest["execution"]["status"] == "succeeded" + assert manifest["execution"]["parameters"] == "omitted" + assert manifest["source"]["document"] == "index.mq.md" + assert manifest["execution"]["core_protocol"] == {"analysis": 3, "trace": 2, "events": 1} + for entry in manifest["files"] + manifest["assets"]: + data = archive.read(entry["path"]) + assert sha(data) == entry["sha256"] and len(data) == entry["size"] + assert not any(name.endswith(".js") for name in names) + html = archive.read("index.html").decode() + assert ", } -/// A private temporary directory for Core artifacts. -pub struct ScratchDir { - path: PathBuf, -} - -impl ScratchDir { - pub fn create(label: &str) -> ViewResult { - 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)] diff --git a/src/error.rs b/src/error.rs index 77f7ee5..6d68698 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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 } diff --git a/src/execution/controller.rs b/src/execution/controller.rs index 810b9ef..bc70520 100644 --- a/src/execution/controller.rs +++ b/src/execution/controller.rs @@ -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, + export_candidate: Option>, 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> { + 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> { - 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) diff --git a/src/execution/export_candidate.rs b/src/execution/export_candidate.rs new file mode 100644 index 0000000..8fef1c2 --- /dev/null +++ b/src/execution/export_candidate.rs @@ -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, + pub core_run_id: String, + pub core_version: String, + pub mode: String, + pub terminal_at: String, + pub state: RunState, + pub value: Option, + 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>, + 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 { + 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()) +} diff --git a/src/execution/mod.rs b/src/execution/mod.rs index 87b3db2..96deca1 100644 --- a/src/execution/mod.rs +++ b/src/execution/mod.rs @@ -11,5 +11,6 @@ pub mod controller; pub mod events; +pub mod export_candidate; pub mod process; pub mod request; diff --git a/src/export.rs b/src/export.rs index f861db2..15fa6af 100644 --- a/src/export.rs +++ b/src/export.rs @@ -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>, ) -> ViewResult { 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 { + 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 { let absolute = if raw.is_absolute() { raw.to_path_buf() diff --git a/src/export_result.rs b/src/export_result.rs new file mode 100644 index 0000000..51f0278 --- /dev/null +++ b/src/export_result.rs @@ -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 { + 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)) + } +} diff --git a/src/lib.rs b/src/lib.rs index 210ffc8..0781f17 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/reader/assemble.rs b/src/reader/assemble.rs index a8e4623..fb8bbd0 100644 --- a/src/reader/assemble.rs +++ b/src/reader/assemble.rs @@ -382,6 +382,7 @@ pub struct StaticDocument { pub source_sha256: String, /// Exact bytes written by `marqdo check --emit`. pub analysis_bytes: Vec, + pub media_digests: std::collections::BTreeMap, 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, }) } diff --git a/src/reader/media.rs b/src/reader/media.rs index 0f47eab..f37be0c 100644 --- a/src/reader/media.rs +++ b/src/reader/media.rs @@ -63,6 +63,13 @@ pub fn collect( result } +pub fn digests(media: &BTreeMap>) -> BTreeMap { + 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 { diff --git a/src/reader/mod.rs b/src/reader/mod.rs index e5904e8..7303d04 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -12,4 +12,5 @@ pub mod math; pub mod media; pub mod model; pub mod render; +pub mod snapshot; pub mod source; diff --git a/src/reader/render.rs b/src/reader/render.rs index a4fa75d..1918676 100644 --- a/src/reader/render.rs +++ b/src/reader/render.rs @@ -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>, } 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!( + "", + 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} - +{script} 跳到正文 "##, 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, "

此文档包含一次执行快照。来源摘要见 manifest.json。

"); + } 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, "
原始源码
{}
", + 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, "\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("\n\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, "
\"\"{}
", + 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, "
", 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 ; 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, "
本次执行快照 · {} · {status}

Core {} · {} ·

", + 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, + "

{label}

{}
", + escape_text(value) + ); + } + } + if let Some(arguments) = &overlay.arguments { + html.push_str("

提交的参数表达式

"); + for (name, expression) in arguments { + let _ = write!( + html, + "
{}
{}
", + escape_text(name), + escape_text(expression) + ); + } + html.push_str("
"); + } else { + html.push_str("

参数未包含

"); + } + let trace_status = match execution.trace_status.as_str() { + "verified" => "已验证", + "truncated" => "已验证,轨迹截断", + "invalid" => "无效", + _ => "不可用", + }; + let _ = write!(html, "

Trace v2 {trace_status}

"); + if let Some(counts) = &overlay.trace_counts { + html.push_str("
"); + for (kind, count) in counts { + let _ = write!(html, "
{}
{count}
", escape_text(kind)); + } + html.push_str("
"); + } + if !execution.output_complete || !execution.result_complete || execution.observation_truncated { + html.push_str( + "

部分结果、输出或事件超过显示上限,或未完成。

", + ); + } + html.push_str("
"); } fn percent_encode_path(raw: &str) -> String { diff --git a/src/reader/snapshot.rs b/src/reader/snapshot.rs new file mode 100644 index 0000000..8d897e2 --- /dev/null +++ b/src/reader/snapshot.rs @@ -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, +} + +#[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, + pub stdout: Option, + pub stderr: Option, + pub trace_counts: Option>, + pub arguments: Option>, +} diff --git a/src/scratch.rs b/src/scratch.rs new file mode 100644 index 0000000..ef00ded --- /dev/null +++ b/src/scratch.rs @@ -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 { + 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() +} diff --git a/src/server/mod.rs b/src/server/mod.rs index 6e5e38a..647aadb 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -48,6 +48,7 @@ pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult { 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}"); diff --git a/src/server/routes.rs b/src/server/routes.rs index d392eef..181c57a 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -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>, 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),