CultNet: schema catalog serves member rows on request (C# server, contract) (#195)

This commit is contained in:
Eureka 2026-11-28 06:54:17 +00:00
commit ccac93abf1
23 changed files with 935 additions and 15 deletions

View file

@ -154,6 +154,13 @@ A malformed put or delete is `message_invalid`, not a per-operation code: the pe
- The C# writer sets every key of a `database_change_raw` message, nil where unset: a removed change carries `document`
nil, an added or updated one `recordKey` and `schemaId` nil. The schema accepts those nils; an added or updated change
still needs a document, and a removed one a `recordKey` and `schemaId`.
- A database or subscription server answers `schema_catalog_request` for each document type its cache registers: kind
`document_payload`, `contentHash` equal to the `schemaContentHash` that type's records carry, `schemaJson` left to
contract schemas and never filled with cache schema JSON. A request that sets `includeMembers` (optional, default false)
gets each descriptor's `members`, the rows every store catalog writes for the type (`slot`, `name`, `type`,
`isReference`, `isMany`, `targetSchemaName`, `isName`, `indexAlias`), in slot order; a peer that did not ask never sees the key.
A subscriber caches rows by `schemaId` plus `schemaContentHash`, and a record whose hash it has no rows for is decoded only after a
catalog request. Both fields are additive within `cultnet.schema_catalog_*.v0`; the C# subscription server serves them first.
- Client-owned input documents may be predicted locally only inside explicit
`CultNetClientAuthorityScope` declarations.
- Predicted input state is not authoritative shared state. The shard log still

View file

@ -12,6 +12,7 @@
"schemaVersion": { "const": "cultnet.schema_catalog_request.v0" },
"messageId": { "type": "string", "minLength": 1 },
"includeSchemaJson": { "type": "boolean" },
"includeMembers": { "type": "boolean" },
"schemaIds": {
"type": "array",
"items": { "type": "string", "minLength": 1 }

View file

@ -34,6 +34,31 @@
}
},
"contentHash": { "type": "string", "minLength": 1 },
"schemaJson": { "type": "string", "minLength": 1 }
"schemaJson": { "type": "string", "minLength": 1 },
"members": {
"type": "array",
"items": {
"type": "object",
"required": [
"slot",
"name",
"type",
"isReference",
"isMany",
"isName"
],
"additionalProperties": false,
"properties": {
"slot": { "type": "integer", "minimum": 0 },
"name": { "type": "string", "minLength": 1 },
"type": { "type": "string", "minLength": 1 },
"isReference": { "type": "boolean" },
"isMany": { "type": "boolean" },
"targetSchemaName": { "type": ["string", "null"] },
"isName": { "type": "boolean" },
"indexAlias": { "type": ["string", "null"] }
}
}
}
}
}

View file

@ -2,6 +2,7 @@
## Unreleased (breaking; version 0.x, so the next minor)
- `schema_catalog_request(include_members=True)` asks a server for each document type's member rows; `CultNetSchemaDescriptor.members` (a tuple of `CultNetSchemaMember`, or None) reads them from a response and `to_wire(include_members=True)` writes them. Both are additive and optional: a request or descriptor without them keeps its older wire shape. A cache subscriber keys rows by `schemaId` plus `schemaContentHash`.
- `raw_record_to_envelope`, where a replicated record becomes an envelope, refuses a record whose `storedAt` is missing, empty or not a stamp (`cultcache_py.stores.parse_stored_at`, the shape pinned by `tests/vectors/stored-at-stamp`) with `ValueError`, nothing minted or stored (`variants:ruling:raw-put-without-stamp-refused`). `apply_raw_document_record`, `apply_raw_snapshot` and `apply_shard_log_response` come through it: a snapshot response with such a record is refused whole before any of its records is stored, as one naming an unregistered schema is; a shard log refuses at that entry, the entries before it already applied. It stored the record under `""`, and the next open of the store raised `CultCacheError` `Missing envelope`. `cultmesh-py`'s raw put builds its envelope through the same function, so there is one owner of the check there; its server gate still answers a peer's put `message_invalid`. A client's `read_next_change` lets the `ValueError` out.
- `decode_witness_artifact_bundle_payload` (and `CultNetWitnessArtifactBundle.from_payload`) read the payload through `cultcache_py.read_payload_tree`: bytes after its first MessagePack value raise `ValueError` `cultnet.witness_artifact_bundle payload has N bytes after its first MessagePack value (refused on read).` instead of `msgpack.ExtraData`, and a payload nested past 256 raises `CultCachePayloadDepthError`. Needs `cultcache-py` 0.4.0, the release that exports `read_payload_tree`: the dependency is now `cultcache-py>=0.4.0` (it was `>=0.2.0`, which admits releases whose `import cultnet_py` fails), and `tests/test_declared_dependency_ranges.py` fails when a declared bound admits a tagged release lacking a name the package imports. The same check found `cultmesh-py` importing `cache.index_text`, which `cultcache-py` 0.2.0 lacks; its bound is `cultcache-py>=0.4.0` too (it has no changelog of its own). `resolve_document_for_raw_record` reads the schema hint from a raw record's first value whether or not bytes follow it, so a record routed by its stamp is refused by count when applied (`ValueError`, in a snapshot, a shard log and a direct apply) like one routed by a registered schema id; `apply_shard_log_response` used to skip it silently as an unknown schema. A tail on a payload whose first value names no registered schema is still `KeyError`, which a shard log skips.
- `apply_raw_document_record` and `apply_raw_snapshot` raise `SchemaConflictError` when a remote record is of another type than the one the cache holds at its key (`cultcache-py` holds one record per key whatever its type); the cache is unchanged, and the caller decides whether to drop the record or the peer. `cultmesh-py`'s server answers such a put with `message_invalid`; its client's `read_next_change` lets the error out.

View file

