Thing 2.0: CultLib pin to 4c9af401 (member rows), whole-value contract lists, resolve on any thread (#11)
This commit is contained in:
parent
edeeee2129
commit
b1c007d8b1
56 changed files with 1212 additions and 829 deletions
146
Cargo.lock
generated
146
Cargo.lock
generated
|
|
@ -17,12 +17,30 @@ version = "1.0.104"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "ar_archive_writer"
|
||||
version = "0.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec"
|
||||
dependencies = [
|
||||
"object",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
|
|
@ -65,10 +83,29 @@ version = "0.8.7"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultcache-rs"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7"
|
||||
version = "0.3.1"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
|
@ -79,20 +116,33 @@ dependencies = [
|
|||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"serde_stacker",
|
||||
"sha2",
|
||||
"stacker",
|
||||
"uuid",
|
||||
"windows-sys",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultcache-rs-derive"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.14"
|
||||
|
|
@ -133,6 +183,16 @@ dependencies = [
|
|||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
|
|
@ -212,6 +272,15 @@ dependencies = [
|
|||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "object"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
|
|
@ -233,6 +302,16 @@ dependencies = [
|
|||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "psm"
|
||||
version = "0.1.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
|
||||
dependencies = [
|
||||
"ar_archive_writer",
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
|
|
@ -335,6 +414,28 @@ dependencies = [
|
|||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_stacker"
|
||||
version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_core",
|
||||
"stacker",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
|
|
@ -347,6 +448,19 @@ version = "0.4.12"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "stacker"
|
||||
version = "0.1.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"psm",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
|
|
@ -385,6 +499,7 @@ dependencies = [
|
|||
name = "thing-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"stacker",
|
||||
"thing-contract",
|
||||
"thing-testkit",
|
||||
]
|
||||
|
|
@ -400,6 +515,12 @@ dependencies = [
|
|||
"thing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.26"
|
||||
|
|
@ -417,6 +538,12 @@ dependencies = [
|
|||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.129"
|
||||
|
|
@ -552,6 +679,15 @@ dependencies = [
|
|||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
|
|
|
|||
|
|
@ -4,6 +4,6 @@ resolver = "2"
|
|||
|
||||
[workspace.dependencies]
|
||||
anyhow = "1"
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7", package = "cultcache-rs" }
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4c9af401ae33812d862dde4ff3131433fc73c7dc", package = "cultcache-rs" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
rmp-serde = "1.3"
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ pub struct AssetCatalog {
|
|||
pub catalog_id: Segment,
|
||||
#[cultcache(key = 2)]
|
||||
pub version: Version,
|
||||
#[cultcache(key = 3)]
|
||||
#[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.AssetEntry>")]
|
||||
pub assets: Vec<AssetEntry>,
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -37,6 +37,7 @@ pub enum CommandRef {
|
|||
|
||||
/// A typed record of the declared `payload_schema`, as its MessagePack bytes.
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
#[cultcache(type_name = "GameCult.Thing.Contract.RecordPayload")]
|
||||
pub struct RecordPayload {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema: SchemaId,
|
||||
|
|
@ -105,7 +106,7 @@ pub struct CommandInvocation {
|
|||
pub command: CommandId,
|
||||
#[cultcache(key = 4)]
|
||||
pub payload: RecordPayload,
|
||||
#[cultcache(key = 5)]
|
||||
#[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CapturedInput>")]
|
||||
pub captured: Vec<CapturedInput>,
|
||||
#[cultcache(key = 6)]
|
||||
pub client: String,
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
|
||||
use std::fmt;
|
||||
|
||||
use cultcache_rs::CultTypeName;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
|
||||
|
||||
/// A value was outside its domain. Names the domain and its bound, never the value.
|
||||
|
|
@ -72,6 +73,13 @@ impl std::error::Error for DomainError {}
|
|||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct Seq(i32);
|
||||
|
||||
impl CultTypeName for Seq {
|
||||
fn cult_type_name() -> String {
|
||||
"System.Int32".to_string()
|
||||
}
|
||||
const VALUE_TYPE: bool = true;
|
||||
}
|
||||
|
||||
impl Seq {
|
||||
pub const FIRST: Seq = Seq(1);
|
||||
|
||||
|
|
@ -108,6 +116,13 @@ impl Seq {
|
|||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct Version(i64);
|
||||
|
||||
impl CultTypeName for Version {
|
||||
fn cult_type_name() -> String {
|
||||
"System.Int64".to_string()
|
||||
}
|
||||
const VALUE_TYPE: bool = true;
|
||||
}
|
||||
|
||||
impl Version {
|
||||
pub fn new(value: i64) -> Result<Self, DomainError> {
|
||||
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) }
|
||||
|
|
@ -166,6 +181,12 @@ impl Count {
|
|||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct Segment(String);
|
||||
|
||||
impl CultTypeName for Segment {
|
||||
fn cult_type_name() -> String {
|
||||
"System.String".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Segment {
|
||||
pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
|
||||
let value = value.into();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
//! Identifier newtypes and the record key of each kind. No caller spells a key as a free string.
|
||||
|
||||
use cultcache_rs::CultTypeName;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::domain::{Segment, Seq, Version};
|
||||
|
|
@ -20,6 +21,12 @@ macro_rules! id_type {
|
|||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl CultTypeName for $name {
|
||||
fn cult_type_name() -> String {
|
||||
"System.String".to_string()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,11 +8,6 @@
|
|||
//! `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;
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ pub struct NodeCommon {
|
|||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
#[cultcache(type_name = "GameCult.Thing.Contract.Node")]
|
||||
pub enum Node {
|
||||
#[cultcache(key = 0)]
|
||||
Box(BoxNode),
|
||||
|
|
@ -444,7 +445,7 @@ pub struct SurfaceDocument {
|
|||
pub title: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub root: Node,
|
||||
#[cultcache(key = 5)]
|
||||
#[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CommandDecl>")]
|
||||
pub commands: Vec<CommandDecl>,
|
||||
}
|
||||
|
||||
|
|
@ -464,7 +465,7 @@ pub struct CompositionDocument {
|
|||
pub name: Segment,
|
||||
#[cultcache(key = 2)]
|
||||
pub version: Version,
|
||||
#[cultcache(key = 3)]
|
||||
#[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.ParamDecl>")]
|
||||
pub params: Vec<ParamDecl>,
|
||||
#[cultcache(key = 4)]
|
||||
pub body: Node,
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ pub struct FailedOutcome {
|
|||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
#[cultcache(type_name = "GameCult.Thing.Contract.Outcome")]
|
||||
pub enum Outcome {
|
||||
#[cultcache(key = 0)]
|
||||
Pending(PendingOutcome),
|
||||
|
|
|
|||
60
crates/thing-contract/tests/catalog_members.rs
Normal file
60
crates/thing-contract/tests/catalog_members.rs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
//! The catalog rows the five document kinds publish are the rows the C# package declares:
|
||||
//! `tests/thing-contract-parity/catalog-members.tsv`, which NameSetTests (C#) and parity.test.ts
|
||||
//! (TypeScript) are held to as well. Schema ids differ by writer, so the comparison is by group,
|
||||
//! as `catalogGroups` in parity.test.ts makes it.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use cultcache_rs::{DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore};
|
||||
use thing_contract::*;
|
||||
|
||||
fn tsv_groups() -> Vec<String> {
|
||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity/catalog-members.tsv");
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
let mut groups: Vec<(String, Vec<String>)> = Vec::new();
|
||||
for row in text.lines().filter(|line| !line.trim().is_empty()) {
|
||||
let (schema, rest) = row.split_once('\t').unwrap();
|
||||
match groups.iter_mut().find(|(id, _)| id == schema) {
|
||||
Some((_, rows)) => rows.push(rest.to_string()),
|
||||
None => groups.push((schema.to_string(), vec![rest.to_string()])),
|
||||
}
|
||||
}
|
||||
sorted(groups.into_iter().map(|(_, rows)| rows.join("\n")).collect())
|
||||
}
|
||||
|
||||
fn group(members: &[SchemaCatalogMember]) -> String {
|
||||
members.iter().map(|m| format!("{}\t{}\t{}", m.slot, m.member_name, m.type_name)).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
fn sorted(mut groups: Vec<String>) -> Vec<String> {
|
||||
groups.sort();
|
||||
groups
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_equal_the_csharp_file() {
|
||||
let mine = sorted(vec![
|
||||
group(&SurfaceDocument::schema_members()),
|
||||
group(&CompositionDocument::schema_members()),
|
||||
group(&CommandInvocation::schema_members()),
|
||||
group(&CommandResult::schema_members()),
|
||||
group(&AssetCatalog::schema_members()),
|
||||
]);
|
||||
assert_eq!(mine, tsv_groups());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_written_store_carries_the_rows() {
|
||||
// goldens.rs writes a store of one record per kind and compares it byte for byte with the
|
||||
// committed surface.cc, so the committed file's catalog is the catalog the crate writes. It is
|
||||
// copied first: reading a store creates a lock file beside it.
|
||||
let committed = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens/surface.cc");
|
||||
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("catalog-members");
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
let copy = work.join("surface.cc");
|
||||
std::fs::copy(committed, ©).unwrap();
|
||||
let catalog = SingleFileMessagePackBackingStore::new(©).pull_schema_catalog().unwrap();
|
||||
let from_store = sorted(catalog.iter().map(|entry| group(&entry.members)).collect());
|
||||
assert_eq!(from_store, tsv_groups());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
|
@ -642,13 +642,6 @@ fn refusal_cases() {
|
|||
|
||||
#[test]
|
||||
fn deep_tree() {
|
||||
// Decoding a Node costs tens of KiB of debug stack per nesting level, so the chain runs on a
|
||||
// thread that has the room; the 2 MiB default does not. The hazard is CultCache's, owned by
|
||||
// cultlib-gaps:follow_up:decode-stack-safety; the test stays on the big thread until it lands.
|
||||
std::thread::Builder::new().stack_size(16 * 1024 * 1024).spawn(deep_tree_body).unwrap().join().unwrap();
|
||||
}
|
||||
|
||||
fn deep_tree_body() {
|
||||
// A 64-deep Box chain.
|
||||
let mut chain = text("leaf", "bottom");
|
||||
for depth in (0..64).rev() {
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -7,6 +7,7 @@ publish = false
|
|||
|
||||
[dependencies]
|
||||
thing-contract = { path = "../thing-contract" }
|
||||
stacker = "0.1.25"
|
||||
|
||||
[dev-dependencies]
|
||||
thing-testkit = { path = "../thing-testkit" }
|
||||
|
|
|
|||
|
|
@ -18,8 +18,8 @@ use super::{Limits, std as thing_std, validate};
|
|||
/// rule (`Limits::max_tree_depth`) is judged by validate on the finished tree, where a slot argument
|
||||
/// the body never places does not count. It exists because an in-memory tree from a Rust caller can
|
||||
/// be deeper than any decoded document (CultCache bounds decoded nesting at 256), and recursion
|
||||
/// over it would overflow the stack. A level costs a few tens of KiB of stack in a debug build, so a
|
||||
/// caller resolving untrusted in-memory trees needs a stack sized for this many levels.
|
||||
/// over it would overflow the stack. The recursion grows its own stack (`super::grow`), so the bound
|
||||
/// holds on any thread.
|
||||
const STACK_BOUND: usize = 1024;
|
||||
|
||||
/// A fault the nearest enclosing Use turns into a placeholder (`Invalid`), or one that ends the
|
||||
|
|
@ -294,7 +294,7 @@ impl<'a> Expander<'a> {
|
|||
(Node::Slot(slot), Some(scope)) => match Self::arg_of(&slot.param, scope)? {
|
||||
ArgValue::Slot(arg) => {
|
||||
self.count(arg.nodes.iter().map(validate::size).sum())?;
|
||||
out.extend(arg.nodes.iter().cloned());
|
||||
out.extend(arg.nodes.iter().map(clone_deep));
|
||||
}
|
||||
other => return wrong_kind(&slot.param, other, "a slot"),
|
||||
},
|
||||
|
|
@ -305,6 +305,10 @@ impl<'a> Expander<'a> {
|
|||
}
|
||||
|
||||
fn node(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
|
||||
super::grow(|| self.node_at(node, scope, depth, root))
|
||||
}
|
||||
|
||||
fn node_at(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
|
||||
if depth > STACK_BOUND {
|
||||
return Err(Fault::Stack(format!("the input nests deeper than {STACK_BOUND} levels")));
|
||||
}
|
||||
|
|
@ -537,6 +541,42 @@ impl<'a> Expander<'a> {
|
|||
}
|
||||
|
||||
/// The id of a body root. A Slot has none, and the body fails on it before an id is read.
|
||||
/// A copy of an expanded subtree that grows its own stack. The derived `Clone` of `Node` costs about
|
||||
/// 12 KiB of debug stack per level, so a spliced slot argument up to `STACK_BOUND` levels deep would
|
||||
/// overflow it; each container here recurses through `grow`. An expanded subtree holds no Slot and no
|
||||
/// Use with arguments, so the four containers are the only nodes that hold nodes.
|
||||
fn clone_deep(node: &Node) -> Node {
|
||||
super::grow(|| match node {
|
||||
Node::Box(b) => Node::Box(BoxNode {
|
||||
common: b.common.clone(),
|
||||
style: b.style.clone(),
|
||||
paint: b.paint.clone(),
|
||||
role: b.role.clone(),
|
||||
children: b.children.iter().map(clone_deep).collect(),
|
||||
}),
|
||||
Node::Button(b) => Node::Button(ButtonNode {
|
||||
common: b.common.clone(),
|
||||
content: b.content.iter().map(clone_deep).collect(),
|
||||
on_activate: b.on_activate.clone(),
|
||||
enabled: b.enabled.clone(),
|
||||
}),
|
||||
Node::Overlay(o) => Node::Overlay(OverlayNode {
|
||||
common: o.common.clone(),
|
||||
anchor: o.anchor.clone(),
|
||||
modal: o.modal,
|
||||
dismiss: o.dismiss.clone(),
|
||||
children: o.children.iter().map(clone_deep).collect(),
|
||||
}),
|
||||
Node::Repeat(r) => Node::Repeat(RepeatNode {
|
||||
common: r.common.clone(),
|
||||
collection: r.collection.clone(),
|
||||
key_member: r.key_member.clone(),
|
||||
template: std::boxed::Box::new(clone_deep(&r.template)),
|
||||
}),
|
||||
other => other.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn body_id(node: &Node) -> NodeId {
|
||||
match node {
|
||||
Node::Box(n) => n.common.id.clone(),
|
||||
|
|
|
|||
|
|
@ -12,6 +12,17 @@ use thing_contract::SurfaceDocument;
|
|||
use crate::diagnostic::{Code, Diagnostic};
|
||||
use crate::port::{Address, StatePort};
|
||||
|
||||
/// Stack left below which recursion moves to a fresh segment, and the segment's size: the values
|
||||
/// cultcache-rs uses for decode. Every recursion over a tree runs through `grow`, so a tree as deep
|
||||
/// as `STACK_BOUND` resolves on a default thread.
|
||||
const RED_ZONE: usize = 512 * 1024;
|
||||
const SEGMENT: usize = 2 * 1024 * 1024;
|
||||
|
||||
/// Runs one recursive step with room for the next, growing the stack when it is nearly spent.
|
||||
fn grow<R>(step: impl FnOnce() -> R) -> R {
|
||||
stacker::maybe_grow(RED_ZONE, SEGMENT, step)
|
||||
}
|
||||
|
||||
/// The bounds of one expansion.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
|
|
@ -81,7 +92,17 @@ pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits
|
|||
let tree = root.and_then(|root| {
|
||||
diagnostics.extend(validate::check(&root, limits, &document.record_key()));
|
||||
let refused = diagnostics.iter().any(|diagnostic| diagnostic.code.refuses_document());
|
||||
(!refused).then(|| ResolvedTree { document: SurfaceDocument { root, ..document.clone() } })
|
||||
// Field by field: `..document.clone()` would clone the whole input tree to discard it.
|
||||
(!refused).then(|| ResolvedTree {
|
||||
document: SurfaceDocument {
|
||||
provider_id: document.provider_id.clone(),
|
||||
label: document.label.clone(),
|
||||
version: document.version,
|
||||
title: document.title.clone(),
|
||||
root,
|
||||
commands: document.commands.clone(),
|
||||
},
|
||||
})
|
||||
});
|
||||
Resolution { tree, diagnostics, reads }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ fn id(node: &Node) -> Option<&NodeId> {
|
|||
|
||||
/// Nodes in the subtree, the node itself included.
|
||||
pub(super) fn size(node: &Node) -> usize {
|
||||
1 + children(node).iter().map(size).sum::<usize>()
|
||||
super::grow(|| 1 + children(node).iter().map(size).sum::<usize>())
|
||||
}
|
||||
|
||||
/// Faults of the finished tree, in pre-order: duplicate ids, then depth. A tree deeper than the limit is not walked further.
|
||||
|
|
@ -73,3 +73,38 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec<Diagnost
|
|||
}
|
||||
found
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use thing_testkit::build::{boxed, text};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Runs `work` with about `left` bytes of stack remaining: the stack is burned first, so a recursion
|
||||
/// that does not grow its own runs out inside it.
|
||||
#[inline(never)]
|
||||
fn with_stack_left(left: usize, work: &mut dyn FnMut()) {
|
||||
if stacker::remaining_stack().expect("the thread's stack limit is known") > left {
|
||||
let burn = [0u8; 4096];
|
||||
std::hint::black_box(&burn);
|
||||
with_stack_left(left, work);
|
||||
std::hint::black_box(&burn);
|
||||
} else {
|
||||
work();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_of_a_deep_subtree_grows_its_own_stack() {
|
||||
// expand counts a slot argument with `size` after the argument was expanded, from wherever the
|
||||
// stack stands; a 1,000-level argument must not run it out.
|
||||
let mut deep = text("bottom", "x");
|
||||
for level in 1..1000 {
|
||||
deep = boxed(&format!("level-{level}"), vec![deep]);
|
||||
}
|
||||
let mut counted = 0;
|
||||
with_stack_left(100 * 1024, &mut || counted = size(&deep));
|
||||
assert_eq!(counted, 1000);
|
||||
// Dropping a tree this deep needs the room the test thread has outside `with_stack_left`.
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -291,7 +291,7 @@ SurfaceDocument {
|
|||
steps: [
|
||||
Name(
|
||||
MemberName {
|
||||
name: "load",
|
||||
name: "Load",
|
||||
},
|
||||
),
|
||||
],
|
||||
|
|
@ -468,7 +468,7 @@ SurfaceDocument {
|
|||
steps: [
|
||||
Name(
|
||||
MemberName {
|
||||
name: "id",
|
||||
name: "Id",
|
||||
},
|
||||
),
|
||||
],
|
||||
|
|
@ -493,7 +493,7 @@ SurfaceDocument {
|
|||
steps: [
|
||||
Name(
|
||||
MemberName {
|
||||
name: "name",
|
||||
name: "Name",
|
||||
},
|
||||
),
|
||||
],
|
||||
|
|
@ -722,7 +722,7 @@ SurfaceDocument {
|
|||
steps: [
|
||||
Name(
|
||||
MemberName {
|
||||
name: "id",
|
||||
name: "Id",
|
||||
},
|
||||
),
|
||||
],
|
||||
|
|
@ -747,7 +747,7 @@ SurfaceDocument {
|
|||
steps: [
|
||||
Name(
|
||||
MemberName {
|
||||
name: "name",
|
||||
name: "Name",
|
||||
},
|
||||
),
|
||||
],
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -194,7 +194,7 @@ fn swarm_ref(key: &str) -> StateSource {
|
|||
fn swarm_dashboard() -> SurfaceDocument {
|
||||
let load = Bind {
|
||||
source: swarm_ref("summary"),
|
||||
member: path(&["load"]),
|
||||
member: path(&["Load"]),
|
||||
format: Some(Format::Number(NumberFormat { precision: count(1), percent: true, unit: None })),
|
||||
};
|
||||
let load_text = Node::Text(TextNode {
|
||||
|
|
@ -212,10 +212,10 @@ fn swarm_dashboard() -> SurfaceDocument {
|
|||
schema: SchemaId::new(SWARM_SCHEMA),
|
||||
key_prefix: "mind-".into(),
|
||||
}),
|
||||
key_member: path(&["id"]),
|
||||
key_member: path(&["Id"]),
|
||||
template: std::boxed::Box::new(Node::Text(TextNode {
|
||||
common: common("mind-name"),
|
||||
content: TextSource::Bound(item_bind(path(&["name"]))),
|
||||
content: TextSource::Bound(item_bind(path(&["Name"]))),
|
||||
style_token: "body".into(),
|
||||
wrap: false,
|
||||
max_lines: Some(count(1)),
|
||||
|
|
@ -258,7 +258,7 @@ const STACK: &str = "provider.stack";
|
|||
|
||||
/// A Use of the publisher's card with one argument of each arm and the given slot children.
|
||||
fn card_use(id: &str, slot: Vec<Node>) -> Node {
|
||||
let source = Bind { source: swarm_ref("summary"), member: path(&["load"]), format: None };
|
||||
let source = Bind { source: swarm_ref("summary"), member: path(&["Load"]), format: None };
|
||||
let rows = CollectionSource::Records(RecordsSource {
|
||||
provider: None,
|
||||
schema: SchemaId::new(SWARM_SCHEMA),
|
||||
|
|
@ -292,7 +292,7 @@ fn composition_stack() -> SurfaceDocument {
|
|||
Arg { name: "label".into(), value: ArgValue::Text(TextArg { value: "Load".into() }) },
|
||||
Arg {
|
||||
name: "value".into(),
|
||||
value: ArgValue::Bind(Bind { source: swarm_ref("summary"), member: path(&["load"]), format: None }),
|
||||
value: ArgValue::Bind(Bind { source: swarm_ref("summary"), member: path(&["Load"]), format: None }),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
|
@ -323,10 +323,10 @@ fn stack_card() -> CompositionDocument {
|
|||
let rows = Node::Repeat(RepeatNode {
|
||||
common: common("card-rows"),
|
||||
collection: CollectionSource::Param(param("rows")),
|
||||
key_member: path(&["id"]),
|
||||
key_member: path(&["Id"]),
|
||||
template: std::boxed::Box::new(Node::Text(TextNode {
|
||||
common: common("card-row"),
|
||||
content: TextSource::Bound(item_bind(path(&["name"]))),
|
||||
content: TextSource::Bound(item_bind(path(&["Name"]))),
|
||||
style_token: "body".into(),
|
||||
wrap: false,
|
||||
max_lines: None,
|
||||
|
|
@ -398,7 +398,7 @@ fn hostile() -> Vec<SurfaceDocument> {
|
|||
schema: SchemaId::new("gamecult.thing.test.nowhere.v1"),
|
||||
key: RecordKey::new("row-1"),
|
||||
}),
|
||||
member: path(&["name"]),
|
||||
member: path(&["Name"]),
|
||||
format: None,
|
||||
}),
|
||||
style_token: "body".into(),
|
||||
|
|
@ -557,7 +557,7 @@ fn input_target() -> FixtureSet {
|
|||
});
|
||||
let label = Node::Text(TextNode {
|
||||
common: common("target-label"),
|
||||
content: TextSource::Bound(record_member(provider, "target", "cursor", &["label"])),
|
||||
content: TextSource::Bound(record_member(provider, "target", "cursor", &["Label"])),
|
||||
style_token: "body".into(),
|
||||
wrap: false,
|
||||
max_lines: Some(count(1)),
|
||||
|
|
@ -608,7 +608,7 @@ fn form() -> FixtureSet {
|
|||
let provider = "provider.settings";
|
||||
let toggle = Node::Toggle(ToggleNode {
|
||||
common: common("enabled"),
|
||||
checked: BoolSource::Bound(record_member(provider, "settings", "current", &["enabled"])),
|
||||
checked: BoolSource::Bound(record_member(provider, "settings", "current", &["Enabled"])),
|
||||
on_change: command("save"),
|
||||
});
|
||||
let slider = Node::Slider(SliderNode {
|
||||
|
|
@ -616,7 +616,7 @@ fn form() -> FixtureSet {
|
|||
min: 0.0,
|
||||
max: 1.0,
|
||||
step: 0.05,
|
||||
value: NumberSource::Bound(record_member(provider, "settings", "current", &["volume"])),
|
||||
value: NumberSource::Bound(record_member(provider, "settings", "current", &["Volume"])),
|
||||
commit: command("save"),
|
||||
});
|
||||
let select = Node::Select(SelectNode {
|
||||
|
|
@ -627,7 +627,7 @@ fn form() -> FixtureSet {
|
|||
SelectOption { value: "light".into(), label: "Light".into() },
|
||||
],
|
||||
}),
|
||||
value: record_member(provider, "settings", "current", &["theme"]),
|
||||
value: record_member(provider, "settings", "current", &["Theme"]),
|
||||
on_change: command("save"),
|
||||
});
|
||||
let port = text_input("port", InputKind::Number, "8080", command("save"));
|
||||
|
|
@ -686,7 +686,7 @@ fn scroll_list() -> SurfaceDocument {
|
|||
role: Role::ListItem,
|
||||
children: vec![Node::Text(TextNode {
|
||||
common: common("item-title"),
|
||||
content: TextSource::Bound(item_bind(path(&["title"]))),
|
||||
content: TextSource::Bound(item_bind(path(&["Title"]))),
|
||||
style_token: "body".into(),
|
||||
wrap: false,
|
||||
max_lines: Some(count(1)),
|
||||
|
|
@ -700,7 +700,7 @@ fn scroll_list() -> SurfaceDocument {
|
|||
schema: SchemaId::new(format!("{TEST_SCHEMA_ROOT}.item.v1")),
|
||||
key_prefix: "item-".into(),
|
||||
}),
|
||||
key_member: path(&["id"]),
|
||||
key_member: path(&["Id"]),
|
||||
template: std::boxed::Box::new(row),
|
||||
});
|
||||
let mut list = style();
|
||||
|
|
@ -718,7 +718,7 @@ fn scroll_list() -> SurfaceDocument {
|
|||
|
||||
fn plot() -> SurfaceDocument {
|
||||
let provider = "provider.market";
|
||||
let series = || record_member(provider, "series", "prices", &["values"]);
|
||||
let series = || record_member(provider, "series", "prices", &["Values"]);
|
||||
let mark = |id: &str, mark: PlotMark, x: (Option<f64>, Option<f64>), y: (Option<f64>, Option<f64>)| {
|
||||
Node::Plot(PlotNode {
|
||||
common: common(id),
|
||||
|
|
|
|||
|
|
@ -20,6 +20,9 @@ pub fn create(path: &Path) -> CultCache {
|
|||
let _ = std::fs::remove_file(path);
|
||||
let mut cache = memory();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
|
||||
// From cultcache-rs 0.4 a cache that attached a store refuses writes until it pulls; the file
|
||||
// was just removed, so the pull is empty.
|
||||
cache.pull_all_backing_stores().unwrap();
|
||||
cache
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -10,61 +10,53 @@ use thing_testkit::mem_state::MemState;
|
|||
use thing_testkit::store;
|
||||
use thing_core::port::{Address, Lookup, StatePort};
|
||||
|
||||
/// Decoding runs on a 16 MiB thread until the workspace pin of cultcache-rs carries
|
||||
/// decode-stack-safety.
|
||||
fn on_big_stack<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
std::thread::Builder::new().stack_size(16 * 1024 * 1024).spawn(work).unwrap().join().unwrap()
|
||||
}
|
||||
|
||||
fn load(fixture: Fixture) -> FixtureSet {
|
||||
on_big_stack(move || fixture.load())
|
||||
fixture.load()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_fixture_round_trips_through_the_contract() {
|
||||
on_big_stack(|| {
|
||||
for fixture in Fixture::ALL {
|
||||
// The builders reproduce the committed file byte for byte (or bless it).
|
||||
let committed = fixture.write();
|
||||
assert_eq!(committed, std::fs::read(Fixture::dir().join(fixture.file_name())).unwrap());
|
||||
assert!(!committed.is_empty());
|
||||
let built = fixture.build();
|
||||
let loaded = fixture.load();
|
||||
assert_eq!(loaded, built, "{}: the store decodes to the built documents", fixture.file_name());
|
||||
for fixture in Fixture::ALL {
|
||||
// The builders reproduce the committed file byte for byte (or bless it).
|
||||
let committed = fixture.write();
|
||||
assert_eq!(committed, std::fs::read(Fixture::dir().join(fixture.file_name())).unwrap());
|
||||
assert!(!committed.is_empty());
|
||||
let built = fixture.build();
|
||||
let loaded = fixture.load();
|
||||
assert_eq!(loaded, built, "{}: the store decodes to the built documents", fixture.file_name());
|
||||
|
||||
// Each record re-encodes to its stored payload.
|
||||
let cache = fixture.open();
|
||||
let stored = cache.snapshot_envelopes();
|
||||
let payload = |kind: &str, key: String| {
|
||||
stored.iter().find(|envelope| envelope.r#type == kind && envelope.key == key).unwrap().payload.clone()
|
||||
};
|
||||
for surface in &loaded.surfaces {
|
||||
assert_eq!(rmp_serde::to_vec(surface).unwrap(), payload("gamecult.thing.surface", surface.record_key()));
|
||||
}
|
||||
for composition in &loaded.compositions {
|
||||
let key = composition.record_key();
|
||||
assert_eq!(rmp_serde::to_vec(composition).unwrap(), payload("gamecult.thing.composition", key));
|
||||
}
|
||||
for catalog in &loaded.catalogs {
|
||||
assert_eq!(rmp_serde::to_vec(catalog).unwrap(), payload("gamecult.thing.asset_catalog", catalog.record_key()));
|
||||
}
|
||||
for invocation in &loaded.invocations {
|
||||
let key = invocation.record_key();
|
||||
assert_eq!(rmp_serde::to_vec(invocation).unwrap(), payload("gamecult.thing.command_invocation", key));
|
||||
}
|
||||
for result in &loaded.results {
|
||||
assert_eq!(rmp_serde::to_vec(result).unwrap(), payload("gamecult.thing.command_result", result.record_key()));
|
||||
}
|
||||
assert_eq!(
|
||||
stored.len(),
|
||||
loaded.document_count(),
|
||||
"{}: the store holds the documents and nothing else",
|
||||
fixture.file_name()
|
||||
);
|
||||
// Each record re-encodes to its stored payload.
|
||||
let cache = fixture.open();
|
||||
let stored = cache.snapshot_envelopes();
|
||||
let payload = |kind: &str, key: String| {
|
||||
stored.iter().find(|envelope| envelope.r#type == kind && envelope.key == key).unwrap().payload.clone()
|
||||
};
|
||||
for surface in &loaded.surfaces {
|
||||
assert_eq!(rmp_serde::to_vec(surface).unwrap(), payload("gamecult.thing.surface", surface.record_key()));
|
||||
}
|
||||
// The payload one Box level past f11's chain is a raw file, not a store.
|
||||
assert_eq!(Fixture::write_deep_refused(), Fixture::deep_refused_payload());
|
||||
});
|
||||
for composition in &loaded.compositions {
|
||||
let key = composition.record_key();
|
||||
assert_eq!(rmp_serde::to_vec(composition).unwrap(), payload("gamecult.thing.composition", key));
|
||||
}
|
||||
for catalog in &loaded.catalogs {
|
||||
assert_eq!(rmp_serde::to_vec(catalog).unwrap(), payload("gamecult.thing.asset_catalog", catalog.record_key()));
|
||||
}
|
||||
for invocation in &loaded.invocations {
|
||||
let key = invocation.record_key();
|
||||
assert_eq!(rmp_serde::to_vec(invocation).unwrap(), payload("gamecult.thing.command_invocation", key));
|
||||
}
|
||||
for result in &loaded.results {
|
||||
assert_eq!(rmp_serde::to_vec(result).unwrap(), payload("gamecult.thing.command_result", result.record_key()));
|
||||
}
|
||||
assert_eq!(
|
||||
stored.len(),
|
||||
loaded.document_count(),
|
||||
"{}: the store holds the documents and nothing else",
|
||||
fixture.file_name()
|
||||
);
|
||||
}
|
||||
// The payload one Box level past f11's chain is a raw file, not a store.
|
||||
assert_eq!(Fixture::write_deep_refused(), Fixture::deep_refused_payload());
|
||||
}
|
||||
|
||||
fn commands_declared(surface: &SurfaceDocument) -> Vec<&str> {
|
||||
|
|
@ -171,7 +163,7 @@ fn f10_holds_exactly_the_four_hostile_surfaces() {
|
|||
|
||||
#[test]
|
||||
fn a_state_holds_every_fixture_document_under_its_publisher() {
|
||||
let state = on_big_stack(|| MemState::from_fixture(Fixture::F09CompositionStack));
|
||||
let state = MemState::from_fixture(Fixture::F09CompositionStack);
|
||||
let set = load(Fixture::F09CompositionStack);
|
||||
let at = Address {
|
||||
provider: ProviderId::new(set.compositions[0].publisher.clone()),
|
||||
|
|
@ -393,7 +385,7 @@ fn f06_scrolls_a_repeat_over_a_records_prefix() {
|
|||
assert_eq!(root.style.overflow, Overflow::Scroll);
|
||||
let [Node::Repeat(items)] = &root.children[..] else { panic!("one Repeat expected") };
|
||||
assert!(matches!(&items.collection, CollectionSource::Records(records) if !records.key_prefix.is_empty()));
|
||||
assert_eq!(items.key_member, thing_testkit::build::path(&["id"]));
|
||||
assert_eq!(items.key_member, thing_testkit::build::path(&["Id"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -424,45 +416,43 @@ fn f08_embeds_a_fixed_size_leaf_among_siblings() {
|
|||
|
||||
#[test]
|
||||
fn f11_is_the_deepest_chain_the_bound_admits_and_one_more_level_is_refused() {
|
||||
on_big_stack(|| {
|
||||
let (set, surface) = single_surface(Fixture::F11Deep);
|
||||
let cache = Fixture::F11Deep.open();
|
||||
let stored = cache.snapshot_envelopes();
|
||||
assert_eq!(stored.len(), 1);
|
||||
// The committed surface passes CultCache's own check and decodes to the built chain.
|
||||
assert_eq!(check_payload_depth(&stored[0].payload), Ok(()));
|
||||
assert_eq!(rmp_serde::to_vec(&surface).unwrap(), stored[0].payload);
|
||||
let levels = {
|
||||
let mut levels = 0;
|
||||
let mut node = &surface.root;
|
||||
while let Node::Box(boxed) = node {
|
||||
levels += 1;
|
||||
match boxed.children.first() {
|
||||
Some(child) => node = child,
|
||||
None => break,
|
||||
}
|
||||
let (set, surface) = single_surface(Fixture::F11Deep);
|
||||
let cache = Fixture::F11Deep.open();
|
||||
let stored = cache.snapshot_envelopes();
|
||||
assert_eq!(stored.len(), 1);
|
||||
// The committed surface passes CultCache's own check and decodes to the built chain.
|
||||
assert_eq!(check_payload_depth(&stored[0].payload), Ok(()));
|
||||
assert_eq!(rmp_serde::to_vec(&surface).unwrap(), stored[0].payload);
|
||||
let levels = {
|
||||
let mut levels = 0;
|
||||
let mut node = &surface.root;
|
||||
while let Node::Box(boxed) = node {
|
||||
levels += 1;
|
||||
match boxed.children.first() {
|
||||
Some(child) => node = child,
|
||||
None => break,
|
||||
}
|
||||
levels
|
||||
};
|
||||
assert!(levels > 1, "a chain, not one Box");
|
||||
assert_eq!(set.surfaces.len(), 1);
|
||||
}
|
||||
levels
|
||||
};
|
||||
assert!(levels > 1, "a chain, not one Box");
|
||||
assert_eq!(set.surfaces.len(), 1);
|
||||
|
||||
// One Box level deeper is refused by the check, naming depth 257, and by CultCache.
|
||||
let refused = golden::read(&Fixture::dir(), Fixture::DEEP_REFUSED);
|
||||
assert_eq!(refused, Fixture::deep_refused_payload());
|
||||
assert_eq!(check_payload_depth(&refused), Err(PayloadTooDeep { depth: 257, limit: 256 }));
|
||||
let mut cache = store::memory();
|
||||
let envelope = CultCacheEnvelope {
|
||||
key: surface.record_key(),
|
||||
r#type: "gamecult.thing.surface".into(),
|
||||
payload: refused,
|
||||
stored_at: store::PINNED_CLOCK.into(),
|
||||
schema_id: Some("gamecult.thing.surface.v1".into()),
|
||||
};
|
||||
let error = cache.put_raw_envelope(envelope).unwrap_err();
|
||||
assert!(error.downcast_ref::<PayloadTooDeep>().is_some(), "{error:#}");
|
||||
assert!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap().is_none());
|
||||
});
|
||||
// One Box level deeper is refused by the check, naming depth 257, and by CultCache.
|
||||
let refused = golden::read(&Fixture::dir(), Fixture::DEEP_REFUSED);
|
||||
assert_eq!(refused, Fixture::deep_refused_payload());
|
||||
assert_eq!(check_payload_depth(&refused), Err(PayloadTooDeep { depth: 257, limit: 256 }));
|
||||
let mut cache = store::memory();
|
||||
let envelope = CultCacheEnvelope {
|
||||
key: surface.record_key(),
|
||||
r#type: "gamecult.thing.surface".into(),
|
||||
payload: refused,
|
||||
stored_at: store::PINNED_CLOCK.into(),
|
||||
schema_id: Some("gamecult.thing.surface.v1".into()),
|
||||
};
|
||||
let error = cache.put_raw_envelope(envelope).unwrap_err();
|
||||
assert!(error.downcast_ref::<PayloadTooDeep>().is_some(), "{error:#}");
|
||||
assert!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -17,15 +17,8 @@ fn scratch_entries() -> Vec<String> {
|
|||
#[test]
|
||||
fn writing_a_fixture_leaves_no_scratch_file_or_lock_behind() {
|
||||
let before = scratch_entries();
|
||||
let stack = std::thread::Builder::new().stack_size(16 * 1024 * 1024);
|
||||
stack
|
||||
.spawn(|| {
|
||||
for fixture in Fixture::ALL {
|
||||
fixture.write();
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
for fixture in Fixture::ALL {
|
||||
fixture.write();
|
||||
}
|
||||
assert_eq!(scratch_entries(), before);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -509,9 +509,8 @@ summary.
|
|||
`file:` path to the published version, and both packages get a release
|
||||
line. Until then both read CultLib from the sibling checkout at the Cargo
|
||||
rev (P22).
|
||||
- CultLib pin bump: when `cultlib-gaps:follow_up:decode-stack-safety` lands,
|
||||
move the pin and run `deep_tree` on the default thread (its 16 MiB thread
|
||||
goes); the crate docs' hazard note goes with it.
|
||||
- CultLib pin bump: done at CultLib `4c9af401` (cut bind-pin); `deep_tree`
|
||||
runs on the default thread and the crate docs' hazard note is gone.
|
||||
- Missing-slot golden: re-added only when
|
||||
`cultlib-gaps:follow_up:rust-missing-slot-vs-reference` settles the rule.
|
||||
2. **Core**, in three cuts: (a) resolution, compositions with `thing.std`,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using GameCult.Caching;
|
||||
using MessagePack;
|
||||
|
||||
|
|
@ -30,7 +31,7 @@ public sealed class AssetCatalog
|
|||
[Key(0)] public string ProviderId { get; }
|
||||
[Key(1)] public string CatalogId { get; }
|
||||
[Key(2)] public long Version { get; }
|
||||
[Key(3)] public IReadOnlyList<AssetEntry> Assets { get; }
|
||||
[Key(3)] public ImmutableArray<AssetEntry> Assets { get; }
|
||||
|
||||
public AssetCatalog(string providerId, string catalogId, long version, IReadOnlyList<AssetEntry> assets)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using GameCult.Caching;
|
||||
using MessagePack;
|
||||
|
||||
|
|
@ -92,7 +93,7 @@ public sealed class CommandDecl
|
|||
{
|
||||
[Key(0)] public string Id { get; }
|
||||
[Key(1)] public string PayloadSchema { get; }
|
||||
[Key(2)] public IReadOnlyList<string> Captures { get; }
|
||||
[Key(2)] public ImmutableArray<string> Captures { get; }
|
||||
[Key(3)] public string? Confirm { get; }
|
||||
|
||||
public CommandDecl(string id, string payloadSchema, IReadOnlyList<string> captures, string? confirm)
|
||||
|
|
@ -155,7 +156,7 @@ public sealed class CommandInvocation
|
|||
[Key(2)] public long SurfaceVersion { get; }
|
||||
[Key(3)] public string Command { get; }
|
||||
[Key(4)] public RecordPayload Payload { get; }
|
||||
[Key(5)] public IReadOnlyList<CapturedInput> Captured { get; }
|
||||
[Key(5)] public ImmutableArray<CapturedInput> Captured { get; }
|
||||
[Key(6)] public string Client { get; }
|
||||
[Key(7)] public string IssuedAt { get; }
|
||||
[Key(8)] public string? Delegation { get; }
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace GameCult.Thing.Contract;
|
||||
|
||||
|
|
@ -50,15 +51,14 @@ public static class ThingDomain
|
|||
value ?? throw new ThingDomainException(slot, "present");
|
||||
|
||||
/// <summary>
|
||||
/// A required list slot: a read-only copy, so the caller's list cannot change the value afterwards. A null list or
|
||||
/// a null item is refused naming the slot.
|
||||
/// A required list slot, as a whole-value holder: a copy, so the caller's list cannot change the value afterwards.
|
||||
/// A null list, a default array (what a nil payload decodes to) or a null item is refused naming the slot.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<T> Items<T>(IReadOnlyList<T>? items, string slot) where T : class
|
||||
public static ImmutableArray<T> Items<T>(IReadOnlyList<T>? items, string slot) where T : class
|
||||
{
|
||||
if (items is null) throw new ThingDomainException(slot, "present");
|
||||
var copy = new T[items.Count];
|
||||
for (var i = 0; i < copy.Length; i++)
|
||||
copy[i] = items[i] ?? throw new ThingDomainException(slot, "free of nil items");
|
||||
return Array.AsReadOnly(copy);
|
||||
if (items is null || items is ImmutableArray<T> { IsDefault: true }) throw new ThingDomainException(slot, "present");
|
||||
var builder = ImmutableArray.CreateBuilder<T>(items.Count);
|
||||
foreach (var item in items) builder.Add(item ?? throw new ThingDomainException(slot, "free of nil items"));
|
||||
return builder.MoveToImmutable();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,5 +18,6 @@
|
|||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching\GameCult.Caching.csproj" />
|
||||
<PackageReference Include="System.Collections.Immutable" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using GameCult.Caching;
|
||||
using MessagePack;
|
||||
|
||||
|
|
@ -30,7 +31,7 @@ public sealed class BoxNode : Node
|
|||
[Key(1)] public BoxStyle Style { get; }
|
||||
[Key(2)] public Paint Paint { get; }
|
||||
[Key(3)] public Role Role { get; }
|
||||
[Key(4)] public IReadOnlyList<Node> Children { get; }
|
||||
[Key(4)] public ImmutableArray<Node> Children { get; }
|
||||
|
||||
public BoxNode(NodeCommon common, BoxStyle style, Paint paint, Role role, IReadOnlyList<Node> children)
|
||||
{
|
||||
|
|
@ -86,7 +87,7 @@ public sealed class ImageNode : Node
|
|||
public sealed class ButtonNode : Node
|
||||
{
|
||||
[Key(0)] public NodeCommon Common { get; }
|
||||
[Key(1)] public IReadOnlyList<Node> Content { get; }
|
||||
[Key(1)] public ImmutableArray<Node> Content { get; }
|
||||
[Key(2)] public CommandRef OnActivate { get; }
|
||||
[Key(3)] public BoolSource Enabled { get; }
|
||||
|
||||
|
|
@ -197,7 +198,7 @@ public sealed class OverlayNode : Node
|
|||
[Key(1)] public Anchor Anchor { get; }
|
||||
[Key(2)] public bool Modal { get; }
|
||||
[Key(3)] public CommandRef Dismiss { get; }
|
||||
[Key(4)] public IReadOnlyList<Node> Children { get; }
|
||||
[Key(4)] public ImmutableArray<Node> Children { get; }
|
||||
|
||||
public OverlayNode(NodeCommon common, Anchor anchor, bool modal, CommandRef dismiss, IReadOnlyList<Node> children)
|
||||
{
|
||||
|
|
@ -256,7 +257,7 @@ public sealed class UseNode : Node
|
|||
{
|
||||
[Key(0)] public NodeCommon Common { get; }
|
||||
[Key(1)] public CompositionRef Composition { get; }
|
||||
[Key(2)] public IReadOnlyList<Arg> Args { get; }
|
||||
[Key(2)] public ImmutableArray<Arg> Args { get; }
|
||||
|
||||
public UseNode(NodeCommon common, CompositionRef composition, IReadOnlyList<Arg> args)
|
||||
{
|
||||
|
|
@ -344,7 +345,7 @@ public abstract class OptionList
|
|||
[MessagePackObject]
|
||||
public sealed class LiteralOptions : OptionList
|
||||
{
|
||||
[Key(0)] public IReadOnlyList<SelectOption> Options { get; }
|
||||
[Key(0)] public ImmutableArray<SelectOption> Options { get; }
|
||||
|
||||
public LiteralOptions(IReadOnlyList<SelectOption> options)
|
||||
{
|
||||
|
|
@ -502,7 +503,7 @@ public sealed class CommandArg : ArgValue
|
|||
[MessagePackObject]
|
||||
public sealed class SlotArg : ArgValue
|
||||
{
|
||||
[Key(0)] public IReadOnlyList<Node> Nodes { get; }
|
||||
[Key(0)] public ImmutableArray<Node> Nodes { get; }
|
||||
|
||||
public SlotArg(IReadOnlyList<Node> nodes)
|
||||
{
|
||||
|
|
@ -642,7 +643,7 @@ public sealed class SurfaceDocument
|
|||
[Key(2)] public long Version { get; }
|
||||
[Key(3)] public string Title { get; }
|
||||
[Key(4)] public Node Root { get; }
|
||||
[Key(5)] public IReadOnlyList<CommandDecl> Commands { get; }
|
||||
[Key(5)] public ImmutableArray<CommandDecl> Commands { get; }
|
||||
|
||||
public SurfaceDocument(string providerId, string label, long version, string title, Node root, IReadOnlyList<CommandDecl> commands)
|
||||
{
|
||||
|
|
@ -664,7 +665,7 @@ public sealed class CompositionDocument
|
|||
[Key(0)] public string Publisher { get; }
|
||||
[Key(1)] public string Name { get; }
|
||||
[Key(2)] public long Version { get; }
|
||||
[Key(3)] public IReadOnlyList<ParamDecl> Params { get; }
|
||||
[Key(3)] public ImmutableArray<ParamDecl> Params { get; }
|
||||
[Key(4)] public Node Body { get; }
|
||||
|
||||
public CompositionDocument(string publisher, string name, long version, IReadOnlyList<ParamDecl> @params, Node body)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using GameCult.Caching;
|
||||
using MessagePack;
|
||||
|
||||
|
|
@ -327,7 +328,7 @@ public sealed class Bind
|
|||
[MessagePackObject]
|
||||
public sealed class MemberPath
|
||||
{
|
||||
[Key(0)] public IReadOnlyList<MemberStep> Steps { get; }
|
||||
[Key(0)] public ImmutableArray<MemberStep> Steps { get; }
|
||||
|
||||
public MemberPath(IReadOnlyList<MemberStep> steps)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using GameCult.Caching;
|
||||
using MessagePack;
|
||||
|
||||
|
|
@ -438,8 +439,8 @@ public sealed class BoxStyle
|
|||
[Key(16)] public double Grow { get; }
|
||||
[Key(17)] public double Shrink { get; }
|
||||
[Key(18)] public Dimension Basis { get; }
|
||||
[Key(19)] public IReadOnlyList<Dimension> GridColumns { get; }
|
||||
[Key(20)] public IReadOnlyList<Dimension> GridRows { get; }
|
||||
[Key(19)] public ImmutableArray<Dimension> GridColumns { get; }
|
||||
[Key(20)] public ImmutableArray<Dimension> GridRows { get; }
|
||||
|
||||
public BoxStyle(Display display, Direction direction, Wrap wrap, Size2 gap, Edges padding, Edges margin, Size2 size, Size2 minSize, Size2 maxSize, Position position, Edges inset, Overflow overflow, ItemAlign alignItems, ItemAlign alignSelf, ContentAlign alignContent, ContentAlign justifyContent, double grow, double shrink, Dimension basis, IReadOnlyList<Dimension> gridColumns, IReadOnlyList<Dimension> gridRows)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -25,13 +25,13 @@ const named = (name: string): string => `GameCult.Thing.Contract.${name}`;
|
|||
|
||||
const blob = present(bytes);
|
||||
|
||||
// The C# member type of a list slot is IReadOnlyList<T>; cultcache-ts names only List<T> (a stopgap, until
|
||||
// thing2:follow_up:cultcache-ts-readonly-list-name lands). A list slot is required.
|
||||
// The C# member type of a list slot is ImmutableArray<T>, a whole-value holder; cultcache-ts names only List<T>
|
||||
// (a stopgap, until thing2:follow_up:cultcache-ts-readonly-list-name lands). A list slot is required.
|
||||
const readOnlyList = <TItem>(item: Codec<TItem>): Codec<TItem[]> => {
|
||||
const inner = sequence(item);
|
||||
const readOnly: Codec<TItem[]> = {
|
||||
get typeName() {
|
||||
return item.typeName === undefined ? undefined : `System.Collections.Generic.IReadOnlyList<${item.typeName}>`;
|
||||
return item.typeName === undefined ? undefined : `System.Collections.Immutable.ImmutableArray<${item.typeName}>`;
|
||||
},
|
||||
encode: (value) => inner.encode(value),
|
||||
decode: (raw) => inner.decode(raw),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// The deepest tree the payload bound admits decodes and re-encodes on Node's default stack (no --stack-size), and one
|
||||
// level deeper is refused with CultCachePayloadDepthError, never an abort. The Rust test of the same name needs a 16 MiB
|
||||
// thread for this; here the stack holds, and the bound refuses first.
|
||||
// level deeper is refused with CultCachePayloadDepthError, never an abort. The Rust test of the same name holds on its
|
||||
// default test thread too.
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// The type names the package gives its codecs are the C# package's (tests/thing-contract-parity), and the member names
|
||||
// follow the owner's: Rust names that C# flattens into arm classes have one codec per arm, a list slot names
|
||||
// IReadOnlyList<T>, and TextInputNode's slot 2 is inputKind, the camelCase of C# InputKind.
|
||||
// ImmutableArray<T>, and TextInputNode's slot 2 is inputKind, the camelCase of C# InputKind.
|
||||
import assert from "node:assert/strict";
|
||||
import { join } from "node:path";
|
||||
import test from "node:test";
|
||||
|
|
@ -35,13 +35,13 @@ test("Scalar is a Rust name the C# package does not have; ParamName is its type
|
|||
}
|
||||
});
|
||||
|
||||
test("a list slot is named IReadOnlyList, never List, and the element is a type of the C# package", () => {
|
||||
test("a list slot is named ImmutableArray, never List, and the element is a type of the C# package", () => {
|
||||
let lists = 0;
|
||||
for (const [key, codec] of entries) {
|
||||
for (const member of codec.members ?? []) {
|
||||
if (!/List</u.test(member.typeName)) continue;
|
||||
if (!/(List|ImmutableArray)</u.test(member.typeName)) continue;
|
||||
lists++;
|
||||
const element = /^System\.Collections\.Generic\.IReadOnlyList<(.+)>$/u.exec(member.typeName);
|
||||
const element = /^System\.Collections\.Immutable\.ImmutableArray<(.+)>$/u.exec(member.typeName);
|
||||
assert.ok(element !== null, `${key}: ${member.typeName}`);
|
||||
assert.ok(element[1] === "System.String" || names.has(element[1]), `${key}: ${member.typeName}`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ public sealed class DeepTreeTests
|
|||
var wide = new SurfaceDocument("provider.a", "wide", 1, "wide", Boxed("root", children.ToArray()), new List<CommandDecl>());
|
||||
var bytes = Wire.Write(wide);
|
||||
var decoded = (SurfaceDocument)Wire.Read(typeof(SurfaceDocument), bytes);
|
||||
Assert.That(((BoxNode)decoded.Root).Children, Has.Count.EqualTo(999));
|
||||
Assert.That(((BoxNode)decoded.Root).Children, Has.Length.EqualTo(999));
|
||||
Assert.That(Convert.ToHexString(Wire.Write(decoded)), Is.EqualTo(Convert.ToHexString(bytes)));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -105,8 +105,6 @@ public sealed class GoldenTests
|
|||
|
||||
// ---- the store ----
|
||||
|
||||
// surface.cc's catalog is written by cultcache-rs with empty members, so this proves bytes and keys only; the type
|
||||
// names are NameSetTests.
|
||||
[Test]
|
||||
public void StoreRead()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ public sealed class NameSetTests
|
|||
var entry = Wire.Registry.GetRequired(t).ToCatalogEntry();
|
||||
return entry.Members.Select(m => $"{entry.SchemaId}\t{m.Slot}\t{m.MemberName}\t{m.TypeName}");
|
||||
}).ToArray();
|
||||
if (Environment.GetEnvironmentVariable("THING_PARITY_WRITE") == "1")
|
||||
File.WriteAllText(ParityTests.SourceParityPath("catalog-members.tsv"), string.Join("\n", actual) + "\n");
|
||||
Assert.That(actual, Is.EqualTo(Lines("catalog-members.tsv")));
|
||||
Assert.That(actual, Has.Length.GreaterThan(20));
|
||||
}
|
||||
|
|
@ -71,7 +73,7 @@ public sealed class NameSetTests
|
|||
var error = Assert.Throws<InvalidOperationException>(() => Wire.Registry.ResolvePersistedSchema(renamed.SchemaId, new[] { renamed }))!;
|
||||
Assert.That(error.Message, Does.Contain("changed type").And.Contain("System.Int32").And.Contain("System.Int64"));
|
||||
|
||||
var listed = Persisted(typeof(AssetCatalog), "System.Collections.Generic.IReadOnlyList<GameCult.Thing.Contract.AssetEntry>",
|
||||
var listed = Persisted(typeof(AssetCatalog), "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.AssetEntry>",
|
||||
"System.Collections.Generic.List<GameCult.Thing.Contract.AssetEntry>");
|
||||
Assert.Throws<InvalidOperationException>(() => Wire.Registry.ResolvePersistedSchema(listed.SchemaId, new[] { listed }),
|
||||
"a store written when Assets was a List is refused");
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ public sealed class ParityTests
|
|||
{
|
||||
private static string ParityPath(string file) => Path.Combine(AppContext.BaseDirectory, "parity", file);
|
||||
|
||||
private static string SourceParityPath(string file)
|
||||
internal static string SourceParityPath(string file)
|
||||
{
|
||||
for (var here = new DirectoryInfo(AppContext.BaseDirectory); here != null; here = here.Parent)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ namespace GameCult.Thing.Contract.Tests;
|
|||
public sealed class ReadOnlyListTests
|
||||
{
|
||||
private static bool IsMutableCollection(Type type) =>
|
||||
!(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Immutable.ImmutableArray<>)) &&
|
||||
(typeof(IList).IsAssignableFrom(type) || type.GetInterfaces().Concat(new[] { type }).Any(i =>
|
||||
i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(ICollection<>) || i.GetGenericTypeDefinition() == typeof(IDictionary<,>))));
|
||||
|
||||
|
|
@ -37,6 +38,35 @@ public sealed class ReadOnlyListTests
|
|||
Assert.That(checkedProperties, Is.GreaterThan(200));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CultLib's element-id walk owns the elements of a list held as a class or interface of
|
||||
/// [MessagePackObject] or [Union] elements, and demands an id on each. A list held as an ImmutableArray is one
|
||||
/// whole value the walk never enters, so the contract holds every list that way.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void NoKeyMemberIsAnOwnedListOfContractObjects()
|
||||
{
|
||||
bool IsContractObject(Type type) =>
|
||||
type.GetCustomAttribute<MessagePackObjectAttribute>() != null || type.GetCustomAttributes<UnionAttribute>(false).Any();
|
||||
var offenders = new List<string>();
|
||||
var checkedMembers = 0;
|
||||
foreach (var type in typeof(CommandResult).Assembly.GetExportedTypes())
|
||||
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
if (property.GetCustomAttribute<KeyAttribute>() is null) continue;
|
||||
checkedMembers++;
|
||||
var t = property.PropertyType;
|
||||
if (t.IsValueType) continue;
|
||||
var element = t.GetInterfaces().Concat(new[] { t })
|
||||
.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>))
|
||||
.Select(i => i.GetGenericArguments()[0]).FirstOrDefault();
|
||||
if (element != null && IsContractObject(element)) offenders.Add($"{type.Name}.{property.Name}: {t.Name}");
|
||||
}
|
||||
|
||||
Assert.That(offenders, Is.Empty);
|
||||
Assert.That(checkedMembers, Is.GreaterThan(100));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryListParameterIsCopiedAndTheCopyCannotGrow()
|
||||
{
|
||||
|
|
@ -76,6 +106,11 @@ public sealed class ReadOnlyListTests
|
|||
args[index] = null;
|
||||
var list = Assert.Throws<ThingDomainException>(() => door.Call(args), $"{door.Name}: nil list")!;
|
||||
Assert.That(list.Bound, Is.EqualTo("present"), door.Name);
|
||||
|
||||
// What a nil list decodes to: a default (uninitialised) ImmutableArray, which throws on first use.
|
||||
args[index] = Activator.CreateInstance(typeof(System.Collections.Immutable.ImmutableArray<>).MakeGenericType(element));
|
||||
var uninitialised = Assert.Throws<ThingDomainException>(() => door.Call(args), $"{door.Name}: default array")!;
|
||||
Assert.That(uninitialised.Bound, Is.EqualTo("present"), door.Name);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -91,7 +126,7 @@ public sealed class ReadOnlyListTests
|
|||
Assert.That(box.Children, Is.Not.SameAs(array));
|
||||
Assert.That(box.Children is Node[], Is.False, "the held list is the caller's array type");
|
||||
var boxed = (BoxNode)Builders.Boxed("c", child, other);
|
||||
Assert.That(boxed.Children, Has.Count.EqualTo(2));
|
||||
Assert.That(boxed.Children, Has.Length.EqualTo(2));
|
||||
|
||||
foreach (var (door, index, element) in ListParameters())
|
||||
{
|
||||
|
|
|
|||
|
|
@ -25,6 +25,6 @@ public sealed class SlotNodeTests
|
|||
var root = (BoxNode)composition.Body;
|
||||
var slot = (SlotNode)root.Children[^1];
|
||||
Assert.That(slot.Param.Name, Is.EqualTo("body"));
|
||||
Assert.That(root.Children, Has.Count.EqualTo(3));
|
||||
Assert.That(root.Children, Has.Length.EqualTo(3));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ The names the C# package `GameCult.Thing.Contract` gives its types. The C# packa
|
|||
|
||||
| File | Rows |
|
||||
|---|---|
|
||||
| `catalog-members.tsv` | One row per document slot, `schemaId`, `slot`, `memberName`, `typeName`, as `Wire.Registry`'s catalog entries print them. A list slot reads `System.Collections.Generic.IReadOnlyList<GameCult.Thing.Contract.X>`. |
|
||||
| `catalog-members.tsv` | One row per document slot, `schemaId`, `slot`, `memberName`, `typeName`, as `Wire.Registry`'s catalog entries print them. A list slot reads `System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.X>`. |
|
||||
| `type-names.txt` | The full name of every public type in `GameCult.Thing.Contract`, sorted ordinally. |
|
||||
| `written-by-cs.cc` | A single-file store the C# package's CultCache wrote from its own builders, one record of each kind. `packages/thing-contract/test/parity.test.ts` reads it. Regenerate: `THING_PARITY_WRITE=1 dotnet test tests/GameCult.Thing.Contract.Tests` (`ParityTests.cs`). |
|
||||
| `written-by-ts.cc` | The same five records, written by `@gamecult/thing-contract`'s CultCache. `ParityTests.cs` reads it. Regenerate: `THING_PARITY_WRITE=1 npm test` in `packages/thing-contract` (`parity.test.ts`). |
|
||||
|
|
|
|||
|
|
@ -1,27 +1,27 @@
|
|||
sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 0 InvocationId System.String
|
||||
sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 1 SurfaceKey System.String
|
||||
sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 2 SurfaceVersion System.Int64
|
||||
sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 3 Command System.String
|
||||
sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 4 Payload GameCult.Thing.Contract.RecordPayload
|
||||
sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 5 Captured System.Collections.Generic.IReadOnlyList<GameCult.Thing.Contract.CapturedInput>
|
||||
sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 6 Client System.String
|
||||
sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 7 IssuedAt System.String
|
||||
sha256:186674dff7658d23646b25b28f54d27b3f05cee34b51a631580be65002c41aa8 8 Delegation System.String
|
||||
sha256:3d751a6fb07487b0c84cf0ae1c4fe55e5ef0c1656eab41ca3236846a638bdd3f 0 ProviderId System.String
|
||||
sha256:3d751a6fb07487b0c84cf0ae1c4fe55e5ef0c1656eab41ca3236846a638bdd3f 1 CatalogId System.String
|
||||
sha256:3d751a6fb07487b0c84cf0ae1c4fe55e5ef0c1656eab41ca3236846a638bdd3f 2 Version System.Int64
|
||||
sha256:3d751a6fb07487b0c84cf0ae1c4fe55e5ef0c1656eab41ca3236846a638bdd3f 3 Assets System.Collections.Generic.IReadOnlyList<GameCult.Thing.Contract.AssetEntry>
|
||||
sha256:531f96346fbff5160daedc82ada2ad5cb3d0477631d2b580ccd1a2834f041b32 0 Publisher System.String
|
||||
sha256:531f96346fbff5160daedc82ada2ad5cb3d0477631d2b580ccd1a2834f041b32 1 Name System.String
|
||||
sha256:531f96346fbff5160daedc82ada2ad5cb3d0477631d2b580ccd1a2834f041b32 2 Version System.Int64
|
||||
sha256:531f96346fbff5160daedc82ada2ad5cb3d0477631d2b580ccd1a2834f041b32 3 Params System.Collections.Generic.IReadOnlyList<GameCult.Thing.Contract.ParamDecl>
|
||||
sha256:531f96346fbff5160daedc82ada2ad5cb3d0477631d2b580ccd1a2834f041b32 4 Body GameCult.Thing.Contract.Node
|
||||
sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 0 ProviderId System.String
|
||||
sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 1 Label System.String
|
||||
sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 2 Version System.Int64
|
||||
sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 3 Title System.String
|
||||
sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 4 Root GameCult.Thing.Contract.Node
|
||||
sha256:da2ca90e225d803191fd9a31ad1894e7dfab186f82e892717be8130d2e7ebf33 5 Commands System.Collections.Generic.IReadOnlyList<GameCult.Thing.Contract.CommandDecl>
|
||||
sha256:054253624267f9b37445b05f7fcf5c4de6f40ad16fa1427eb596c56e5471383e 0 ProviderId System.String
|
||||
sha256:054253624267f9b37445b05f7fcf5c4de6f40ad16fa1427eb596c56e5471383e 1 CatalogId System.String
|
||||
sha256:054253624267f9b37445b05f7fcf5c4de6f40ad16fa1427eb596c56e5471383e 2 Version System.Int64
|
||||
sha256:054253624267f9b37445b05f7fcf5c4de6f40ad16fa1427eb596c56e5471383e 3 Assets System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.AssetEntry>
|
||||
sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 0 ProviderId System.String
|
||||
sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 1 Label System.String
|
||||
sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 2 Version System.Int64
|
||||
sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 3 Title System.String
|
||||
sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 4 Root GameCult.Thing.Contract.Node
|
||||
sha256:9611b1313cb4cd285ba02e4170f5204c1fb009c52a058c864c0382abd26202bc 5 Commands System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CommandDecl>
|
||||
sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 0 InvocationId System.String
|
||||
sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 1 SurfaceKey System.String
|
||||
sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 2 SurfaceVersion System.Int64
|
||||
sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 3 Command System.String
|
||||
sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 4 Payload GameCult.Thing.Contract.RecordPayload
|
||||
sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 5 Captured System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CapturedInput>
|
||||
sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 6 Client System.String
|
||||
sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 7 IssuedAt System.String
|
||||
sha256:9749a22fe62c6de13e396697af2ac2dafb713eb21e30c3ed0eda21ba68085647 8 Delegation System.String
|
||||
sha256:bcc1513ee682d1d58746836d4d2e98df086eb62c3fd9a797a2e72e561437393e 0 Publisher System.String
|
||||
sha256:bcc1513ee682d1d58746836d4d2e98df086eb62c3fd9a797a2e72e561437393e 1 Name System.String
|
||||
sha256:bcc1513ee682d1d58746836d4d2e98df086eb62c3fd9a797a2e72e561437393e 2 Version System.Int64
|
||||
sha256:bcc1513ee682d1d58746836d4d2e98df086eb62c3fd9a797a2e72e561437393e 3 Params System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.ParamDecl>
|
||||
sha256:bcc1513ee682d1d58746836d4d2e98df086eb62c3fd9a797a2e72e561437393e 4 Body GameCult.Thing.Contract.Node
|
||||
sha256:e0273199abadb60da0bd9a7bcb863e131ef08bb2284f7eb729f76159caa369fd 0 InvocationId System.String
|
||||
sha256:e0273199abadb60da0bd9a7bcb863e131ef08bb2284f7eb729f76159caa369fd 1 Seq System.Int32
|
||||
sha256:e0273199abadb60da0bd9a7bcb863e131ef08bb2284f7eb729f76159caa369fd 2 Outcome GameCult.Thing.Contract.Outcome
|
||||
|
|
|
|||
|
Binary file not shown.
Binary file not shown.
Loading…
Reference in a new issue