Thing 2.0 cut 2: thing-core state port and thing-testkit (testkit-ports) #7
22 changed files with 1504 additions and 74 deletions
19
Cargo.lock
generated
19
Cargo.lock
generated
|
|
@ -378,6 +378,25 @@ dependencies = [
|
|||
"rmp-serde",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"thing-testkit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thing-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"thing-contract",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thing-testkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cultcache-rs",
|
||||
"rmp-serde",
|
||||
"thing-contract",
|
||||
"thing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -12,4 +12,5 @@ serde = { workspace = true }
|
|||
serde_bytes = "0.11"
|
||||
|
||||
[dev-dependencies]
|
||||
thing-testkit = { path = "../thing-testkit" }
|
||||
rmp-serde = { workspace = true }
|
||||
|
|
|
|||
|
|
@ -2,23 +2,24 @@
|
|||
//! byte. The TypeScript and C# packages and core are held to these files; none of them writes
|
||||
//! one. `THING_BLESS=1` rewrites them; any other run compares.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt::Debug;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use common::*;
|
||||
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use thing_testkit::{build::*, golden, store};
|
||||
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry};
|
||||
use thing_contract::*;
|
||||
|
||||
const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z";
|
||||
fn goldens_dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
||||
}
|
||||
|
||||
// A value that must never appear in a refusal.
|
||||
const CANARY: &str = "CANARY-7f3a91c2";
|
||||
|
||||
fn golden<T: DatabaseEntry + PartialEq + Debug>(name: &str, value: &T) -> String {
|
||||
let produced = rmp_serde::to_vec(value).unwrap();
|
||||
let committed = golden_bytes(&format!("{name}.bin"), &produced);
|
||||
let committed = golden::check(&goldens_dir(), &format!("{name}.bin"), &produced);
|
||||
let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
assert_eq!(&decoded, value, "{name}: the golden does not decode to the constructed value");
|
||||
assert_eq!(rmp_serde::to_vec(&decoded).unwrap(), committed, "{name}: re-encoding changed the bytes");
|
||||
|
|
@ -416,26 +417,17 @@ fn asset_catalog() -> AssetCatalog {
|
|||
|
||||
/// A store with one record of each kind, written by cultcache-rs under a pinned clock.
|
||||
fn write_store(path: &std::path::Path) {
|
||||
let _ = std::fs::remove_file(path);
|
||||
let mut cache = CultCache::new();
|
||||
ThingContract.register_entries(&mut cache).unwrap();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
|
||||
let mut cache = store::create(path);
|
||||
let surface = full_surface();
|
||||
let composition = full_composition();
|
||||
let invocation = invocation();
|
||||
let result = CommandResult::pending(&invocation, seq(1), "working");
|
||||
let catalog = asset_catalog();
|
||||
put(&mut cache, &surface.record_key(), &surface);
|
||||
put(&mut cache, &composition.record_key(), &composition);
|
||||
put(&mut cache, &invocation.record_key(), &invocation);
|
||||
put(&mut cache, &result.record_key(), &result);
|
||||
put(&mut cache, &catalog.record_key(), &catalog);
|
||||
}
|
||||
|
||||
fn put<T: DatabaseEntry>(cache: &mut CultCache, key: &str, value: &T) {
|
||||
let (mut envelope, _) = cache.prepare_entry(key, value).unwrap();
|
||||
envelope.stored_at = PINNED_CLOCK.into();
|
||||
cache.put_envelope::<T>(envelope).unwrap();
|
||||
store::put_pinned(&mut cache, &surface.record_key(), &surface);
|
||||
store::put_pinned(&mut cache, &composition.record_key(), &composition);
|
||||
store::put_pinned(&mut cache, &invocation.record_key(), &invocation);
|
||||
store::put_pinned(&mut cache, &result.record_key(), &result);
|
||||
store::put_pinned(&mut cache, &catalog.record_key(), &catalog);
|
||||
}
|
||||
|
||||
fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope {
|
||||
|
|
@ -443,19 +435,11 @@ fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope
|
|||
key: key.into(),
|
||||
r#type: T::TYPE.into(),
|
||||
payload,
|
||||
stored_at: PINNED_CLOCK.into(),
|
||||
stored_at: store::PINNED_CLOCK.into(),
|
||||
schema_id: Some(T::TYPE.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_store(path: &std::path::Path) -> CultCache {
|
||||
let mut cache = CultCache::new();
|
||||
ThingContract.register_entries(&mut cache).unwrap();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
|
||||
cache.pull_all_backing_stores().unwrap();
|
||||
cache
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn goldens_match() {
|
||||
let mut names = BTreeSet::new();
|
||||
|
|
@ -472,7 +456,7 @@ fn goldens_match() {
|
|||
// that no case names is an orphan.
|
||||
let refusals = refusal_payloads();
|
||||
for (name, bytes) in &refusals {
|
||||
golden_bytes(&format!("{name}.bin"), bytes);
|
||||
golden::check(&goldens_dir(), &format!("{name}.bin"), bytes);
|
||||
names.insert((*name).to_string());
|
||||
}
|
||||
let on_disk: BTreeSet<String> = std::fs::read_dir(goldens_dir())
|
||||
|
|
@ -485,10 +469,10 @@ fn goldens_match() {
|
|||
// The store: one record of each kind, written under a pinned clock, byte for byte.
|
||||
let scratch = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("goldens-surface.cc");
|
||||
write_store(&scratch);
|
||||
let committed = golden_bytes("surface.cc", &std::fs::read(&scratch).unwrap());
|
||||
let committed = golden::check(&goldens_dir(), "surface.cc", &std::fs::read(&scratch).unwrap());
|
||||
let reopened = goldens_dir().join("surface.cc");
|
||||
assert_eq!(std::fs::read(&reopened).unwrap(), committed);
|
||||
let cache = open_store(&scratch);
|
||||
let cache = store::open(&scratch);
|
||||
let surface = full_surface();
|
||||
assert_eq!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap(), Some(surface));
|
||||
let composition = full_composition();
|
||||
|
|
@ -572,7 +556,7 @@ fn refusal_payloads() -> Vec<(&'static str, Vec<u8>)> {
|
|||
#[test]
|
||||
fn refusal_cases() {
|
||||
let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect();
|
||||
let committed = |name: &str| golden_bytes(&format!("{name}.bin"), &payloads[name]);
|
||||
let committed = |name: &str| golden::check(&goldens_dir(), &format!("{name}.bin"), &payloads[name]);
|
||||
|
||||
// Stored under their key, each is refused naming the kind and the key, never a value.
|
||||
let cases: [(&str, &str, &str); 7] = [
|
||||
|
|
@ -679,15 +663,12 @@ fn deep_tree_body() {
|
|||
};
|
||||
|
||||
let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
{
|
||||
let mut cache = CultCache::new();
|
||||
ThingContract.register_entries(&mut cache).unwrap();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
|
||||
put(&mut cache, &deep.record_key(), &deep);
|
||||
put(&mut cache, &wide.record_key(), &wide);
|
||||
let mut cache = store::create(&path);
|
||||
store::put_pinned(&mut cache, &deep.record_key(), &deep);
|
||||
store::put_pinned(&mut cache, &wide.record_key(), &wide);
|
||||
}
|
||||
let cache = open_store(&path);
|
||||
let cache = store::open(&path);
|
||||
assert_eq!(cache.get::<SurfaceDocument>(&deep.record_key()).unwrap(), Some(deep));
|
||||
assert_eq!(cache.get::<SurfaceDocument>(&wide.record_key()).unwrap(), Some(wide));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,14 +4,13 @@
|
|||
//! TypeScript packages hold no list of their own and are held to every row.
|
||||
//! `THING_BLESS=1` rewrites `goldens/nil-positions.tsv`; any other run compares.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use common::*;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use thing_contract::*;
|
||||
use thing_testkit::golden;
|
||||
|
||||
/// One MessagePack value's byte span; `kids` is set for arrays only (maps are never walked).
|
||||
struct Span {
|
||||
|
|
@ -79,7 +78,7 @@ fn elements(span: &Span, prefix: &str, out: &mut Vec<(String, usize, usize)>) {
|
|||
/// The rows of one golden: nil spliced over each element, decoded as `T`. An accepted variant
|
||||
/// must re-encode to the spliced bytes.
|
||||
fn rows<T: DeserializeOwned + Serialize + Debug>(file: &str, out: &mut String) -> (usize, usize) {
|
||||
let bytes = std::fs::read(goldens_dir().join(format!("{file}.bin"))).unwrap();
|
||||
let bytes = golden::read(&goldens_dir(), &format!("{file}.bin"));
|
||||
let mut found = Vec::new();
|
||||
elements(&item(&bytes, 0), "", &mut found);
|
||||
let (mut accepted, mut refused) = (0, 0);
|
||||
|
|
@ -125,5 +124,9 @@ fn nil_positions_match() {
|
|||
for (file, (accepted, refused)) in &totals {
|
||||
println!("NILTOTAL {file} accept={accepted} refuse={refused}");
|
||||
}
|
||||
golden_bytes("nil-positions.tsv", table.as_bytes());
|
||||
golden::check(&goldens_dir(), "nil-positions.tsv", table.as_bytes());
|
||||
}
|
||||
|
||||
fn goldens_dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,4 @@
|
|||
mod common;
|
||||
|
||||
use common::*;
|
||||
use thing_testkit::build::*;
|
||||
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload};
|
||||
use serde::Deserialize;
|
||||
use serde::de::IntoDeserializer;
|
||||
|
|
|
|||
9
crates/thing-core/Cargo.toml
Normal file
9
crates/thing-core/Cargo.toml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "thing-core"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
thing-contract = { path = "../thing-contract" }
|
||||
4
crates/thing-core/src/lib.rs
Normal file
4
crates/thing-core/src/lib.rs
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
//! Thing's core: a function of documents, state, input and time. It touches the world only
|
||||
//! through ports; it reads no clock, spawns nothing and awaits nothing.
|
||||
|
||||
pub mod port;
|
||||
137
crates/thing-core/src/port.rs
Normal file
137
crates/thing-core/src/port.rs
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
//! What core may ask of state. The port reads and queues changes; nothing in it writes, and
|
||||
//! it never awaits: core drains queued changes inside its frame.
|
||||
|
||||
use thing_contract::{AssetCatalog, CommandResult, CompositionDocument, ProviderId, RecordKey, SchemaId, SurfaceDocument};
|
||||
|
||||
/// One record: the provider that holds it, its schema and its key.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Address {
|
||||
pub provider: ProviderId,
|
||||
pub schema: SchemaId,
|
||||
pub key: RecordKey,
|
||||
}
|
||||
|
||||
/// Every record of one provider and schema whose key starts with `key_prefix`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Prefix {
|
||||
pub provider: ProviderId,
|
||||
pub schema: SchemaId,
|
||||
pub key_prefix: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Interest {
|
||||
Record(Address),
|
||||
Prefix(Prefix),
|
||||
}
|
||||
|
||||
impl Prefix {
|
||||
pub fn matches(&self, address: &Address) -> bool {
|
||||
self.provider == address.provider
|
||||
&& self.schema == address.schema
|
||||
&& address.key.as_str().starts_with(&self.key_prefix)
|
||||
}
|
||||
}
|
||||
|
||||
impl Interest {
|
||||
/// Whether a change at `address` is of interest.
|
||||
pub fn matches(&self, address: &Address) -> bool {
|
||||
match self {
|
||||
Interest::Record(record) => record == address,
|
||||
Interest::Prefix(prefix) => prefix.matches(address),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SubscriptionId(pub u64);
|
||||
|
||||
/// A contract record the port carries, decoded.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Record {
|
||||
Surface(SurfaceDocument),
|
||||
Composition(CompositionDocument),
|
||||
Result(CommandResult),
|
||||
Catalog(AssetCatalog),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Entry {
|
||||
pub address: Address,
|
||||
pub record: Record,
|
||||
}
|
||||
|
||||
/// A record the contract refused. `detail` is the decoder's message, which never carries a
|
||||
/// value.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Refusal {
|
||||
pub address: Address,
|
||||
pub kind: SchemaId,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
/// The answer for one address. A refusal is never absence.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Lookup {
|
||||
Present(Entry),
|
||||
Absent,
|
||||
Refused(Refusal),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Change {
|
||||
Upsert(Entry),
|
||||
Delete(Address),
|
||||
Refused(Refusal),
|
||||
}
|
||||
|
||||
/// Core's view of state. Object safe, and no method writes.
|
||||
pub trait StatePort {
|
||||
fn read(&self, address: &Address) -> Lookup;
|
||||
|
||||
/// One lookup per record under the prefix, in key order.
|
||||
fn list(&self, prefix: &Prefix) -> Vec<Lookup>;
|
||||
|
||||
fn subscribe(&mut self, interest: Interest) -> SubscriptionId;
|
||||
|
||||
fn unsubscribe(&mut self, id: SubscriptionId);
|
||||
|
||||
/// Every change since the last drain that some interest matched when it happened, in mutation
|
||||
/// order (unsubscribing does not recall changes already queued),
|
||||
/// each once.
|
||||
fn drain(&mut self) -> Vec<Change>;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn address(provider: &str, schema: &str, key: &str) -> Address {
|
||||
Address { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key: RecordKey::new(key) }
|
||||
}
|
||||
|
||||
fn prefix(provider: &str, schema: &str, key_prefix: &str) -> Prefix {
|
||||
Prefix { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key_prefix: key_prefix.into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_matches_provider_schema_and_key_prefix_together() {
|
||||
let under = prefix("p", "s", "row-");
|
||||
assert!(under.matches(&address("p", "s", "row-1")));
|
||||
assert!(under.matches(&address("p", "s", "row-")));
|
||||
assert!(!under.matches(&address("q", "s", "row-1")));
|
||||
assert!(!under.matches(&address("p", "t", "row-1")));
|
||||
assert!(!under.matches(&address("p", "s", "col-1")));
|
||||
assert!(!under.matches(&address("p", "s", "ro")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_interest_matches_only_its_address() {
|
||||
let interest = Interest::Record(address("p", "s", "k"));
|
||||
assert!(interest.matches(&address("p", "s", "k")));
|
||||
assert!(!interest.matches(&address("p", "s", "k2")));
|
||||
assert!(!interest.matches(&address("q", "s", "k")));
|
||||
assert!(Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "k2")));
|
||||
assert!(!Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "j")));
|
||||
}
|
||||
}
|
||||
15
crates/thing-testkit/Cargo.toml
Normal file
15
crates/thing-testkit/Cargo.toml
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
[package]
|
||||
name = "thing-testkit"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
thing-contract = { path = "../thing-contract" }
|
||||
cultcache-rs = { workspace = true }
|
||||
thing-core = { path = "../thing-core" }
|
||||
anyhow = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
rmp-serde = { workspace = true }
|
||||
22
crates/thing-testkit/fixtures/README.md
Normal file
22
crates/thing-testkit/fixtures/README.md
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# thing-testkit fixtures
|
||||
|
||||
Each `.cc` is a CultCache single-file store of contract documents, written under the pinned
|
||||
clock `2026-01-01T00:00:00Z`. The builders are `thing_testkit::fixture`; the bytes below are
|
||||
frozen, and a normal test run only compares and reads them. The rows are the fixture table of
|
||||
`docs/thing2-build-spec.md` section 2.5; map rules are those of the build spec.
|
||||
|
||||
| File | Holds | Map rules |
|
||||
|---|---|---|
|
||||
| `f01-swarm-dashboard.surface.cc` | One surface: a Grid Box root, a Text bound with a Number Format, a Repeat over a RecordsSource prefix whose template binds Item members, and a Button whose CommandRef is declared | 6, 9 |
|
||||
| `f09-composition-stack.surface.cc` | One surface whose Use passes one argument of each ArgValue arm and a Slot holding a second Use (two levels), and the publisher CompositionDocument both name | 5 |
|
||||
| `f10-hostile.surface.cc` | Four surfaces, one hostile shape each: an undeclared CommandRef, a duplicate id after expansion, an unresolved Use, and a Bind whose schema no fixture provides; plus the one composition (`dup`) the duplicate-id surface expands | 4, 5, 6 |
|
||||
|
||||
A surface whose bytes the contract refuses (an unknown union arm) cannot live in a store: that
|
||||
case is `crates/thing-contract/tests/goldens/node-unknown-arm.bin`, read in place and fed to
|
||||
`MemState::put_raw`.
|
||||
|
||||
## Regenerate
|
||||
|
||||
`THING_BLESS=1 cargo test -p thing-testkit --test fixtures every_fixture_round_trips` rewrites
|
||||
the files through `golden::check`, the one bless door; review the diff before committing. Run
|
||||
the tests without `THING_BLESS` to compare.
|
||||
BIN
crates/thing-testkit/fixtures/f01-swarm-dashboard.surface.cc
Normal file
BIN
crates/thing-testkit/fixtures/f01-swarm-dashboard.surface.cc
Normal file
Binary file not shown.
BIN
crates/thing-testkit/fixtures/f09-composition-stack.surface.cc
Normal file
BIN
crates/thing-testkit/fixtures/f09-composition-stack.surface.cc
Normal file
Binary file not shown.
BIN
crates/thing-testkit/fixtures/f10-hostile.surface.cc
Normal file
BIN
crates/thing-testkit/fixtures/f10-hostile.surface.cc
Normal file
Binary file not shown.
|
|
@ -1,31 +1,8 @@
|
|||
//! Constructors for the values the goldens and the other tests share. Every value is built
|
||||
//! through the crate's public types; no bytes are spelled here.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
//! Constructors for the values the contract goldens, the fixtures and the other tests share.
|
||||
//! Every value is built through the crate's public types; no bytes are spelled here.
|
||||
|
||||
use thing_contract::*;
|
||||
|
||||
pub fn goldens_dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
||||
}
|
||||
|
||||
pub fn blessing() -> bool {
|
||||
std::env::var("THING_BLESS").as_deref() == Ok("1")
|
||||
}
|
||||
|
||||
/// Bless the file or compare against it. Returns the committed bytes.
|
||||
pub fn golden_bytes(file: &str, produced: &[u8]) -> Vec<u8> {
|
||||
let path = goldens_dir().join(file);
|
||||
if blessing() {
|
||||
std::fs::write(&path, produced).unwrap_or_else(|error| panic!("{file}: {error}"));
|
||||
}
|
||||
let committed = std::fs::read(&path).unwrap_or_else(|error| panic!("{file}: {error}"));
|
||||
assert_eq!(committed, produced, "{file}: the committed golden differs from what the crate writes");
|
||||
committed
|
||||
}
|
||||
|
||||
pub fn seq(value: i32) -> Seq {
|
||||
Seq::new(value).unwrap()
|
||||
}
|
||||
341
crates/thing-testkit/src/fixture.rs
Normal file
341
crates/thing-testkit/src/fixture.rs
Normal file
|
|
@ -0,0 +1,341 @@
|
|||
//! The frozen fixture stores: typed contract documents built here, encoded through CultCache
|
||||
//! under a pinned clock, committed under `fixtures/`, and loaded back through the same door
|
||||
//! every consumer uses. `THING_BLESS=1` through `golden::check` is the only writer.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use cultcache_rs::CultCache;
|
||||
use thing_contract::*;
|
||||
|
||||
use crate::build::*;
|
||||
use crate::{golden, store};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Fixture {
|
||||
F01SwarmDashboard,
|
||||
F09CompositionStack,
|
||||
F10Hostile,
|
||||
}
|
||||
|
||||
/// The documents of one fixture, each kind in record-key order.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FixtureSet {
|
||||
pub surfaces: Vec<SurfaceDocument>,
|
||||
pub compositions: Vec<CompositionDocument>,
|
||||
pub catalogs: Vec<AssetCatalog>,
|
||||
}
|
||||
|
||||
impl FixtureSet {
|
||||
fn new(
|
||||
mut surfaces: Vec<SurfaceDocument>,
|
||||
mut compositions: Vec<CompositionDocument>,
|
||||
mut catalogs: Vec<AssetCatalog>,
|
||||
) -> Self {
|
||||
surfaces.sort_by_key(SurfaceDocument::record_key);
|
||||
compositions.sort_by_key(CompositionDocument::record_key);
|
||||
catalogs.sort_by_key(AssetCatalog::record_key);
|
||||
Self { surfaces, compositions, catalogs }
|
||||
}
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
pub const ALL: [Fixture; 3] = [Fixture::F01SwarmDashboard, Fixture::F09CompositionStack, Fixture::F10Hostile];
|
||||
|
||||
pub fn file_name(self) -> &'static str {
|
||||
match self {
|
||||
Fixture::F01SwarmDashboard => "f01-swarm-dashboard.surface.cc",
|
||||
Fixture::F09CompositionStack => "f09-composition-stack.surface.cc",
|
||||
Fixture::F10Hostile => "f10-hostile.surface.cc",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures")
|
||||
}
|
||||
|
||||
/// The documents the builders produce.
|
||||
pub fn build(self) -> FixtureSet {
|
||||
match self {
|
||||
Fixture::F01SwarmDashboard => FixtureSet::new(vec![swarm_dashboard()], vec![], vec![]),
|
||||
Fixture::F09CompositionStack => FixtureSet::new(vec![composition_stack()], vec![stack_card()], vec![]),
|
||||
Fixture::F10Hostile => FixtureSet::new(hostile(), vec![hostile_dup()], vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode the built documents into a store and bless or compare the committed file; returns
|
||||
/// the committed bytes.
|
||||
pub fn write(self) -> Vec<u8> {
|
||||
let scratch = std::env::temp_dir().join(format!("thing-testkit-{}-{}", std::process::id(), self.file_name()));
|
||||
let mut cache = store::create(&scratch);
|
||||
let set = self.build();
|
||||
for surface in &set.surfaces {
|
||||
store::put_pinned(&mut cache, &surface.record_key(), surface);
|
||||
}
|
||||
for composition in &set.compositions {
|
||||
store::put_pinned(&mut cache, &composition.record_key(), composition);
|
||||
}
|
||||
for catalog in &set.catalogs {
|
||||
store::put_pinned(&mut cache, &catalog.record_key(), catalog);
|
||||
}
|
||||
let bytes = std::fs::read(&scratch).unwrap();
|
||||
let _ = std::fs::remove_file(&scratch);
|
||||
golden::check(&Self::dir(), self.file_name(), &bytes)
|
||||
}
|
||||
|
||||
|
||||
/// The committed store, opened through the contract. Opening creates a lock file beside the
|
||||
/// store, so this opens a copy in a directory of its own (process id and a serial), removed
|
||||
/// once the store is read: the fixtures directory is never written.
|
||||
pub fn open(self) -> CultCache {
|
||||
static OPENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let serial = OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let work = std::env::temp_dir().join(format!("thing-testkit-open-{}-{serial}", std::process::id()));
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
let copy = work.join(self.file_name());
|
||||
std::fs::copy(Self::dir().join(self.file_name()), ©).unwrap();
|
||||
let cache = store::open(©);
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
cache
|
||||
}
|
||||
|
||||
/// The committed store, decoded through the contract.
|
||||
pub fn load(self) -> FixtureSet {
|
||||
let cache = self.open();
|
||||
FixtureSet::new(cache.get_all().unwrap(), cache.get_all().unwrap(), cache.get_all().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
const SWARM: &str = "provider.swarm";
|
||||
const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1";
|
||||
|
||||
fn swarm_ref(key: &str) -> StateSource {
|
||||
StateSource::Record(StateRef {
|
||||
provider: Some(ProviderId::new(SWARM)),
|
||||
schema: SchemaId::new(SWARM_SCHEMA),
|
||||
key: RecordKey::new(key),
|
||||
})
|
||||
}
|
||||
|
||||
fn swarm_dashboard() -> SurfaceDocument {
|
||||
let load = Bind {
|
||||
source: swarm_ref("summary"),
|
||||
member: path(&["load"]),
|
||||
format: Some(Format::Number(NumberFormat { precision: count(1), percent: true, unit: None })),
|
||||
};
|
||||
let load_text = Node::Text(TextNode {
|
||||
common: common("load"),
|
||||
content: TextSource::Bound(load),
|
||||
style_token: "title".into(),
|
||||
wrap: false,
|
||||
max_lines: Some(count(1)),
|
||||
selectable: false,
|
||||
});
|
||||
let minds = Node::Repeat(RepeatNode {
|
||||
common: common("minds"),
|
||||
collection: CollectionSource::Records(RecordsSource {
|
||||
provider: Some(ProviderId::new(SWARM)),
|
||||
schema: SchemaId::new(SWARM_SCHEMA),
|
||||
key_prefix: "mind-".into(),
|
||||
}),
|
||||
key_member: path(&["id"]),
|
||||
template: std::boxed::Box::new(Node::Text(TextNode {
|
||||
common: common("mind-name"),
|
||||
content: TextSource::Bound(item_bind(path(&["name"]))),
|
||||
style_token: "body".into(),
|
||||
wrap: false,
|
||||
max_lines: Some(count(1)),
|
||||
selectable: true,
|
||||
})),
|
||||
});
|
||||
let restart = Node::Button(ButtonNode {
|
||||
common: common("restart"),
|
||||
content: vec![text("restart-label", "Restart")],
|
||||
on_activate: command("restart"),
|
||||
enabled: lit_bool(true),
|
||||
});
|
||||
let mut grid = style();
|
||||
grid.display = Display::Grid;
|
||||
grid.grid_columns = vec![Dimension::Percent(Scalar { value: 50.0 }), Dimension::Percent(Scalar { value: 50.0 })];
|
||||
grid.grid_rows = vec![Dimension::Auto, Dimension::Auto];
|
||||
let root = Node::Box(BoxNode {
|
||||
common: common("root"),
|
||||
style: grid,
|
||||
paint: plain_paint(),
|
||||
role: Role::Group,
|
||||
children: vec![load_text, minds, restart],
|
||||
});
|
||||
SurfaceDocument {
|
||||
provider_id: ProviderId::new(SWARM),
|
||||
label: seg("dashboard"),
|
||||
version: ver(1),
|
||||
title: "Swarm".into(),
|
||||
root,
|
||||
commands: vec![CommandDecl {
|
||||
id: CommandId::new("restart"),
|
||||
payload_schema: SchemaId::new("gamecult.thing.test.restart.v1"),
|
||||
captures: vec![],
|
||||
confirm: Some("Restart the swarm?".into()),
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
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 rows = CollectionSource::Records(RecordsSource {
|
||||
provider: None,
|
||||
schema: SchemaId::new(SWARM_SCHEMA),
|
||||
key_prefix: "mind-".into(),
|
||||
});
|
||||
let args = vec![
|
||||
Arg { name: "title".into(), value: ArgValue::Text(TextArg { value: "Card".into() }) },
|
||||
Arg { name: "count".into(), value: ArgValue::Number(NumberArg { value: 3.0 }) },
|
||||
Arg { name: "on".into(), value: ArgValue::Bool(BoolArg { value: true }) },
|
||||
Arg { name: "source".into(), value: ArgValue::Bind(source) },
|
||||
Arg { name: "rows".into(), value: ArgValue::Collection(CollectionArg { source: rows }) },
|
||||
Arg { name: "act".into(), value: ArgValue::Command(CommandArg { command: command("open") }) },
|
||||
Arg { name: "body".into(), value: ArgValue::Slot(SlotArg { nodes: slot }) },
|
||||
];
|
||||
Node::Use(UseNode {
|
||||
common: common(id),
|
||||
composition: CompositionRef { publisher: STACK.into(), name: seg("card"), version: ver(1) },
|
||||
args,
|
||||
})
|
||||
}
|
||||
|
||||
fn composition_stack() -> SurfaceDocument {
|
||||
// Two levels: the outer card's slot holds a second card.
|
||||
let inner = card_use("inner-card", vec![text("inner-note", "nested")]);
|
||||
let outer = card_use("outer-card", vec![inner]);
|
||||
SurfaceDocument {
|
||||
provider_id: ProviderId::new(STACK),
|
||||
label: seg("stack"),
|
||||
version: ver(1),
|
||||
title: "Stack".into(),
|
||||
root: boxed("root", vec![outer]),
|
||||
commands: vec![CommandDecl {
|
||||
id: CommandId::new("open"),
|
||||
payload_schema: SchemaId::new("gamecult.thing.test.open.v1"),
|
||||
captures: vec![],
|
||||
confirm: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn stack_card() -> CompositionDocument {
|
||||
let title = Node::Text(TextNode {
|
||||
common: common("card-title"),
|
||||
content: TextSource::Param(param("title")),
|
||||
style_token: "title".into(),
|
||||
wrap: true,
|
||||
max_lines: None,
|
||||
selectable: false,
|
||||
});
|
||||
let rows = Node::Repeat(RepeatNode {
|
||||
common: common("card-rows"),
|
||||
collection: CollectionSource::Param(param("rows")),
|
||||
key_member: path(&["id"]),
|
||||
template: std::boxed::Box::new(Node::Text(TextNode {
|
||||
common: common("card-row"),
|
||||
content: TextSource::Bound(item_bind(path(&["name"]))),
|
||||
style_token: "body".into(),
|
||||
wrap: false,
|
||||
max_lines: None,
|
||||
selectable: false,
|
||||
})),
|
||||
});
|
||||
let act = Node::Button(ButtonNode {
|
||||
common: common("card-act"),
|
||||
content: vec![text("card-act-label", "Open")],
|
||||
on_activate: CommandRef::Param(param("act")),
|
||||
enabled: BoolSource::Param(param("on")),
|
||||
});
|
||||
CompositionDocument {
|
||||
publisher: STACK.into(),
|
||||
name: seg("card"),
|
||||
version: ver(1),
|
||||
params: [
|
||||
("title", ParamKind::Text),
|
||||
("count", ParamKind::Number),
|
||||
("on", ParamKind::Bool),
|
||||
("source", ParamKind::Bind),
|
||||
("rows", ParamKind::Collection),
|
||||
("act", ParamKind::Command),
|
||||
("body", ParamKind::Slot),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, kind)| ParamDecl { name: name.into(), kind })
|
||||
.collect(),
|
||||
body: boxed("card-root", vec![title, rows, act]),
|
||||
}
|
||||
}
|
||||
|
||||
const HOSTILE: &str = "provider.hostile";
|
||||
|
||||
fn hostile_use(id: &str, name: &str) -> Node {
|
||||
Node::Use(UseNode {
|
||||
common: common(id),
|
||||
composition: CompositionRef { publisher: HOSTILE.into(), name: seg(name), version: ver(1) },
|
||||
args: vec![],
|
||||
})
|
||||
}
|
||||
|
||||
fn hostile_surface(label: &str, children: Vec<Node>) -> SurfaceDocument {
|
||||
SurfaceDocument {
|
||||
provider_id: ProviderId::new(HOSTILE),
|
||||
label: seg(label),
|
||||
version: ver(1),
|
||||
title: label.into(),
|
||||
root: boxed("root", children),
|
||||
commands: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Four surfaces the resolver must refuse or flag, one hostile shape each. A surface whose
|
||||
/// bytes the contract itself refuses (an unknown union arm) cannot live in a store, so that
|
||||
/// case is the committed `node-unknown-arm.bin` golden, fed to a fake by the test.
|
||||
fn hostile() -> Vec<SurfaceDocument> {
|
||||
let undeclared = Node::Button(ButtonNode {
|
||||
common: common("go"),
|
||||
content: vec![text("go-label", "Go")],
|
||||
on_activate: command("missing"),
|
||||
enabled: lit_bool(true),
|
||||
});
|
||||
let mismatched = Node::Text(TextNode {
|
||||
common: common("mismatch"),
|
||||
content: TextSource::Bound(Bind {
|
||||
source: StateSource::Record(StateRef {
|
||||
provider: Some(ProviderId::new(HOSTILE)),
|
||||
schema: SchemaId::new("gamecult.thing.test.nowhere.v1"),
|
||||
key: RecordKey::new("row-1"),
|
||||
}),
|
||||
member: path(&["name"]),
|
||||
format: None,
|
||||
}),
|
||||
style_token: "body".into(),
|
||||
wrap: false,
|
||||
max_lines: None,
|
||||
selectable: false,
|
||||
});
|
||||
vec![
|
||||
hostile_surface("undeclared-command", vec![undeclared]),
|
||||
// The composition `dup` emits `shared-id`, which the surface also uses.
|
||||
hostile_surface("duplicate-id", vec![hostile_use("dup-use", "dup"), text("shared-id", "also here")]),
|
||||
// No composition `ghost` exists anywhere.
|
||||
hostile_surface("unresolved-use", vec![hostile_use("ghost-use", "ghost")]),
|
||||
hostile_surface("schema-mismatch", vec![mismatched]),
|
||||
]
|
||||
}
|
||||
|
||||
/// The one composition a hostile surface needs: the duplicate-id case cannot expand without it.
|
||||
fn hostile_dup() -> CompositionDocument {
|
||||
CompositionDocument {
|
||||
publisher: HOSTILE.into(),
|
||||
name: seg("dup"),
|
||||
version: ver(1),
|
||||
params: vec![],
|
||||
body: boxed("dup-root", vec![text("shared-id", "from the composition")]),
|
||||
}
|
||||
}
|
||||
32
crates/thing-testkit/src/golden.rs
Normal file
32
crates/thing-testkit/src/golden.rs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
//! The one bless door. `THING_BLESS=1` writes; any other run compares and never writes.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
fn blessing() -> bool {
|
||||
std::env::var("THING_BLESS").as_deref() == Ok("1")
|
||||
}
|
||||
|
||||
/// Bless the file or compare against it. Returns the committed bytes. A mismatch panics naming
|
||||
/// the file and leaves it unchanged.
|
||||
pub fn check(dir: &Path, file: &str, produced: &[u8]) -> Vec<u8> {
|
||||
let path = dir.join(file);
|
||||
if blessing() {
|
||||
std::fs::write(&path, produced).unwrap_or_else(|error| panic!("{file}: {error}"));
|
||||
}
|
||||
let committed = std::fs::read(&path).unwrap_or_else(|error| panic!("{file}: {error}"));
|
||||
assert_eq!(committed, produced, "{file}: the committed golden differs from what the crate writes");
|
||||
committed
|
||||
}
|
||||
|
||||
/// Bless or compare `stem.bin` and `stem.txt` together: the binary is the oracle, the text is
|
||||
/// compared too so it cannot rot. Returns the committed binary.
|
||||
pub fn check_with_text(dir: &Path, stem: &str, bytes: &[u8], text: &str) -> Vec<u8> {
|
||||
let committed = check(dir, &format!("{stem}.bin"), bytes);
|
||||
check(dir, &format!("{stem}.txt"), text.as_bytes());
|
||||
committed
|
||||
}
|
||||
|
||||
/// Read a committed file. Never writes: backends read core's goldens through this.
|
||||
pub fn read(dir: &Path, file: &str) -> Vec<u8> {
|
||||
std::fs::read(dir.join(file)).unwrap_or_else(|error| panic!("{file}: {error}"))
|
||||
}
|
||||
8
crates/thing-testkit/src/lib.rs
Normal file
8
crates/thing-testkit/src/lib.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! The fakes, builders and the one bless door the Thing crates test with. A test crate
|
||||
//! depends on this; no shipped crate does.
|
||||
|
||||
pub mod build;
|
||||
pub mod fixture;
|
||||
pub mod golden;
|
||||
pub mod mem_state;
|
||||
pub mod store;
|
||||
260
crates/thing-testkit/src/mem_state.rs
Normal file
260
crates/thing-testkit/src/mem_state.rs
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
//! `MemState`: an in-memory `StatePort`. Each provider's records live in a CultCache with the
|
||||
//! contract registered, so a typed value and a raw payload meet one decode door. A payload the
|
||||
//! contract refuses is never stored: the address becomes refused, and stays refused until a
|
||||
//! record or a delete replaces it.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use cultcache_rs::{CultCache, CultCacheEnvelope, DatabaseEntry};
|
||||
use thing_contract::*;
|
||||
use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, SubscriptionId};
|
||||
|
||||
use crate::store;
|
||||
|
||||
/// A contract kind the port carries.
|
||||
pub trait StateKind: DatabaseEntry {
|
||||
fn record_key(&self) -> String;
|
||||
fn into_record(self) -> Record;
|
||||
}
|
||||
|
||||
macro_rules! state_kinds {
|
||||
($($kind:ident => $arm:ident),* $(,)?) => {
|
||||
$(impl StateKind for $kind {
|
||||
fn record_key(&self) -> String {
|
||||
$kind::record_key(self)
|
||||
}
|
||||
fn into_record(self) -> Record {
|
||||
Record::$arm(self)
|
||||
}
|
||||
})*
|
||||
};
|
||||
}
|
||||
|
||||
state_kinds!(
|
||||
SurfaceDocument => Surface,
|
||||
CompositionDocument => Composition,
|
||||
CommandResult => Result,
|
||||
AssetCatalog => Catalog,
|
||||
);
|
||||
|
||||
/// Run `$body` with `$t` bound to the contract kind whose schema is `$schema`, or `$none` for
|
||||
/// a schema the port does not carry.
|
||||
macro_rules! by_schema {
|
||||
($schema:expr, $t:ident => $body:expr, else $none:expr) => {
|
||||
match $schema {
|
||||
SurfaceDocument::SCHEMA_NAME => {
|
||||
type $t = SurfaceDocument;
|
||||
$body
|
||||
}
|
||||
CompositionDocument::SCHEMA_NAME => {
|
||||
type $t = CompositionDocument;
|
||||
$body
|
||||
}
|
||||
CommandResult::SCHEMA_NAME => {
|
||||
type $t = CommandResult;
|
||||
$body
|
||||
}
|
||||
AssetCatalog::SCHEMA_NAME => {
|
||||
type $t = AssetCatalog;
|
||||
$body
|
||||
}
|
||||
_ => $none,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// One call the port received.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Call {
|
||||
Read(Address),
|
||||
List(Prefix),
|
||||
Subscribe(Interest),
|
||||
Unsubscribe(SubscriptionId),
|
||||
Drain,
|
||||
}
|
||||
|
||||
pub struct MemState {
|
||||
providers: HashMap<String, CultCache>,
|
||||
refused: HashMap<Address, Refusal>,
|
||||
interests: Vec<(SubscriptionId, Interest)>,
|
||||
next_subscription: u64,
|
||||
queue: Vec<Change>,
|
||||
calls: RefCell<Vec<Call>>,
|
||||
}
|
||||
|
||||
impl Default for MemState {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl MemState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
providers: HashMap::new(),
|
||||
refused: HashMap::new(),
|
||||
interests: Vec::new(),
|
||||
next_subscription: 0,
|
||||
queue: Vec::new(),
|
||||
calls: RefCell::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A state holding every document of a fixture, each under the provider that publishes it.
|
||||
pub fn from_fixture(fixture: crate::fixture::Fixture) -> Self {
|
||||
let set = fixture.load();
|
||||
let mut state = Self::new();
|
||||
for surface in &set.surfaces {
|
||||
state.put(&surface.provider_id, surface);
|
||||
}
|
||||
for composition in &set.compositions {
|
||||
state.put(&ProviderId::new(composition.publisher.clone()), composition);
|
||||
}
|
||||
for catalog in &set.catalogs {
|
||||
state.put(&catalog.provider_id, catalog);
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
/// Store a record under its record key at `provider`.
|
||||
pub fn put<T: StateKind>(&mut self, provider: &ProviderId, value: &T) {
|
||||
let address = Address {
|
||||
provider: provider.clone(),
|
||||
schema: SchemaId::new(T::SCHEMA_NAME),
|
||||
key: RecordKey::new(value.record_key()),
|
||||
};
|
||||
let outcome = self.cache(provider).put(address.key.as_str(), value);
|
||||
self.admit::<T>(address, outcome);
|
||||
}
|
||||
|
||||
/// Store a payload under `address`; the address's schema names the contract kind. A payload
|
||||
/// the contract refuses makes the address refused.
|
||||
pub fn put_raw(&mut self, address: Address, payload: Vec<u8>) {
|
||||
by_schema!(address.schema.as_str(), T => {
|
||||
let envelope = CultCacheEnvelope {
|
||||
key: address.key.as_str().into(),
|
||||
r#type: T::TYPE.into(),
|
||||
payload,
|
||||
stored_at: store::PINNED_CLOCK.into(),
|
||||
schema_id: Some(T::SCHEMA_NAME.into()),
|
||||
};
|
||||
let outcome = self.cache(&address.provider).put_envelope::<T>(envelope);
|
||||
self.admit::<T>(address, outcome);
|
||||
}, else panic!("no contract record kind has schema {}", address.schema.as_str()))
|
||||
}
|
||||
|
||||
/// Remove the record or the refusal at `address`; removing nothing is not a change.
|
||||
pub fn delete(&mut self, address: &Address) {
|
||||
let refused = self.refused.remove(address).is_some();
|
||||
let stored = by_schema!(address.schema.as_str(), T => {
|
||||
match self.providers.get_mut(address.provider.as_str()) {
|
||||
Some(cache) => cache.delete::<T>(address.key.as_str()).unwrap(),
|
||||
None => false,
|
||||
}
|
||||
}, else false);
|
||||
if refused || stored {
|
||||
self.queue(Change::Delete(address.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Every call the port received, in order.
|
||||
pub fn calls(&self) -> Vec<Call> {
|
||||
self.calls.borrow().clone()
|
||||
}
|
||||
|
||||
fn cache(&mut self, provider: &ProviderId) -> &mut CultCache {
|
||||
self.providers.entry(provider.as_str().to_string()).or_insert_with(store::memory)
|
||||
}
|
||||
|
||||
fn admit<T: StateKind>(&mut self, address: Address, outcome: anyhow::Result<T>) {
|
||||
match outcome {
|
||||
Ok(value) => {
|
||||
self.refused.remove(&address);
|
||||
self.queue(Change::Upsert(Entry { address, record: value.into_record() }));
|
||||
}
|
||||
Err(error) => {
|
||||
// The address is now refused: an older valid record under it no longer stands.
|
||||
self.cache(&address.provider).delete::<T>(address.key.as_str()).unwrap();
|
||||
let refusal =
|
||||
Refusal { address: address.clone(), kind: address.schema.clone(), detail: format!("{error:#}") };
|
||||
self.refused.insert(address, refusal.clone());
|
||||
self.queue(Change::Refused(refusal));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn queue(&mut self, change: Change) {
|
||||
let address = match &change {
|
||||
Change::Upsert(entry) => &entry.address,
|
||||
Change::Delete(address) => address,
|
||||
Change::Refused(refusal) => &refusal.address,
|
||||
};
|
||||
if self.interests.iter().any(|(_, interest)| interest.matches(address)) {
|
||||
self.queue.push(change);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StatePort for MemState {
|
||||
fn read(&self, address: &Address) -> Lookup {
|
||||
self.calls.borrow_mut().push(Call::Read(address.clone()));
|
||||
if let Some(refusal) = self.refused.get(address) {
|
||||
return Lookup::Refused(refusal.clone());
|
||||
}
|
||||
by_schema!(address.schema.as_str(), T => {
|
||||
let stored = self.providers.get(address.provider.as_str());
|
||||
match stored.and_then(|cache| cache.get::<T>(address.key.as_str()).expect("stored records decode")) {
|
||||
Some(value) => Lookup::Present(Entry { address: address.clone(), record: value.into_record() }),
|
||||
None => Lookup::Absent,
|
||||
}
|
||||
// A schema outside the four contract arms reads Absent. Cut 4 replaces this with the provider-state
|
||||
// answer once thing2:question:provider-state-value is ruled.
|
||||
}, else Lookup::Absent)
|
||||
}
|
||||
|
||||
fn list(&self, prefix: &Prefix) -> Vec<Lookup> {
|
||||
self.calls.borrow_mut().push(Call::List(prefix.clone()));
|
||||
let at = |key: &str| Address {
|
||||
provider: prefix.provider.clone(),
|
||||
schema: prefix.schema.clone(),
|
||||
key: RecordKey::new(key),
|
||||
};
|
||||
let mut found: Vec<(String, Lookup)> = self
|
||||
.refused
|
||||
.values()
|
||||
.filter(|refusal| prefix.matches(&refusal.address))
|
||||
.map(|refusal| (refusal.address.key.as_str().to_string(), Lookup::Refused(refusal.clone())))
|
||||
.collect();
|
||||
by_schema!(prefix.schema.as_str(), T => {
|
||||
if let Some(cache) = self.providers.get(prefix.provider.as_str()) {
|
||||
for (key, value) in cache.get_all_with_keys::<T>().expect("stored records decode") {
|
||||
if key.starts_with(&prefix.key_prefix) {
|
||||
let entry = Entry { address: at(&key), record: value.into_record() };
|
||||
found.push((key, Lookup::Present(entry)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}, else ());
|
||||
found.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
found.into_iter().map(|(_, lookup)| lookup).collect()
|
||||
}
|
||||
|
||||
fn subscribe(&mut self, interest: Interest) -> SubscriptionId {
|
||||
self.calls.borrow_mut().push(Call::Subscribe(interest.clone()));
|
||||
let id = SubscriptionId(self.next_subscription);
|
||||
self.next_subscription += 1;
|
||||
self.interests.push((id, interest));
|
||||
id
|
||||
}
|
||||
|
||||
fn unsubscribe(&mut self, id: SubscriptionId) {
|
||||
self.calls.borrow_mut().push(Call::Unsubscribe(id));
|
||||
self.interests.retain(|(live, _)| *live != id);
|
||||
}
|
||||
|
||||
fn drain(&mut self) -> Vec<Change> {
|
||||
self.calls.borrow_mut().push(Call::Drain);
|
||||
std::mem::take(&mut self.queue)
|
||||
}
|
||||
}
|
||||
39
crates/thing-testkit/src/store.rs
Normal file
39
crates/thing-testkit/src/store.rs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
//! CultCache single-file stores of contract documents, written under a pinned clock so the
|
||||
//! bytes are reproducible.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use cultcache_rs::{CultCache, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use thing_contract::ThingContract;
|
||||
|
||||
pub const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z";
|
||||
|
||||
/// A cache with the contract registered and no backing store.
|
||||
pub fn memory() -> CultCache {
|
||||
let mut cache = CultCache::new();
|
||||
ThingContract.register_entries(&mut cache).unwrap();
|
||||
cache
|
||||
}
|
||||
|
||||
/// An empty cache with the contract registered over a fresh single-file store at `path`.
|
||||
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();
|
||||
cache
|
||||
}
|
||||
|
||||
/// Store `value` under `key` with `stored_at` pinned.
|
||||
pub fn put_pinned<T: DatabaseEntry>(cache: &mut CultCache, key: &str, value: &T) {
|
||||
let (mut envelope, _) = cache.prepare_entry(key, value).unwrap();
|
||||
envelope.stored_at = PINNED_CLOCK.into();
|
||||
cache.put_envelope::<T>(envelope).unwrap();
|
||||
}
|
||||
|
||||
/// A cache with the contract registered, pulled from the store at `path`.
|
||||
pub fn open(path: &Path) -> CultCache {
|
||||
let mut cache = memory();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
|
||||
cache.pull_all_backing_stores().unwrap();
|
||||
cache
|
||||
}
|
||||
193
crates/thing-testkit/tests/fixtures.rs
Normal file
193
crates/thing-testkit/tests/fixtures.rs
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
//! The committed fixture stores: they open through the contract, the builders reproduce them
|
||||
//! byte for byte, and each holds the shapes its row of the fixture table names.
|
||||
//! `THING_BLESS=1` on this test rewrites them; any other run compares.
|
||||
|
||||
use thing_contract::*;
|
||||
use thing_testkit::fixture::{Fixture, FixtureSet};
|
||||
use thing_testkit::mem_state::MemState;
|
||||
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())
|
||||
}
|
||||
|
||||
#[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());
|
||||
|
||||
// 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));
|
||||
}
|
||||
assert_eq!(
|
||||
stored.len(),
|
||||
loaded.surfaces.len() + loaded.compositions.len() + loaded.catalogs.len(),
|
||||
"{}: the store holds the documents and nothing else",
|
||||
fixture.file_name()
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn commands_declared(surface: &SurfaceDocument) -> Vec<&str> {
|
||||
surface.commands.iter().map(|decl| decl.id.as_str()).collect()
|
||||
}
|
||||
|
||||
fn box_children(node: &Node) -> &[Node] {
|
||||
match node {
|
||||
Node::Box(node) => &node.children,
|
||||
other => panic!("not a Box: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f01_is_the_swarm_dashboard() {
|
||||
let set = load(Fixture::F01SwarmDashboard);
|
||||
assert_eq!(set.surfaces.len(), 1);
|
||||
let surface = &set.surfaces[0];
|
||||
let Node::Box(root) = &surface.root else { panic!("root is not a Box") };
|
||||
assert_eq!(root.style.display, Display::Grid);
|
||||
let [load, minds, restart] = &root.children[..] else { panic!("three children expected") };
|
||||
|
||||
let Node::Text(load) = load else { panic!("not a Text") };
|
||||
let TextSource::Bound(bind) = &load.content else { panic!("Text is not bound") };
|
||||
assert!(matches!(bind.format, Some(Format::Number(_))));
|
||||
|
||||
let Node::Repeat(minds) = minds else { panic!("not a Repeat") };
|
||||
assert!(matches!(minds.collection, CollectionSource::Records(_)));
|
||||
|
||||
let Node::Button(restart) = restart else { panic!("not a Button") };
|
||||
let CommandRef::Id(command) = &restart.on_activate else { panic!("not a command id") };
|
||||
assert_eq!(commands_declared(surface), [command.id.as_str()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f09_stacks_compositions_with_every_argument_arm() {
|
||||
let set = load(Fixture::F09CompositionStack);
|
||||
assert_eq!((set.surfaces.len(), set.compositions.len()), (1, 1));
|
||||
let surface = &set.surfaces[0];
|
||||
let [outer] = box_children(&surface.root) else { panic!("one Use expected") };
|
||||
let Node::Use(outer) = outer else { panic!("not a Use") };
|
||||
assert_eq!(outer.composition.publisher, set.compositions[0].publisher);
|
||||
assert_eq!(outer.composition.name, set.compositions[0].name);
|
||||
assert_eq!(outer.composition.version, set.compositions[0].version);
|
||||
|
||||
let arms: Vec<&str> = outer
|
||||
.args
|
||||
.iter()
|
||||
.map(|arg| match arg.value {
|
||||
ArgValue::Text(_) => "text",
|
||||
ArgValue::Number(_) => "number",
|
||||
ArgValue::Bool(_) => "bool",
|
||||
ArgValue::Bind(_) => "bind",
|
||||
ArgValue::Collection(_) => "collection",
|
||||
ArgValue::Command(_) => "command",
|
||||
ArgValue::Slot(_) => "slot",
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(arms, ["text", "number", "bool", "bind", "collection", "command", "slot"]);
|
||||
|
||||
// The slot holds a second Use of the same composition: two levels.
|
||||
let ArgValue::Slot(slot) = &outer.args[6].value else { unreachable!() };
|
||||
assert!(slot.nodes.iter().any(|node| matches!(node, Node::Use(inner) if inner.composition == outer.composition)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f10_holds_exactly_the_four_hostile_surfaces() {
|
||||
let set = load(Fixture::F10Hostile);
|
||||
let labels: Vec<&str> = set.surfaces.iter().map(|surface| surface.label.as_str()).collect();
|
||||
assert_eq!(labels, ["duplicate-id", "schema-mismatch", "undeclared-command", "unresolved-use"]);
|
||||
|
||||
let by = |label: &str| set.surfaces.iter().find(|surface| surface.label.as_str() == label).unwrap();
|
||||
|
||||
let undeclared = by("undeclared-command");
|
||||
let Node::Button(button) = &box_children(&undeclared.root)[0] else { panic!("not a Button") };
|
||||
let CommandRef::Id(command) = &button.on_activate else { panic!("not a command id") };
|
||||
assert!(!commands_declared(undeclared).contains(&command.id.as_str()));
|
||||
|
||||
// The surface uses `shared-id` and so does the composition its Use expands to.
|
||||
let dup = by("duplicate-id");
|
||||
let children = box_children(&dup.root);
|
||||
assert!(children.iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "shared-id")));
|
||||
let Node::Use(used) = &children[0] else { panic!("not a Use") };
|
||||
let composition = set.compositions.iter().find(|composition| composition.name == used.composition.name).unwrap();
|
||||
assert!(box_children(&composition.body).iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "shared-id")));
|
||||
|
||||
// The unresolved Use names a composition no document holds.
|
||||
let Node::Use(ghost) = &box_children(&by("unresolved-use").root)[0] else { panic!("not a Use") };
|
||||
assert!(set.compositions.iter().all(|composition| composition.name != ghost.composition.name));
|
||||
|
||||
// The Bind names a schema none of the fixtures use for state.
|
||||
let Node::Text(text) = &box_children(&by("schema-mismatch").root)[0] else { panic!("not a Text") };
|
||||
let TextSource::Bound(Bind { source: StateSource::Record(state), .. }) = &text.content else {
|
||||
panic!("Text is not bound to a record")
|
||||
};
|
||||
let f01 = load(Fixture::F01SwarmDashboard);
|
||||
let Node::Box(root) = &f01.surfaces[0].root else { unreachable!() };
|
||||
let Node::Text(f01_text) = &root.children[0] else { unreachable!() };
|
||||
let TextSource::Bound(Bind { source: StateSource::Record(f01_state), .. }) = &f01_text.content else { unreachable!() };
|
||||
assert_ne!(state.schema, f01_state.schema);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_state_holds_every_fixture_document_under_its_publisher() {
|
||||
let state = on_big_stack(|| MemState::from_fixture(Fixture::F09CompositionStack));
|
||||
let set = load(Fixture::F09CompositionStack);
|
||||
let at = Address {
|
||||
provider: ProviderId::new(set.compositions[0].publisher.clone()),
|
||||
schema: SchemaId::new("gamecult.thing.composition.v1"),
|
||||
key: RecordKey::new(set.compositions[0].record_key()),
|
||||
};
|
||||
assert!(matches!(state.read(&at), Lookup::Present(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_a_fixture_writes_nothing_in_the_fixtures_directory() {
|
||||
let listing = || {
|
||||
let mut names: Vec<_> = std::fs::read_dir(Fixture::dir())
|
||||
.unwrap()
|
||||
.map(|entry| entry.unwrap().file_name().into_string().unwrap())
|
||||
.collect();
|
||||
names.sort();
|
||||
names
|
||||
};
|
||||
let before = listing();
|
||||
// Restores the directory's permissions even when the test panics.
|
||||
struct Restore(std::fs::Permissions);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::set_permissions(Fixture::dir(), self.0.clone());
|
||||
}
|
||||
}
|
||||
let mut permissions = std::fs::metadata(Fixture::dir()).unwrap().permissions();
|
||||
let _restore = Restore(permissions.clone());
|
||||
permissions.set_readonly(true);
|
||||
std::fs::set_permissions(Fixture::dir(), permissions).unwrap();
|
||||
for fixture in Fixture::ALL {
|
||||
load(fixture);
|
||||
}
|
||||
assert_eq!(listing(), before);
|
||||
}
|
||||
86
crates/thing-testkit/tests/golden.rs
Normal file
86
crates/thing-testkit/tests/golden.rs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
//! The bless door compares and never writes unless `THING_BLESS=1`. These tests assume it is
|
||||
//! unset; the bless job runs only the fixtures test.
|
||||
|
||||
use std::panic::catch_unwind;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use thing_testkit::golden;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("golden-{name}"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mismatch_panics_naming_the_file_and_leaves_it_unchanged() {
|
||||
let dir = scratch("mismatch");
|
||||
std::fs::write(dir.join("a.bin"), b"committed").unwrap();
|
||||
|
||||
assert_eq!(golden::check(&dir, "a.bin", b"committed"), b"committed");
|
||||
|
||||
let panic = catch_unwind(|| golden::check(&dir, "a.bin", b"different")).unwrap_err();
|
||||
let message = panic.downcast_ref::<String>().cloned().unwrap_or_default();
|
||||
assert!(message.contains("a.bin"), "the panic names the file: {message}");
|
||||
assert_eq!(std::fs::read(dir.join("a.bin")).unwrap(), b"committed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_is_a_failure_not_a_write() {
|
||||
let dir = scratch("missing");
|
||||
assert!(catch_unwind(|| golden::check(&dir, "absent.bin", b"x")).is_err());
|
||||
assert!(catch_unwind(|| golden::read(&dir, "absent.bin")).is_err());
|
||||
assert!(!dir.join("absent.bin").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_text_beside_the_binary_is_compared_too() {
|
||||
let dir = scratch("text");
|
||||
std::fs::write(dir.join("s.bin"), b"bytes").unwrap();
|
||||
std::fs::write(dir.join("s.txt"), "text").unwrap();
|
||||
|
||||
assert_eq!(golden::check_with_text(&dir, "s", b"bytes", "text"), b"bytes");
|
||||
|
||||
let panic = catch_unwind(|| golden::check_with_text(&dir, "s", b"bytes", "other")).unwrap_err();
|
||||
let message = panic.downcast_ref::<String>().cloned().unwrap_or_default();
|
||||
assert!(message.contains("s.txt"), "the panic names the text file: {message}");
|
||||
assert_eq!(std::fs::read(dir.join("s.txt")).unwrap(), b"text");
|
||||
|
||||
assert!(catch_unwind(|| golden::check_with_text(&dir, "s", b"changed", "text")).is_err());
|
||||
assert_eq!(std::fs::read(dir.join("s.bin")).unwrap(), b"bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_returns_the_committed_bytes() {
|
||||
let dir = scratch("read");
|
||||
std::fs::write(dir.join("r.bin"), b"abc").unwrap();
|
||||
assert_eq!(golden::read(&dir, "r.bin"), b"abc");
|
||||
}
|
||||
|
||||
/// Re-runs this binary with THING_BLESS=1 so the writer is observed without touching this
|
||||
/// process's environment.
|
||||
#[test]
|
||||
fn blessing_writes_the_file_and_the_text() {
|
||||
let dir = scratch("bless");
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "bless_child", "--test-threads=1"])
|
||||
.env("THING_BLESS", "1")
|
||||
.env("THING_BLESS_CHILD_DIR", &dir)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
assert_eq!(std::fs::read(dir.join("b.bin")).unwrap(), b"blessed");
|
||||
assert_eq!(std::fs::read(dir.join("t.bin")).unwrap(), b"tb");
|
||||
assert_eq!(std::fs::read(dir.join("t.txt")).unwrap(), b"tt");
|
||||
}
|
||||
|
||||
/// The child half of the test above; does nothing in a normal run.
|
||||
#[test]
|
||||
fn bless_child() {
|
||||
if let Ok(dir) = std::env::var("THING_BLESS_CHILD_DIR") {
|
||||
let dir = PathBuf::from(dir);
|
||||
golden::check(&dir, "b.bin", b"blessed");
|
||||
golden::check_with_text(&dir, "t", b"tb", "tt");
|
||||
}
|
||||
}
|
||||
305
crates/thing-testkit/tests/mem_state.rs
Normal file
305
crates/thing-testkit/tests/mem_state.rs
Normal file
|
|
@ -0,0 +1,305 @@
|
|||
//! MemState as core sees it: through `StatePort`, with its own put and delete as the only
|
||||
//! writers.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use thing_contract::*;
|
||||
use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, StatePort, SubscriptionId};
|
||||
use thing_testkit::build::*;
|
||||
use thing_testkit::golden;
|
||||
use thing_testkit::mem_state::{Call, MemState};
|
||||
|
||||
const SURFACE: &str = "gamecult.thing.surface.v1";
|
||||
const COMPOSITION: &str = "gamecult.thing.composition.v1";
|
||||
const RESULT: &str = "gamecult.thing.command_result.v1";
|
||||
const CATALOG: &str = "gamecult.thing.asset_catalog.v1";
|
||||
// A value that must never appear in a refusal; node-unknown-arm.bin carries it.
|
||||
const CANARY: &str = "CANARY-7f3a91c2";
|
||||
|
||||
fn provider(name: &str) -> ProviderId {
|
||||
ProviderId::new(name)
|
||||
}
|
||||
|
||||
fn address(provider_name: &str, schema: &str, key: &str) -> Address {
|
||||
Address { provider: provider(provider_name), schema: SchemaId::new(schema), key: RecordKey::new(key) }
|
||||
}
|
||||
|
||||
fn prefix(provider_name: &str, schema: &str, key_prefix: &str) -> Prefix {
|
||||
Prefix { provider: provider(provider_name), schema: SchemaId::new(schema), key_prefix: key_prefix.into() }
|
||||
}
|
||||
|
||||
fn surface(provider_name: &str, label: &str) -> SurfaceDocument {
|
||||
SurfaceDocument {
|
||||
provider_id: provider(provider_name),
|
||||
label: seg(label),
|
||||
version: ver(1),
|
||||
title: label.into(),
|
||||
root: boxed("root", vec![]),
|
||||
commands: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn composition(publisher: &str, name: &str) -> CompositionDocument {
|
||||
CompositionDocument {
|
||||
publisher: publisher.into(),
|
||||
name: seg(name),
|
||||
version: ver(1),
|
||||
params: vec![],
|
||||
body: boxed("body", vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
fn catalog(provider_name: &str, id: &str) -> AssetCatalog {
|
||||
AssetCatalog { provider_id: provider(provider_name), catalog_id: seg(id), version: ver(1), assets: vec![] }
|
||||
}
|
||||
|
||||
fn surface_at(provider_name: &str, value: &SurfaceDocument) -> Address {
|
||||
address(provider_name, SURFACE, &value.record_key())
|
||||
}
|
||||
|
||||
fn unknown_arm() -> Vec<u8> {
|
||||
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../thing-contract/tests/goldens");
|
||||
golden::read(&dir, "node-unknown-arm.bin")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn port_is_object_safe() {
|
||||
let one = surface("provider.a", "one");
|
||||
let mut state = MemState::new();
|
||||
state.put(&provider("provider.a"), &one);
|
||||
let port: &mut dyn StatePort = &mut state;
|
||||
let id = port.subscribe(Interest::Record(surface_at("provider.a", &one)));
|
||||
assert!(matches!(port.read(&surface_at("provider.a", &one)), Lookup::Present(_)));
|
||||
assert_eq!(port.list(&prefix("provider.a", SURFACE, "thing:")).len(), 1);
|
||||
port.unsubscribe(id);
|
||||
assert!(port.drain().is_empty());
|
||||
let boxed: Box<dyn StatePort> = Box::new(MemState::new());
|
||||
assert_eq!(boxed.read(&address("provider.a", SURFACE, "k")), Lookup::Absent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_is_not_absence() {
|
||||
let main = surface("provider.a", "main");
|
||||
let at = surface_at("provider.a", &main);
|
||||
assert_eq!(at.key.as_str(), "thing:surface:provider.a.main");
|
||||
let mut state = MemState::new();
|
||||
state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:")));
|
||||
|
||||
state.put_raw(at.clone(), unknown_arm());
|
||||
|
||||
let drained = state.drain();
|
||||
assert_eq!(drained.len(), 1, "one change: {drained:?}");
|
||||
let Change::Refused(refusal) = &drained[0] else { panic!("not a refusal: {drained:?}") };
|
||||
assert_eq!(refusal.address, at);
|
||||
assert_eq!(refusal.kind, SchemaId::new(SURFACE));
|
||||
assert!(refusal.detail.contains(at.key.as_str()), "the detail names the key: {}", refusal.detail);
|
||||
assert!(!refusal.detail.contains(CANARY), "the detail echoed a value: {}", refusal.detail);
|
||||
assert_eq!(state.read(&at), Lookup::Refused(refusal.clone()));
|
||||
assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:")), vec![Lookup::Refused(refusal.clone())]);
|
||||
|
||||
// A valid record replaces the refusal; a refusal over a valid record leaves the address
|
||||
// refused, not the older record.
|
||||
state.put(&provider("provider.a"), &main);
|
||||
assert!(matches!(state.read(&at), Lookup::Present(_)));
|
||||
state.put_raw(at.clone(), unknown_arm());
|
||||
assert!(matches!(state.read(&at), Lookup::Refused(_)));
|
||||
assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:")).len(), 1);
|
||||
state.drain();
|
||||
|
||||
// Deleting a refusal is a change; deleting nothing is not.
|
||||
state.delete(&at);
|
||||
assert_eq!(state.read(&at), Lookup::Absent);
|
||||
assert_eq!(state.drain(), vec![Change::Delete(at.clone())]);
|
||||
state.delete(&at);
|
||||
assert!(state.drain().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_drain_in_mutation_order_for_live_interests() {
|
||||
let provider_a = provider("provider.a");
|
||||
let one = surface("provider.a", "one");
|
||||
let two = surface("provider.a", "two");
|
||||
let panel = composition("provider.a", "panel");
|
||||
let other = composition("provider.a", "other");
|
||||
let icons = catalog("provider.a", "icons");
|
||||
let one_at = surface_at("provider.a", &one);
|
||||
let panel_at = address("provider.a", COMPOSITION, &panel.record_key());
|
||||
|
||||
let mut state = MemState::new();
|
||||
let ids: Vec<SubscriptionId> = vec![
|
||||
state.subscribe(Interest::Record(one_at.clone())),
|
||||
state.subscribe(Interest::Record(panel_at.clone())),
|
||||
state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:"))),
|
||||
];
|
||||
|
||||
state.put(&provider_a, &one); // matches two interests and drains once
|
||||
state.put(&provider_a, &panel);
|
||||
state.put(&provider_a, &icons); // another schema under the same provider
|
||||
state.put(&provider_a, &other); // a composition nobody asked for
|
||||
// The same key and schema under another provider.
|
||||
state.put_raw(address("provider.b", SURFACE, &two.record_key()), rmp_serde::to_vec(&two).unwrap());
|
||||
state.put(&provider_a, &two);
|
||||
state.delete(&one_at);
|
||||
|
||||
let entry = |address: Address, record: Record| Change::Upsert(Entry { address, record });
|
||||
assert_eq!(
|
||||
state.drain(),
|
||||
vec![
|
||||
entry(one_at.clone(), Record::Surface(one.clone())),
|
||||
entry(panel_at, Record::Composition(panel)),
|
||||
entry(surface_at("provider.a", &two), Record::Surface(two.clone())),
|
||||
Change::Delete(one_at),
|
||||
]
|
||||
);
|
||||
assert!(state.drain().is_empty(), "each change drains once");
|
||||
|
||||
for id in ids {
|
||||
state.unsubscribe(id);
|
||||
}
|
||||
state.put(&provider_a, &one);
|
||||
assert!(state.drain().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_live_interest_nothing_queues() {
|
||||
let mut state = MemState::new();
|
||||
state.put_raw(address("provider.a", SURFACE, "thing:surface:provider.a.main"), unknown_arm());
|
||||
state.put(&provider("provider.a"), &surface("provider.a", "one"));
|
||||
assert!(state.drain().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_kind_reads_back_as_its_own_arm() {
|
||||
let provider_a = provider("provider.a");
|
||||
let mut state = MemState::new();
|
||||
let first = surface("provider.a", "b");
|
||||
let invocation = invocation();
|
||||
let result = CommandResult::pending(&invocation, seq(1), "working");
|
||||
let panel = composition("provider.a", "panel");
|
||||
let icons = catalog("provider.a", "icons");
|
||||
state.put(&provider_a, &first);
|
||||
state.put(&provider_a, &panel);
|
||||
state.put(&provider_a, &result);
|
||||
state.put(&provider_a, &icons);
|
||||
|
||||
let present = |at: Address, record: Record| Lookup::Present(Entry { address: at, record });
|
||||
let first_at = surface_at("provider.a", &first);
|
||||
assert_eq!(state.read(&first_at), present(first_at.clone(), Record::Surface(first.clone())));
|
||||
let panel_at = address("provider.a", COMPOSITION, &panel.record_key());
|
||||
assert_eq!(state.read(&panel_at), present(panel_at.clone(), Record::Composition(panel)));
|
||||
let result_at = address("provider.a", RESULT, &result.record_key());
|
||||
assert_eq!(state.read(&result_at), present(result_at.clone(), Record::Result(result)));
|
||||
let icons_at = address("provider.a", CATALOG, &icons.record_key());
|
||||
assert_eq!(state.read(&icons_at), present(icons_at.clone(), Record::Catalog(icons)));
|
||||
|
||||
// A newer record replaces the older; an absent key, another provider and another schema read Absent.
|
||||
let mut newer = first.clone();
|
||||
newer.title = "newer".into();
|
||||
state.put(&provider_a, &newer);
|
||||
assert_eq!(state.read(&first_at), present(first_at.clone(), Record::Surface(newer)));
|
||||
assert_eq!(state.read(&address("provider.a", SURFACE, "missing")), Lookup::Absent);
|
||||
assert_eq!(state.read(&address("provider.b", SURFACE, first_at.key.as_str())), Lookup::Absent);
|
||||
assert_eq!(state.read(&address("provider.a", COMPOSITION, first_at.key.as_str())), Lookup::Absent);
|
||||
assert_eq!(state.read(&address("provider.a", "gamecult.thing.nowhere.v1", "k")), Lookup::Absent);
|
||||
|
||||
// A list holds the prefix's records in key order and no others.
|
||||
let a = surface("provider.a", "a");
|
||||
let c = surface("provider.a", "c");
|
||||
state.put(&provider_a, &c);
|
||||
state.put(&provider_a, &a);
|
||||
let keys: Vec<String> = state
|
||||
.list(&prefix("provider.a", SURFACE, "thing:surface:provider.a."))
|
||||
.into_iter()
|
||||
.map(|lookup| match lookup {
|
||||
Lookup::Present(entry) => entry.address.key.as_str().to_string(),
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(keys, ["thing:surface:provider.a.a", "thing:surface:provider.a.b", "thing:surface:provider.a.c"]);
|
||||
assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:surface:provider.a.b")).len(), 1);
|
||||
assert!(state.list(&prefix("provider.b", SURFACE, "thing:")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_call_is_logged_in_order() {
|
||||
let at = address("provider.a", SURFACE, "k");
|
||||
let under = prefix("provider.a", SURFACE, "p");
|
||||
let mut state = MemState::new();
|
||||
state.read(&at);
|
||||
let id = state.subscribe(Interest::Prefix(under.clone()));
|
||||
state.list(&under);
|
||||
state.drain();
|
||||
state.unsubscribe(id);
|
||||
assert_eq!(
|
||||
state.calls(),
|
||||
vec![
|
||||
Call::Read(at.clone()),
|
||||
Call::Subscribe(Interest::Prefix(under.clone())),
|
||||
Call::List(under),
|
||||
Call::Drain,
|
||||
Call::Unsubscribe(id),
|
||||
]
|
||||
);
|
||||
let second = state.subscribe(Interest::Record(at));
|
||||
assert_ne!(second, id, "a subscription id is never reused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsubscribing_ends_only_that_interest() {
|
||||
let provider_a = provider("provider.a");
|
||||
let panel = composition("provider.a", "panel");
|
||||
let one = surface("provider.a", "one");
|
||||
let panel_at = address("provider.a", COMPOSITION, &panel.record_key());
|
||||
let mut state = MemState::new();
|
||||
let by_record = state.subscribe(Interest::Record(panel_at.clone()));
|
||||
let by_prefix = state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:")));
|
||||
|
||||
state.unsubscribe(by_prefix);
|
||||
state.put(&provider_a, &one);
|
||||
state.put(&provider_a, &panel);
|
||||
let drained = state.drain();
|
||||
assert_eq!(drained.len(), 1, "only the composition interest is live: {drained:?}");
|
||||
assert!(matches!(&drained[0], Change::Upsert(entry) if entry.address == panel_at));
|
||||
|
||||
state.unsubscribe(by_record);
|
||||
state.put(&provider_a, &panel);
|
||||
assert!(state.drain().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsubscribing_keeps_changes_already_queued() {
|
||||
let one = surface("provider.a", "one");
|
||||
let mut state = MemState::new();
|
||||
let id = state.subscribe(Interest::Record(surface_at("provider.a", &one)));
|
||||
state.put(&provider("provider.a"), &one);
|
||||
state.unsubscribe(id);
|
||||
assert_eq!(state.drain().len(), 1, "a change queued while the interest was live is still drained");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_list_mixes_refused_and_present_in_key_order() {
|
||||
let a = surface("provider.a", "a");
|
||||
let c = surface("provider.a", "c");
|
||||
let b_at = address("provider.a", SURFACE, "thing:surface:provider.a.b");
|
||||
let mut state = MemState::new();
|
||||
state.put(&provider("provider.a"), &c);
|
||||
state.put_raw(b_at.clone(), unknown_arm());
|
||||
state.put(&provider("provider.a"), &a);
|
||||
let kinds: Vec<(&str, String)> = state
|
||||
.list(&prefix("provider.a", SURFACE, "thing:"))
|
||||
.into_iter()
|
||||
.map(|lookup| match lookup {
|
||||
Lookup::Present(entry) => ("present", entry.address.key.as_str().to_string()),
|
||||
Lookup::Refused(refusal) => ("refused", refusal.address.key.as_str().to_string()),
|
||||
Lookup::Absent => panic!("a list holds no absence"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[
|
||||
("present", "thing:surface:provider.a.a".to_string()),
|
||||
("refused", b_at.key.as_str().to_string()),
|
||||
("present", "thing:surface:provider.a.c".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
Loading…
Reference in a new issue