Thing 2.0 cut 12a: RecordStore in thing-state; MemState becomes its test front (#28)
This commit is contained in:
parent
17a0008d3e
commit
6fe8c58cba
8 changed files with 808 additions and 244 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
|
@ -714,6 +714,7 @@ dependencies = [
|
|||
"cultcache-rs",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"thing-contract",
|
||||
"thing-core",
|
||||
]
|
||||
|
||||
|
|
@ -721,7 +722,6 @@ dependencies = [
|
|||
name = "thing-testkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cultcache-rs",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
|
|
|
|||
|
|
@ -98,7 +98,9 @@ pub enum Change {
|
|||
pub trait StatePort {
|
||||
fn read(&self, address: &Address) -> Lookup;
|
||||
|
||||
/// One lookup per record under the prefix, in key order.
|
||||
/// One lookup per record under the prefix, in key order, refusals included. Every lookup is of
|
||||
/// the prefix's one provider and schema: a record of another schema is never listed (the
|
||||
/// `Binder` relies on this; its own other-schema refusal is only a guard).
|
||||
fn list(&self, prefix: &Prefix) -> Vec<Lookup>;
|
||||
|
||||
fn subscribe(&mut self, interest: Interest) -> SubscriptionId;
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ publish = false
|
|||
|
||||
[dependencies]
|
||||
thing-core = { path = "../thing-core" }
|
||||
thing-contract = { path = "../thing-contract" }
|
||||
cultcache-rs = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
|
|
|||
|
|
@ -1,13 +1,21 @@
|
|||
//! The one by-name decode of a provider record. A state port implementation (`MemState` now,
|
||||
//! thing-mesh next) calls `decode` with the record's payload and the catalog member rows of its
|
||||
//! schema; core never sees bytes. The catalog names only a document's top-level members, so below
|
||||
//! that level a payload decodes by its own shape.
|
||||
//! The one by-name decode of a provider record, and the store that holds what it admits. A state
|
||||
//! port implementation (`MemState` now, thing-mesh next) calls `decode` with the record's payload
|
||||
//! and the catalog member rows of its schema; core never sees bytes. The catalog names only a
|
||||
//! document's top-level members, so below that level a payload decodes by its own shape.
|
||||
//!
|
||||
//! [`RecordStore`] is the one place a `StatePort` implementation's records, refusals, interests
|
||||
//! and queued changes live, fed by the implementation's own source (a test script or a wire).
|
||||
//! `RecordStore::admit_value` bypasses the decode door and is for tests only.
|
||||
//!
|
||||
//! Registration contract: a provider's state record type must be registered with its entry type
|
||||
//! equal to its schema id (`TYPE == SCHEMA_NAME`). A CultCache store names a record's schema by
|
||||
//! its entry type, so the id a `Bind` names is the id the store holds only when the two are one
|
||||
//! string; the member rows a reader finds are the rows published under that id.
|
||||
|
||||
mod store;
|
||||
|
||||
pub use store::{RecordStore, is_contract};
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::fmt;
|
||||
|
|
|
|||
370
crates/thing-state/src/store.rs
Normal file
370
crates/thing-state/src/store.rs
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
//! `RecordStore`: the one place a `StatePort` implementation's records, refusals, interests and
|
||||
//! queued changes live. The implementation owns only where bytes come from (a test script, a
|
||||
//! wire) and feeds them through `admit_contract`, `admit_state`, `refuse` and `remove`; the store
|
||||
//! owns every decision after that.
|
||||
//!
|
||||
//! A contract kind's records live per provider in a CultCache with the contract registered, so a
|
||||
//! typed value and a raw payload meet one decode door. A payload that door refuses is never
|
||||
//! stored: the address becomes refused, and stays refused until a record or a removal replaces
|
||||
//! it. A provider's own state (any schema outside the contract) is held per (provider, key), one
|
||||
//! record per key as CultCache holds them, already decoded by [`decode`] with the schema's catalog
|
||||
//! member rows; a payload `decode` refuses is held as a refusal.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, SchemaCatalogMember};
|
||||
use thing_contract::{
|
||||
AssetCatalog, CommandResult, CompositionDocument, ProviderId, RecordKey, SchemaId, SurfaceDocument, ThingContract,
|
||||
};
|
||||
use thing_core::port::{
|
||||
Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, StateValue, SubscriptionId,
|
||||
};
|
||||
|
||||
use crate::decode;
|
||||
|
||||
/// A contract kind a store carries, and the record it becomes.
|
||||
trait ContractKind: DatabaseEntry {
|
||||
fn into_record(self) -> Record;
|
||||
}
|
||||
|
||||
macro_rules! contract_kinds {
|
||||
($($kind:ident => $arm:ident),* $(,)?) => {
|
||||
$(impl ContractKind for $kind {
|
||||
fn into_record(self) -> Record {
|
||||
Record::$arm(self)
|
||||
}
|
||||
})*
|
||||
};
|
||||
}
|
||||
|
||||
contract_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 store does not carry as a contract kind.
|
||||
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,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Whether `schema` names a contract kind: one `admit_contract` decodes by type. Any other schema
|
||||
/// is provider state, which arrives through `admit_state` with its member rows.
|
||||
pub fn is_contract(schema: &SchemaId) -> bool {
|
||||
by_schema!(schema.as_str(), _T => true, else false)
|
||||
}
|
||||
|
||||
/// What a provider key holds of provider state.
|
||||
#[derive(Clone)]
|
||||
enum Held {
|
||||
Value { schema: SchemaId, value: StateValue },
|
||||
Refused(Refusal),
|
||||
}
|
||||
|
||||
impl Held {
|
||||
fn schema(&self) -> &SchemaId {
|
||||
match self {
|
||||
Held::Value { schema, .. } => schema,
|
||||
Held::Refused(refusal) => &refusal.kind,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct RecordStore {
|
||||
providers: HashMap<String, CultCache>,
|
||||
state: HashMap<(String, String), Held>,
|
||||
refused: HashMap<Address, Refusal>,
|
||||
interests: Vec<(SubscriptionId, Interest)>,
|
||||
next_subscription: u64,
|
||||
queue: Vec<Change>,
|
||||
}
|
||||
|
||||
impl RecordStore {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Store the contract-kind payload under `address`; the address's schema names the kind. A
|
||||
/// payload the contract refuses, or one `accept` refuses once decoded, makes the address
|
||||
/// refused and replaces any record it held. `accept` is how a transport refuses a record it
|
||||
/// could decode but must not take (filed under another provider's route, or under a key other
|
||||
/// than its own); it sees the decoded record and answers the refusal's detail. A schema that
|
||||
/// is not a contract kind makes the address refused too.
|
||||
pub fn admit_contract(
|
||||
&mut self,
|
||||
address: Address,
|
||||
payload: Vec<u8>,
|
||||
stored_at: &str,
|
||||
accept: impl FnOnce(&Record) -> Result<(), String>,
|
||||
) {
|
||||
by_schema!(address.schema.as_str(), T => {
|
||||
let envelope = CultCacheEnvelope {
|
||||
key: address.key.as_str().into(),
|
||||
r#type: T::TYPE.into(),
|
||||
payload,
|
||||
stored_at: stored_at.into(),
|
||||
schema_id: Some(T::SCHEMA_NAME.into()),
|
||||
};
|
||||
let outcome = self.cache(&address.provider).put_envelope::<T>(envelope).map_err(|error| format!("{error:#}"));
|
||||
let outcome = outcome.and_then(|value| {
|
||||
let record = value.into_record();
|
||||
accept(&record).map(|()| record)
|
||||
});
|
||||
match outcome {
|
||||
Ok(record) => {
|
||||
self.refused.remove(&address);
|
||||
self.queue(Change::Upsert(Entry { address, record }));
|
||||
}
|
||||
Err(detail) => self.refuse(address, detail),
|
||||
}
|
||||
}, else {
|
||||
let detail = format!("{} is not a contract kind", address.schema.as_str());
|
||||
self.refuse(address, detail)
|
||||
})
|
||||
}
|
||||
|
||||
/// Store a provider-state payload under `address`, decoded with the schema's member `rows`.
|
||||
/// A payload `decode` refuses makes the key refused, replacing any record it held.
|
||||
pub fn admit_state(&mut self, address: Address, payload: Vec<u8>, rows: &[SchemaCatalogMember]) {
|
||||
match decode(&payload, rows) {
|
||||
Ok(value) => self.admit_value(address, value),
|
||||
Err(error) => {
|
||||
let detail = format!("{}: {error}", address.schema.as_str());
|
||||
self.refuse(address, detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Store an already-decoded provider-state `value` under `address`, as a port that decoded it
|
||||
/// would hand it over. This bypasses the decode door and is for tests: it holds kinds a typed
|
||||
/// record cannot (bytes, a float where an int is asked) that a reader's tests feed in. A
|
||||
/// contract-kind schema makes the address refused.
|
||||
pub fn admit_value(&mut self, address: Address, value: StateValue) {
|
||||
if is_contract(&address.schema) {
|
||||
let detail = format!("{} is a contract kind", address.schema.as_str());
|
||||
return self.refuse(address, detail);
|
||||
}
|
||||
let schema = address.schema.clone();
|
||||
self.state.insert(state_slot(&address), Held::Value { schema: schema.clone(), value: value.clone() });
|
||||
self.queue(Change::Upsert(Entry { address, record: Record::State { schema, value } }));
|
||||
}
|
||||
|
||||
/// Hold `address` as refused with `detail`, replacing any record or refusal it held, for what
|
||||
/// a transport cannot give the store (no member rows, a wrong schema).
|
||||
pub fn refuse(&mut self, address: Address, detail: String) {
|
||||
let refusal = Refusal { kind: address.schema.clone(), address: address.clone(), detail };
|
||||
if is_contract(&address.schema) {
|
||||
// An older valid record under the address no longer stands.
|
||||
by_schema!(address.schema.as_str(), T => {
|
||||
if let Some(cache) = self.providers.get_mut(address.provider.as_str()) {
|
||||
cache.delete::<T>(address.key.as_str()).unwrap();
|
||||
}
|
||||
}, else ());
|
||||
self.refused.insert(address, refusal.clone());
|
||||
} else {
|
||||
self.state.insert(state_slot(&address), Held::Refused(refusal.clone()));
|
||||
}
|
||||
self.queue(Change::Refused(refusal));
|
||||
}
|
||||
|
||||
/// Remove the record or the refusal at `address`; removing nothing is not a change.
|
||||
pub fn remove(&mut self, address: &Address) {
|
||||
if !is_contract(&address.schema) {
|
||||
let slot = state_slot(address);
|
||||
if self.state.get(&slot).is_some_and(|held| held.schema() == &address.schema) {
|
||||
self.state.remove(&slot);
|
||||
self.queue(Change::Delete(address.clone()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop every record and refusal of `provider`'s `schema`, queueing nothing: the consumer let
|
||||
/// go of them, which is not the provider deleting them. Another schema and another provider
|
||||
/// are untouched.
|
||||
pub fn purge(&mut self, provider: &ProviderId, schema: &SchemaId) {
|
||||
if !is_contract(schema) {
|
||||
self.state.retain(|(held_provider, _), held| held_provider != provider.as_str() || held.schema() != schema);
|
||||
return;
|
||||
}
|
||||
self.refused.retain(|address, _| &address.provider != provider || &address.schema != schema);
|
||||
by_schema!(schema.as_str(), T => {
|
||||
if let Some(cache) = self.providers.get_mut(provider.as_str()) {
|
||||
for (key, _) in cache.get_all_with_keys::<T>().expect("stored records decode") {
|
||||
cache.delete::<T>(&key).unwrap();
|
||||
}
|
||||
}
|
||||
}, else ());
|
||||
}
|
||||
|
||||
/// The keys held under `provider`'s `schema`, refusals included, in key order.
|
||||
pub fn keys(&self, provider: &ProviderId, schema: &SchemaId) -> Vec<RecordKey> {
|
||||
let mut keys: Vec<String> = if is_contract(schema) {
|
||||
let mut keys: Vec<String> = self
|
||||
.refused
|
||||
.keys()
|
||||
.filter(|address| &address.provider == provider && &address.schema == schema)
|
||||
.map(|address| address.key.as_str().to_string())
|
||||
.collect();
|
||||
by_schema!(schema.as_str(), T => {
|
||||
if let Some(cache) = self.providers.get(provider.as_str()) {
|
||||
keys.extend(cache.get_all_with_keys::<T>().expect("stored records decode").into_iter().map(|(key, _)| key));
|
||||
}
|
||||
}, else ());
|
||||
keys
|
||||
} else {
|
||||
self.state
|
||||
.iter()
|
||||
.filter(|((held_provider, _), held)| held_provider == provider.as_str() && held.schema() == schema)
|
||||
.map(|((_, key), _)| key.clone())
|
||||
.collect()
|
||||
};
|
||||
keys.sort();
|
||||
keys.into_iter().map(RecordKey::new).collect()
|
||||
}
|
||||
|
||||
/// The interests live now, in subscription order.
|
||||
pub fn interests(&self) -> impl Iterator<Item = &Interest> {
|
||||
self.interests.iter().map(|(_, interest)| interest)
|
||||
}
|
||||
|
||||
fn cache(&mut self, provider: &ProviderId) -> &mut CultCache {
|
||||
self.providers.entry(provider.as_str().to_string()).or_insert_with(|| {
|
||||
let mut cache = CultCache::new();
|
||||
ThingContract.register_entries(&mut cache).unwrap();
|
||||
cache
|
||||
})
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn state_slot(address: &Address) -> (String, String) {
|
||||
(address.provider.as_str().to_string(), address.key.as_str().to_string())
|
||||
}
|
||||
|
||||
impl StatePort for RecordStore {
|
||||
fn read(&self, address: &Address) -> Lookup {
|
||||
if !is_contract(&address.schema) {
|
||||
return match self.state.get(&state_slot(address)) {
|
||||
Some(Held::Value { schema, value }) => Lookup::Present(Entry {
|
||||
address: address.clone(),
|
||||
record: Record::State { schema: schema.clone(), value: value.clone() },
|
||||
}),
|
||||
Some(Held::Refused(refusal)) => Lookup::Refused(refusal.clone()),
|
||||
None => Lookup::Absent,
|
||||
};
|
||||
}
|
||||
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,
|
||||
}
|
||||
}, else unreachable!("is_contract admitted the schema"))
|
||||
}
|
||||
|
||||
fn list(&self, prefix: &Prefix) -> Vec<Lookup> {
|
||||
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();
|
||||
if !is_contract(&prefix.schema) {
|
||||
for ((provider, key), held) in &self.state {
|
||||
if provider != prefix.provider.as_str() || !key.starts_with(&prefix.key_prefix) {
|
||||
continue;
|
||||
}
|
||||
match held {
|
||||
Held::Value { schema, value } if schema == &prefix.schema => {
|
||||
let record = Record::State { schema: schema.clone(), value: value.clone() };
|
||||
found.push((key.clone(), Lookup::Present(Entry { address: at(key), record })));
|
||||
}
|
||||
Held::Refused(refusal) if refusal.kind == prefix.schema => {
|
||||
found.push((key.clone(), Lookup::Refused(refusal.clone())));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
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 unreachable!("is_contract admitted the schema"));
|
||||
}
|
||||
found.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
found.into_iter().map(|(_, lookup)| lookup).collect()
|
||||
}
|
||||
|
||||
fn subscribe(&mut self, interest: Interest) -> SubscriptionId {
|
||||
let id = SubscriptionId(self.next_subscription);
|
||||
self.next_subscription += 1;
|
||||
self.interests.push((id, interest));
|
||||
id
|
||||
}
|
||||
|
||||
fn unsubscribe(&mut self, id: SubscriptionId) {
|
||||
self.interests.retain(|(live, _)| *live != id);
|
||||
}
|
||||
|
||||
fn drain(&mut self) -> Vec<Change> {
|
||||
std::mem::take(&mut self.queue)
|
||||
}
|
||||
}
|
||||
394
crates/thing-state/tests/store.rs
Normal file
394
crates/thing-state/tests/store.rs
Normal file
|
|
@ -0,0 +1,394 @@
|
|||
//! `RecordStore` through `StatePort` and its own admit, refuse, remove and purge doors: what a
|
||||
//! store holds, refuses, queues and lists. Contract records are AssetCatalogs (the smallest
|
||||
//! contract kind); provider state is a one-member array.
|
||||
|
||||
use cultcache_rs::{CultCache, CultCacheRegistry, SchemaCatalogMember};
|
||||
use thing_contract::*;
|
||||
use thing_core::port::{
|
||||
Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, StateValue, SubscriptionId,
|
||||
};
|
||||
use thing_state::{RecordStore, is_contract};
|
||||
|
||||
const CATALOG: &str = "gamecult.thing.asset_catalog.v1";
|
||||
const SURFACE: &str = "gamecult.thing.surface.v1";
|
||||
const STATE: &str = "gamecult.thing.test.v1";
|
||||
const CLOCK: &str = "2026-01-01T00:00:00Z";
|
||||
|
||||
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() }
|
||||
}
|
||||
|
||||
fn catalog(provider: &str, id: &str) -> AssetCatalog {
|
||||
AssetCatalog {
|
||||
provider_id: ProviderId::new(provider),
|
||||
catalog_id: Segment::new(id).unwrap(),
|
||||
version: Version::new(1).unwrap(),
|
||||
assets: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn payload(value: &AssetCatalog) -> Vec<u8> {
|
||||
let mut cache = CultCache::new();
|
||||
ThingContract.register_entries(&mut cache).unwrap();
|
||||
cache.prepare_entry("payload", value).unwrap().0.payload
|
||||
}
|
||||
|
||||
fn catalog_at(provider: &str, value: &AssetCatalog) -> Address {
|
||||
address(provider, CATALOG, &value.record_key())
|
||||
}
|
||||
|
||||
fn put(store: &mut RecordStore, provider: &str, value: &AssetCatalog) -> Address {
|
||||
let at = catalog_at(provider, value);
|
||||
store.admit_contract(at.clone(), payload(value), CLOCK, |_| Ok(()));
|
||||
at
|
||||
}
|
||||
|
||||
/// A MessagePack array no contract kind decodes.
|
||||
fn garbage() -> Vec<u8> {
|
||||
vec![0xc1]
|
||||
}
|
||||
|
||||
fn rows() -> Vec<SchemaCatalogMember> {
|
||||
vec![SchemaCatalogMember {
|
||||
slot: 0,
|
||||
member_name: "n".into(),
|
||||
type_name: "System.Object".into(),
|
||||
is_reference: false,
|
||||
is_many: false,
|
||||
target_schema_name: None,
|
||||
is_name: false,
|
||||
index_alias: None,
|
||||
}]
|
||||
}
|
||||
|
||||
/// The one-member array `[value]`.
|
||||
fn one(value: u8) -> Vec<u8> {
|
||||
vec![0x91, value]
|
||||
}
|
||||
|
||||
fn upsert(address: Address, record: Record) -> Change {
|
||||
Change::Upsert(Entry { address, record })
|
||||
}
|
||||
|
||||
fn refused(lookup: &Lookup) -> &Refusal {
|
||||
let Lookup::Refused(refusal) = lookup else { panic!("not refused: {lookup:?}") };
|
||||
refusal
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusing_payload_replaces_a_good_record() {
|
||||
let main = catalog("p", "main");
|
||||
let mut store = RecordStore::new();
|
||||
store.subscribe(Interest::Prefix(prefix("p", CATALOG, "")));
|
||||
let at = put(&mut store, "p", &main);
|
||||
assert!(matches!(store.read(&at), Lookup::Present(_)));
|
||||
store.drain();
|
||||
|
||||
store.admit_contract(at.clone(), garbage(), CLOCK, |_| Ok(()));
|
||||
|
||||
let lookup = store.read(&at);
|
||||
let refusal = refused(&lookup).clone();
|
||||
assert_eq!(refusal.address, at);
|
||||
assert_eq!(refusal.kind, SchemaId::new(CATALOG));
|
||||
assert_eq!(store.drain(), vec![Change::Refused(refusal)]);
|
||||
assert_eq!(store.list(&prefix("p", CATALOG, "")).len(), 1, "the old record no longer stands");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_good_record_replaces_a_refusal() {
|
||||
let main = catalog("p", "main");
|
||||
let at = catalog_at("p", &main);
|
||||
let mut store = RecordStore::new();
|
||||
store.admit_contract(at.clone(), garbage(), CLOCK, |_| Ok(()));
|
||||
assert!(matches!(store.read(&at), Lookup::Refused(_)));
|
||||
|
||||
put(&mut store, "p", &main);
|
||||
|
||||
assert!(matches!(store.read(&at), Lookup::Present(_)));
|
||||
assert_eq!(store.keys(&at.provider, &at.schema), vec![at.key.clone()], "held once, not also refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accept_sees_the_decoded_record_and_may_pass_it() {
|
||||
let main = catalog("p", "main");
|
||||
let at = catalog_at("p", &main);
|
||||
let mut store = RecordStore::new();
|
||||
store.subscribe(Interest::Record(at.clone()));
|
||||
let mut seen = None;
|
||||
store.admit_contract(at.clone(), payload(&main), CLOCK, |record| {
|
||||
seen = Some(record.clone());
|
||||
Ok(())
|
||||
});
|
||||
assert_eq!(seen, Some(Record::Catalog(main.clone())));
|
||||
assert_eq!(store.drain(), vec![upsert(at, Record::Catalog(main))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accept_refuses_after_decode() {
|
||||
let main = catalog("p", "main");
|
||||
let at = catalog_at("p", &main);
|
||||
let mut store = RecordStore::new();
|
||||
store.subscribe(Interest::Record(at.clone()));
|
||||
put(&mut store, "p", &main);
|
||||
store.drain();
|
||||
|
||||
store.admit_contract(at.clone(), payload(&main), CLOCK, |_| Err("filed under another route".into()));
|
||||
|
||||
let lookup = store.read(&at);
|
||||
assert_eq!(refused(&lookup).detail, "filed under another route");
|
||||
let drained = store.drain();
|
||||
assert_eq!(drained.len(), 1, "{drained:?}");
|
||||
assert!(matches!(&drained[0], Change::Refused(refusal) if refusal.detail == "filed under another route"));
|
||||
|
||||
// A first-time record accept refuses is never held.
|
||||
let other = catalog("p", "other");
|
||||
let other_at = catalog_at("p", &other);
|
||||
store.admit_contract(other_at.clone(), payload(&other), CLOCK, |_| Err("no".into()));
|
||||
assert!(matches!(store.read(&other_at), Lookup::Refused(_)));
|
||||
assert_eq!(store.list(&prefix("p", CATALOG, "")).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_schema_that_is_not_a_contract_kind_is_refused_at_the_contract_door() {
|
||||
let mut store = RecordStore::new();
|
||||
let at = address("p", STATE, "row");
|
||||
store.admit_contract(at.clone(), one(1), CLOCK, |_| Ok(()));
|
||||
let lookup = store.read(&at);
|
||||
assert!(refused(&lookup).detail.contains(STATE));
|
||||
assert!(!is_contract(&SchemaId::new(STATE)));
|
||||
assert!(is_contract(&SchemaId::new(SURFACE)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_state_decodes_with_rows_and_refuses_without() {
|
||||
let mut store = RecordStore::new();
|
||||
store.subscribe(Interest::Prefix(prefix("p", STATE, "")));
|
||||
let good = address("p", STATE, "good");
|
||||
let bad = address("p", STATE, "bad");
|
||||
store.admit_state(good.clone(), one(7), &rows());
|
||||
store.admit_state(bad.clone(), one(7), &[]);
|
||||
|
||||
let value = StateValue::Record(vec![("n".into(), StateValue::Int(7.into()))]);
|
||||
let record = Record::State { schema: SchemaId::new(STATE), value };
|
||||
assert_eq!(store.read(&good), Lookup::Present(Entry { address: good.clone(), record: record.clone() }));
|
||||
let lookup = store.read(&bad);
|
||||
assert!(refused(&lookup).detail.starts_with(STATE), "{}", refused(&lookup).detail);
|
||||
let drained = store.drain();
|
||||
assert_eq!(drained.len(), 2, "{drained:?}");
|
||||
assert_eq!(drained[0], upsert(good.clone(), record));
|
||||
assert!(matches!(&drained[1], Change::Refused(refusal) if refusal.address == bad));
|
||||
|
||||
// A refusal replaces the good record under the key.
|
||||
store.admit_state(good.clone(), vec![0xc1], &rows());
|
||||
assert!(matches!(store.read(&good), Lookup::Refused(_)));
|
||||
// The same key under another provider is another slot.
|
||||
assert_eq!(store.read(&address("q", STATE, "good")), Lookup::Absent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_contract_schema_is_refused_at_the_state_doors() {
|
||||
let mut store = RecordStore::new();
|
||||
let at = address("p", CATALOG, "k");
|
||||
store.admit_state(at.clone(), one(1), &rows());
|
||||
assert!(refused(&store.read(&at)).detail.contains("contract kind"));
|
||||
let other = address("p", CATALOG, "j");
|
||||
store.admit_value(other.clone(), StateValue::Nil);
|
||||
assert!(refused(&store.read(&other)).detail.contains("contract kind"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admit_value_bypasses_the_decode_and_a_read_of_another_schema_answers_the_held_one() {
|
||||
let mut store = RecordStore::new();
|
||||
let at = address("p", STATE, "row");
|
||||
store.admit_value(at.clone(), StateValue::Bytes(vec![1, 2].into()));
|
||||
let asked = address("p", "gamecult.thing.other.v1", "row");
|
||||
// The slot is the provider and key; the held schema rides in the record.
|
||||
let Lookup::Present(entry) = store.read(&asked) else { panic!("absent") };
|
||||
assert!(matches!(entry.record, Record::State { schema, .. } if schema == SchemaId::new(STATE)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuse_holds_what_a_transport_states() {
|
||||
let mut store = RecordStore::new();
|
||||
store.subscribe(Interest::Prefix(prefix("p", STATE, "")));
|
||||
let at = address("p", STATE, "row");
|
||||
store.admit_state(at.clone(), one(1), &rows());
|
||||
store.drain();
|
||||
store.refuse(at.clone(), "no member rows".into());
|
||||
let lookup = store.read(&at);
|
||||
assert_eq!(refused(&lookup).detail, "no member rows");
|
||||
assert_eq!(refused(&lookup).kind, SchemaId::new(STATE));
|
||||
assert_eq!(store.drain(), vec![Change::Refused(refused(&lookup).clone())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_is_a_change_only_when_something_is_held() {
|
||||
let main = catalog("p", "main");
|
||||
let mut store = RecordStore::new();
|
||||
store.subscribe(Interest::Prefix(prefix("p", CATALOG, "")));
|
||||
store.subscribe(Interest::Prefix(prefix("p", STATE, "")));
|
||||
let at = put(&mut store, "p", &main);
|
||||
let state_at = address("p", STATE, "row");
|
||||
store.admit_state(state_at.clone(), one(1), &rows());
|
||||
store.drain();
|
||||
|
||||
store.remove(&at);
|
||||
store.remove(&state_at);
|
||||
assert_eq!(store.read(&at), Lookup::Absent);
|
||||
assert_eq!(store.read(&state_at), Lookup::Absent);
|
||||
assert_eq!(store.drain(), vec![Change::Delete(at.clone()), Change::Delete(state_at.clone())]);
|
||||
|
||||
store.remove(&at);
|
||||
store.remove(&state_at);
|
||||
store.remove(&address("nobody", CATALOG, "k"));
|
||||
assert!(store.drain().is_empty());
|
||||
|
||||
// A refusal is removable; the state slot answers only for its own schema.
|
||||
store.admit_contract(at.clone(), garbage(), CLOCK, |_| Ok(()));
|
||||
store.drain();
|
||||
store.remove(&at);
|
||||
assert_eq!(store.drain(), vec![Change::Delete(at)]);
|
||||
store.admit_state(state_at.clone(), one(1), &rows());
|
||||
store.drain();
|
||||
store.remove(&address("p", "gamecult.thing.other.v1", "row"));
|
||||
assert!(store.drain().is_empty());
|
||||
assert!(matches!(store.read(&state_at), Lookup::Present(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn purge_is_silent() {
|
||||
let mut store = RecordStore::new();
|
||||
store.subscribe(Interest::Prefix(prefix("p", CATALOG, "")));
|
||||
store.subscribe(Interest::Prefix(prefix("p", STATE, "")));
|
||||
let main = catalog("p", "main");
|
||||
let main_at = put(&mut store, "p", &main);
|
||||
let bad_at = address("p", CATALOG, "thing:asset_catalog:p.bad");
|
||||
store.admit_contract(bad_at.clone(), garbage(), CLOCK, |_| Ok(()));
|
||||
let theirs = catalog("q", "main");
|
||||
let theirs_at = put(&mut store, "q", &theirs);
|
||||
let state_at = address("p", STATE, "row");
|
||||
store.admit_state(state_at.clone(), one(1), &rows());
|
||||
// The same provider's other schemas and the same schema at another provider.
|
||||
let other_state = address("p", "gamecult.thing.other.v1", "other-row");
|
||||
store.admit_state(other_state.clone(), one(1), &rows());
|
||||
let theirs_state = address("q", STATE, "row");
|
||||
store.admit_state(theirs_state.clone(), one(1), &rows());
|
||||
let surface_refused = address("p", SURFACE, "thing:surface:p.bad");
|
||||
store.admit_contract(surface_refused.clone(), garbage(), CLOCK, |_| Ok(()));
|
||||
let theirs_refused = address("q", CATALOG, "thing:asset_catalog:q.bad");
|
||||
store.admit_contract(theirs_refused.clone(), garbage(), CLOCK, |_| Ok(()));
|
||||
store.drain();
|
||||
|
||||
store.purge(&ProviderId::new("p"), &SchemaId::new(CATALOG));
|
||||
|
||||
assert_eq!(store.read(&main_at), Lookup::Absent);
|
||||
assert_eq!(store.read(&bad_at), Lookup::Absent);
|
||||
assert!(matches!(store.read(&theirs_at), Lookup::Present(_)), "another provider stays");
|
||||
assert!(matches!(store.read(&state_at), Lookup::Present(_)), "another schema stays");
|
||||
assert!(matches!(store.read(&surface_refused), Lookup::Refused(_)), "another contract schema's refusal stays");
|
||||
assert!(matches!(store.read(&theirs_refused), Lookup::Refused(_)), "another provider's refusal stays");
|
||||
assert!(store.drain().is_empty(), "the consumer letting go is not the provider deleting");
|
||||
|
||||
store.purge(&ProviderId::new("p"), &SchemaId::new(STATE));
|
||||
assert_eq!(store.read(&state_at), Lookup::Absent);
|
||||
assert!(matches!(store.read(&other_state), Lookup::Present(_)), "the provider's other state schema stays");
|
||||
assert!(matches!(store.read(&theirs_state), Lookup::Present(_)), "another provider's state stays");
|
||||
assert!(store.drain().is_empty());
|
||||
// Purging what is not held, or a provider never seen, is nothing.
|
||||
store.purge(&ProviderId::new("nobody"), &SchemaId::new(CATALOG));
|
||||
store.purge(&ProviderId::new("p"), &SchemaId::new(SURFACE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_includes_refusals() {
|
||||
let mut store = RecordStore::new();
|
||||
let held = put(&mut store, "p", &catalog("p", "b"));
|
||||
let bad = address("p", CATALOG, "thing:asset_catalog:p.a");
|
||||
store.admit_contract(bad.clone(), garbage(), CLOCK, |_| Ok(()));
|
||||
put(&mut store, "q", &catalog("q", "c")); // another provider
|
||||
let state_at = address("p", STATE, "row");
|
||||
store.admit_state(state_at.clone(), one(1), &rows());
|
||||
store.admit_state(address("p", STATE, "bad"), one(1), &[]);
|
||||
store.admit_state(address("q", STATE, "elsewhere"), one(1), &rows()); // another provider
|
||||
store.admit_state(address("p", "gamecult.thing.other.v1", "other-schema"), one(1), &rows()); // another schema
|
||||
|
||||
let provider = ProviderId::new("p");
|
||||
assert_eq!(store.keys(&provider, &SchemaId::new(CATALOG)), vec![bad.key, held.key]);
|
||||
assert_eq!(store.keys(&provider, &SchemaId::new(STATE)), vec![RecordKey::new("bad"), RecordKey::new("row")]);
|
||||
assert!(store.keys(&provider, &SchemaId::new(SURFACE)).is_empty());
|
||||
assert!(store.keys(&ProviderId::new("nobody"), &SchemaId::new(CATALOG)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_returns_one_provider_and_schema_in_key_order_with_refusals() {
|
||||
let mut store = RecordStore::new();
|
||||
let b = put(&mut store, "p", &catalog("p", "b"));
|
||||
let a = address("p", CATALOG, "thing:asset_catalog:p.a");
|
||||
store.admit_contract(a.clone(), garbage(), CLOCK, |_| Ok(()));
|
||||
let c = put(&mut store, "p", &catalog("p", "c"));
|
||||
put(&mut store, "q", &catalog("q", "a")); // another provider, same schema
|
||||
store.admit_state(address("p", STATE, "thing:asset_catalog:p.0"), one(1), &rows()); // another schema, same provider
|
||||
store.admit_contract(address("p", SURFACE, "thing:asset_catalog:p.z"), garbage(), CLOCK, |_| Ok(())); // a refusal of another schema
|
||||
|
||||
let listed = store.list(&prefix("p", CATALOG, "thing:"));
|
||||
let keys: Vec<&str> = listed
|
||||
.iter()
|
||||
.map(|lookup| match lookup {
|
||||
Lookup::Present(entry) => entry.address.key.as_str(),
|
||||
Lookup::Refused(refusal) => refusal.address.key.as_str(),
|
||||
Lookup::Absent => panic!("absent in a list"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(keys, vec![a.key.as_str(), b.key.as_str(), c.key.as_str()]);
|
||||
assert!(matches!(listed[0], Lookup::Refused(_)));
|
||||
assert!(listed.iter().all(|lookup| match lookup {
|
||||
Lookup::Present(entry) => entry.address.provider.as_str() == "p" && entry.address.schema.as_str() == CATALOG,
|
||||
Lookup::Refused(refusal) => refusal.address.provider.as_str() == "p" && refusal.kind.as_str() == CATALOG,
|
||||
Lookup::Absent => false,
|
||||
}));
|
||||
|
||||
// The key prefix narrows; provider state obeys the same rule.
|
||||
assert_eq!(store.list(&prefix("p", CATALOG, "thing:asset_catalog:p.b")).len(), 1);
|
||||
store.admit_state(address("p", STATE, "row-2"), one(2), &rows());
|
||||
store.admit_state(address("p", STATE, "row-1"), one(1), &rows());
|
||||
store.admit_state(address("p", STATE, "other"), one(3), &[]);
|
||||
store.admit_state(address("q", STATE, "row-0"), one(0), &rows());
|
||||
store.admit_state(address("p", "gamecult.thing.other.v1", "row-bad"), one(0), &[]); // another schema's refusal
|
||||
let state: Vec<Lookup> = store.list(&prefix("p", STATE, "row-"));
|
||||
assert_eq!(state.len(), 2);
|
||||
assert!(matches!(&state[0], Lookup::Present(entry) if entry.address.key.as_str() == "row-1"));
|
||||
assert!(matches!(&state[1], Lookup::Present(entry) if entry.address.key.as_str() == "row-2"));
|
||||
let all = store.list(&prefix("p", STATE, ""));
|
||||
assert_eq!(all.len(), 4, "a refusal is listed with its schema's records");
|
||||
assert!(matches!(&all[0], Lookup::Refused(refusal) if refusal.address.key.as_str() == "other"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_queue_only_under_a_matching_interest_and_unsubscribing_recalls_nothing() {
|
||||
let mut store = RecordStore::new();
|
||||
put(&mut store, "p", &catalog("p", "unwatched"));
|
||||
assert!(store.drain().is_empty());
|
||||
|
||||
let ids: Vec<SubscriptionId> = vec![
|
||||
store.subscribe(Interest::Prefix(prefix("p", CATALOG, "thing:"))),
|
||||
store.subscribe(Interest::Record(catalog_at("p", &catalog("p", "one")))),
|
||||
];
|
||||
assert_eq!(ids[0], SubscriptionId(0));
|
||||
assert_eq!(ids[1], SubscriptionId(1));
|
||||
assert_eq!(store.interests().count(), 2);
|
||||
let one_at = put(&mut store, "p", &catalog("p", "one")); // matches both interests and queues once
|
||||
put(&mut store, "q", &catalog("q", "one")); // no interest
|
||||
store.unsubscribe(ids[0]);
|
||||
store.unsubscribe(ids[1]);
|
||||
assert_eq!(store.interests().count(), 0);
|
||||
assert_eq!(store.drain(), vec![upsert(one_at, Record::Catalog(catalog("p", "one")))]);
|
||||
assert!(store.drain().is_empty(), "each change drains once");
|
||||
put(&mut store, "p", &catalog("p", "two"));
|
||||
assert!(store.drain().is_empty());
|
||||
let id = store.subscribe(Interest::Prefix(prefix("p", CATALOG, "")));
|
||||
assert_eq!(id, SubscriptionId(2), "ids are never reused");
|
||||
}
|
||||
|
|
@ -10,7 +10,6 @@ thing-contract = { path = "../thing-contract" }
|
|||
cultcache-rs = { workspace = true }
|
||||
thing-core = { path = "../thing-core" }
|
||||
thing-state = { path = "../thing-state" }
|
||||
anyhow = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
|
|
|
|||
|
|
@ -1,79 +1,39 @@
|
|||
//! `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.
|
||||
//! `MemState`: an in-memory `StatePort`, the test front of `thing_state::RecordStore`. The store
|
||||
//! owns every record, refusal, interest and queued change; `MemState` feeds it typed values,
|
||||
//! payloads and fixtures, and logs each port call it receives.
|
||||
//!
|
||||
//! A provider's own state (any schema outside the contract) is held per (provider, key), one record
|
||||
//! per key as CultCache holds them, already decoded by `thing_state::decode` with
|
||||
//! the schema's catalog member rows. A payload that decode refuses is held as a refusal.
|
||||
//! A typed value is encoded with the contract and admitted through the store's one decode door,
|
||||
//! the door a raw payload meets. A payload the contract refuses is never stored: the address
|
||||
//! becomes refused, and stays refused until a record or a delete replaces it. A provider's own
|
||||
//! state (any schema outside the contract) is decoded with the schema's catalog member rows;
|
||||
//! `put_value` alone bypasses that decode, for the kinds a typed record cannot hold.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use cultcache_rs::{
|
||||
CacheBackingStore, CultCache, CultCacheEnvelope, DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore,
|
||||
resolve_schema_entry,
|
||||
};
|
||||
use cultcache_rs::{CacheBackingStore, CultCache, DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore, resolve_schema_entry};
|
||||
use thing_contract::*;
|
||||
use thing_state::decode;
|
||||
use thing_core::port::{
|
||||
Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, StateValue, SubscriptionId,
|
||||
};
|
||||
use thing_core::port::{Address, Change, Interest, Lookup, Prefix, StatePort, StateValue, SubscriptionId};
|
||||
use thing_state::{RecordStore, is_contract};
|
||||
|
||||
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),* $(,)?) => {
|
||||
($($kind: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,
|
||||
}
|
||||
};
|
||||
}
|
||||
state_kinds!(SurfaceDocument, CompositionDocument, CommandResult, AssetCatalog);
|
||||
|
||||
/// One call the port received.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
|
@ -85,22 +45,6 @@ pub enum Call {
|
|||
Drain,
|
||||
}
|
||||
|
||||
/// What a provider key holds of provider state.
|
||||
#[derive(Clone)]
|
||||
enum Held {
|
||||
Value { schema: SchemaId, value: StateValue },
|
||||
Refused(Refusal),
|
||||
}
|
||||
|
||||
impl Held {
|
||||
fn schema(&self) -> &SchemaId {
|
||||
match self {
|
||||
Held::Value { schema, .. } => schema,
|
||||
Held::Refused(refusal) => &refusal.kind,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The schema id of the contract kind whose CultCache entry type is `entry_type`.
|
||||
fn contract_schema(entry_type: &str) -> Option<&'static str> {
|
||||
[
|
||||
|
|
@ -113,17 +57,8 @@ fn contract_schema(entry_type: &str) -> Option<&'static str> {
|
|||
.find_map(|(entry, schema)| (entry == entry_type).then_some(schema))
|
||||
}
|
||||
|
||||
fn is_contract(schema: &SchemaId) -> bool {
|
||||
by_schema!(schema.as_str(), _T => true, else false)
|
||||
}
|
||||
|
||||
pub struct MemState {
|
||||
providers: HashMap<String, CultCache>,
|
||||
state: HashMap<(String, String), Held>,
|
||||
refused: HashMap<Address, Refusal>,
|
||||
interests: Vec<(SubscriptionId, Interest)>,
|
||||
next_subscription: u64,
|
||||
queue: Vec<Change>,
|
||||
store: RecordStore,
|
||||
calls: RefCell<Vec<Call>>,
|
||||
}
|
||||
|
||||
|
|
@ -135,15 +70,7 @@ impl Default for MemState {
|
|||
|
||||
impl MemState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
providers: HashMap::new(),
|
||||
state: HashMap::new(),
|
||||
refused: HashMap::new(),
|
||||
interests: Vec::new(),
|
||||
next_subscription: 0,
|
||||
queue: Vec::new(),
|
||||
calls: RefCell::new(Vec::new()),
|
||||
}
|
||||
Self { store: RecordStore::new(), calls: RefCell::new(Vec::new()) }
|
||||
}
|
||||
|
||||
/// A state holding every document of a fixture, each under the provider that publishes it. Invocations
|
||||
|
|
@ -172,24 +99,14 @@ impl MemState {
|
|||
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);
|
||||
self.put_raw(address, store::payload(value));
|
||||
}
|
||||
|
||||
/// 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()))
|
||||
assert!(is_contract(&address.schema), "no contract record kind has schema {}", address.schema.as_str());
|
||||
self.store.admit_contract(address, payload, store::PINNED_CLOCK, |_| Ok(()));
|
||||
}
|
||||
|
||||
/// Store provider state `value` under `key` at `provider`: the type's own schema and member
|
||||
|
|
@ -209,33 +126,17 @@ impl MemState {
|
|||
|
||||
/// Store an already-decoded provider-state `value` under `address`, as a port that decoded it
|
||||
/// would hand it over: for the kinds a typed record cannot hold (bytes, a float where an int is
|
||||
/// asked), which the tests of a reader feed through the one door.
|
||||
/// asked), which the tests of a reader feed through the one door. It bypasses the decode.
|
||||
pub fn put_value(&mut self, address: Address, value: StateValue) {
|
||||
assert!(!is_contract(&address.schema), "{} is a contract kind: put", address.schema.as_str());
|
||||
let slot = (address.provider.as_str().to_string(), address.key.as_str().to_string());
|
||||
let schema = address.schema.clone();
|
||||
self.state.insert(slot, Held::Value { schema: schema.clone(), value: value.clone() });
|
||||
self.queue(Change::Upsert(Entry { address, record: Record::State { schema, value } }));
|
||||
self.store.admit_value(address, value);
|
||||
}
|
||||
|
||||
/// Store a provider-state payload under `address`, decoded with the schema's member `rows`.
|
||||
/// A payload decode refuses makes the key refused, replacing any record it held.
|
||||
pub fn put_state_raw(&mut self, address: Address, payload: Vec<u8>, rows: &[SchemaCatalogMember]) {
|
||||
assert!(!is_contract(&address.schema), "{} is a contract kind: put_raw", address.schema.as_str());
|
||||
let slot = (address.provider.as_str().to_string(), address.key.as_str().to_string());
|
||||
match decode(&payload, rows) {
|
||||
Ok(value) => {
|
||||
let schema = address.schema.clone();
|
||||
self.state.insert(slot, Held::Value { schema: schema.clone(), value: value.clone() });
|
||||
self.queue(Change::Upsert(Entry { address, record: Record::State { schema, value } }));
|
||||
}
|
||||
Err(error) => {
|
||||
let detail = format!("{}: {error}", address.schema.as_str());
|
||||
let refusal = Refusal { kind: address.schema.clone(), address, detail };
|
||||
self.state.insert(slot, Held::Refused(refusal.clone()));
|
||||
self.queue(Change::Refused(refusal));
|
||||
}
|
||||
}
|
||||
self.store.admit_state(address, payload, rows);
|
||||
}
|
||||
|
||||
/// Read a single-file store, routing each record: a contract kind to `put_raw`, anything else
|
||||
|
|
@ -268,149 +169,38 @@ impl MemState {
|
|||
|
||||
/// Remove the record or the refusal at `address`; removing nothing is not a change.
|
||||
pub fn delete(&mut self, address: &Address) {
|
||||
if !is_contract(&address.schema) {
|
||||
let slot = (address.provider.as_str().to_string(), address.key.as_str().to_string());
|
||||
if self.state.get(&slot).is_some_and(|held| held.schema() == &address.schema) {
|
||||
self.state.remove(&slot);
|
||||
self.queue(Change::Delete(address.clone()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
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()));
|
||||
}
|
||||
self.store.remove(address);
|
||||
}
|
||||
|
||||
/// 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 !is_contract(&address.schema) {
|
||||
return match self.state.get(&(address.provider.as_str().to_string(), address.key.as_str().to_string())) {
|
||||
Some(Held::Value { schema, value }) => Lookup::Present(Entry {
|
||||
address: address.clone(),
|
||||
record: Record::State { schema: schema.clone(), value: value.clone() },
|
||||
}),
|
||||
Some(Held::Refused(refusal)) => Lookup::Refused(refusal.clone()),
|
||||
None => Lookup::Absent,
|
||||
};
|
||||
}
|
||||
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,
|
||||
}
|
||||
}, else unreachable!("is_contract admitted the schema"))
|
||||
self.store.read(address)
|
||||
}
|
||||
|
||||
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();
|
||||
if !is_contract(&prefix.schema) {
|
||||
for ((provider, key), held) in &self.state {
|
||||
if provider != prefix.provider.as_str() || !key.starts_with(&prefix.key_prefix) {
|
||||
continue;
|
||||
}
|
||||
match held {
|
||||
Held::Value { schema, value } if schema == &prefix.schema => {
|
||||
let record = Record::State { schema: schema.clone(), value: value.clone() };
|
||||
found.push((key.clone(), Lookup::Present(Entry { address: at(key), record })));
|
||||
}
|
||||
Held::Refused(refusal) if refusal.kind == prefix.schema => {
|
||||
found.push((key.clone(), Lookup::Refused(refusal.clone())));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
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 unreachable!("is_contract admitted the schema"));
|
||||
}
|
||||
found.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
found.into_iter().map(|(_, lookup)| lookup).collect()
|
||||
self.store.list(prefix)
|
||||
}
|
||||
|
||||
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
|
||||
self.store.subscribe(interest)
|
||||
}
|
||||
|
||||
fn unsubscribe(&mut self, id: SubscriptionId) {
|
||||
self.calls.borrow_mut().push(Call::Unsubscribe(id));
|
||||
self.interests.retain(|(live, _)| *live != id);
|
||||
self.store.unsubscribe(id);
|
||||
}
|
||||
|
||||
fn drain(&mut self) -> Vec<Change> {
|
||||
self.calls.borrow_mut().push(Call::Drain);
|
||||
std::mem::take(&mut self.queue)
|
||||
self.store.drain()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue