Vectors: catalog member rows across C#, Rust, TypeScript and Python (#185)
This commit is contained in:
parent
be036b1fda
commit
b7f2a7dbd0
8 changed files with 707 additions and 0 deletions
51
packages/cultcache-py/tests/test_catalog_members.py
Normal file
51
packages/cultcache-py/tests/test_catalog_members.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from cultcache_py import SingleFileMessagePackBackingStore
|
||||
|
||||
# tests/vectors/catalog-members (variants:ruling:rs-catalog-member-rows-every-member): one record in two stores. The C# reference's
|
||||
# publishes a catalog row for each of the 29 members, every one of which members.json spells; the one cultcache-rs wrote before it
|
||||
# wrote member rows publishes members []. A reader takes both and pulls the one record m:1.
|
||||
VECTORS = Path(__file__).resolve().parents[3] / "tests" / "vectors" / "catalog-members"
|
||||
|
||||
# [slot, member, typeName, isReference, isMany, targetSchemaName, isName, indexAlias]
|
||||
TABLE = json.loads((VECTORS / "members.json").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def pull(name: str):
|
||||
directory = Path(tempfile.mkdtemp())
|
||||
copy = directory / "store.cc"
|
||||
shutil.copyfile(VECTORS / name, copy)
|
||||
try:
|
||||
return SingleFileMessagePackBackingStore(copy).pull_all()
|
||||
finally:
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
|
||||
|
||||
class CatalogMembersVectorTests(unittest.TestCase):
|
||||
def test_the_csharp_written_store_publishes_every_row_of_the_shared_table(self) -> None:
|
||||
envelopes = pull("csharp-members-store.cc")
|
||||
self.assertEqual([envelope.key for envelope in envelopes], ["m:1"])
|
||||
entry = envelopes[0].catalog_entry
|
||||
self.assertEqual(entry.schema_name, "tests.catalog_members")
|
||||
self.assertEqual(len(TABLE), 29)
|
||||
rows = [
|
||||
[m.slot, m.member_name, m.type_name, m.is_reference, m.is_many, m.target_schema_name, m.is_name, m.index_alias]
|
||||
for m in entry.members
|
||||
]
|
||||
self.assertEqual(rows, TABLE)
|
||||
|
||||
def test_the_rust_written_store_publishes_no_members_and_one_record(self) -> None:
|
||||
envelopes = pull("rust-members-empty-store.cc")
|
||||
self.assertEqual([envelope.key for envelope in envelopes], ["m:1"])
|
||||
self.assertEqual(envelopes[0].catalog_entry.schema_name, "tests.catalog_members")
|
||||
self.assertEqual(tuple(envelopes[0].catalog_entry.members), ())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
248
packages/cultcache-rs/tests/catalog_members.rs
Normal file
248
packages/cultcache-rs/tests/catalog_members.rs
Normal file
|
|
@ -0,0 +1,248 @@
|
|||
//! `tests/vectors/catalog-members`: a record that holds a value in every member shape, in the two stores the vector folder
|
||||
//! holds. `csharp-members-store.cc` is written by the C# reference and publishes one catalog row per member;
|
||||
//! `rust-members-empty-store.cc` is written by this runtime as it stood at e503edf2, whose catalog entry holds `members []`.
|
||||
//! Rust writes the second only under `CULTCACHE_WRITE_VECTORS=1` and it is never regenerated: it pins the bytes old Rust
|
||||
//! wrote, so a runtime that reads a store with no member rows keeps reading one. Both stores must read back the same record.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use cultcache_rs::{CultCache, CultSlots, CultUnion, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct CatalogMemberMark {
|
||||
#[cultcache(key = 0)]
|
||||
label: String,
|
||||
#[cultcache(key = 1)]
|
||||
weight: i32,
|
||||
#[cultcache(key = 2)]
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct CatalogMemberTextArm {
|
||||
#[cultcache(key = 0)]
|
||||
text: String,
|
||||
#[cultcache(key = 1)]
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||
struct CatalogMemberCountArm {
|
||||
#[cultcache(key = 0)]
|
||||
count: i32,
|
||||
#[cultcache(key = 1)]
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||
enum CatalogMemberArm {
|
||||
#[cultcache(key = 0)]
|
||||
Text(CatalogMemberTextArm),
|
||||
#[cultcache(key = 1)]
|
||||
Count(CatalogMemberCountArm),
|
||||
}
|
||||
|
||||
/// The slot a C# `DateTime` is: a MessagePack timestamp extension (type -1), kept as the bytes C# wrote.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Timestamp(Vec<u8>);
|
||||
|
||||
impl serde::Serialize for Timestamp {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_newtype_struct("_ExtStruct", &(-1i8, serde_bytes::Bytes::new(&self.0)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserialize<'de> for Timestamp {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct Visit;
|
||||
impl<'de> serde::de::Visitor<'de> for Visit {
|
||||
type Value = Timestamp;
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("a MessagePack extension")
|
||||
}
|
||||
fn visit_newtype_struct<D: serde::Deserializer<'de>>(self, deserializer: D) -> Result<Timestamp, D::Error> {
|
||||
let (tag, bytes): (i8, serde_bytes::ByteBuf) = serde::Deserialize::deserialize(deserializer)?;
|
||||
if tag != -1 {
|
||||
return Err(serde::de::Error::custom("not a timestamp extension"));
|
||||
}
|
||||
Ok(Timestamp(bytes.into_vec()))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_newtype_struct("_ExtStruct", Visit)
|
||||
}
|
||||
}
|
||||
|
||||
/// A field type that names no C# type: no `type_name` attribute, so the row the library cut writes for it is `System.Object`.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(transparent)]
|
||||
struct Opaque(String);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(type = "tests.catalog_members", schema = "tests.catalog_members")]
|
||||
struct CatalogMembers {
|
||||
#[cultcache(key = 0, name)]
|
||||
title: String,
|
||||
#[cultcache(key = 1, index = "sku")]
|
||||
sku: String,
|
||||
#[cultcache(key = 2)]
|
||||
count: i32,
|
||||
#[cultcache(key = 3)]
|
||||
total: u64,
|
||||
#[cultcache(key = 4)]
|
||||
ratio: f64,
|
||||
#[cultcache(key = 5)]
|
||||
scale: f32,
|
||||
#[cultcache(key = 6)]
|
||||
flag: bool,
|
||||
#[cultcache(key = 7)]
|
||||
maybe_count: Option<i32>,
|
||||
#[cultcache(key = 8)]
|
||||
note: Option<String>,
|
||||
#[cultcache(key = 9)]
|
||||
tags: Vec<String>,
|
||||
#[cultcache(key = 10)]
|
||||
labels: Vec<String>,
|
||||
#[cultcache(key = 11, bytes)]
|
||||
raw: Vec<u8>,
|
||||
#[cultcache(key = 12)]
|
||||
chunks: Vec<serde_bytes::ByteBuf>,
|
||||
#[cultcache(key = 13)]
|
||||
weights: std::collections::BTreeMap<String, i32>,
|
||||
#[cultcache(key = 14)]
|
||||
mark: CatalogMemberMark,
|
||||
#[cultcache(key = 15)]
|
||||
arm: CatalogMemberArm,
|
||||
#[cultcache(key = 17)]
|
||||
late: i64,
|
||||
#[cultcache(key = 18)]
|
||||
items: Vec<CatalogMemberMark>,
|
||||
#[cultcache(key = 19)]
|
||||
marks: Vec<CatalogMemberMark>,
|
||||
#[cultcache(key = 20)]
|
||||
by_label: std::collections::BTreeMap<String, CatalogMemberMark>,
|
||||
#[cultcache(key = 21)]
|
||||
maybe_mark: Option<CatalogMemberMark>,
|
||||
#[cultcache(key = 22)]
|
||||
arms: Vec<CatalogMemberArm>,
|
||||
#[cultcache(key = 23)]
|
||||
grid: Vec<Vec<i32>>,
|
||||
#[cultcache(key = 24)]
|
||||
by_number: std::collections::BTreeMap<i32, String>,
|
||||
#[cultcache(key = 25)]
|
||||
kind: i32,
|
||||
#[cultcache(key = 26)]
|
||||
ident: String,
|
||||
#[cultcache(key = 27)]
|
||||
when: Timestamp,
|
||||
#[cultcache(key = 28)]
|
||||
price: String,
|
||||
#[cultcache(key = 29)]
|
||||
opaque: Opaque,
|
||||
}
|
||||
|
||||
fn expected() -> CatalogMembers {
|
||||
CatalogMembers {
|
||||
title: "Brass lantern".into(),
|
||||
sku: "LAN-0042".into(),
|
||||
count: -7,
|
||||
total: 10_000_000_000,
|
||||
ratio: 0.25,
|
||||
scale: 1.5,
|
||||
flag: true,
|
||||
maybe_count: Some(3),
|
||||
note: Some("handle with care".into()),
|
||||
tags: vec!["fragile".into(), "lit".into()],
|
||||
labels: vec!["a".into(), "b".into(), "c".into()],
|
||||
raw: vec![0, 1, 2, 254, 255],
|
||||
chunks: vec![serde_bytes::ByteBuf::from(vec![9, 8]), serde_bytes::ByteBuf::from(vec![7])],
|
||||
weights: [("brass".to_string(), 12), ("glass".to_string(), 3)].into_iter().collect(),
|
||||
mark: CatalogMemberMark { label: "stamp".into(), weight: 5, id: "0000000000a0".into() },
|
||||
arm: CatalogMemberArm::Count(CatalogMemberCountArm { count: 21, id: "0000000000a1".into() }),
|
||||
late: -9_000_000_000,
|
||||
items: vec![CatalogMemberMark { label: "i0".into(), weight: 1, id: "0000000000b0".into() }, CatalogMemberMark { label: "i1".into(), weight: 2, id: "0000000000b1".into() }],
|
||||
marks: vec![CatalogMemberMark { label: "m0".into(), weight: 3, id: "0000000000c0".into() }],
|
||||
by_label: [
|
||||
("x".to_string(), CatalogMemberMark { label: "bx".into(), weight: 4, id: "0000000000d0".into() }),
|
||||
("y".to_string(), CatalogMemberMark { label: "by".into(), weight: 5, id: "0000000000d1".into() }),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
maybe_mark: Some(CatalogMemberMark { label: "maybe".into(), weight: 6, id: "0000000000e0".into() }),
|
||||
arms: vec![
|
||||
CatalogMemberArm::Text(CatalogMemberTextArm { text: "t".into(), id: "0000000000f0".into() }),
|
||||
CatalogMemberArm::Count(CatalogMemberCountArm { count: 8, id: "0000000000f1".into() }),
|
||||
],
|
||||
grid: vec![vec![1, 2], vec![3]],
|
||||
by_number: [(-1, "neg".to_string()), (7, "seven".to_string())].into_iter().collect(),
|
||||
kind: 2,
|
||||
ident: "00112233-4455-6677-8899-aabbccddeeff".into(),
|
||||
when: Timestamp(vec![0x69, 0xa7, 0xbd, 0xbf]),
|
||||
price: "12.50".into(),
|
||||
opaque: Opaque("opaque".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn vectors() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/vectors/catalog-members")
|
||||
}
|
||||
|
||||
fn read_from(path: &std::path::Path) -> CatalogMembers {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let copy = dir.path().join("store.cc");
|
||||
std::fs::copy(path, ©).unwrap();
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<CatalogMembers>().unwrap();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(©)).unwrap();
|
||||
cache.pull_all_backing_stores().unwrap();
|
||||
cache.get::<CatalogMembers>("m:1").unwrap().expect("m:1 is in the store")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_members_empty_store_vector() {
|
||||
let path = vectors().join("rust-members-empty-store.cc");
|
||||
if std::env::var("CULTCACHE_WRITE_VECTORS").as_deref() == Ok("1") {
|
||||
std::fs::create_dir_all(vectors()).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<CatalogMembers>().unwrap();
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
|
||||
cache.pull_all_backing_stores().unwrap();
|
||||
cache.put("m:1", &expected()).unwrap();
|
||||
return;
|
||||
}
|
||||
assert_eq!(read_from(&path), expected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_csharp_written_store_reads_in_rust() {
|
||||
assert_eq!(read_from(&vectors().join("csharp-members-store.cc")), expected());
|
||||
}
|
||||
|
||||
/// The shared expected rows (members.json): [slot, member, typeName, isReference, isMany, targetSchemaName, isName, indexAlias].
|
||||
type Row = (i64, String, String, bool, bool, Option<String>, bool, Option<String>);
|
||||
|
||||
/// The store's catalog entries as the file spells them (id, name, version, hash, canonical json, compatible ids, members).
|
||||
type Entry = (String, String, String, String, String, Vec<String>, Vec<Row>);
|
||||
|
||||
fn catalog_rows(store: &str) -> Vec<Row> {
|
||||
let bytes = std::fs::read(vectors().join(store)).unwrap();
|
||||
let (_header, mut catalog, _records): (String, Vec<Entry>, serde::de::IgnoredAny) = rmp_serde::from_slice(&bytes).unwrap();
|
||||
assert_eq!(catalog.len(), 1, "one schema in {store}");
|
||||
catalog.remove(0).6
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_csharp_catalog_holds_every_row_of_the_shared_table() {
|
||||
let table: Vec<Row> = serde_json::from_slice(&std::fs::read(vectors().join("members.json")).unwrap()).unwrap();
|
||||
assert_eq!(table.len(), 29);
|
||||
let rows = catalog_rows("csharp-members-store.cc");
|
||||
assert_eq!(rows.len(), table.len());
|
||||
for (index, (row, expected)) in rows.iter().zip(&table).enumerate() {
|
||||
assert_eq!(row, expected, "row {index}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rust_written_catalog_holds_no_rows() {
|
||||
assert!(catalog_rows("rust-members-empty-store.cc").is_empty());
|
||||
}
|
||||
47
packages/cultcache-ts/test/catalog-members.test.ts
Normal file
47
packages/cultcache-ts/test/catalog-members.test.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { readSingleFileStore } from "../src/single-file-messagepack-backing-store";
|
||||
|
||||
// tests/vectors/catalog-members (variants:ruling:rs-catalog-member-rows-every-member): one record in two stores. The C# reference's
|
||||
// publishes a catalog row for each of the 29 members, every one of which members.json spells; the one cultcache-rs wrote before it
|
||||
// wrote member rows publishes members []. A reader takes both and pulls the one record m:1.
|
||||
|
||||
function findVectors(from: string): string {
|
||||
for (let dir = from; ; dir = dirname(dir)) {
|
||||
if (existsSync(join(dir, "tests", "vectors", "catalog-members"))) return join(dir, "tests", "vectors", "catalog-members");
|
||||
if (resolve(dir, "..") === dir) throw new Error("tests/vectors/catalog-members not found above the test.");
|
||||
}
|
||||
}
|
||||
const vectors = findVectors(__dirname);
|
||||
|
||||
// [slot, member, typeName, isReference, isMany, targetSchemaName, isName, indexAlias]
|
||||
const table = JSON.parse(readFileSync(join(vectors, "members.json"), "utf8")) as unknown[][];
|
||||
|
||||
test("the C# written store publishes every row of the shared table and one record m:1", () => {
|
||||
const { envelopes } = readSingleFileStore(join(vectors, "csharp-members-store.cc"));
|
||||
assert.deepEqual(envelopes.map((envelope) => envelope.key), ["m:1"]);
|
||||
const entry = envelopes[0].catalogEntry;
|
||||
assert.equal(entry?.schemaName, "tests.catalog_members");
|
||||
assert.equal(table.length, 29);
|
||||
const rows = (entry?.members ?? []).map((member) => [
|
||||
member.slot,
|
||||
member.memberName,
|
||||
member.typeName,
|
||||
member.isReference ?? false,
|
||||
member.isMany ?? false,
|
||||
member.targetSchemaName ?? null,
|
||||
member.isName ?? false,
|
||||
member.indexAlias ?? null,
|
||||
]);
|
||||
assert.deepEqual(rows, table);
|
||||
});
|
||||
|
||||
test("the Rust written store publishes members [] for tests.catalog_members and one record m:1", () => {
|
||||
const { envelopes } = readSingleFileStore(join(vectors, "rust-members-empty-store.cc"));
|
||||
assert.deepEqual(envelopes.map((envelope) => envelope.key), ["m:1"]);
|
||||
assert.equal(envelopes[0].catalogEntry?.schemaName, "tests.catalog_members");
|
||||
assert.deepEqual(envelopes[0].catalogEntry?.members ?? [], []);
|
||||
});
|
||||
268
tests/GameCult.Caching.Tests/CatalogMemberVectorTests.cs
Normal file
268
tests/GameCult.Caching.Tests/CatalogMemberVectorTests.cs
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace GameCult.Caching.Tests
|
||||
{
|
||||
[MessagePackObject]
|
||||
public sealed class CatalogMemberMark
|
||||
{
|
||||
[Key(0)] public string Label = string.Empty;
|
||||
[Key(1)] public int Weight;
|
||||
[Key(2)] [CultElementId] public string Id = string.Empty;
|
||||
}
|
||||
|
||||
[Union(0, typeof(CatalogMemberTextArm))]
|
||||
[Union(1, typeof(CatalogMemberCountArm))]
|
||||
public abstract class CatalogMemberArm { }
|
||||
|
||||
[MessagePackObject]
|
||||
public sealed class CatalogMemberTextArm : CatalogMemberArm
|
||||
{
|
||||
[Key(0)] public string Text = string.Empty;
|
||||
[Key(1)] [CultElementId] public string Id = string.Empty;
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public sealed class CatalogMemberCountArm : CatalogMemberArm
|
||||
{
|
||||
[Key(0)] public int Count;
|
||||
[Key(1)] [CultElementId] public string Id = string.Empty;
|
||||
}
|
||||
|
||||
public enum CatalogMemberKind
|
||||
{
|
||||
Plain = 0,
|
||||
Fancy = 2,
|
||||
}
|
||||
|
||||
[CultDocument("tests.catalog_members", "tests.catalog_members.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class CatalogMembersDocument
|
||||
{
|
||||
[Key(0)] [CultName] public string Title = string.Empty;
|
||||
[Key(1)] [CultIndex("sku")] public string Sku = string.Empty;
|
||||
[Key(2)] public int Count;
|
||||
[Key(3)] public ulong Total;
|
||||
[Key(4)] public double Ratio;
|
||||
[Key(5)] public float Scale;
|
||||
[Key(6)] public bool Flag;
|
||||
[Key(7)] public int? MaybeCount;
|
||||
[Key(8)] public string? Note;
|
||||
[Key(9)] public List<string> Tags = new();
|
||||
[Key(10)] public string[] Labels = Array.Empty<string>();
|
||||
[Key(11)] public byte[] Raw = Array.Empty<byte>();
|
||||
[Key(12)] public List<byte[]> Chunks = new();
|
||||
[Key(13)] public Dictionary<string, int> Weights = new();
|
||||
[Key(14)] public CatalogMemberMark Mark = new();
|
||||
[Key(15)] public CatalogMemberArm? Arm;
|
||||
// Slot 16 is a gap.
|
||||
[Key(17)] public long Late;
|
||||
[Key(18)] public List<CatalogMemberMark> Items = new();
|
||||
[Key(19)] public CatalogMemberMark[] Marks = Array.Empty<CatalogMemberMark>();
|
||||
[Key(20)] public Dictionary<string, CatalogMemberMark> ByLabel = new();
|
||||
[Key(21)] public CatalogMemberMark? MaybeMark;
|
||||
[Key(22)] public List<CatalogMemberArm> Arms = new();
|
||||
[Key(23)] public List<List<int>> Grid = new();
|
||||
[Key(24)] public Dictionary<int, string> ByNumber = new();
|
||||
[Key(25)] public CatalogMemberKind Kind;
|
||||
[Key(26)] public Guid Ident;
|
||||
[Key(27)] public DateTime When;
|
||||
[Key(28)] public decimal Price;
|
||||
// The Rust counterpart is a field type no C# name describes (variants:ruling:rs-member-unnamed-object-fallback): the row is System.Object.
|
||||
[Key(29)] public object? Opaque;
|
||||
}
|
||||
|
||||
// tests/vectors/catalog-members (variants:ruling:rs-catalog-member-rows-every-member): a record holding a value in every
|
||||
// member shape, in two stores. csharp-members-store.cc is written by this reference, under CULTCACHE_WRITE_VECTORS=1, and
|
||||
// carries one catalog row per member; every other run compares its bytes. rust-members-empty-store.cc is written by
|
||||
// cultcache-rs as it stood at e503edf2, whose catalog entry holds members [], and is never regenerated; it is only read.
|
||||
public class CatalogMemberVectorTests
|
||||
{
|
||||
private const string Vector = "catalog-members";
|
||||
|
||||
private static readonly CultDocumentRegistry Registry = CultDocumentRegistry.ForTypes(new[] { typeof(CatalogMembersDocument) });
|
||||
|
||||
private static CatalogMembersDocument Expected() => new()
|
||||
{
|
||||
Title = "Brass lantern",
|
||||
Sku = "LAN-0042",
|
||||
Count = -7,
|
||||
Total = 10_000_000_000UL,
|
||||
Ratio = 0.25,
|
||||
Scale = 1.5f,
|
||||
Flag = true,
|
||||
MaybeCount = 3,
|
||||
Note = "handle with care",
|
||||
Tags = new List<string> { "fragile", "lit" },
|
||||
Labels = new[] { "a", "b", "c" },
|
||||
Raw = new byte[] { 0, 1, 2, 254, 255 },
|
||||
Chunks = new List<byte[]> { new byte[] { 9, 8 }, new byte[] { 7 } },
|
||||
Weights = new Dictionary<string, int> { ["brass"] = 12, ["glass"] = 3 },
|
||||
Mark = new CatalogMemberMark { Label = "stamp", Weight = 5, Id = "0000000000a0" },
|
||||
Arm = new CatalogMemberCountArm { Count = 21, Id = "0000000000a1" },
|
||||
Late = -9_000_000_000L,
|
||||
Items = new List<CatalogMemberMark> { new() { Label = "i0", Weight = 1, Id = "0000000000b0" }, new() { Label = "i1", Weight = 2, Id = "0000000000b1" } },
|
||||
Marks = new[] { new CatalogMemberMark { Label = "m0", Weight = 3, Id = "0000000000c0" } },
|
||||
ByLabel = new Dictionary<string, CatalogMemberMark> { ["x"] = new() { Label = "bx", Weight = 4, Id = "0000000000d0" }, ["y"] = new() { Label = "by", Weight = 5, Id = "0000000000d1" } },
|
||||
MaybeMark = new CatalogMemberMark { Label = "maybe", Weight = 6, Id = "0000000000e0" },
|
||||
Arms = new List<CatalogMemberArm> { new CatalogMemberTextArm { Text = "t", Id = "0000000000f0" }, new CatalogMemberCountArm { Count = 8, Id = "0000000000f1" } },
|
||||
Grid = new List<List<int>> { new() { 1, 2 }, new() { 3 } },
|
||||
ByNumber = new Dictionary<int, string> { [-1] = "neg", [7] = "seven" },
|
||||
Kind = CatalogMemberKind.Fancy,
|
||||
Ident = new Guid("00112233-4455-6677-8899-aabbccddeeff"),
|
||||
When = new DateTime(2026, 3, 4, 5, 6, 7, DateTimeKind.Utc),
|
||||
Price = 12.50m,
|
||||
Opaque = "opaque",
|
||||
};
|
||||
|
||||
private static void AssertEqualToExpected(CatalogMembersDocument? actual)
|
||||
{
|
||||
var expected = Expected();
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.That(actual!.Title, Is.EqualTo(expected.Title));
|
||||
Assert.That(actual.Sku, Is.EqualTo(expected.Sku));
|
||||
Assert.That(actual.Count, Is.EqualTo(expected.Count));
|
||||
Assert.That(actual.Total, Is.EqualTo(expected.Total));
|
||||
Assert.That(actual.Ratio, Is.EqualTo(expected.Ratio));
|
||||
Assert.That(actual.Scale, Is.EqualTo(expected.Scale));
|
||||
Assert.That(actual.Flag, Is.EqualTo(expected.Flag));
|
||||
Assert.That(actual.MaybeCount, Is.EqualTo(expected.MaybeCount));
|
||||
Assert.That(actual.Note, Is.EqualTo(expected.Note));
|
||||
Assert.That(actual.Tags, Is.EqualTo(expected.Tags));
|
||||
Assert.That(actual.Labels, Is.EqualTo(expected.Labels));
|
||||
Assert.That(actual.Raw, Is.EqualTo(expected.Raw));
|
||||
Assert.That(actual.Chunks, Is.EqualTo(expected.Chunks));
|
||||
Assert.That(actual.Weights, Is.EquivalentTo(expected.Weights));
|
||||
Assert.That(actual.Mark.Label, Is.EqualTo(expected.Mark.Label));
|
||||
Assert.That(actual.Mark.Weight, Is.EqualTo(expected.Mark.Weight));
|
||||
Assert.That(actual.Arm, Is.TypeOf<CatalogMemberCountArm>());
|
||||
Assert.That(((CatalogMemberCountArm)actual.Arm!).Count, Is.EqualTo(21));
|
||||
Assert.That(actual.Late, Is.EqualTo(expected.Late));
|
||||
Assert.That(actual.Items.Select(m => (m.Label, m.Weight)), Is.EqualTo(expected.Items.Select(m => (m.Label, m.Weight))));
|
||||
Assert.That(actual.Marks.Select(m => (m.Label, m.Weight)), Is.EqualTo(expected.Marks.Select(m => (m.Label, m.Weight))));
|
||||
Assert.That(actual.ByLabel.Select(p => (p.Key, p.Value.Label, p.Value.Weight)), Is.EqualTo(expected.ByLabel.Select(p => (p.Key, p.Value.Label, p.Value.Weight))));
|
||||
Assert.That(actual.MaybeMark!.Label, Is.EqualTo("maybe"));
|
||||
Assert.That(actual.Arms.Select(a => a.GetType()), Is.EqualTo(new[] { typeof(CatalogMemberTextArm), typeof(CatalogMemberCountArm) }));
|
||||
Assert.That(((CatalogMemberTextArm)actual.Arms[0]).Text, Is.EqualTo("t"));
|
||||
Assert.That(((CatalogMemberCountArm)actual.Arms[1]).Count, Is.EqualTo(8));
|
||||
Assert.That(actual.Grid, Is.EqualTo(expected.Grid));
|
||||
Assert.That(actual.ByNumber, Is.EquivalentTo(expected.ByNumber));
|
||||
Assert.That(actual.Kind, Is.EqualTo(expected.Kind));
|
||||
Assert.That(actual.Ident, Is.EqualTo(expected.Ident));
|
||||
Assert.That(actual.When, Is.EqualTo(expected.When));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
Assert.That(actual.Opaque, Is.EqualTo("opaque"));
|
||||
}
|
||||
|
||||
private static byte[] StoreBytes()
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), $"cultlib-cmv-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
var path = Path.Combine(directory, "store.cc");
|
||||
using (var cache = CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = Registry, StoreFlushOnDispose = true }))
|
||||
{
|
||||
cache.Clock = () => VectorFiles.StoredAt;
|
||||
cache.UpsertAsync(typeof(CatalogMembersDocument), Expected(), new CultRecordKey("m:1")).GetAwaiter().GetResult();
|
||||
cache.FlushAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
return File.ReadAllBytes(path);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static CatalogMembersDocument? ReadM1(string name, out CultSchemaMigrationReport[] reports)
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), $"cultlib-cmr-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
var path = Path.Combine(directory, "store.cc");
|
||||
File.WriteAllBytes(path, VectorFiles.Committed(Vector, name));
|
||||
var store = new SingleFileMessagePackBackingStore(path);
|
||||
using var cache = new CultCache();
|
||||
cache.AddBackingStore(store);
|
||||
cache.PullAllBackingStoresAsync().GetAwaiter().GetResult();
|
||||
reports = store.LastSchemaMigrationReports.ToArray();
|
||||
return cache.Get<CatalogMembersDocument>(new CultRecordKey("m:1"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
// The expected catalog rows, one table every runtime reads (members.json): [slot, member, typeName, isReference, isMany, targetSchemaName, isName, indexAlias].
|
||||
private static List<object?[]> ExpectedRows()
|
||||
{
|
||||
using var document = System.Text.Json.JsonDocument.Parse(VectorFiles.Committed(Vector, "members.json"));
|
||||
return document.RootElement.EnumerateArray().Select(row => new object?[]
|
||||
{
|
||||
row[0].GetInt32(), row[1].GetString(), row[2].GetString(), row[3].GetBoolean(), row[4].GetBoolean(),
|
||||
row[5].ValueKind == System.Text.Json.JsonValueKind.Null ? null : row[5].GetString(), row[6].GetBoolean(),
|
||||
row[7].ValueKind == System.Text.Json.JsonValueKind.Null ? null : row[7].GetString(),
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
private static List<object?[]> CatalogRows(string name)
|
||||
{
|
||||
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(VectorFiles.Committed(Vector, name));
|
||||
return snapshot.SchemaCatalog.Single().Members
|
||||
.Select(m => new object?[] { m.Slot, m.MemberName, m.TypeName, m.IsReference, m.IsMany, m.TargetSchemaName, m.IsName, m.IndexAlias })
|
||||
.ToList();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheCSharpStoreIsTheReferencesBytesAndReadsBack()
|
||||
{
|
||||
VectorFiles.Check(Vector, "csharp-members-store.cc", StoreBytes());
|
||||
AssertEqualToExpected(ReadM1("csharp-members-store.cc", out var reports));
|
||||
Assert.That(reports.SelectMany(report => report.Warnings), Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheCSharpStoreCatalogHoldsEveryRowOfTheSharedTable()
|
||||
{
|
||||
var expected = ExpectedRows();
|
||||
Assert.That(expected, Has.Count.EqualTo(29));
|
||||
var actual = CatalogRows("csharp-members-store.cc");
|
||||
Assert.That(actual, Has.Count.EqualTo(expected.Count));
|
||||
for (var i = 0; i < expected.Count; i++) Assert.That(actual[i], Is.EqualTo(expected[i]), "row " + i);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheRustStoreCatalogHoldsNoRows()
|
||||
{
|
||||
Assert.That(CatalogRows("rust-members-empty-store.cc"), Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MembersEmptyRustStoreStillLoads()
|
||||
{
|
||||
AssertEqualToExpected(ReadM1("rust-members-empty-store.cc", out var reports));
|
||||
// The reader loads a members-[] entry with warnings and no refusal. Counts per code, with the reason for each:
|
||||
// compatible_schema_id_drift (1): the Rust entry's id is its schema name, not the fingerprint this type derives.
|
||||
// content_hash_drift (1): the Rust entry's content hash is the schema name too, not the hash of the local canonical schema.
|
||||
// defaulted_missing_slot (29): the entry lists no members, so each of this type's 29 members is absent from the persisted schema.
|
||||
var warnings = reports.SelectMany(report => report.Warnings).GroupBy(warning => warning.Code).ToDictionary(group => group.Key, group => group.Count());
|
||||
Assert.That(warnings, Is.EquivalentTo(new Dictionary<string, int>
|
||||
{
|
||||
["compatible_schema_id_drift"] = 1,
|
||||
["content_hash_drift"] = 1,
|
||||
["defaulted_missing_slot"] = 29,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
62
tests/vectors/catalog-members/README.md
Normal file
62
tests/vectors/catalog-members/README.md
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
# catalog-members vector
|
||||
|
||||
Two stores holding the same record, `m:1` of type `tests.catalog_members` (version `tests.catalog_members.v1`), with a value in every slot.
|
||||
`variants:ruling:rs-catalog-member-rows-every-member` is the ruling they serve: cultcache-rs writes a catalog row for every member, and
|
||||
every runtime keeps reading a store whose Rust-written entry holds `members []`.
|
||||
|
||||
- `csharp-members-store.cc` is written by the C# reference (`CatalogMemberVectorTests`, under `CULTCACHE_WRITE_VECTORS=1`; every other run compares
|
||||
the bytes). Its catalog entry carries the 29 rows of `members.json`, in slot order, which is the order C# discovers members in.
|
||||
- `members.json` is the one expected table: `[slot, member, typeName, isReference, isMany, targetSchemaName, isName, indexAlias]` per row. C#, Rust,
|
||||
TypeScript and Python each read the catalog rows of `csharp-members-store.cc` and compare every row to it; none picks rows by hand.
|
||||
- `rust-members-empty-store.cc` is written by cultcache-rs at base e503edf2 (`packages/cultcache-rs/tests/catalog_members.rs`, `the_members_empty_store_vector`,
|
||||
under `CULTCACHE_WRITE_VECTORS=1`). It is the one store in this folder C# does not write, and it is regenerated only by a reviewed commit with the Rust
|
||||
source of e503edf2: it pins the bytes old Rust wrote, and a later Rust writes member rows. A Rust-written entry has id = schema name = `tests.catalog_members`,
|
||||
version `tests.catalog_members.v1`, and `members []`. Its payload spells the slots through the Rust mirror below.
|
||||
|
||||
The type holds: a name (Title), a unique index (Sku), the scalar leaves, a nullable struct, a nullable string, a list, an array, a byte array, a list of byte arrays,
|
||||
a dictionary, a record (`Mark`: 0 Label, 1 Weight, 2 Id), a union (`Arm`: arm 0 `CatalogMemberTextArm {Text, Id}`, arm 1 `CatalogMemberCountArm {Count, Id}`), a gap at slot 16,
|
||||
a slot above it (Late), and slots 18-29: list, array and map of records, a record, a list of unions, a nested list, a map keyed by int, an enum, a Guid, a DateTime,
|
||||
a decimal, and an object. A record in a collection carries a `[CultElementId]` member, so the records and arms have an Id slot.
|
||||
|
||||
What C# cannot express: a nullable record is the record's own type name (`MaybeMark` has no row of its own shape; nullable annotations on reference types are not
|
||||
in the typeName, and `MaybeCount` is the nullable struct row); a field type that names nothing in Rust is spelled in C# as `object` (`Opaque`, row `System.Object`),
|
||||
the row the library cut writes for a Rust field with no `type_name` (`variants:ruling:rs-member-unnamed-object-fallback`).
|
||||
|
||||
The Rust mirror reads the C# bytes: Guid and decimal as their strings, the enum as its int, DateTime as the timestamp extension (kept as bytes), `Opaque` as a newtype of String.
|
||||
|
||||
Rows (slot, member, typeName):
|
||||
|
||||
| slot | member | typeName | role |
|
||||
| --- | --- | --- | --- |
|
||||
| 0 | Title | `System.String` | name |
|
||||
| 1 | Sku | `System.String` | index `sku` |
|
||||
| 2 | Count | `System.Int32` | |
|
||||
| 3 | Total | `System.UInt64` | |
|
||||
| 4 | Ratio | `System.Double` | |
|
||||
| 5 | Scale | `System.Single` | |
|
||||
| 6 | Flag | `System.Boolean` | |
|
||||
| 7 | MaybeCount | `System.Nullable<System.Int32>` | |
|
||||
| 8 | Note | `System.String` | |
|
||||
| 9 | Tags | `System.Collections.Generic.List<System.String>` | |
|
||||
| 10 | Labels | `System.String[]` | |
|
||||
| 11 | Raw | `System.Byte[]` | |
|
||||
| 12 | Chunks | `System.Collections.Generic.List<System.Byte[]>` | |
|
||||
| 13 | Weights | `System.Collections.Generic.Dictionary<System.String, System.Int32>` | |
|
||||
| 14 | Mark | `GameCult.Caching.Tests.CatalogMemberMark` | |
|
||||
| 15 | Arm | `GameCult.Caching.Tests.CatalogMemberArm` | |
|
||||
| 17 | Late | `System.Int64` | |
|
||||
| 18 | Items | `System.Collections.Generic.List<GameCult.Caching.Tests.CatalogMemberMark>` | |
|
||||
| 19 | Marks | `GameCult.Caching.Tests.CatalogMemberMark[]` | |
|
||||
| 20 | ByLabel | `System.Collections.Generic.Dictionary<System.String, GameCult.Caching.Tests.CatalogMemberMark>` | |
|
||||
| 21 | MaybeMark | `GameCult.Caching.Tests.CatalogMemberMark` | |
|
||||
| 22 | Arms | `System.Collections.Generic.List<GameCult.Caching.Tests.CatalogMemberArm>` | |
|
||||
| 23 | Grid | `System.Collections.Generic.List<System.Collections.Generic.List<System.Int32>>` | |
|
||||
| 24 | ByNumber | `System.Collections.Generic.Dictionary<System.Int32, System.String>` | |
|
||||
| 25 | Kind | `GameCult.Caching.Tests.CatalogMemberKind` | |
|
||||
| 26 | Ident | `System.Guid` | |
|
||||
| 27 | When | `System.DateTime` | |
|
||||
| 28 | Price | `System.Decimal` | |
|
||||
| 29 | Opaque | `System.Object` | |
|
||||
|
||||
Readers: C# loads both stores typed (the Rust one with `compatible_schema_id_drift` x1, `content_hash_drift` x1 and `defaulted_missing_slot` x29, no refusal) and reads the catalog rows of both;
|
||||
Rust reads both records and the rows of both (raw catalog); TypeScript and Python read both stores and compare all 29 rows and 0 rows.
|
||||
BIN
tests/vectors/catalog-members/csharp-members-store.cc
Normal file
BIN
tests/vectors/catalog-members/csharp-members-store.cc
Normal file
Binary file not shown.
31
tests/vectors/catalog-members/members.json
Normal file
31
tests/vectors/catalog-members/members.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
[
|
||||
[0, "Title", "System.String", false, false, null, true, null],
|
||||
[1, "Sku", "System.String", false, false, null, false, "sku"],
|
||||
[2, "Count", "System.Int32", false, false, null, false, null],
|
||||
[3, "Total", "System.UInt64", false, false, null, false, null],
|
||||
[4, "Ratio", "System.Double", false, false, null, false, null],
|
||||
[5, "Scale", "System.Single", false, false, null, false, null],
|
||||
[6, "Flag", "System.Boolean", false, false, null, false, null],
|
||||
[7, "MaybeCount", "System.Nullable<System.Int32>", false, false, null, false, null],
|
||||
[8, "Note", "System.String", false, false, null, false, null],
|
||||
[9, "Tags", "System.Collections.Generic.List<System.String>", false, false, null, false, null],
|
||||
[10, "Labels", "System.String[]", false, false, null, false, null],
|
||||
[11, "Raw", "System.Byte[]", false, false, null, false, null],
|
||||
[12, "Chunks", "System.Collections.Generic.List<System.Byte[]>", false, false, null, false, null],
|
||||
[13, "Weights", "System.Collections.Generic.Dictionary<System.String, System.Int32>", false, false, null, false, null],
|
||||
[14, "Mark", "GameCult.Caching.Tests.CatalogMemberMark", false, false, null, false, null],
|
||||
[15, "Arm", "GameCult.Caching.Tests.CatalogMemberArm", false, false, null, false, null],
|
||||
[17, "Late", "System.Int64", false, false, null, false, null],
|
||||
[18, "Items", "System.Collections.Generic.List<GameCult.Caching.Tests.CatalogMemberMark>", false, false, null, false, null],
|
||||
[19, "Marks", "GameCult.Caching.Tests.CatalogMemberMark[]", false, false, null, false, null],
|
||||
[20, "ByLabel", "System.Collections.Generic.Dictionary<System.String, GameCult.Caching.Tests.CatalogMemberMark>", false, false, null, false, null],
|
||||
[21, "MaybeMark", "GameCult.Caching.Tests.CatalogMemberMark", false, false, null, false, null],
|
||||
[22, "Arms", "System.Collections.Generic.List<GameCult.Caching.Tests.CatalogMemberArm>", false, false, null, false, null],
|
||||
[23, "Grid", "System.Collections.Generic.List<System.Collections.Generic.List<System.Int32>>", false, false, null, false, null],
|
||||
[24, "ByNumber", "System.Collections.Generic.Dictionary<System.Int32, System.String>", false, false, null, false, null],
|
||||
[25, "Kind", "GameCult.Caching.Tests.CatalogMemberKind", false, false, null, false, null],
|
||||
[26, "Ident", "System.Guid", false, false, null, false, null],
|
||||
[27, "When", "System.DateTime", false, false, null, false, null],
|
||||
[28, "Price", "System.Decimal", false, false, null, false, null],
|
||||
[29, "Opaque", "System.Object", false, false, null, false, null]
|
||||
]
|
||||
BIN
tests/vectors/catalog-members/rust-members-empty-store.cc
Normal file
BIN
tests/vectors/catalog-members/rust-members-empty-store.cc
Normal file
Binary file not shown.
Loading…
Reference in a new issue