commit 5cf638cc4b977b3e8e49c810955be10d0789cc62 Author: Pavel Isaev Date: Thu Nov 5 21:27:25 2026 +0300 Initialize contracts experimental implementation and documentation diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4a5d54a --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "archipelago-contracts" +version = "0.0.0" +edition = "2024" +rust-version = "1.90" +publish = false + +[dependencies] +serde_json = "1" +regex = "1" +yaml-rust2 = { version = "=0.10.4", default-features = false } +jsonschema = { version = "=0.33.0", default-features = false } diff --git a/README.md b/README.md new file mode 100644 index 0000000..ce5b62e --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +# Archipelago contracts + +Экспериментальные внутренние Rust-типы (D-062). Сериализация, схемы артефактов +и получение content-derived snapshot identity здесь ещё не реализованы. + +`layer` реализует строгий YAML/JSON parser и структурную проверку по замороженной +схеме D-070, уникальность именованных элементов, ссылки checks и action DAG. +CLI: `archipelago layer validate FILE`. Проверка не разрешает пакеты и не подтверждает +adapter compatibility, source containment, effective ownership или readiness образа. +Вход ограничен 4 MiB и вложенностью 64 — ограничения первой реализации. +Схема включается из соседнего `rfc/schemas/layer-v1.schema.json`; её исходники +должны входить в закреплённый source tree сборки CLI. + +Новые компиляции и тесты — на `terra` по D-071. Исторические результаты superserv1 +не являются проверкой текущего парсера. diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..c3891f0 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.90.0" +profile = "minimal" diff --git a/src/layer.rs b/src/layer.rs new file mode 100644 index 0000000..906190b --- /dev/null +++ b/src/layer.rs @@ -0,0 +1,139 @@ +//! Frozen Layer v1 parser and source-local validation, not package resolution. +use serde_json::{Map, Value}; +use std::{collections::{BTreeMap, BTreeSet}, str::Chars}; +use yaml_rust2::{parser::{Event, Parser}, scanner::TScalarStyle}; + +type Result = std::result::Result; +const SCHEMA: &str = include_str!("../../rfc/schemas/layer-v1.schema.json"); + +fn next(parser: &mut Parser>) -> Result { + parser.next_token().map(|(event, _)| event).map_err(|e| e.to_string()) +} + +fn scalar(text: String, style: TScalarStyle) -> Result { + if style == TScalarStyle::Plain { + match text.as_str() { + "true" => return Ok(Value::Bool(true)), + "false" => return Ok(Value::Bool(false)), + "null" => return Ok(Value::Null), + _ => {} + } + // Parse JSON numbers only. YAML-specific spellings stay strings. + static NUMBER: std::sync::LazyLock = std::sync::LazyLock::new(|| + regex::Regex::new(r"\A-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?\z").unwrap()); + if NUMBER.is_match(&text) { + if text.contains(['.', 'e', 'E']) { return Err("Floats are forbidden".into()); } + let integer: i64 = text.parse().map_err(|_| "Integer outside interoperable JSON range")?; + if !(-9007199254740991..=9007199254740991).contains(&integer) { + return Err("Integer outside interoperable JSON range".into()); + } + return Ok(Value::from(integer)); + } + } + Ok(Value::String(text)) +} + +fn node(parser: &mut Parser>, event: Event, depth: usize) -> Result { + if depth > 64 { return Err("Manifest nesting exceeds implementation limit (64)".into()); } + match event { + Event::Scalar(text, style, 0, None) => scalar(text, style), + Event::SequenceStart(0, None) => { + let mut items = Vec::new(); + loop { + let event = next(parser)?; + if event == Event::SequenceEnd { break; } + items.push(node(parser, event, depth + 1)?); + } + Ok(Value::Array(items)) + } + Event::MappingStart(0, None) => { + let mut items = Map::new(); + loop { + let event = next(parser)?; + if event == Event::MappingEnd { break; } + let key = node(parser, event, depth + 1)?; + let key = key.as_str().ok_or("Mapping keys must be strings")?; + if key == "<<" || items.contains_key(key) { return Err(format!("Merge or duplicate key: {key}")); } + let event = next(parser)?; + items.insert(key.into(), node(parser, event, depth + 1)?); + } + Ok(Value::Object(items)) + } + _ => Err("Anchors, aliases, tags or unexpected YAML event".into()), + } +} + +pub fn parse(text: &str) -> Result { + if text.len() > 4 * 1024 * 1024 { return Err("Manifest exceeds implementation limit (4 MiB)".into()); } + let mut parser = Parser::new_from_str(text); + if next(&mut parser)? != Event::StreamStart || next(&mut parser)? != Event::DocumentStart { + return Err("Exactly one nonempty YAML/JSON document is required".into()); + } + let first = next(&mut parser)?; + let value = node(&mut parser, first, 0)?; + if next(&mut parser)? != Event::DocumentEnd || next(&mut parser)? != Event::StreamEnd { + return Err("Exactly one document is required".into()); + } + Ok(value) +} + +fn entries(value: &Value) -> &[Value] { + value.as_array().map(Vec::as_slice).unwrap_or(&[]) +} + +pub fn validate(text: &str) -> Result { + let data = parse(text)?; + let schema: Value = serde_json::from_str(SCHEMA).map_err(|e| e.to_string())?; + let validator = jsonschema::validator_for(&schema).map_err(|e| e.to_string())?; + validator.validate(&data).map_err(|e| format!("{}: {e}", e.instance_path))?; + let spec = &data["spec"]; + for (list, key) in [(&spec["packages"]["runtime"], "name"), (&spec["packages"]["build"], "name"), + (&spec["actions"], "id"), (&spec["runtime"]["units"], "name"), (&spec["files"], "path")] { + let mut seen = BTreeSet::new(); + for item in entries(list) { + if !seen.insert(item[key].as_str().unwrap()) { return Err(format!("Duplicate {key}: {}", item[key])); } + } + } + let actions: BTreeMap<_, _> = entries(&spec["actions"]).iter().map(|a| (a["id"].as_str().unwrap(), a)).collect(); + for field in ["boot_checks", "functional_checks"] { + for name in entries(&spec["runtime"][field]) { + if !actions.contains_key(name.as_str().unwrap()) { return Err(format!("Missing check action: {name}")); } + } + } + // Iterative topological validation avoids recursion on authored action graphs. + let mut completed = BTreeSet::new(); + while completed.len() < actions.len() { + let previous = completed.len(); + for (name, action) in &actions { + for predecessor in entries(&action["after"]) { + actions.get(predecessor.as_str().unwrap()).ok_or("Missing predecessor action")?; + } + if entries(&action["after"]).iter().all(|v| completed.contains(v.as_str().unwrap())) { + completed.insert(*name); + } + } + if completed.len() == previous { return Err("Action cycle".into()); } + } + Ok(data) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strict_scalar_and_mapping_contract() { + for text in ["a: 1\na: 2", "a: &a x\nb: *a", "a: !!str x", "a: x\n---\nb: y", + "a: 1.5", "a: 1e99999", "a: 9007199254740992", "a: 999999999999999999999999999", + "a: -9007199254740992", "<<: {}", "true: x", "[a, b]: x", ""] { + assert!(parse(text).is_err(), "accepted {text:?}"); + } + let value = parse("yes: yes\nno: no\na: 0755\nb: 'true'\nc: true\nd: 9007199254740991").unwrap(); + assert_eq!(value["yes"], "yes"); + assert_eq!(value["no"], "no"); + assert_eq!(value["a"], "0755"); + assert_eq!(value["b"], "true"); + assert_eq!(value["c"], true); + assert_eq!(value["d"], 9007199254740991_i64); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..6debaa3 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,19 @@ +//! Experimental internal types, not a serialized manifest or lockfile schema. +//! Identity strings must come from a verified artifact adapter; this module does +//! not derive snapshot identities or authenticate artifact metadata. + +pub mod layer; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LayerKind { + Core, + Purpose, + Overlay, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LayerInput { + pub kind: LayerKind, + pub snapshot_id: String, + pub architecture: String, +}