@ -80,6 +80,7 @@ from .replication import (
from .schema_catalog import (
CultNetSchemaCatalog,
CultNetSchemaDescriptor,
CultNetSchemaMember,
INTEROP_WIRE_CONTRACT,
wire_message_schema_descriptors,
wire_message_schema_catalog,
@ -195,6 +196,7 @@ __all__ = [
"CultNetServerSecurityOptions",
"CultNetSchemaCatalog",
"CultNetSchemaDescriptor",
"CultNetSchemaMember",
"CultNetShardCatalog",
"CultNetShardDescriptor",
"CultNetShardLogEntry",

View file

@ -350,16 +350,17 @@ def schema_catalog_request(
include_schema_json: bool = False,
schema_ids: list[str] | None = None,
kinds: list[str] | None = None,
include_members: bool = False,
) -> CultNetMessage:
return CultNetMessage(
"cultnet.schema_catalog_request.v0",
{
"messageId": message_id,
"includeSchemaJson": include_schema_json,
"schemaIds": schema_ids or [],
"kinds": kinds or [],
},
)
body: dict[str, Any] = {
"messageId": message_id,
"includeSchemaJson": include_schema_json,
"schemaIds": schema_ids or [],
"kinds": kinds or [],
}
if include_members:
body["includeMembers"] = True
return CultNetMessage("cultnet.schema_catalog_request.v0", body)
def database_subscribe(

View file

@ -58,6 +58,48 @@ SHARED_CONTRACT_SCHEMA_VERSIONS = (
)
@dataclass(frozen=True)
class CultNetSchemaMember:
"""One member row of a document-payload schema: the row every store catalog writes for a member."""
slot: int
name: str
type: str
is_reference: bool = False
is_many: bool = False
target_schema_name: str | None = None
is_name: bool = False
index_alias: str | None = None
@classmethod
def from_wire(cls, value: dict[str, Any]) -> "CultNetSchemaMember":
return cls(
slot=int(value["slot"]),
name=str(value["name"]),
type=str(value["type"]),
is_reference=value.get("isReference") is True,
is_many=value.get("isMany") is True,
target_schema_name=_optional_string(value.get("targetSchemaName")),
is_name=value.get("isName") is True,
index_alias=_optional_string(value.get("indexAlias")),
)
def to_wire(self) -> dict[str, Any]:
wire: dict[str, Any] = {
"slot": self.slot,
"name": self.name,
"type": self.type,
"isReference": self.is_reference,
"isMany": self.is_many,
"isName": self.is_name,
}
if self.target_schema_name is not None:
wire["targetSchemaName"] = self.target_schema_name
if self.index_alias is not None:
wire["indexAlias"] = self.index_alias
return wire
@dataclass(frozen=True)
class CultNetSchemaDescriptor:
schema_id: str
@ -68,6 +110,8 @@ class CultNetSchemaDescriptor:
wire_contracts: tuple[str, ...] = ()
content_hash: str | None = None
schema_json: str | None = None
# The member rows, present only on a response to a request that set includeMembers; None leaves the key off the wire.
members: tuple[CultNetSchemaMember, ...] | None = None
@classmethod
def from_wire(cls, value: dict[str, Any]) -> "CultNetSchemaDescriptor":
@ -86,9 +130,14 @@ class CultNetSchemaDescriptor:
wire_contracts=tuple(str(contract) for contract in value.get("wireContracts") or []),
content_hash=_optional_string(value.get("contentHash")),
schema_json=_optional_string(value.get("schemaJson")),
members=(
tuple(CultNetSchemaMember.from_wire(row) for row in value["members"])
if isinstance(value.get("members"), list)
else None
),
)
def to_wire(self, *, include_schema_json: bool | None = None) -> dict[str, Any]:
def to_wire(self, *, include_schema_json: bool | None = None, include_members: bool = False) -> dict[str, Any]:
wire: dict[str, Any] = {
"schemaId": self.schema_id,
"kind": self.kind,
@ -104,6 +153,8 @@ class CultNetSchemaDescriptor:
wire["contentHash"] = self.content_hash
if self.schema_json is not None and include_schema_json is not False:
wire["schemaJson"] = self.schema_json
if self.members is not None and include_members:
wire["members"] = [member.to_wire() for member in self.members]
return wire
@ -149,6 +200,7 @@ class CultNetSchemaCatalog:
*,
message_id: str = "",
include_schema_json: bool = False,
include_members: bool = False,
schema_ids: list[str] | None = None,
kinds: list[str] | None = None,
) -> dict[str, Any]:
@ -156,7 +208,7 @@ class CultNetSchemaCatalog:
"schemaVersion": "cultnet.schema_catalog_response.v0",
"messageId": message_id,
"schemas": [
descriptor.to_wire(include_schema_json=include_schema_json)
descriptor.to_wire(include_schema_json=include_schema_json, include_members=include_members)
for descriptor in self.list(schema_ids=schema_ids, kinds=kinds)
],
}

View file

@ -1631,6 +1631,33 @@ class CultNetTests(unittest.TestCase):
self.assertEqual(put["shardId"], "interop")
self.assertEqual(put["shardEpoch"], 1)
def test_schema_catalog_decodes_the_csharp_written_response_with_members(self) -> None:
# contracts/cultnet/interop/schema-catalog-members.cs-written.msgpack: the C# server's answer to includeMembers; its nil
# schemaJson/targetSchemaName/indexAlias are written as nil, and the members key is absent from a descriptor that has none.
vector = Path(__file__).resolve().parents[3] / "contracts" / "cultnet" / "interop" / "schema-catalog-members.cs-written.msgpack"
response = msgpack.unpackb(vector.read_bytes(), raw=False)
catalog = CultNetSchemaCatalog()
citer, leaf = catalog.apply_response(response)
self.assertIsNone(citer.schema_json)
self.assertEqual(
[(m.slot, m.name, m.type, m.is_reference, m.is_many, m.target_schema_name, m.is_name, m.index_alias) for m in citer.members],
[
(0, "Id", "string", False, False, None, True, "id"),
(1, "Targets", "ref[]", True, True, "tests.leaf", False, None),
(7, "Mass", "double", False, False, None, False, None),
],
)
self.assertEqual(leaf.members, ())
# Members leave only for a request that asked; an older descriptor without them keeps its older wire shape.
self.assertNotIn("members", catalog.create_response(message_id="m")["schemas"][0])
self.assertEqual(
catalog.create_response(message_id="m", include_members=True)["schemas"][0]["members"][1],
{"slot": 1, "name": "Targets", "type": "ref[]", "isReference": True, "isMany": True, "isName": False, "targetSchemaName": "tests.leaf"},
)
self.assertNotIn("members", CultNetSchemaDescriptor.from_wire({"schemaId": "a", "kind": "wire_message"}).to_wire(include_members=True))
self.assertNotIn("includeMembers", schema_catalog_request(message_id="old").to_wire())
self.assertTrue(schema_catalog_request(message_id="new", include_members=True).to_wire()["includeMembers"])
def test_cultnet_catalog_and_snapshot_helpers_accept_filters(self) -> None:
catalog = schema_catalog_request(
message_id="catalog-1",

View file

@ -12,6 +12,7 @@
"schemaVersion": { "const": "cultnet.schema_catalog_request.v0" },
"messageId": { "type": "string", "minLength": 1 },
"includeSchemaJson": { "type": "boolean" },
"includeMembers": { "type": "boolean" },
"schemaIds": {
"type": "array",
"items": { "type": "string", "minLength": 1 }

View file

@ -417,6 +417,7 @@ fn dial(config: DialConfig) -> Result<()> {
transport.send_schema_message(&CultNetMessage::SchemaCatalogRequest {
message_id: format!("{}-catalog", config.runtime_id),
include_schema_json: Some(true),
include_members: None,
schema_ids: None,
kinds: None,
})?;
@ -692,6 +693,7 @@ fn rudp_dial_message_once(options: &BTreeMap<String, String>) -> Result<()> {
let request = CultNetMessage::SchemaCatalogRequest {
message_id: "rust-ts-schema-message".to_string(),
include_schema_json: Some(false),
include_members: None,
schema_ids: Some(vec![]),
kinds: Some(vec![CultNetSchemaKind::WireMessage]),
};

View file

@ -185,6 +185,26 @@ pub struct CultNetSchemaDescriptor {
pub content_hash: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema_json: Option<String>,
/// The member rows of a document-payload schema, present only on a response to a request that set `includeMembers`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub members: Option<Vec<CultNetSchemaMember>>,
}
/// One member row of a document-payload schema: the row every store catalog writes for a member.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CultNetSchemaMember {
pub slot: u32,
pub name: String,
#[serde(rename = "type")]
pub type_name: String,
pub is_reference: bool,
pub is_many: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_schema_name: Option<String>,
pub is_name: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub index_alias: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -494,6 +514,9 @@ pub enum CultNetMessage {
message_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
include_schema_json: Option<bool>,
/// Ask each document-payload descriptor to carry its member rows.
#[serde(default, skip_serializing_if = "Option::is_none")]
include_members: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
schema_ids: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@ -877,6 +900,7 @@ fn validate_message(message: &CultNetMessage) -> Result<()> {
CultNetMessage::SchemaCatalogRequest {
message_id,
include_schema_json: _,
include_members: _,
schema_ids,
kinds: _,
} => {
@ -1744,6 +1768,7 @@ fn parse_gamecult_networking_message(input: &rmpv::Value) -> Result<CultNetMessa
payload.get(1),
"SchemaCatalogRequestMessage.IncludeSchemaJson",
)?),
include_members: None,
schema_ids: require_legacy_optional_string_array(
payload.get(2),
"SchemaCatalogRequestMessage.SchemaIds",
@ -1832,9 +1857,17 @@ fn encode_gamecult_networking_message(message: &CultNetMessage) -> Result<rmpv::
CultNetMessage::SchemaCatalogRequest {
message_id,
include_schema_json,
include_members,
schema_ids,
kinds,
} => vec![
} => {
// The legacy union's request has no such field: a request that asks for members is refused, never sent without the ask.
if include_members.unwrap_or(false) {
return Err(anyhow!(
"includeMembers is not part of gamecult.networking.v0; send cultnet.schema.v0"
));
}
vec![
rmpv::Value::from(7),
rmpv::Value::Array(vec![
message_id.as_str().into(),
@ -1842,7 +1875,8 @@ fn encode_gamecult_networking_message(message: &CultNetMessage) -> Result<rmpv::
legacy_optional_string_array(schema_ids.as_deref()),
legacy_optional_schema_kind_array(kinds.as_deref()),
]),
],
]
}
CultNetMessage::SchemaCatalogResponse {
message_id,
schemas,
@ -2010,6 +2044,7 @@ fn require_legacy_schema_descriptor(
wire_contracts,
content_hash,
schema_json,
members: None,
})
}

View file

@ -66,6 +66,7 @@ impl CultNetSchemaRegistry {
wire_contracts: registration.wire_contracts,
content_hash,
schema_json: registration.schema_json,
members: None,
},
);
@ -119,6 +120,7 @@ impl CultNetSchemaRegistry {
include_schema_json,
schema_ids,
kinds,
..
} = request
else {
return Err(anyhow!(

View file

@ -1552,6 +1552,7 @@ fn cultmesh_facade_connects_authorized_rudp_client_for_schema_messages() -> Resu
client.send_schema_message(&CultNetMessage::SchemaCatalogRequest {
message_id: "rust-cultmesh-rudp-schema-catalog".to_string(),
include_schema_json: Some(true),
include_members: None,
schema_ids: None,
kinds: Some(vec![CultNetSchemaKind::DocumentPayload]),
})?;
@ -2372,6 +2373,7 @@ fn builtin_schema_registry_advertises_canonical_ghostlight_schema_without_inline
let response = registry.create_catalog_response(&CultNetMessage::SchemaCatalogRequest {
message_id: "catalog-1".to_string(),
include_schema_json: None,
include_members: None,
schema_ids: None,
kinds: None,
})?;
@ -2416,6 +2418,7 @@ fn builtin_schema_registry_advertises_shard_catalog_wire_messages() -> Result<()
let response = registry.create_catalog_response(&CultNetMessage::SchemaCatalogRequest {
message_id: "catalog-shards".to_string(),
include_schema_json: None,
include_members: None,
schema_ids: None,
kinds: Some(vec![CultNetSchemaKind::WireMessage]),
})?;
@ -2524,6 +2527,7 @@ fn schema_discovery_round_trips_over_legacy_gamecult_contract_when_inline_schema
let response = registry.create_catalog_response(&CultNetMessage::SchemaCatalogRequest {
message_id: "catalog-legacy".to_string(),
include_schema_json: Some(true),
include_members: None,
schema_ids: None,
kinds: None,
})?;

View file

@ -0,0 +1,104 @@
//! `contracts/cultnet/interop/schema-catalog-members.cs-written.msgpack` is written only by the C# reference: the answer of
//! the subscription server to a `schema_catalog_request` that set `includeMembers`, every descriptor key present (nil where
//! unset) and `members` on each. This decodes it into the typed response, and checks that a request keeps its older bytes
//! unless it asks for members.
use cultnet_rs::*;
fn vector() -> Vec<u8> {
std::fs::read(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../contracts/cultnet/interop/schema-catalog-members.cs-written.msgpack"
))
.expect("the vector is committed")
}
#[test]
fn schema_catalog_response_written_by_csharp_decodes_with_typed_members() {
let message = decode_cultnet_message_from_slice(&vector(), CultNetWireContract::CultNetSchemaV0).unwrap();
let CultNetMessage::SchemaCatalogResponse { message_id, schemas } = message else {
panic!("expected a schema catalog response");
};
assert_eq!(message_id, "catalog-members-vector");
assert_eq!(schemas.len(), 2);
assert_eq!(schemas[0].kind, CultNetSchemaKind::DocumentPayload);
assert_eq!(schemas[0].schema_json, None);
assert_eq!(
schemas[0].members.as_deref().unwrap(),
[
CultNetSchemaMember {
slot: 0,
name: "Id".into(),
type_name: "string".into(),
is_reference: false,
is_many: false,
target_schema_name: None,
is_name: true,
index_alias: Some("id".into()),
},
CultNetSchemaMember {
slot: 1,
name: "Targets".into(),
type_name: "ref[]".into(),
is_reference: true,
is_many: true,
target_schema_name: Some("tests.leaf".into()),
is_name: false,
index_alias: None,
},
CultNetSchemaMember {
slot: 7,
name: "Mass".into(),
type_name: "double".into(),
is_reference: false,
is_many: false,
target_schema_name: None,
is_name: false,
index_alias: None,
},
]
);
assert_eq!(schemas[1].members.as_deref(), Some(&[][..]));
}
#[test]
fn schema_catalog_request_writes_include_members_only_when_asked() {
let request = |include_members| CultNetMessage::SchemaCatalogRequest {
message_id: "m".into(),
include_schema_json: None,
include_members,
schema_ids: None,
kinds: None,
};
let encode = |message: &CultNetMessage| {
let bytes = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0).unwrap();
rmpv::decode::read_value(&mut &bytes[..]).unwrap()
};
let has = |value: &rmpv::Value, key: &str| value.as_map().unwrap().iter().any(|(k, _)| k.as_str() == Some(key));
let older = encode(&request(None));
let asked = encode(&request(Some(true)));
assert!(!has(&older, "includeMembers"));
assert!(has(&asked, "includeMembers"));
let decoded = decode_cultnet_message_from_slice(
&encode_cultnet_message_to_vec(&request(Some(true)), CultNetWireContract::CultNetSchemaV0).unwrap(),
CultNetWireContract::CultNetSchemaV0,
)
.unwrap();
assert_eq!(decoded, request(Some(true)));
}
#[test]
fn schema_catalog_request_for_members_is_refused_by_the_legacy_contract_not_sent_without_the_ask() {
let request = |include_members| CultNetMessage::SchemaCatalogRequest {
message_id: "m".into(),
include_schema_json: None,
include_members,
schema_ids: None,
kinds: None,
};
let error = encode_cultnet_message_to_vec(&request(Some(true)), CultNetWireContract::GameCultNetworkingV0).unwrap_err();
assert!(error.to_string().contains("includeMembers"), "{error}");
assert!(encode_cultnet_message_to_vec(&request(None), CultNetWireContract::GameCultNetworkingV0).is_ok());
}

View file

@ -3,6 +3,12 @@
All notable changes to `@gamecult/cultnet-ts` are recorded here, following
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
### Added
- `CultNetSchemaCatalogRequestMessage.includeMembers` and `CultNetSchemaDescriptor.members` (`CultNetSchemaMember[]`), additive and optional: the C# subscription server answers a request that sets `includeMembers` with each document type's member rows. `parseCultNetMessage` accepts the C# writer's nil `schemaJson`, `targetSchemaName` and `indexAlias` in a catalog response.
## [0.4.0]
### Breaking

View file

@ -430,6 +430,18 @@ export interface CultNetDatabaseChangeRawMessage {
commitCount?: number | null;
}
/** One member row of a document-payload schema: the row every store catalog writes for a member. */
export interface CultNetSchemaMember {
slot: number;
name: string;
type: string;
isReference: boolean;
isMany: boolean;
targetSchemaName?: string;
isName: boolean;
indexAlias?: string;
}
export interface CultNetSchemaDescriptor {
schemaId: string;
kind: CultNetSchemaKind;
@ -439,12 +451,16 @@ export interface CultNetSchemaDescriptor {
wireContracts: CultNetWireContract[];
contentHash: string;
schemaJson?: string;
/** Present only on a response to a request that set includeMembers. */
members?: CultNetSchemaMember[];
}
export interface CultNetSchemaCatalogRequestMessage {
schemaVersion: "cultnet.schema_catalog_request.v0";
messageId: string;
includeSchemaJson?: boolean;
/** Ask each document-payload descriptor to carry its member rows. */
includeMembers?: boolean;
schemaIds?: string[];
kinds?: CultNetSchemaKind[];
}
@ -1107,6 +1123,10 @@ function encodeGameCultNetworkingMessage(message: CultNetMessage): [number, unkn
case "cultnet.sample.chat.v0":
return [6, [message.text]];
case "cultnet.schema_catalog_request.v0":
if (message.includeMembers) {
// The legacy union's request has no such field: refuse the ask rather than send the request without it.
throw new Error("includeMembers is not part of gamecult.networking.v0; send cultnet.schema.v0.");
}
return [7, [
message.messageId,
message.includeSchemaJson ?? false,
@ -1608,6 +1628,19 @@ function normalizeCultNetOptionalNulls(
case "cultnet.schema_catalog_request.v0":
stripNullProperties(candidate, ["schemaIds", "kinds"]);
return;
case "cultnet.schema_catalog_response.v0":
// The C# writer sets every key of a descriptor and of a member row, nil where unset.
for (const schema of Array.isArray(candidate.schemas) ? candidate.schemas : []) {
if (!schema || typeof schema !== "object") continue;
const descriptor = schema as Record<string, unknown>;
stripNullProperties(descriptor, ["schemaVersion", "documentType", "title", "schemaJson", "members"]);
for (const member of Array.isArray(descriptor.members) ? descriptor.members : []) {
if (member && typeof member === "object") {
stripNullProperties(member as Record<string, unknown>, ["targetSchemaName", "indexAlias"]);
}
}
}
return;
case "cultnet.shard_catalog_request.v0":
stripNullProperties(candidate, ["schemaIds", "recordKeys"]);
return;

View file

@ -169,3 +169,33 @@ test("CultNetSelectionInvalidError carries the field and offending value", () =>
(error: unknown) => error instanceof CultNetSelectionInvalidError && error.field === "keys" && error.value === "",
);
});
// ---- schema catalog members ----
const CATALOG_MEMBERS = join(__dirname, "..", "..", "..", "..", "contracts", "cultnet", "interop", "schema-catalog-members.cs-written.msgpack");
test("the C#-written catalog response with members decodes, and its rows are the descriptor's typed members", () => {
const message = parseCultNetMessage(decode(new Uint8Array(readFileSync(CATALOG_MEMBERS))));
assert.equal(message.schemaVersion, "cultnet.schema_catalog_response.v0");
const [citer, leaf] = (message as { schemas: { schemaId: string; contentHash: string; members?: unknown[]; schemaJson?: string }[] }).schemas;
assert.equal(citer.schemaJson, undefined, "a nil schemaJson is absent after parse");
assert.deepEqual(citer.members, [
{ slot: 0, name: "Id", type: "string", isReference: false, isMany: false, isName: true, indexAlias: "id" },
{ slot: 1, name: "Targets", type: "ref[]", isReference: true, isMany: true, targetSchemaName: "tests.leaf", isName: false },
{ slot: 7, name: "Mass", type: "double", isReference: false, isMany: false, isName: false },
]);
assert.deepEqual(leaf.members, []);
});
test("a catalog request asks for members with includeMembers and an older request still parses", () => {
const asked = parseCultNetMessage({ schemaVersion: "cultnet.schema_catalog_request.v0", messageId: "m", includeMembers: true });
assert.equal((asked as { includeMembers?: boolean }).includeMembers, true);
const old = parseCultNetMessage({ schemaVersion: "cultnet.schema_catalog_request.v0", messageId: "m", includeSchemaJson: false, schemaIds: null, kinds: null });
assert.equal((old as { includeMembers?: boolean }).includeMembers, undefined);
});
test("the legacy gamecult.networking.v0 contract refuses a request for members instead of dropping the ask", () => {
const request = { schemaVersion: "cultnet.schema_catalog_request.v0", messageId: "m", includeMembers: true } as const;
assert.throws(() => encodeCultNetMessageForWire(request, "gamecult.networking.v0"), /includeMembers/);
assert.doesNotThrow(() => encodeCultNetMessageForWire({ ...request, includeMembers: undefined }, "gamecult.networking.v0"));
});

View file

@ -68,7 +68,7 @@ test("send a typed document over loopback and receive it into a second cache", a
test("docs show the tested snippet", async () => {
// Compiled to dist-test/test/first-call.test.js, so the package root is two levels up.
const source = await readFile(join(__dirname, "..", "..", "test", "first-call.test.ts"), "utf8");
const source = (await readFile(join(__dirname, "..", "..", "test", "first-call.test.ts"), "utf8")).replace(/\r\n/g, "\n");
const snippet = source
.split("// snippet:begin\n")[1]
.split("// snippet:end\n")[0]

View file

@ -24,6 +24,7 @@ namespace GameCult.Networking
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, Task> _subscribe;
private readonly Func<CultNetDatabaseSubscribeV1Message, ICultNetSchemaServerPeer, Task> _subscribeV1;
private readonly Func<CultNetDatabaseUnsubscribeMessage, ICultNetSchemaServerPeer, Task> _unsubscribe;
private readonly Func<CultNetSchemaCatalogRequestMessage, ICultNetSchemaServerPeer, Task> _catalog;
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, bool>? _authorizeRequest;
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, string, string, bool>? _authorizeRecord;
private readonly ICultNetSchemaServerPeerLifecycle? _peerLifecycle;
@ -50,9 +51,11 @@ namespace GameCult.Networking
_subscribe = HandleSubscribeAsync;
_subscribeV1 = HandleSubscribeV1Async;
_unsubscribe = HandleUnsubscribeAsync;
_catalog = HandleCatalogAsync;
_server.OnCultNet(_subscribe);
_server.OnCultNet(_subscribeV1);
_server.OnCultNet(_unsubscribe);
_server.OnCultNet(_catalog);
_peerLifecycle = server as ICultNetSchemaServerPeerLifecycle;
if (_peerLifecycle != null)
_peerLifecycle.PeerDisconnected += HandlePeerDisconnected;
@ -97,6 +100,7 @@ namespace GameCult.Networking
_server.RemoveCultNetMessageListener<CultNetDatabaseSubscribeMessage>(_subscribe);
_server.RemoveCultNetMessageListener<CultNetDatabaseSubscribeV1Message>(_subscribeV1);
_server.RemoveCultNetMessageListener<CultNetDatabaseUnsubscribeMessage>(_unsubscribe);
_server.RemoveCultNetMessageListener<CultNetSchemaCatalogRequestMessage>(_catalog);
if (_peerLifecycle != null)
_peerLifecycle.PeerDisconnected -= HandlePeerDisconnected;
foreach (var entry in _subscriptions.ToArray())
@ -117,6 +121,52 @@ namespace GameCult.Networking
}
}
// Answers a catalog request with the document types this database's cache registers: kind document_payload, contentHash the
// schemaContentHash its records carry. The cache's descriptor owns the member rows and the hash; nothing is kept here, and
// schemaJson stays the contract-schema field, never filled with cache schema JSON. Members leave only for a request that asked.
// A type is listed only for a peer the subscribe authorization admits to subscribe to it (the same authorizeRequest, asked with
// that schema alone), and schemaIds match as a subscription's schemas do (id, name, version or alias; none listed: every type).
private Task HandleCatalogAsync(CultNetSchemaCatalogRequestMessage request, ICultNetSchemaServerPeer peer)
{
var kinds = request.Kinds != null ? new HashSet<string>(request.Kinds, StringComparer.Ordinal) : null;
var schemas = _database.Cache.Registry.AllDescriptors
.Where(descriptor =>
(kinds == null || kinds.Contains("document_payload")) &&
(request.SchemaIds == null || CultNetSchemaAliasMatching.MatchesAny(request.SchemaIds, descriptor)) &&
(_authorizeRequest == null || _authorizeRequest(new CultNetDatabaseSubscribeMessage
{
MessageId = request.MessageId,
SubscriptionId = request.MessageId,
SchemaIds = new[] { descriptor.SchemaId }
}, peer)))
.Select(descriptor => new CultNetSchemaDescriptor
{
SchemaId = descriptor.SchemaId,
Kind = "document_payload",
SchemaVersion = descriptor.SchemaVersion,
DocumentType = descriptor.SchemaName,
Title = descriptor.SchemaName,
WireContracts = new[] { CultNetWireContracts.SchemaV0 },
ContentHash = descriptor.ContentHash,
Members = request.IncludeMembers
? descriptor.ToCatalogEntry().Members.Select(member => new CultNetSchemaMember
{
Slot = member.Slot,
Name = member.MemberName,
Type = member.TypeName,
IsReference = member.IsReference,
IsMany = member.IsMany,
TargetSchemaName = member.TargetSchemaName,
IsName = member.IsName,
IndexAlias = member.IndexAlias
}).ToArray()
: null
})
.ToArray();
peer.SendCultNet(new CultNetSchemaCatalogResponseMessage { MessageId = request.MessageId, Schemas = schemas });
return Task.CompletedTask;
}
private Task HandleSubscribeAsync(CultNetDatabaseSubscribeMessage request, ICultNetSchemaServerPeer peer)
{
// v0 has no engine of its own (docs/cultnet-selection-cut.md, D3/D4): it lowers into a

View file

@ -0,0 +1,161 @@
#nullable enable
using System;
using MessagePack;
using MessagePack.Formatters;
namespace GameCult.Networking
{
// The catalog request and descriptor write every key their older shape wrote, and add one key only when it carries a value:
// includeMembers when true, members when set. A peer that never asked therefore receives exactly the bytes it always did.
// MessagePack's generated formatter writes every [Key] (nil for unset), so these two types write their own map.
internal sealed class CultNetSchemaCatalogRequestFormatter : IMessagePackFormatter<CultNetSchemaCatalogRequestMessage?>
{
public void Serialize(ref MessagePackWriter writer, CultNetSchemaCatalogRequestMessage? value, MessagePackSerializerOptions options)
{
if (value == null)
{
writer.WriteNil();
return;
}
writer.WriteMapHeader(value.IncludeMembers ? 6 : 5);
writer.Write("schemaVersion");
writer.Write(value.SchemaVersion);
writer.Write("messageId");
writer.Write(value.MessageId);
writer.Write("includeSchemaJson");
writer.Write(value.IncludeSchemaJson);
writer.Write("schemaIds");
WriteStrings(ref writer, value.SchemaIds);
writer.Write("kinds");
WriteStrings(ref writer, value.Kinds);
if (value.IncludeMembers)
{
writer.Write("includeMembers");
writer.Write(true);
}
}
public CultNetSchemaCatalogRequestMessage? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.TryReadNil()) return null;
options.Security.DepthStep(ref reader);
try
{
var value = new CultNetSchemaCatalogRequestMessage();
var count = reader.ReadMapHeader();
for (var i = 0; i < count; i++)
{
switch (reader.ReadString())
{
case "schemaVersion": value.SchemaVersion = reader.ReadString() ?? string.Empty; break;
case "messageId": value.MessageId = reader.ReadString() ?? string.Empty; break;
case "includeSchemaJson": value.IncludeSchemaJson = !reader.TryReadNil() && reader.ReadBoolean(); break;
case "schemaIds": value.SchemaIds = ReadStrings(ref reader); break;
case "kinds": value.Kinds = ReadStrings(ref reader); break;
case "includeMembers": value.IncludeMembers = !reader.TryReadNil() && reader.ReadBoolean(); break;
default: reader.Skip(); break;
}
}
return value;
}
finally
{
reader.Depth--;
}
}
internal static void WriteStrings(ref MessagePackWriter writer, string[]? values)
{
if (values == null)
{
writer.WriteNil();
return;
}
writer.WriteArrayHeader(values.Length);
foreach (var value in values) writer.Write(value);
}
internal static string[]? ReadStrings(ref MessagePackReader reader)
{
if (reader.TryReadNil()) return null;
var count = reader.ReadArrayHeader();
var values = new string[count];
for (var i = 0; i < count; i++) values[i] = reader.ReadString() ?? string.Empty;
return values;
}
}
internal sealed class CultNetSchemaDescriptorFormatter : IMessagePackFormatter<CultNetSchemaDescriptor?>
{
public void Serialize(ref MessagePackWriter writer, CultNetSchemaDescriptor? value, MessagePackSerializerOptions options)
{
if (value == null)
{
writer.WriteNil();
return;
}
writer.WriteMapHeader(value.Members != null ? 9 : 8);
writer.Write("schemaId");
writer.Write(value.SchemaId);
writer.Write("kind");
writer.Write(value.Kind);
writer.Write("schemaVersion");
writer.Write(value.SchemaVersion);
writer.Write("documentType");
writer.Write(value.DocumentType);
writer.Write("title");
writer.Write(value.Title);
writer.Write("wireContracts");
CultNetSchemaCatalogRequestFormatter.WriteStrings(ref writer, value.WireContracts);
writer.Write("contentHash");
writer.Write(value.ContentHash);
writer.Write("schemaJson");
writer.Write(value.SchemaJson);
if (value.Members != null)
{
writer.Write("members");
options.Resolver.GetFormatterWithVerify<CultNetSchemaMember[]>().Serialize(ref writer, value.Members, options);
}
}
public CultNetSchemaDescriptor? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.TryReadNil()) return null;
options.Security.DepthStep(ref reader);
try
{
var value = new CultNetSchemaDescriptor();
var count = reader.ReadMapHeader();
for (var i = 0; i < count; i++)
{
switch (reader.ReadString())
{
case "schemaId": value.SchemaId = reader.ReadString() ?? string.Empty; break;
case "kind": value.Kind = reader.ReadString() ?? string.Empty; break;
case "schemaVersion": value.SchemaVersion = reader.ReadString(); break;
case "documentType": value.DocumentType = reader.ReadString(); break;
case "title": value.Title = reader.ReadString(); break;
case "wireContracts": value.WireContracts = CultNetSchemaCatalogRequestFormatter.ReadStrings(ref reader) ?? Array.Empty<string>(); break;
case "contentHash": value.ContentHash = reader.ReadString() ?? string.Empty; break;
case "schemaJson": value.SchemaJson = reader.ReadString(); break;
case "members":
value.Members = options.Resolver.GetFormatterWithVerify<CultNetSchemaMember[]>().Deserialize(ref reader, options);
break;
default: reader.Skip(); break;
}
}
return value;
}
finally
{
reader.Depth--;
}
}
}
}

View file

@ -1842,6 +1842,7 @@ namespace GameCult.Networking
/// Describes one schema exposed through the CultNet schema catalog.
/// </summary>
[MessagePackObject]
[MessagePackFormatter(typeof(CultNetSchemaDescriptorFormatter))]
public class CultNetSchemaDescriptor
{
/// <summary>
@ -1876,12 +1877,42 @@ namespace GameCult.Networking
/// Gets or sets the schema json.
/// </summary>
[Key("schemaJson")] public string? SchemaJson { get; set; }
/// <summary>
/// Gets or sets the member rows a document-payload schema declares, sent only to a request that asked for them
/// (<see cref="CultNetSchemaCatalogRequestMessage.IncludeMembers"/>). A descriptor without rows leaves the key off the wire.
/// </summary>
[Key("members")] public CultNetSchemaMember[]? Members { get; set; }
}
/// <summary>
/// One member row of a document-payload schema: the row every store catalog writes for a member, in slot order.
/// </summary>
[MessagePackObject]
public class CultNetSchemaMember
{
/// <summary>Gets or sets the member's slot.</summary>
[Key("slot")] public int Slot { get; set; }
/// <summary>Gets or sets the member's name.</summary>
[Key("name")] public string Name { get; set; } = string.Empty;
/// <summary>Gets or sets the member's schema type name.</summary>
[Key("type")] public string Type { get; set; } = string.Empty;
/// <summary>Gets or sets whether the member is a reference to another record.</summary>
[Key("isReference")] public bool IsReference { get; set; }
/// <summary>Gets or sets whether the member holds many references.</summary>
[Key("isMany")] public bool IsMany { get; set; }
/// <summary>Gets or sets the schema name a reference targets.</summary>
[Key("targetSchemaName")] public string? TargetSchemaName { get; set; }
/// <summary>Gets or sets whether the member is the record's name.</summary>
[Key("isName")] public bool IsName { get; set; }
/// <summary>Gets or sets the member's unique-index alias.</summary>
[Key("indexAlias")] public string? IndexAlias { get; set; }
}
/// <summary>
/// CultNet message requesting schema catalog entries.
/// </summary>
[MessagePackObject]
[MessagePackFormatter(typeof(CultNetSchemaCatalogRequestFormatter))]
public class CultNetSchemaCatalogRequestMessage : ICultNetSchemaMessage
{
/// <summary>
@ -1904,6 +1935,10 @@ namespace GameCult.Networking
/// Gets or sets the kinds.
/// </summary>
[Key("kinds")] public string[]? Kinds { get; set; }
/// <summary>
/// Gets or sets whether document-payload descriptors carry their member rows. False leaves the key off the wire.
/// </summary>
[Key("includeMembers")] public bool IncludeMembers { get; set; }
}
/// <summary>

View file

@ -0,0 +1,341 @@
#nullable enable
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
using NUnit.Framework;
using static GameCult.Networking.Tests.NetworkingTests;
namespace GameCult.Networking.Tests
{
// schema_catalog_request answered by the subscription server from its cache's registry: the cache owns each type's member rows and
// content hash, a request opts into the rows with includeMembers, and a peer that did not ask gets the bytes it always got.
public sealed class CultNetSchemaCatalogMembersTests
{
// The descriptor and request as they were written before members: the bytes an older peer must still be sent.
[MessagePackObject]
public sealed class LegacyDescriptor
{
[Key("schemaId")] public string SchemaId { get; set; } = string.Empty;
[Key("kind")] public string Kind { get; set; } = string.Empty;
[Key("schemaVersion")] public string? SchemaVersion { get; set; }
[Key("documentType")] public string? DocumentType { get; set; }
[Key("title")] public string? Title { get; set; }
[Key("wireContracts")] public string[] WireContracts { get; set; } = Array.Empty<string>();
[Key("contentHash")] public string ContentHash { get; set; } = string.Empty;
[Key("schemaJson")] public string? SchemaJson { get; set; }
}
[MessagePackObject]
public sealed class LegacyCatalogRequest
{
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SchemaCatalogRequest;
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
[Key("includeSchemaJson")] public bool IncludeSchemaJson { get; set; }
[Key("schemaIds")] public string[]? SchemaIds { get; set; }
[Key("kinds")] public string[]? Kinds { get; set; }
}
[MessagePackObject]
public sealed class LegacyCatalogResponse
{
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SchemaCatalogResponse;
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
[Key("schemas")] public LegacyDescriptor[] Schemas { get; set; } = Array.Empty<LegacyDescriptor>();
}
private sealed class Wire : IDisposable
{
private readonly CancellationTokenSource _cancellation = new();
private readonly Thread _thread;
private readonly RudpCultNetSchemaServer _server;
private readonly CultNetDatabaseSubscriptionServer _subscriptions;
private readonly ICultNetSchemaClient _client;
public ConcurrentQueue<CultNetSchemaCatalogResponseMessage> Catalogs { get; } = new();
public ConcurrentQueue<CultNetSnapshotResponseRawMessage> Snapshots { get; } = new();
public Wire(CultNetDatabase database, Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, bool>? authorizeRequest = null)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.ReceiveTimeout = 20;
_server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions { RuntimeId = "catalog-server", Socket = socket });
_subscriptions = new CultNetDatabaseSubscriptionServer(_server, database, authorizeRequest);
_thread = new Thread(() =>
{
while (!_cancellation.IsCancellationRequested)
{
_ = _server.PollOnceAsync().GetAwaiter().GetResult();
Thread.Sleep(1);
}
}) { IsBackground = true };
_thread.Start();
_client = CultNetSchemaClients.CreateRudp("catalog-client");
_client.OnCultNet<CultNetSchemaCatalogResponseMessage>(Catalogs.Enqueue);
_client.OnCultNet<CultNetSnapshotResponseRawMessage>(Snapshots.Enqueue);
_client.Connect("127.0.0.1", _server.LocalEndPoint.Port);
}
public async Task<CultNetSchemaCatalogResponseMessage> AskAsync(CultNetSchemaCatalogRequestMessage request)
{
await Until(() => _client.Connected);
var before = Catalogs.Count;
_client.SendCultNet(request);
await Until(() => Catalogs.Count > before);
return Catalogs.ToArray()[before];
}
public async Task<CultNetSnapshotResponseRawMessage> SnapshotAsync(string schemaId)
{
await Until(() => _client.Connected);
_client.SendCultNet(new CultNetDatabaseSubscribeMessage
{
MessageId = "subscribe",
SubscriptionId = "all",
SchemaIds = new[] { schemaId },
IncludeSnapshot = true
});
await Until(() => !Snapshots.IsEmpty);
return Snapshots.First();
}
public void Dispose()
{
_cancellation.Cancel();
_thread.Join();
_client.Dispose();
_subscriptions.Dispose();
_server.Dispose();
}
}
private static async Task Until(Func<bool> condition)
{
var deadline = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(5);
while (!condition())
{
if (DateTimeOffset.UtcNow > deadline)
Assert.Fail("Condition was not satisfied before timeout.");
await Task.Delay(5);
}
}
private static CultNetDatabase DatabaseWithANote(out CultDocumentDescriptor descriptor)
{
var cache = new CultCache();
descriptor = cache.Registry.GetRequired<NetworkSchemaNote>();
cache.Commit(batch => batch.Upsert(
new NetworkSchemaNote { Schema = "tests.networking_note.v1", Text = "row" },
new CultRecordHandle<NetworkSchemaNote>(new CultRecordKey("tests:catalog:row"))));
return new CultNetDatabase(cache);
}
[Test]
public async Task SchemaCatalogMembersAreTheCacheCatalogRowsUnderTheHashItsRecordsCarry()
{
var database = DatabaseWithANote(out var descriptor);
using var wire = new Wire(database);
var response = await wire.AskAsync(new CultNetSchemaCatalogRequestMessage
{
MessageId = "catalog-members",
IncludeMembers = true,
SchemaIds = new[] { descriptor.SchemaId }
});
var served = response.Schemas.Single();
Assert.That(served.Kind, Is.EqualTo("document_payload"));
Assert.That(served.SchemaJson, Is.Null, "schemaJson keeps its contract-schema meaning");
var rows = descriptor.ToCatalogEntry().Members;
Assert.That(rows, Is.Not.Empty);
Assert.That(served.Members!.Select(m => (m.Slot, m.Name, m.Type, m.IsReference, m.IsMany, m.TargetSchemaName, m.IsName, m.IndexAlias)),
Is.EqualTo(rows.Select(m => (m.Slot, m.MemberName, m.TypeName, m.IsReference, m.IsMany, m.TargetSchemaName, m.IsName, m.IndexAlias))));
var snapshot = await wire.SnapshotAsync(descriptor.SchemaId);
Assert.That(snapshot.Documents, Is.Not.Empty);
Assert.That(snapshot.Documents.Select(d => d.SchemaContentHash).Distinct(), Is.EqualTo(new[] { served.ContentHash }));
}
[Test]
public async Task SchemaCatalogWithoutIncludeMembersIsExactlyTheOldBytes()
{
var database = DatabaseWithANote(out var descriptor);
using var wire = new Wire(database);
var request = new CultNetSchemaCatalogRequestMessage { MessageId = "old-client", SchemaIds = new[] { descriptor.SchemaId } };
var oldRequestBytes = MessagePackSerializer.Serialize(
new LegacyCatalogRequest { MessageId = "old-client", SchemaIds = new[] { descriptor.SchemaId } }, CultNetSchemaMessageSerialization.Options);
Assert.That(CultNetSchemaMessageSerialization.Serialize(request), Is.EqualTo(oldRequestBytes), "a request that does not ask keeps its older bytes");
var response = await wire.AskAsync(request);
var legacy = new LegacyCatalogResponse
{
MessageId = "old-client",
Schemas = response.Schemas.Select(s => new LegacyDescriptor
{
SchemaId = s.SchemaId, Kind = s.Kind, SchemaVersion = s.SchemaVersion, DocumentType = s.DocumentType, Title = s.Title,
WireContracts = s.WireContracts, ContentHash = s.ContentHash, SchemaJson = s.SchemaJson
}).ToArray()
};
Assert.That(response.Schemas.Single().Members, Is.Null);
Assert.That(CultNetSchemaMessageSerialization.Serialize(response),
Is.EqualTo(MessagePackSerializer.Serialize(legacy, CultNetSchemaMessageSerialization.Options)));
}
[Test]
public async Task SchemaCatalogListsOnlyTheTypesThePeerMaySubscribeTo()
{
var cache = new CultCache();
var note = cache.Registry.GetRequired<NetworkSchemaNote>();
var mesh = cache.Registry.GetRequired<MeshQuickstartNote>();
var database = new CultNetDatabase(cache);
using var wire = new Wire(database, (request, _) => request.SchemaIds!.All(id => id == note.SchemaId));
var response = await wire.AskAsync(new CultNetSchemaCatalogRequestMessage { MessageId = "denied", IncludeMembers = true });
var served = response.Schemas.Single();
Assert.That(served.SchemaId, Is.EqualTo(note.SchemaId));
Assert.That(served.Members, Is.Not.Empty);
Assert.That(response.Schemas.Select(s => s.SchemaId), Does.Not.Contain(mesh.SchemaId));
using var closed = new Wire(database, (_, _) => false);
var none = await closed.AskAsync(new CultNetSchemaCatalogRequestMessage { MessageId = "closed", IncludeMembers = true });
Assert.That(none.Schemas, Is.Empty, "a peer denied every subscription learns no member rows");
}
[Test]
public async Task SchemaCatalogSchemaIdsMatchAsASubscriptionsSchemasDo()
{
var database = DatabaseWithANote(out var descriptor);
using var wire = new Wire(database);
var byName = await wire.AskAsync(new CultNetSchemaCatalogRequestMessage
{
MessageId = "by-name", SchemaIds = new[] { descriptor.SchemaName }
});
Assert.That(byName.Schemas.Single().SchemaId, Is.EqualTo(descriptor.SchemaId));
var unknown = await wire.AskAsync(new CultNetSchemaCatalogRequestMessage { MessageId = "unknown", SchemaIds = new[] { "no.such.schema" } });
Assert.That(unknown.Schemas, Is.Empty);
}
// The two types with a hand formatter: every [Key] member must be written by its formatter and read back, so a key added to
// the contract type without the formatter fails here instead of vanishing from the wire.
private static object Populated(Type type, string name)
{
if (type == typeof(string)) return "v-" + name;
if (type == typeof(bool)) return true;
if (type == typeof(int)) return 7;
if (type == typeof(string[])) return new[] { "a-" + name, "b-" + name };
if (type == typeof(CultNetSchemaMember[]))
return new[] { (CultNetSchemaMember)PopulatedInstance(typeof(CultNetSchemaMember)) };
Assert.Fail($"{name}: the test cannot populate {type}; teach Populated about it");
return null!;
}
private static object PopulatedInstance(Type type)
{
var instance = Activator.CreateInstance(type)!;
foreach (var property in KeyedProperties(type))
property.SetValue(instance, Populated(property.PropertyType, property.Name));
return instance;
}
private static PropertyInfo[] KeyedProperties(Type type) =>
type.GetProperties().Where(p => p.GetCustomAttribute<KeyAttribute>() != null).ToArray();
[TestCase(typeof(CultNetSchemaCatalogRequestMessage))]
[TestCase(typeof(CultNetSchemaDescriptor))]
public void EveryKeyOfAHandFormattedTypeIsWrittenAndReadBack(Type type)
{
var instance = PopulatedInstance(type);
var bytes = MessagePackSerializer.Serialize(type, instance, CultNetSchemaMessageSerialization.Options);
var reader = new MessagePackReader(bytes);
var written = new System.Collections.Generic.List<string>();
for (var entries = reader.ReadMapHeader(); entries > 0; entries--)
{
written.Add(reader.ReadString()!);
reader.Skip();
}
var declared = KeyedProperties(type).Select(p => p.GetCustomAttribute<KeyAttribute>()!.StringKey!).ToArray();
Assert.That(written, Is.EquivalentTo(declared), $"{type.Name}: its formatter must write exactly the [Key] members");
var back = MessagePackSerializer.Deserialize(type, bytes, CultNetSchemaMessageSerialization.Options);
foreach (var property in KeyedProperties(type))
Assert.That(JsonSerializer.Serialize(property.GetValue(back)), Is.EqualTo(JsonSerializer.Serialize(property.GetValue(instance))),
$"{type.Name}.{property.Name} was not read back by its formatter");
}
private static CultNetSchemaCatalogResponseMessage VectorResponse() => new()
{
MessageId = "catalog-members-vector",
Schemas = new[]
{
new CultNetSchemaDescriptor
{
SchemaId = "sha256:9d0bc9aebc3619b07aabf564f98667afde41444c1b866661d777687d443608dc",
Kind = "document_payload",
SchemaVersion = "tests.citer.v1",
DocumentType = "tests.citer",
Title = "tests.citer",
WireContracts = new[] { CultNetWireContracts.SchemaV0 },
ContentHash = "sha256:ff35f3d9d6de3f1066b9369e73fe6c7648e88368d18efc2275c994730cd84cff",
Members = new[]
{
new CultNetSchemaMember { Slot = 0, Name = "Id", Type = "string", IsName = true, IndexAlias = "id" },
new CultNetSchemaMember { Slot = 1, Name = "Targets", Type = "ref[]", IsReference = true, IsMany = true, TargetSchemaName = "tests.leaf" },
new CultNetSchemaMember { Slot = 7, Name = "Mass", Type = "double" }
}
},
new CultNetSchemaDescriptor
{
SchemaId = "sha256:ff35f3d9d6de3f1066b9369e73fe6c7648e88368d18efc2275c994730cd84cff",
Kind = "document_payload",
SchemaVersion = "tests.leaf.v1",
DocumentType = "tests.leaf",
Title = "tests.leaf",
WireContracts = new[] { CultNetWireContracts.SchemaV0 },
ContentHash = "sha256:abc",
Members = Array.Empty<CultNetSchemaMember>()
}
}
};
private static string VectorPath()
{
var directory = new DirectoryInfo(TestContext.CurrentContext.TestDirectory);
while (directory != null && !File.Exists(Path.Combine(directory.FullName, "CultLib.sln")))
directory = directory.Parent;
var root = directory?.FullName ?? throw new InvalidOperationException("CultLib.sln was not found above the test directory.");
return Path.Combine(root, "contracts", "cultnet", "interop", "schema-catalog-members.cs-written.msgpack");
}
[Test]
public void WriteSchemaCatalogMembersVector()
{
if (Environment.GetEnvironmentVariable("CULTNET_WRITE_VECTORS") != "1")
Assert.Ignore("Set CULTNET_WRITE_VECTORS=1 to (re)write the committed vector file.");
File.WriteAllBytes(VectorPath(), CultNetSchemaMessageSerialization.Serialize(VectorResponse()));
}
[Test]
public void CommittedSchemaCatalogMembersVectorMatchesAFreshSerialization()
{
var committed = File.ReadAllBytes(VectorPath());
Assert.That(committed, Is.EqualTo(CultNetSchemaMessageSerialization.Serialize(VectorResponse())),
"the committed bytes drifted from the reference serializer");
var decoded = CultNetSchemaMessageSerialization.Deserialize<CultNetSchemaCatalogResponseMessage>(committed);
Assert.That(decoded.Schemas[0].Members!.Select(m => m.Name), Is.EqualTo(new[] { "Id", "Targets", "Mass" }));
}
}
}