Files
marqdo-view/src/error.rs
T
Marqdo View 340ecb035f
ci/woodpecker/push/woodpecker Pipeline was successful
feat: migrate View 0.3.0 to marqdo 3.0.0-rc.4 contracts
Replace the retired rc.2 Analysis v2/Trace v2/Execution Events v1 stack with the
single current contract family:

- Analysis v3 (ADR-0069 public boundary): one check --emit artifact carries the
  exact source, Markdown AST, heading scopes (heading_span + complete span),
  anchors, state-bearing references, calls, resources and diagnostics; the old
  revision-3 shape is rejected with a rebuild hint.
- Observation v1: one run/call --output jsonl stream (+ atomic
  --observation-file snapshot) decoded by one decoder and projected into the
  reader/SSE/export layers; stale/malformed/truncated/incomplete never render
  as success.
- CLI Tool revision 1: requires {api_revision:1, analysis:3, observation:1},
  product range >=3.0.0-rc.3,<4.0.0, only MARQDO_BIN and
  MARQDO_API_REVISION are consumed.
- Remove compatibility branches, retired flags/env vars and duplicate decoders;
  re-record Analysis v3 and Observation v1 fixtures; rewrite contract,
  integration and security tests (173 passing locally).
- Add check-no-legacy/check-docs/check-observation gates, rc.4 pins in the
  CI pipelines, 0.3.0 Tool bundle and evidence manifest support.

See issues #4, #5 and #6; acceptance baseline is CLI source
452e9a32bd9e40dba427d4180691c58bab74449e, archive
9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8.
2026-11-25 22:12:51 +08:00

350 lines
14 KiB
Rust

