xirang_kernel/registry_core/plugin/contracts/contracts.rs
1//! Flow contracts and plugin records carried by registration declarations.
2//! 注册声明携带的数据流合同与插件记录。
3//!
4//! These are pure protocol nouns. They live in the plugin module because that
5//! is what they describe; `declaration` re-exports them so a declaration can
6//! keep naming them without a second copy in the tree.
7//! 这些是纯协议名词。它们住在 plugin 模块,因为描述的正是插件;`declaration`
8//! 再导出它们,让声明继续以原名引用,而不在树里出现第二份副本。
9
10#[path = "signing.rs"]
11mod signing;
12
13use std::fmt;
14
15/// A stable host identity. Package names are not enough when several
16/// frameworks share one process.
17/// 稳定的宿主身份。同一进程存在多个框架时,crate 名称并不足以区分目标。
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
19pub struct FrameworkId(pub &'static str);
20
21impl FrameworkId {
22 /// Wrap a host identity; the text is used verbatim for equality and display.
23 /// 包装宿主身份;该文本原样用于相等比较与展示。
24 pub const fn new(value: &'static str) -> Self {
25 Self(value)
26 }
27}
28
29impl fmt::Display for FrameworkId {
30 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31 formatter.write_str(self.0)
32 }
33}
34
35/// A logical replacement slot. Concrete implementations keep their own node identity;
36/// the slot is the stable name that a graft targets.
37/// 逻辑替换插槽。具体实现保留各自 node identity;嫁接针对的是稳定插槽名。
38///
39/// "Slot" is the alias the vocabulary lists for a node's `registry_name`
40/// (`kernel/src/registry_core/lexicon/lexicon.rs`, audit `KRN-C-11`): what a graft cut addresses
41/// is the last component of a node's path, and that component is written `registry_name`
42/// wherever it is recorded.
43/// 这里的"插槽"是词表为节点的 `registry_name` 列出的别名
44/// (`kernel/src/registry_core/lexicon/lexicon.rs`,审计 `KRN-C-11`):graft 切口寻址的是节点路径
45/// 的最后一段,而那段在落盘处一律写作 `registry_name`。
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47pub struct ContractId(pub &'static str);
48
49impl ContractId {
50 /// The undeclared slot id, spelled as the empty string.
51 /// 未声明的插槽 id,即空字符串。
52 pub const NONE: Self = Self("");
53
54 /// Wrap a slot name; an empty string means no slot was declared.
55 /// 包装插槽名;空字符串表示没有声明插槽。
56 pub const fn new(value: &'static str) -> Self {
57 Self(value)
58 }
59}
60
61impl fmt::Display for ContractId {
62 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63 formatter.write_str(self.0)
64 }
65}
66
67/// The mechanically comparable part of a data-flow contract.
68/// 数据流合同中可以机械比较的部分。
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub struct FlowContract {
71 /// Slot this contract describes.
72 /// 本合同描述的插槽。
73 pub id: ContractId,
74 /// Contract version; it must match exactly for either comparison to pass.
75 /// 合同版本;两种比较都要求它完全一致。
76 pub version: u32,
77 /// Declared type label of the contract input.
78 /// 合同输入端声明的类型标签。
79 pub input: &'static str,
80 /// Declared type label of the contract output.
81 /// 合同输出端声明的类型标签。
82 pub output: &'static str,
83}
84
85/// Owned flow contract used by file-backed snapshots.
86/// 文件快照使用的拥有型数据流合同。
87///
88/// Compiled declarations keep static strings. Reloaded source owns its
89/// strings, so replacing a file does not leak old contracts.
90/// 编译期声明继续使用静态字符串;热重载源码拥有自己的字符串,替换文件时不会泄漏旧合同。
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub struct OwnedFlowContract {
93 /// Target slot; the owned snapshot's twin of `FlowContract::id`.
94 /// 目标插槽;owned 快照中对应 `FlowContract::id` 的一侧。
95 pub id: String,
96 /// Contract version; the owned twin of `FlowContract::version`.
97 /// 合同版本;`FlowContract::version` 的 owned 孪生。
98 pub version: u32,
99 /// Declared input label; the owned twin of `FlowContract::input`.
100 /// 声明的输入标签;`FlowContract::input` 的 owned 孪生。
101 pub input: String,
102 /// Declared output label; the owned twin of `FlowContract::output`.
103 /// 声明的输出标签;`FlowContract::output` 的 owned 孪生。
104 pub output: String,
105}
106
107impl OwnedFlowContract {
108 /// The undeclared owned contract: empty strings and version zero.
109 /// 未声明的 owned 合同:字符串为空、版本为 0。
110 pub fn none() -> Self {
111 Self {
112 id: String::new(),
113 version: 0,
114 input: String::new(),
115 output: String::new(),
116 }
117 }
118
119 /// Whether this owned contract carries a slot id.
120 /// 本 owned 合同是否带有插槽 id。
121 pub fn is_declared(&self) -> bool {
122 flow_is_declared(&self.id)
123 }
124
125 /// Whether the two owned contracts agree literally or after known domains compare.
126 /// 两份 owned 合同是字面一致,还是在已知语义域比较后相容。
127 pub fn semantically_compatible_with(&self, expected: &Self) -> bool {
128 let left = FlowFields::from_owned(self);
129 let right = FlowFields::from_owned(expected);
130 flow_fields_equal(left, right) || flow_fields_semantically_compatible(left, right)
131 }
132}
133
134impl From<FlowContract> for OwnedFlowContract {
135 fn from(contract: FlowContract) -> Self {
136 Self {
137 id: contract.id.0.to_owned(),
138 version: contract.version,
139 input: contract.input.to_owned(),
140 output: contract.output.to_owned(),
141 }
142 }
143}
144
145impl fmt::Display for OwnedFlowContract {
146 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
147 write!(
148 formatter,
149 "{} v{} ({} -> {})",
150 self.id, self.version, self.input, self.output
151 )
152 }
153}
154
155/// Normalized semantic labels used by tooling when string contracts are too
156/// coarse to explain a mismatch (for example local vs absolute coordinates).
157/// 调试工具使用的规范化语义标签,避免仅凭字符串无法解释坐标域差异。
158#[derive(Clone, Copy, Debug, PartialEq, Eq)]
159pub enum FlowSemantic {
160 /// Label no table entry knows; only literal equality is meaningful.
161 /// 语义表不认识的标签;只有字面相等才有意义。
162 Unknown,
163 /// Coordinates relative to the parent node.
164 /// 相对于父节点的坐标。
165 LocalCoordinates,
166 /// Coordinates in the host's absolute space.
167 /// 宿主绝对空间中的坐标。
168 AbsoluteCoordinates,
169 /// Device-independent pixel units.
170 /// 设备无关的像素单位。
171 LogicalPixels,
172 /// Device pixel units.
173 /// 设备像素单位。
174 PhysicalPixels,
175}
176
177impl FlowContract {
178 /// The undeclared static contract: empty id, version 0, empty labels.
179 /// 未声明的编译期合同:id 为空、版本为 0、标签为空。
180 pub const NONE: Self = Self {
181 id: ContractId::NONE,
182 version: 0,
183 input: "",
184 output: "",
185 };
186
187 /// Build a declared contract from its slot, version, and two type labels.
188 /// 由插槽、版本与两个类型标签构造一份已声明合同。
189 pub const fn new(
190 id: ContractId,
191 version: u32,
192 input: &'static str,
193 output: &'static str,
194 ) -> Self {
195 Self {
196 id,
197 version,
198 input,
199 output,
200 }
201 }
202
203 /// Whether a slot id was declared; the compiled twin of the owned check.
204 /// 是否声明了插槽 id;owned 检查的编译期孪生。
205 pub const fn is_declared(self) -> bool {
206 flow_is_declared(self.id.0)
207 }
208
209 /// Whether the two contracts are literally the same wire contract.
210 /// 两份合同字面上是否是同一个线上合同。
211 ///
212 /// This is the literal half of the comparison pair. Spelling differences in
213 /// known semantic domains are handled by
214 /// [`FlowContract::semantically_compatible_with`], not here, so a caller
215 /// that means "same domain" must call that method.
216 /// 这是比较对中的字面一半。已知语义域里的拼写差异由
217 /// [`FlowContract::semantically_compatible_with`] 处理,不在本方法;因此想要
218 /// "同一语义域"的调用方必须调用那个方法。
219 pub fn compatible_with(self, expected: Self) -> bool {
220 flow_fields_equal(
221 FlowFields::from_declared(self),
222 FlowFields::from_declared(expected),
223 )
224 }
225
226 /// Normalized semantic domain of the declared input label.
227 /// 声明的输入标签所归入的语义域。
228 pub fn input_semantic(self) -> FlowSemantic {
229 flow_semantic(self.input)
230 }
231
232 /// Normalized semantic domain of the declared output label.
233 /// 声明的输出标签所归入的语义域。
234 pub fn output_semantic(self) -> FlowSemantic {
235 flow_semantic(self.output)
236 }
237
238 /// Compare both the wire type and its known semantic domain.
239 /// 同时比较线上的类型名称和已知语义域。
240 pub fn semantically_compatible_with(self, expected: Self) -> bool {
241 let left = FlowFields::from_declared(self);
242 let right = FlowFields::from_declared(expected);
243 flow_fields_equal(left, right) || flow_fields_semantically_compatible(left, right)
244 }
245}
246
247/// The four fields every flow comparison reads, borrowed from either twin.
248/// 每次 flow 比较都会读取的四个字段,从任一孪生借用而来。
249///
250/// `FlowContract` and `OwnedFlowContract` used to compare these fields in two
251/// separate bodies, so the two *pairs* of entry points could drift apart on, say,
252/// whether the version participates. Borrowing the fields once keeps each pair on
253/// one comparison: the literal pair is `FlowContract::compatible_with` and
254/// `OwnedFlowContract`'s `PartialEq`, and the semantic pair is both
255/// `semantically_compatible_with` methods. `compatible_with` deliberately stays
256/// literal-only — it is not the compiled spelling of the semantic entry point —
257/// and `static_and_owned_flow_contracts_compare_identically` pins each pairing
258/// separately so the distinction cannot hide behind the other.
259/// `FlowContract` 与 `OwnedFlowContract` 过去在两个各自的方法体里比较这些字段,因此
260/// 两*对*入口可能在"版本号是否参与比较"这类点上悄悄分叉。只借用一次字段,每一对就共用
261/// 一套比较:字面对是 `FlowContract::compatible_with` 与 `OwnedFlowContract` 的
262/// `PartialEq`,语义对是两个 `semantically_compatible_with`。`compatible_with` 有意
263/// 只做字面比较——它不是语义入口的编译期写法——而
264/// `static_and_owned_flow_contracts_compare_identically` 分别钉住两对,使这一区分无法
265/// 借另一对藏起来。
266#[derive(Clone, Copy)]
267struct FlowFields<'a> {
268 id: &'a str,
269 version: u32,
270 input: &'a str,
271 output: &'a str,
272}
273
274impl<'a> FlowFields<'a> {
275 fn from_declared(contract: FlowContract) -> Self {
276 Self {
277 id: contract.id.0,
278 version: contract.version,
279 input: contract.input,
280 output: contract.output,
281 }
282 }
283
284 fn from_owned(contract: &'a OwnedFlowContract) -> Self {
285 Self {
286 id: &contract.id,
287 version: contract.version,
288 input: &contract.input,
289 output: &contract.output,
290 }
291 }
292}
293
294/// Whether a flow identity was declared at all.
295/// 是否声明了数据流身份。
296///
297/// `FlowContract` compares its `ContractId` newtype while `OwnedFlowContract`
298/// compares an owned `String`, so "is this contract declared?" was spelled
299/// `!self.id.0.is_empty()` in one place and `!self.id.is_empty()` in another.
300/// Both ask the same question about the same text; one const function answers it
301/// and keeps the compiled twin usable in a const context.
302/// `static_and_owned_flow_contracts_compare_identically` pins the two answers.
303/// `FlowContract` 比较的是 `ContractId` newtype,`OwnedFlowContract` 比较的是自有
304/// `String`,因此"该合同是否已声明"一处写成 `!self.id.0.is_empty()`,另一处写成
305/// `!self.id.is_empty()`。两者问的是同一段文本的同一个问题;用一个 const 函数回答,
306/// 编译期孪生也仍可用于 const 环境。
307/// `static_and_owned_flow_contracts_compare_identically` 把两个答案互钉。
308const fn flow_is_declared(id: &str) -> bool {
309 !id.is_empty()
310}
311
312/// Whether two flow field sets are literally the same contract.
313/// 两组 flow 字段是否字面上就是同一份合同。
314fn flow_fields_equal(left: FlowFields<'_>, right: FlowFields<'_>) -> bool {
315 left.id == right.id
316 && left.version == right.version
317 && left.input == right.input
318 && left.output == right.output
319}
320
321/// Whether two flow field sets still agree after known semantic domains compare.
322/// 已知语义域参与比较后,两组 flow 字段是否仍然相容。
323///
324/// The identity and version must match exactly; only the two labels are allowed
325/// to be respelled through [`labels_compatible`], which is the semantic-label
326/// core shared here. The compiled twin reaches this through
327/// `semantically_compatible_with` — *not* through the literal-only
328/// `compatible_with` — while the owned twin used to repeat the whole conjunction
329/// inline, so a fourth term could be added to one and not the other.
330/// 身份与版本必须完全一致;只有两个标签允许经 [`labels_compatible`](此处的语义标签
331/// 核)换一种拼写。编译期孪生经 `semantically_compatible_with`——而**不是**只做字面
332/// 比较的 `compatible_with`——走到这里,而 owned 孪生过去把整个合取式内联重写了一遍,
333/// 因此某一侧多出一个条件时另一侧不会跟着变。
334fn flow_fields_semantically_compatible(left: FlowFields<'_>, right: FlowFields<'_>) -> bool {
335 left.id == right.id
336 && left.version == right.version
337 && labels_compatible(left.input, right.input)
338 && labels_compatible(left.output, right.output)
339}
340
341/// Whether two declared type labels may stand for the same domain.
342/// 两个声明的类型标签是否可能指同一个语义域。
343///
344/// A label the table below does not know carries no domain information, so it
345/// can only agree with itself, literally. Treating two *different* unknown
346/// labels as compatible is exactly what let a type-incompatible replacement
347/// occupy a slot while every check reported success.
348/// 下表不认识的标签不携带任何语义域信息,因此只能与自身字面相等才算一致。把两个
349/// *不同*的未知标签当作兼容,正是类型不兼容的替换件得以占位、而所有检查都报成功的
350/// 原因。
351fn labels_compatible(left: &str, right: &str) -> bool {
352 match (flow_semantic(left), flow_semantic(right)) {
353 (FlowSemantic::Unknown, FlowSemantic::Unknown) => left == right,
354 (FlowSemantic::Unknown, _) | (_, FlowSemantic::Unknown) => false,
355 (left, right) => left == right,
356 }
357}
358
359fn flow_semantic(value: &str) -> FlowSemantic {
360 if value == "LocalCoordinates" || value == "local_coordinates" {
361 FlowSemantic::LocalCoordinates
362 } else if value == "AbsoluteCoordinates" || value == "absolute_coordinates" {
363 FlowSemantic::AbsoluteCoordinates
364 } else if value == "LogicalPixels" || value == "logical_pixels" {
365 FlowSemantic::LogicalPixels
366 } else if value == "PhysicalPixels" || value == "physical_pixels" {
367 FlowSemantic::PhysicalPixels
368 } else {
369 FlowSemantic::Unknown
370 }
371}
372
373/// A handle can expose its data-flow contract once; registration faces then
374/// read it without repeating input/output strings.
375/// handle 只需声明一次数据流合同;注册面直接读取,不重复填写输入输出字符串。
376pub trait FlowContractProvider {
377 /// The one contract this face declares, exposed as a compile-time constant.
378 /// 本面声明的那一份合同,以编译期常量形式暴露。
379 const FLOW_CONTRACT: FlowContract;
380}
381
382/// Whether a plugin adds a new capability or replaces an existing slot.
383/// 插件是增加能力还是替换已有插槽。
384#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
385pub enum PluginMode {
386 /// Adds a new face without removing any existing one.
387 /// 增加新面,不移除任何已有面。
388 Extension,
389 /// Takes over the slot occupied by an existing face.
390 /// 接管已有面所占的插槽。
391 Replacement,
392}
393
394/// Where the plugin came from. Trust policy is deliberately separate from
395/// registration structure and flow compatibility.
396/// 插件来源。信任策略与注册结构、数据流兼容性刻意分离。
397#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
398pub enum PluginSource {
399 /// Published and signed by the official distribution.
400 /// 由官方分发渠道发布并签名。
401 Official,
402 /// Supplied by a user or a third party.
403 /// 由用户或第三方提供。
404 User,
405}
406
407impl PluginSource {
408 /// The word a lock line spells for this source.
409 /// 锁记录为这个来源拼写的词。
410 ///
411 /// This is the one place the spelling lives: the parser below reads it back instead of
412 /// repeating it, so a lock line this kernel writes can never use a word this kernel would not
413 /// accept.
414 /// 这是该词形唯一的所在地:下面的解析器把它读回来,而不是再写一遍,因此内核写出的锁记录
415 /// 不可能用一个内核自己不接受的词。
416 pub fn text(self) -> &'static str {
417 match self {
418 Self::Official => "official",
419 Self::User => "user",
420 }
421 }
422
423 #[doc(hidden)]
424 pub fn parse_plugin_source(value: &str) -> Option<Self> {
425 [Self::Official, Self::User]
426 .into_iter()
427 .find(|source| source.text() == value)
428 }
429}
430
431impl PluginMode {
432 /// The word a lock line spells for this mode; see [`PluginSource::text`].
433 /// 锁记录为这个模式拼写的词;见 [`PluginSource::text`]。
434 pub fn text(self) -> &'static str {
435 match self {
436 Self::Extension => "extension",
437 Self::Replacement => "replacement",
438 }
439 }
440
441 #[doc(hidden)]
442 pub fn parse_plugin_mode(value: &str) -> Option<Self> {
443 [Self::Extension, Self::Replacement]
444 .into_iter()
445 .find(|mode| mode.text() == value)
446 }
447}
448
449/// Plugin manifest metadata.
450/// 插件 manifest 元数据。
451#[derive(Clone, Copy, Debug, PartialEq, Eq)]
452pub struct PluginManifest {
453 /// Manifest name; trust and lock checks match on this package identity.
454 /// manifest 名称;信任与锁检查以它作为包身份匹配。
455 pub name: &'static str,
456 /// Rust crate that carries the plugin implementation.
457 /// 承载插件实现的 Rust crate。
458 pub crate_name: &'static str,
459 /// Declared plugin version.
460 /// 声明的插件版本。
461 pub version: &'static str,
462 /// Host framework the plugin targets.
463 /// 插件针对的宿主框架。
464 pub framework: FrameworkId,
465 /// Trust lane the plugin came from.
466 /// 插件的来源信任通道。
467 pub source: PluginSource,
468 /// Whether the plugin extends or replaces a slot.
469 /// 插件是扩展还是替换插槽。
470 pub mode: PluginMode,
471 /// Digest of the plugin bytes, optionally carrying a `sha256:` prefix.
472 /// 插件字节的摘要,可带 `sha256:` 前缀。
473 pub checksum: &'static str,
474 /// Hex-encoded Ed25519 signature over `signing_payload`, when supplied.
475 /// `signing_payload` 上的十六进制 Ed25519 签名;插件没有签名时为 None。
476 pub signature: Option<&'static str>,
477 /// Fingerprint of the public key used for the signature.
478 /// 用于签名的公钥指纹。
479 pub public_key_fingerprint: Option<&'static str>,
480 /// Identifier of the revocation-list snapshot used by the publisher.
481 /// 发布者使用的撤销列表快照标识。
482 pub revocation_list: Option<&'static str>,
483}
484
485impl PluginManifest {
486 /// Whether the manifest names exactly this framework.
487 /// manifest 指明的框架是否就是这一个。
488 pub fn targets_framework(self, framework: FrameworkId) -> bool {
489 self.framework.0 == framework.0
490 }
491
492 /// The historical name of [`Self::targets_framework`], kept for hosts that already
493 /// call it (`NAM-35`). Prefer `targets_framework`.
494 /// [`Self::targets_framework`] 的历史名字,为已经在调它的宿主保留(`NAM-35`)。
495 /// 请优先用 `targets_framework`。
496 pub fn targets(self, framework: FrameworkId) -> bool {
497 self.targets_framework(framework)
498 }
499
500 /// Verify the manifest digest against plugin bytes before native loading.
501 /// 在 native 加载前,用插件字节验证 manifest 摘要。
502 pub fn verify_bytes(self, bytes: &[u8]) -> bool {
503 let expected = self
504 .checksum
505 .strip_prefix("sha256:")
506 .unwrap_or(self.checksum);
507 expected.len() == 64 && crate::sha256_hex(bytes).eq_ignore_ascii_case(expected)
508 }
509
510 /// Build the canonical bytes covered by an official plugin signature.
511 /// 构造官方插件签名覆盖的规范化字节。
512 ///
513 /// The payload covers the manifest's own fields, the plugin bytes, **and**
514 /// every field of the `registration` those bytes are claimed to produce. A
515 /// signature over only the first two left the registration unauthenticated:
516 /// a tampered `parent` or `flow` still verified as `Signature` and could
517 /// pass a slot contract check the honest artifact failed. The manifest's
518 /// `signature` field is excluded, because a signature cannot cover the bytes
519 /// that carry it.
520 /// 载荷覆盖 manifest 自身字段、插件字节,**以及**这些字节声称产出的 `registration` 的每个
521 /// 字段。只覆盖前两者的签名让注册声明完全未被认证:被篡改的 `parent` 或 `flow` 仍会验证为
522 /// `Signature`,甚至能通过诚实工件通不过的槽位合同检查。manifest 的 `signature` 字段被排除,
523 /// 因为签名无法覆盖承载它的那段字节。
524 pub fn signing_payload(self, registration: &crate::RegistrationInfo, bytes: &[u8]) -> Vec<u8> {
525 let mut payload = Vec::with_capacity(bytes.len() + 512);
526 signing::manifest(&mut payload, self);
527 signing::registration(registration, &mut payload);
528 payload.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
529 payload.extend_from_slice(bytes);
530 payload
531 }
532}
533
534#[cfg(test)]
535#[path = "contracts_tests.rs"]
536mod contracts_tests;