thing-contract: each field's type owns its domain (Seq, Version, Count, Segment), injective record keys, domain refusal cases, per-field privacy doctests

Seq, Version, Count and Segment check their domain in new, and their Deserialize calls new, so the constructors and every decode door hold one rule. Record keys take Segment so they split at the last dot; the asset key prefix is thing:asset_catalog:. result-missing-slot is dropped (CultLib's rule). Goldens are re-blessed in the next commit; this commit's goldens_match fails until then.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-12 07:21:52 +02:00
commit f2ab72d84d
13 changed files with 629 additions and 124 deletions

View file

@ -2,6 +2,7 @@
use cultcache_rs::{CultSlots, DatabaseEntry};
use crate::domain::{Count, Segment, Version};
use crate::keys::{ProviderId, asset_catalog_key};
#[derive(Clone, Debug, PartialEq, CultSlots)]
@ -13,9 +14,9 @@ pub struct AssetEntry {
#[cultcache(key = 2)]
pub uri: String,
#[cultcache(key = 3)]
pub width: i32,
pub width: Count,
#[cultcache(key = 4)]
pub height: i32,
pub height: Count,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
@ -24,9 +25,9 @@ pub struct AssetCatalog {
#[cultcache(key = 0)]
pub provider_id: ProviderId,
#[cultcache(key = 1)]
pub catalog_id: String,
pub catalog_id: Segment,
#[cultcache(key = 2)]
pub version: i64,
pub version: Version,
#[cultcache(key = 3)]
pub assets: Vec<AssetEntry>,
}

View file

@ -3,6 +3,7 @@
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
use crate::domain::Version;
use crate::keys::{CommandId, NodeId, SchemaId, invocation_key};
use crate::source::ParamName;
@ -87,7 +88,9 @@ pub struct CapturedInput {
pub value: InputValue,
}
/// A consumer's request that a provider run a declared command.
/// A consumer's request that a provider run a declared command. Its fields are public, so a
/// result's copy of `invocation_id` is a convenience and not provenance: core binds results
/// to the invocations it issued.
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.thing.command_invocation", schema = "gamecult.thing.command_invocation.v1")]
pub struct CommandInvocation {
@ -97,7 +100,7 @@ pub struct CommandInvocation {
#[cultcache(key = 1)]
pub surface_key: String,
#[cultcache(key = 2)]
pub surface_version: i64,
pub surface_version: Version,
#[cultcache(key = 3)]
pub command: CommandId,
#[cultcache(key = 4)]

View file

@ -0,0 +1,216 @@
//! The value domains of the contract's numbers and local names. Each domain is one field
//! type, and `new` is its only door: constructors, struct literals and every serde
//! `Deserializer` reach a value through it, so a value out of domain cannot exist.
//!
//! Each type writes and reads exactly the leaf of its inner type (`Int32`, `Int64`,
//! `String`), so the bytes are the plain leaf's. The reference's unsigned leaves are absent
//! from the TypeScript and Python packages, which is why the bound is a checked type here
//! and a refusal golden there.
use std::fmt;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
/// A value was outside its domain. Names the domain and its bound, never the value.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DomainError {
domain: &'static str,
bound: &'static str,
}
impl DomainError {
const fn new(domain: &'static str, bound: &'static str) -> Self {
Self { domain, bound }
}
/// The type that refused.
pub fn domain(&self) -> &'static str {
self.domain
}
/// The bound that was not met.
pub fn bound(&self) -> &'static str {
self.bound
}
}
impl fmt::Display for DomainError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} must be {}", self.domain, self.bound)
}
}
impl std::error::Error for DomainError {}
/// A result's position in its invocation's answers, counting from 1. `new` is the only door:
///
/// ```
/// use thing_contract::Seq;
/// assert!(Seq::new(1).is_ok());
/// ```
///
/// ```compile_fail,E0423
/// use thing_contract::Seq;
/// let _ = Seq(0);
/// ```
///
/// ```compile_fail,E0616
/// use thing_contract::Seq;
/// let mut seq = Seq::FIRST;
/// seq.0 = 0;
/// ```
///
/// ```compile_fail,E0599
/// use thing_contract::Seq;
/// let _ = Seq::default();
/// ```
///
/// ```compile_fail,E0277
/// use thing_contract::Seq;
/// let _ = Seq::from(0);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Seq(i32);
impl Seq {
pub const FIRST: Seq = Seq(1);
pub fn new(value: i32) -> Result<Self, DomainError> {
if value >= 1 { Ok(Self(value)) } else { Err(DomainError::new("Seq", "at least 1")) }
}
pub fn get(self) -> i32 {
self.0
}
/// The following position; stays at `i32::MAX` rather than leaving the domain.
pub fn next(self) -> Seq {
Seq(self.0.saturating_add(1))
}
}
/// A document or source version, never negative. `new` is the only door:
///
/// ```
/// use thing_contract::Version;
/// assert!(Version::new(0).is_ok());
/// ```
///
/// ```compile_fail,E0423
/// use thing_contract::Version;
/// let _ = Version(-1);
/// ```
///
/// ```compile_fail,E0599
/// use thing_contract::Version;
/// let _ = Version::default();
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Version(i64);
impl Version {
pub fn new(value: i64) -> Result<Self, DomainError> {
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) }
}
pub fn get(self) -> i64 {
self.0
}
}
/// A count, an extent or an index, never negative. `new` is the only door:
///
/// ```
/// use thing_contract::Count;
/// assert!(Count::new(0).is_ok());
/// ```
///
/// ```compile_fail,E0423
/// use thing_contract::Count;
/// let _ = Count(-1);
/// ```
///
/// ```compile_fail,E0277
/// use thing_contract::Count;
/// let _: Count = (-1).into();
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Count(i32);
impl Count {
pub fn new(value: i32) -> Result<Self, DomainError> {
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Count", "at least 0")) }
}
pub fn get(self) -> i32 {
self.0
}
}
/// A name the contract joins into a record key: non-empty, no `.`. `new` is the only door:
///
/// ```
/// use thing_contract::Segment;
/// assert!(Segment::new("main").is_ok());
/// ```
///
/// ```compile_fail,E0423
/// use thing_contract::Segment;
/// let _ = Segment(String::from("a.b"));
/// ```
///
/// ```compile_fail,E0277
/// use thing_contract::Segment;
/// let _: Segment = "a.b".into();
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Segment(String);
impl Segment {
pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
let value = value.into();
if value.is_empty() {
Err(DomainError::new("Segment", "non-empty"))
} else if value.contains('.') {
Err(DomainError::new("Segment", "free of '.'"))
} else {
Ok(Self(value))
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
macro_rules! leaf_serde {
($name:ident, $inner:ty, $serialize:ident) => {
impl Serialize for $name {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.$serialize(self.0)
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::new(<$inner>::deserialize(deserializer)?).map_err(de::Error::custom)
}
}
};
}
leaf_serde!(Seq, i32, serialize_i32);
leaf_serde!(Version, i64, serialize_i64);
leaf_serde!(Count, i32, serialize_i32);
impl Serialize for Segment {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for Segment {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::new(String::deserialize(deserializer)?).map_err(de::Error::custom)
}
}

View file

@ -2,6 +2,8 @@
use serde::{Deserialize, Serialize};
use crate::domain::{Segment, Seq, Version};
macro_rules! id_type {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
@ -42,22 +44,27 @@ id_type!(
CommandId
);
pub(crate) fn surface_key(provider: &ProviderId, label: &str) -> String {
format!("thing:surface:{}.{}", provider.as_str(), label)
// Each key joins free-string provider or publisher ids (dotted, as the Verse names them)
// with typed trailing parts: a `Segment` holds no dot and a `Seq` or `Version` is digits. A
// key therefore splits at its last dot (surface, asset catalog, result) or last two
// (composition), so two different field sets never build one key.
pub(crate) fn surface_key(provider: &ProviderId, label: &Segment) -> String {
format!("thing:surface:{}.{}", provider.as_str(), label.as_str())
}
pub(crate) fn composition_key(publisher: &str, name: &str, version: i32) -> String {
format!("thing:composition:{publisher}.{name}.v{version}")
pub(crate) fn composition_key(publisher: &str, name: &Segment, version: Version) -> String {
format!("thing:composition:{publisher}.{}.v{}", name.as_str(), version.get())
}
pub(crate) fn invocation_key(invocation_id: &str) -> String {
format!("thing:invocation:{invocation_id}")
}
pub(crate) fn result_key(invocation_id: &str, seq: i32) -> String {
format!("thing:result:{invocation_id}.{seq}")
pub(crate) fn result_key(invocation_id: &str, seq: Seq) -> String {
format!("thing:result:{invocation_id}.{}", seq.get())
}
pub(crate) fn asset_catalog_key(provider: &ProviderId, catalog_id: &str) -> String {
format!("thing:assets:{}.{}", provider.as_str(), catalog_id)
pub(crate) fn asset_catalog_key(provider: &ProviderId, catalog_id: &Segment) -> String {
format!("thing:asset_catalog:{}.{}", provider.as_str(), catalog_id.as_str())
}

View file

@ -3,9 +3,20 @@
//!
//! Every kind is a CultCache `DatabaseEntry`; every closed set is a `CultUnion` written
//! `[armKey, [slots...]]`, the shape the C# reference reads and writes.
//!
//! Decoding is a door as well as the constructors: every kind keeps its public serde
//! `Deserialize` (CultCache's `DatabaseEntry` requires it). The domains therefore live in the
//! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same
//! `new` the constructors call, so no door skips a check.
//!
//! Hazard: decoding these kinds from untrusted bytes on a default-size thread can abort the
//! process inside CultCache's nesting bound before the bound refuses (the stack is not
//! bounded by nesting depth). The owner is `cultlib-gaps:follow_up:decode-stack-safety`; the
//! tests decode on a 16 MiB thread until it lands.
mod asset;
mod command;
mod domain;
mod keys;
mod node;
mod result;
@ -14,6 +25,7 @@ mod style;
pub use asset::*;
pub use command::*;
pub use domain::{Count, DomainError, Segment, Seq, Version};
pub use keys::{CommandId, NodeId, ProviderId, RecordKey, SchemaId};
pub use node::*;
pub use result::*;

View file

@ -3,6 +3,7 @@
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
use crate::domain::{Count, Segment, Version};
use crate::command::{CommandDecl, CommandRef};
use crate::keys::{NodeId, ProviderId, composition_key, surface_key};
use crate::source::{Bind, BoolSource, CollectionSource, MemberPath, NumberSource, TextSource};
@ -74,7 +75,7 @@ pub struct TextNode {
#[cultcache(key = 3)]
pub wrap: bool,
#[cultcache(key = 4)]
pub max_lines: Option<i32>,
pub max_lines: Option<Count>,
#[cultcache(key = 5)]
pub selectable: bool,
}
@ -303,9 +304,9 @@ pub struct CompositionRef {
#[cultcache(key = 0)]
pub publisher: String,
#[cultcache(key = 1)]
pub name: String,
pub name: Segment,
#[cultcache(key = 2)]
pub version: i32,
pub version: Version,
}
#[derive(Clone, Debug, PartialEq, CultSlots)]
@ -414,9 +415,9 @@ pub struct SurfaceDocument {
#[cultcache(key = 0)]
pub provider_id: ProviderId,
#[cultcache(key = 1)]
pub label: String,
pub label: Segment,
#[cultcache(key = 2)]
pub version: i64,
pub version: Version,
#[cultcache(key = 3)]
pub title: String,
#[cultcache(key = 4)]
@ -438,9 +439,9 @@ pub struct CompositionDocument {
#[cultcache(key = 0)]
pub publisher: String,
#[cultcache(key = 1)]
pub name: String,
pub name: Segment,
#[cultcache(key = 2)]
pub version: i32,
pub version: Version,
#[cultcache(key = 3)]
pub params: Vec<ParamDecl>,
#[cultcache(key = 4)]

View file

@ -1,10 +1,12 @@
//! The answer to a command invocation. A `CommandResult` is built only by its four
//! constructors, each of which copies the invocation's id, and is read through accessors.
//! Nothing here takes a state as a string, and nothing builds a result from a map.
//! The answer to a command invocation. A `CommandResult` is built by its four constructors,
//! each of which copies the invocation's id, and is read through accessors. Decoding is the
//! other door and holds the same domain: `seq` is a `Seq`, refused below 1 whichever door
//! it enters by. No API takes a state as a string or converts a map.
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
use crate::command::{CommandInvocation, CommandRef};
use crate::domain::{Seq, Version};
use crate::keys::{NodeId, result_key};
#[derive(Clone, Debug, PartialEq, CultSlots)]
@ -16,7 +18,7 @@ pub struct PendingOutcome {
#[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct CompletedOutcome {
#[cultcache(key = 0)]
pub source_version: Option<i64>,
pub source_version: Option<Version>,
/// Whether the captured drafts of the invocation clear.
#[cultcache(key = 1)]
pub clear_drafts: bool,
@ -73,34 +75,77 @@ pub enum Effect {
OpenExternal(OpenExternalEffect),
}
/// A provider's answer to one invocation. `seq` counts from 1 per invocation.
/// A provider's answer to one invocation. `seq` counts from 1 per invocation. The copied
/// invocation id is a convenience: core binds a result to an invocation it issued.
///
/// The positive case, a result built by a constructor from the invocation it answers:
///
/// ```
/// use thing_contract::{CommandInvocation, CommandResult};
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
/// fn answer(invocation: &CommandInvocation) -> CommandResult {
/// CommandResult::failed(invocation, 1, "refused")
/// CommandResult::failed(invocation, Seq::FIRST, "refused")
/// }
/// ```
///
/// A struct literal does not compile, because the fields are private:
///
/// ```compile_fail,E0451
/// use thing_contract::{CommandResult, Outcome, FailedOutcome};
/// use thing_contract::{CommandResult, FailedOutcome, Outcome, Seq};
/// let _ = CommandResult {
/// invocation_id: String::new(),
/// seq: 1,
/// seq: Seq::FIRST,
/// outcome: Outcome::Failed(FailedOutcome { reason: String::new() }),
/// };
/// ```
///
/// Neither does assigning the outcome:
/// Each field is read through its accessor:
///
/// ```
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
/// fn read(invocation: &CommandInvocation) {
/// let result = CommandResult::failed(invocation, Seq::FIRST, "refused");
/// let _ = result.invocation_id();
/// }
/// ```
///
/// and assigning it does not compile:
///
/// ```compile_fail,E0616
/// use thing_contract::{CommandInvocation, CommandResult, Outcome, FailedOutcome};
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
/// fn tamper(invocation: &CommandInvocation) {
/// let mut result = CommandResult::failed(invocation, 1, "refused");
/// let mut result = CommandResult::failed(invocation, Seq::FIRST, "refused");
/// result.invocation_id = String::new();
/// }
/// ```
///
/// ```
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
/// fn read(invocation: &CommandInvocation) {
/// let result = CommandResult::failed(invocation, Seq::FIRST, "refused");
/// let _ = result.seq();
/// }
/// ```
///
/// ```compile_fail,E0616
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
/// fn tamper(invocation: &CommandInvocation) {
/// let mut result = CommandResult::failed(invocation, Seq::FIRST, "refused");
/// result.seq = Seq::FIRST.next();
/// }
/// ```
///
/// ```
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
/// fn read(invocation: &CommandInvocation) {
/// let result = CommandResult::failed(invocation, Seq::FIRST, "refused");
/// let _ = result.outcome();
/// }
/// ```
///
/// ```compile_fail,E0616
/// use thing_contract::{CommandInvocation, CommandResult, FailedOutcome, Outcome, Seq};
/// fn tamper(invocation: &CommandInvocation) {
/// let mut result = CommandResult::failed(invocation, Seq::FIRST, "refused");
/// result.outcome = Outcome::Failed(FailedOutcome { reason: String::new() });
/// }
/// ```
@ -126,24 +171,24 @@ pub struct CommandResult {
#[cultcache(key = 0)]
invocation_id: String,
#[cultcache(key = 1)]
seq: i32,
seq: Seq,
#[cultcache(key = 2)]
outcome: Outcome,
}
impl CommandResult {
fn answering(invocation: &CommandInvocation, seq: i32, outcome: Outcome) -> Self {
fn answering(invocation: &CommandInvocation, seq: Seq, outcome: Outcome) -> Self {
Self { invocation_id: invocation.invocation_id.clone(), seq, outcome }
}
pub fn pending(invocation: &CommandInvocation, seq: i32, message: impl Into<String>) -> Self {
pub fn pending(invocation: &CommandInvocation, seq: Seq, message: impl Into<String>) -> Self {
Self::answering(invocation, seq, Outcome::Pending(PendingOutcome { message: message.into() }))
}
pub fn completed(
invocation: &CommandInvocation,
seq: i32,
source_version: Option<i64>,
seq: Seq,
source_version: Option<Version>,
clear_drafts: bool,
effect: Option<Effect>,
) -> Self {
@ -156,14 +201,14 @@ impl CommandResult {
pub fn denied(
invocation: &CommandInvocation,
seq: i32,
seq: Seq,
reason: impl Into<String>,
node: Option<NodeId>,
) -> Self {
Self::answering(invocation, seq, Outcome::Denied(DeniedOutcome { reason: reason.into(), node }))
}
pub fn failed(invocation: &CommandInvocation, seq: i32, reason: impl Into<String>) -> Self {
pub fn failed(invocation: &CommandInvocation, seq: Seq, reason: impl Into<String>) -> Self {
Self::answering(invocation, seq, Outcome::Failed(FailedOutcome { reason: reason.into() }))
}
@ -171,7 +216,7 @@ impl CommandResult {
&self.invocation_id
}
pub fn seq(&self) -> i32 {
pub fn seq(&self) -> Seq {
self.seq
}

View file

@ -3,6 +3,7 @@
use cultcache_rs::{CultSlots, CultUnion};
use crate::domain::Count;
use crate::keys::{ProviderId, RecordKey, SchemaId};
/// A composition parameter, named.
@ -114,7 +115,7 @@ pub struct MemberName {
#[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct MemberIndex {
#[cultcache(key = 0)]
pub index: i32,
pub index: Count,
}
#[derive(Clone, Debug, PartialEq, CultUnion)]
@ -132,7 +133,7 @@ pub enum Format {
#[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct NumberFormat {
#[cultcache(key = 0)]
pub precision: i32,
pub precision: Count,
#[cultcache(key = 1)]
pub percent: bool,
#[cultcache(key = 2)]