//! Stable View-owned error kinds.
//!
//! Every failure that reaches the user has exactly one stable machine code
//! (`view.*`), an exit code class and a `source` field so Core diagnostics can
//! never be mistaken for View diagnostics. See RFC-VIEW-0001 §10.2.
use std::fmt;
/// Exit code 0: success. Exit code 1: runtime/I/O failure. Exit code 2:
/// argument, protocol or permission failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitClass {
Runtime,
Argument,
}
#[derive(Debug)]
pub enum ViewError {
/// `MARQDO_BIN` unset, missing, or not executable.
CoreMissing {
detail: String,
},
/// Tool/Analysis/Trace protocol or product range mismatch.
ProtocolIncompatible {
detail: String,
},
/// Core `check` failed; prose stays readable but semantics are unusable.
AnalysisFailed {
detail: String,
},
/// Analysis `source_digest` does not match the current source bytes.
SourceMismatch {
expected: String,
actual: String,
},
/// A Core byte span is out of range or not on a UTF-8 boundary.
SourceSpanInvalid {
detail: String,
},
/// Observation v1 is malformed, mixed, out of order or violates the
/// selected observation policy.
ObservationInvalid {
detail: String,
},
/// Observation does not bind to the current Analysis bytes/source.
ObservationStale {
detail: String,
},
/// The CLI rejected an option combination before starting (exit code 2).
CoreOptionRejected {
detail: String,
},
/// The user did not confirm, or the requested mode/grants are not allowed.
RunDenied {
detail: String,
},
/// Path escapes the allowed project root or is otherwise forbidden.
PathForbidden {
detail: String,
},
/// Refused a bind address that is not explicitly allowed.
BindDenied {
detail: String,
},
/// Embedded asset digest mismatch (build/package integrity).
AssetIntegrity {
detail: String,
},
/// Export target is unsafe or the write failed.
ExportFailed {
detail: String,
},
ExportInvalid {
detail: String,
},
ExportUnavailable {
detail: String,
},
ExportSourceChanged {
detail: String,
},
/// A configured resource limit was exceeded.
ResourceLimit {
detail: String,
},
/// Core subprocess could not be spawned.
CoreSpawn {
detail: String,
},
/// The submitted run request failed schema/target/parameter validation.
RunInvalid {
detail: String,
},
/// The entry document has no resolvable `main`; View never substitutes one.
NoEntryFunction {
detail: String,
},
/// A page/SSE/POST requires a valid local session cookie.
SessionRequired {
detail: String,
},
/// Another explicit run is already active; View allows one at a time.
RunBusy {
detail: String,
},
/// The same client request id was reused with a different payload.
RunConflict {
detail: String,
},
/// The requested run id is unknown, expired or belongs to another session.
RunNotFound {
detail: String,
},
/// Bounded capture of CLI stdout/stderr/JSON/trace exceeded the budget.
OutputLimit {
detail: String,
},
/// The CLI exited but its Observation v1 stream was missing or invalid.
CoreProtocol {
detail: String,
},
/// More than two concurrent SSE observers for one job.
SseBusy {
detail: String,
},
/// Core subprocess exceeded the View-level timeout and was killed.
CoreTimeout {
detail: String,
},
/// Local file system / HTTP I/O failure.
Io {
detail: String,
},
/// Feature intentionally not implemented in this build (honest status).
Unsupported {
detail: String,
},
}
impl ViewError {
pub fn code(&self) -> &'static str {
match self {
ViewError::CoreMissing { .. } => "view.core_missing",
ViewError::ProtocolIncompatible { .. } => "view.protocol_incompatible",
ViewError::AnalysisFailed { .. } => "view.analysis_failed",
ViewError::SourceMismatch { .. } => "view.source_mismatch",
ViewError::SourceSpanInvalid { .. } => "view.source_span_invalid",
ViewError::ObservationInvalid { .. } => "view.observation_invalid",
ViewError::ObservationStale { .. } => "view.observation_stale",
ViewError::CoreOptionRejected { .. } => "view.core_option_rejected",
ViewError::RunDenied { .. } => "view.run_denied",
ViewError::PathForbidden { .. } => "view.path_forbidden",
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",
ViewError::RunInvalid { .. } => "view.run_invalid",
ViewError::NoEntryFunction { .. } => "view.no_entry_function",
ViewError::SessionRequired { .. } => "view.session_required",
ViewError::RunBusy { .. } => "view.run_busy",
ViewError::RunConflict { .. } => "view.run_conflict",
ViewError::RunNotFound { .. } => "view.run_not_found",
ViewError::OutputLimit { .. } => "view.output_limit",
ViewError::CoreProtocol { .. } => "view.core_protocol",
ViewError::SseBusy { .. } => "view.sse_busy",
ViewError::Io { .. } => "view.io",
ViewError::Unsupported { .. } => "view.unsupported",
}
}
pub fn exit_class(&self) -> ExitClass {
match self {
ViewError::CoreMissing { .. }
| ViewError::ProtocolIncompatible { .. }
| ViewError::RunDenied { .. }
| ViewError::PathForbidden { .. }
| ViewError::BindDenied { .. }
| ViewError::SourceSpanInvalid { .. }
| ViewError::ObservationInvalid { .. }
| ViewError::CoreOptionRejected { .. }
| ViewError::Unsupported { .. }
| ViewError::RunInvalid { .. }
| ViewError::NoEntryFunction { .. }
| ViewError::SessionRequired { .. }
| ViewError::RunBusy { .. }
| ViewError::RunConflict { .. }
| ViewError::RunNotFound { .. }
| ViewError::OutputLimit { .. }
| ViewError::CoreProtocol { .. }
| ViewError::SseBusy { .. } => ExitClass::Argument,
_ => ExitClass::Runtime,
}
}
pub fn exit_code(&self) -> i32 {
match self.exit_class() {
ExitClass::Runtime => 1,
ExitClass::Argument => 2,
}
}
/// `core` is used only for diagnostics that came from the frozen CLI.
pub fn source(&self) -> &'static str {
"view"
}
/// JSON diagnostic with `source:"view"` so it can never masquerade as a
/// Core diagnostic. Contains no absolute machine paths beyond what the
/// caller already supplied.
/// Public, detail-free message for pages/JSON served to the browser. Never
/// contains absolute machine paths, scratch paths or raw subprocess text.
pub fn public_message(&self) -> &'static str {
match self.code() {
"view.core_missing" => "未找到可用的冻结核心(MARQDO_BIN)。",
"view.protocol_incompatible" => "核心或协议版本不兼容。",
"view.analysis_failed" => "Core 静态检查失败;正文仍可阅读,语义标注已撤销。",
"view.source_mismatch" => "当前源码与 Analysis 字节摘要不一致。",
"view.source_span_invalid" => "语义位置超出源码或不在 UTF-8 边界。",
"view.observation_invalid" => "运行观察事件无效或不符合当前协议,已拒绝展示。",
"view.observation_stale" => "运行结果与当前 Analysis 不匹配,已标记为过期。",
"view.core_option_rejected" => {
"冻结核心在启动前拒绝了该选项组合( exit 2 );View 不会去掉参数重试。"
}
"view.run_denied" => "运行请求未获授权或被拒绝。",
"view.path_forbidden" => "请求的路径超出允许的项目根目录。",
"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" => "冻结核心执行超时,已终止。",
"view.run_invalid" => "运行请求未通过校验(目标、参数、模式或授权不合法)。",
"view.no_entry_function" => "文档没有可调用的 main;请改选一个 H2 Exec 函数。",
"view.session_required" => "缺少或过期的本地会话;请先打开阅读页面。",
"view.run_busy" => "已有一次运行正在进行;本版本每个 View 服务只允许一个任务。",
"view.run_conflict" => "同一客户端请求 ID 携带了不同内容,拒绝执行。",
"view.run_not_found" => "运行任务不存在、已过期或不属于当前会话。",
"view.core_protocol" => "冻结核心退出但未给出合法的 Observation v1 事件流。",
"view.sse_busy" => "该运行任务的 SSE 观察连接超过上限,请稍后重试。",
"view.output_limit" => "执行输出超过 View 的接收上限,已停止接收。",
"view.io" => "本地 I/O 失败。",
"view.unsupported" => "当前版本不支持该功能。",
_ => "View 内部错误。",
}
}
/// Browser-safe JSON diagnostic: stable code + public message only.
pub fn to_public_json(&self) -> serde_json::Value {
serde_json::json!({
"schema": "marqdo.view-error",
"schema_version": 1,
"code": self.code(),
"source": "view",
"message": self.public_message(),
"exit_code": self.exit_code(),
})
}
pub fn to_json(&self) -> serde_json::Value {
serde_json::json!({
"schema": "marqdo.view-error",
"schema_version": 1,
"code": self.code(),
"source": self.source(),
"message": self.detail(),
"exit_code": self.exit_code(),
})
}
pub fn detail(&self) -> &str {
match self {
ViewError::CoreMissing { detail }
| ViewError::ProtocolIncompatible { detail }
| ViewError::AnalysisFailed { detail }
| ViewError::SourceSpanInvalid { detail }
| ViewError::ObservationInvalid { detail }
| ViewError::ObservationStale { detail }
| ViewError::CoreOptionRejected { detail }
| ViewError::RunDenied { detail }
| ViewError::PathForbidden { detail }
| 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 }
| ViewError::RunInvalid { detail }
| ViewError::NoEntryFunction { detail }
| ViewError::SessionRequired { detail }
| ViewError::RunBusy { detail }
| ViewError::RunConflict { detail }
| ViewError::RunNotFound { detail }
| ViewError::OutputLimit { detail }
| ViewError::CoreProtocol { detail }
| ViewError::SseBusy { detail }
| ViewError::Io { detail }
| ViewError::Unsupported { detail } => detail,
ViewError::SourceMismatch { expected, actual } => {
// Cannot return a formatted &str; handled in Display instead.
let _ = (expected, actual);
"source digest mismatch"
}
}
}
}
impl fmt::Display for ViewError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ViewError::SourceMismatch { expected, actual } => write!(
f,
"{}: source digest mismatch (expected {expected}, actual {actual})",
self.code()
),
other => write!(f, "{}: {}", other.code(), other.detail()),
}
}
}
impl std::error::Error for ViewError {}
impl From<std::io::Error> for ViewError {
fn from(err: std::io::Error) -> Self {
ViewError::Io {
detail: err.to_string(),
}
}
}
pub type ViewResult<T> = Result<T, ViewError>;
impl ViewError {
pub fn io(context: &str, err: std::io::Error) -> Self {
ViewError::Io {
detail: format!("{context}: {err}"),
}
}
}