CultNet: catalog answers only types the peer may subscribe to, matches schemaIds as subscribe does; keys pinned by reflection; legacy contract refuses includeMembers; first-call docs test reads CRLF

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 05:45:56 +01:00
commit 3687edee28
7 changed files with 135 additions and 9 deletions

View file

@ -1857,10 +1857,17 @@ fn encode_gamecult_networking_message(message: &CultNetMessage) -> Result<rmpv::
CultNetMessage::SchemaCatalogRequest {
message_id,
include_schema_json,
include_members: _,
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(),
@ -1868,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,

View file

@ -88,3 +88,17 @@ fn schema_catalog_request_writes_include_members_only_when_asked() {
.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

@ -1123,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,

View file

@ -193,3 +193,9 @@ test("a catalog request asks for members with includeMembers and an older reques
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

@ -124,14 +124,21 @@ 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 schemaIds = request.SchemaIds != null ? new HashSet<string>(request.SchemaIds, StringComparer.Ordinal) : null;
var kinds = request.Kinds != null ? new HashSet<string>(request.Kinds, StringComparer.Ordinal) : null;
var schemas = _database.Cache.Registry.AllDescriptors
.Where(descriptor =>
(schemaIds == null || schemaIds.Contains(descriptor.SchemaId)) &&
(kinds == null || kinds.Contains("document_payload")))
(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,

View file

@ -5,6 +5,8 @@ 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;
@ -61,13 +63,13 @@ namespace GameCult.Networking.Tests
public ConcurrentQueue<CultNetSchemaCatalogResponseMessage> Catalogs { get; } = new();
public ConcurrentQueue<CultNetSnapshotResponseRawMessage> Snapshots { get; } = new();
public Wire(CultNetDatabase database)
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);
_subscriptions = new CultNetDatabaseSubscriptionServer(_server, database, authorizeRequest);
_thread = new Thread(() =>
{
while (!_cancellation.IsCancellationRequested)
@ -189,6 +191,91 @@ namespace GameCult.Networking.Tests
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 = Enumerable.Range(0, reader.ReadMapHeader()).Select(_ =>
{
var key = reader.ReadString()!;
reader.Skip();
return key;
}).ToArray();
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",