Add CultMesh wire parity harnesses
This commit is contained in:
parent
2cc572ca8f
commit
d420118a7b
10 changed files with 549 additions and 2 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -195,6 +195,7 @@ dependencies = [
|
|||
"cultnet-rs",
|
||||
"pretty_assertions",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.31903.59
|
||||
|
|
@ -25,6 +24,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Networking.Tests",
|
|||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Caching.Tests", "tests\GameCult.Caching.Tests\GameCult.Caching.Tests.csproj", "{EB15435B-7147-4BD9-BB9C-B0A14318D3D5}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Mesh.InteropPeer", "tests\GameCult.Mesh.InteropPeer\GameCult.Mesh.InteropPeer.csproj", "{D74A7697-8A3D-45CF-B4B4-06D7263C1163}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
|
|
@ -70,6 +71,10 @@ Global
|
|||
{DBE06954-EC85-4034-9049-72C7D27556DF}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{DBE06954-EC85-4034-9049-72C7D27556DF}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{DBE06954-EC85-4034-9049-72C7D27556DF}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D74A7697-8A3D-45CF-B4B4-06D7263C1163}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D74A7697-8A3D-45CF-B4B4-06D7263C1163}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D74A7697-8A3D-45CF-B4B4-06D7263C1163}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D74A7697-8A3D-45CF-B4B4-06D7263C1163}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{72AEDD42-E881-4EB7-99A8-FD3B9667189C} = {E733CBFF-42AE-4B6A-B5B9-0071ECFB45F1}
|
||||
|
|
@ -81,5 +86,6 @@ Global
|
|||
{EB15435B-7147-4BD9-BB9C-B0A14318D3D5} = {39D316AB-ABB5-49A2-8E83-CAF4C75B48F4}
|
||||
{0E990C96-3808-450E-9349-A0C3262195ED} = {E733CBFF-42AE-4B6A-B5B9-0071ECFB45F1}
|
||||
{DBE06954-EC85-4034-9049-72C7D27556DF} = {E733CBFF-42AE-4B6A-B5B9-0071ECFB45F1}
|
||||
{D74A7697-8A3D-45CF-B4B4-06D7263C1163} = {39D316AB-ABB5-49A2-8E83-CAF4C75B48F4}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
|
|
|||
|
|
@ -18,4 +18,5 @@ cultnet-rs = { path = "../cultnet-rs" }
|
|||
[dev-dependencies]
|
||||
pretty_assertions = "1.4"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tempfile = "3"
|
||||
|
|
|
|||
126
crates/cultmesh-rs/examples/cultmesh_interop.rs
Normal file
126
crates/cultmesh-rs/examples/cultmesh_interop.rs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultmesh_rs::CultMesh;
|
||||
use cultmesh_rs::CultMeshNodeOptions;
|
||||
use cultmesh_rs::cultmesh_documents;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const INTEROP_TYPE: &str = "cultmesh.interop-note";
|
||||
const INTEROP_SCHEMA_VERSION: &str = "cultmesh.interop_note.v0";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(type = "cultmesh.interop-note", schema = "CultMeshInteropNote")]
|
||||
struct CultMeshInteropNote {
|
||||
#[cultcache(key = 0)]
|
||||
schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
document_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
author_runtime_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
verse_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
body: String,
|
||||
#[cultcache(key = 5, default)]
|
||||
tags: Vec<String>,
|
||||
}
|
||||
|
||||
cultmesh_documents!(InteropDocuments {
|
||||
CultMeshInteropNote => INTEROP_SCHEMA_VERSION,
|
||||
});
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let mode = args
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("expected mode: write | read"))?;
|
||||
let options = parse_args(args.collect());
|
||||
let file = require_arg(&options, "file")?;
|
||||
|
||||
match mode.as_str() {
|
||||
"write" => write_note(file, require_arg(&options, "runtime-id")?)?,
|
||||
"read" => read_note(file)?,
|
||||
_ => return Err(anyhow!("unknown mode {mode}")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_note(file: &str, runtime_id: &str) -> Result<()> {
|
||||
let mut node = CultMesh::create_node(
|
||||
file,
|
||||
InteropDocuments,
|
||||
CultMeshNodeOptions {
|
||||
runtime_id: runtime_id.to_string(),
|
||||
..CultMeshNodeOptions::default()
|
||||
},
|
||||
)?;
|
||||
let note = CultMeshInteropNote {
|
||||
schema_version: INTEROP_SCHEMA_VERSION.to_string(),
|
||||
document_id: format!("note:{runtime_id}"),
|
||||
author_runtime_id: runtime_id.to_string(),
|
||||
verse_id: "verse:interop".to_string(),
|
||||
body: "CultMesh local node state uses the shared CultCache wire store.".to_string(),
|
||||
tags: vec![
|
||||
runtime_id.to_string(),
|
||||
"rust".to_string(),
|
||||
"interop".to_string(),
|
||||
"cultmesh".to_string(),
|
||||
],
|
||||
};
|
||||
node.put(note.document_id.clone(), ¬e)?;
|
||||
node.flush()?;
|
||||
print_note(¬e)
|
||||
}
|
||||
|
||||
fn read_note(file: &str) -> Result<()> {
|
||||
let node = CultMesh::start_node(file, InteropDocuments)?;
|
||||
let notes = node.cache().get_all::<CultMeshInteropNote>()?;
|
||||
let note = notes
|
||||
.first()
|
||||
.ok_or_else(|| anyhow!("no {INTEROP_TYPE} records found"))?;
|
||||
print_note(note)
|
||||
}
|
||||
|
||||
fn print_note(note: &CultMeshInteropNote) -> Result<()> {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&json!({
|
||||
"schemaVersion": note.schema_version,
|
||||
"documentId": note.document_id,
|
||||
"authorRuntimeId": note.author_runtime_id,
|
||||
"verseId": note.verse_id,
|
||||
"body": note.body,
|
||||
"tags": note.tags,
|
||||
}))?
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_args(args: Vec<String>) -> BTreeMap<String, String> {
|
||||
let mut parsed = BTreeMap::new();
|
||||
let mut index = 0;
|
||||
while index < args.len() {
|
||||
let token = &args[index];
|
||||
if !token.starts_with("--") {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
let name = token.trim_start_matches("--").to_string();
|
||||
let value = args
|
||||
.get(index + 1)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| panic!("missing value for --{name}"));
|
||||
parsed.insert(name, value);
|
||||
index += 2;
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
fn require_arg<'a>(options: &'a BTreeMap<String, String>, name: &str) -> Result<&'a str> {
|
||||
options
|
||||
.get(name)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| anyhow!("missing required argument --{name}"))
|
||||
}
|
||||
1
package-lock.json
generated
1
package-lock.json
generated
|
|
@ -5084,6 +5084,7 @@
|
|||
"cultnet-ts": "file:../cultnet-ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@msgpack/msgpack": "^3.1.2",
|
||||
"@types/node": "^24.0.0",
|
||||
"typescript": "^5.9.0",
|
||||
"zod": "^3.25.76"
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@
|
|||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --pretty false",
|
||||
"test": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js"
|
||||
"test": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js dist-test/test/interop/*.test.js"
|
||||
},
|
||||
"keywords": [
|
||||
"cultmesh",
|
||||
|
|
@ -26,6 +26,7 @@
|
|||
"cultnet-ts": "file:../cultnet-ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@msgpack/msgpack": "^3.1.2",
|
||||
"@types/node": "^24.0.0",
|
||||
"typescript": "^5.9.0",
|
||||
"zod": "^3.25.76"
|
||||
|
|
|
|||
77
packages/cultmesh-ts/test/interop/cultmesh-interop-shared.ts
Normal file
77
packages/cultmesh-ts/test/interop/cultmesh-interop-shared.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import { decode, encode } from "@msgpack/msgpack";
|
||||
|
||||
import { z } from "zod";
|
||||
import { defineDocumentType } from "cultcache-ts";
|
||||
|
||||
export const INTEROP_DOCUMENT_TYPE = "cultmesh.interop-note";
|
||||
export const INTEROP_SCHEMA_VERSION = "cultmesh.interop_note.v0";
|
||||
export const INTEROP_BODY = "CultMesh local node state uses the shared CultCache wire store.";
|
||||
|
||||
export const interopNoteSchema = z.object({
|
||||
schemaVersion: z.literal(INTEROP_SCHEMA_VERSION),
|
||||
documentId: z.string().min(1),
|
||||
authorRuntimeId: z.string().min(1),
|
||||
verseId: z.string().min(1),
|
||||
body: z.string().min(1),
|
||||
tags: z.array(z.string().min(1)),
|
||||
});
|
||||
|
||||
export type InteropNote = z.infer<typeof interopNoteSchema>;
|
||||
|
||||
export const interopNoteDocument = defineDocumentType({
|
||||
type: INTEROP_DOCUMENT_TYPE,
|
||||
schemaId: INTEROP_DOCUMENT_TYPE,
|
||||
schemaName: INTEROP_DOCUMENT_TYPE,
|
||||
schemaVersion: INTEROP_SCHEMA_VERSION,
|
||||
contentHash: INTEROP_DOCUMENT_TYPE,
|
||||
canonicalSchemaJson: "{\"schemaName\":\"cultmesh.interop-note\",\"schemaVersion\":\"cultmesh.interop_note.v0\",\"members\":[{\"slot\":0,\"name\":\"SchemaVersion\",\"type\":\"System.String\",\"isReference\":false,\"many\":false,\"targetSchemaName\":null,\"indexAlias\":null,\"isName\":false},{\"slot\":1,\"name\":\"DocumentId\",\"type\":\"System.String\",\"isReference\":false,\"many\":false,\"targetSchemaName\":null,\"indexAlias\":null,\"isName\":true},{\"slot\":2,\"name\":\"AuthorRuntimeId\",\"type\":\"System.String\",\"isReference\":false,\"many\":false,\"targetSchemaName\":null,\"indexAlias\":null,\"isName\":false},{\"slot\":3,\"name\":\"VerseId\",\"type\":\"System.String\",\"isReference\":false,\"many\":false,\"targetSchemaName\":null,\"indexAlias\":null,\"isName\":false},{\"slot\":4,\"name\":\"Body\",\"type\":\"System.String\",\"isReference\":false,\"many\":false,\"targetSchemaName\":null,\"indexAlias\":null,\"isName\":false},{\"slot\":5,\"name\":\"Tags\",\"type\":\"System.String[]\",\"isReference\":false,\"many\":false,\"targetSchemaName\":null,\"indexAlias\":null,\"isName\":false}]}",
|
||||
compatibleSchemaIds: [INTEROP_DOCUMENT_TYPE],
|
||||
members: [
|
||||
{ slot: 0, memberName: "SchemaVersion", typeName: "System.String" },
|
||||
{ slot: 1, memberName: "DocumentId", typeName: "System.String", isName: true },
|
||||
{ slot: 2, memberName: "AuthorRuntimeId", typeName: "System.String" },
|
||||
{ slot: 3, memberName: "VerseId", typeName: "System.String" },
|
||||
{ slot: 4, memberName: "Body", typeName: "System.String" },
|
||||
{ slot: 5, memberName: "Tags", typeName: "System.String[]" },
|
||||
],
|
||||
schema: interopNoteSchema,
|
||||
formatter: {
|
||||
encode(value: InteropNote): Uint8Array {
|
||||
return encode([
|
||||
value.schemaVersion,
|
||||
value.documentId,
|
||||
value.authorRuntimeId,
|
||||
value.verseId,
|
||||
value.body,
|
||||
value.tags,
|
||||
]);
|
||||
},
|
||||
decode(payload: Uint8Array): InteropNote {
|
||||
const decoded = decode(payload);
|
||||
if (!Array.isArray(decoded) || decoded.length < 5) {
|
||||
throw new Error("CultMesh interop note payload must be a MessagePack slot array.");
|
||||
}
|
||||
|
||||
const [schemaVersion, documentId, authorRuntimeId, verseId, body, tags] = decoded;
|
||||
return interopNoteSchema.parse({
|
||||
schemaVersion,
|
||||
documentId,
|
||||
authorRuntimeId,
|
||||
verseId,
|
||||
body,
|
||||
tags: Array.isArray(tags) ? tags : [],
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export function buildInteropNote(runtimeId: string, runtimeKind: string): InteropNote {
|
||||
return {
|
||||
schemaVersion: INTEROP_SCHEMA_VERSION,
|
||||
documentId: `note:${runtimeId}`,
|
||||
authorRuntimeId: runtimeId,
|
||||
verseId: "verse:interop",
|
||||
body: INTEROP_BODY,
|
||||
tags: [runtimeId, runtimeKind, "interop", "cultmesh"],
|
||||
};
|
||||
}
|
||||
172
packages/cultmesh-ts/test/interop/cultmesh-interop.test.ts
Normal file
172
packages/cultmesh-ts/test/interop/cultmesh-interop.test.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { exec, execFile } from "node:child_process";
|
||||
import { access, mkdtemp, readFile } from "node:fs/promises";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { decode } from "@msgpack/msgpack";
|
||||
|
||||
import { CultMesh } from "../../src/index";
|
||||
import {
|
||||
INTEROP_BODY,
|
||||
buildInteropNote,
|
||||
interopNoteDocument,
|
||||
type InteropNote,
|
||||
} from "./cultmesh-interop-shared";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const execAsync = promisify(exec);
|
||||
const cargoCommand = process.env.CARGO ?? (process.platform === "win32" ? join(homedir(), ".cargo", "bin", "cargo.exe") : "cargo");
|
||||
const dotnetCommand = process.env.DOTNET ?? (process.platform === "win32" ? join("C:", "Program Files", "dotnet", "dotnet.exe") : "dotnet");
|
||||
const cultMeshTsRoot = resolve(__dirname, "../../..");
|
||||
const cultLibRoot = resolve(cultMeshTsRoot, "..", "..");
|
||||
const cultmeshRsRoot = resolve(cultLibRoot, "crates", "cultmesh-rs");
|
||||
const rustInteropBinary = resolve(
|
||||
cultLibRoot,
|
||||
"target",
|
||||
"debug",
|
||||
"examples",
|
||||
process.platform === "win32" ? "cultmesh_interop.exe" : "cultmesh_interop",
|
||||
);
|
||||
const csharpInteropProject = resolve(
|
||||
cultLibRoot,
|
||||
"tests",
|
||||
"GameCult.Mesh.InteropPeer",
|
||||
"GameCult.Mesh.InteropPeer.csproj",
|
||||
);
|
||||
const csharpInteropDll = resolve(
|
||||
cultLibRoot,
|
||||
"bin",
|
||||
"GameCult.Mesh.InteropPeer",
|
||||
"Debug",
|
||||
"net10.0",
|
||||
"GameCult.Mesh.InteropPeer.dll",
|
||||
);
|
||||
|
||||
test("CultMesh local nodes read and write one MessagePack store across TS, Rust, and C#", async () => {
|
||||
await buildInteropPeers();
|
||||
const tempDir = await mkdtemp(join(tmpdir(), "cultmesh-interop-"));
|
||||
const writers = [
|
||||
{
|
||||
name: "ts",
|
||||
write: async (file: string) => writeTsInteropStore(file, "ts-writer"),
|
||||
},
|
||||
{
|
||||
name: "rust",
|
||||
write: async (file: string) => runJsonCommand("rust-write", rustInteropBinary, [
|
||||
"write",
|
||||
"--file", file,
|
||||
"--runtime-id", "rust-writer",
|
||||
], cultmeshRsRoot),
|
||||
},
|
||||
{
|
||||
name: "csharp",
|
||||
write: async (file: string) => runJsonCommand("csharp-write", dotnetCommand, [
|
||||
csharpInteropDll,
|
||||
"write",
|
||||
"--file", file,
|
||||
"--runtime-id", "csharp-writer",
|
||||
], cultLibRoot),
|
||||
},
|
||||
];
|
||||
const readers = [
|
||||
{
|
||||
name: "ts",
|
||||
read: async (file: string) => readTsInteropStore(file),
|
||||
},
|
||||
{
|
||||
name: "rust",
|
||||
read: async (file: string) => runJsonCommand("rust-read", rustInteropBinary, [
|
||||
"read",
|
||||
"--file", file,
|
||||
], cultmeshRsRoot),
|
||||
},
|
||||
{
|
||||
name: "csharp",
|
||||
read: async (file: string) => runJsonCommand("csharp-read", dotnetCommand, [
|
||||
csharpInteropDll,
|
||||
"read",
|
||||
"--file", file,
|
||||
], cultLibRoot),
|
||||
},
|
||||
];
|
||||
|
||||
for (const writer of writers) {
|
||||
const file = join(tempDir, `${writer.name}.msgpack`);
|
||||
const written = await writer.write(file);
|
||||
const decoded = decode(await readFile(file)) as unknown[];
|
||||
assert.equal(decoded[0], "cultcache.store.v1");
|
||||
assert.ok(Array.isArray(decoded[1]), `${writer.name} did not write a schema catalog`);
|
||||
assert.ok(Array.isArray(decoded[2]), `${writer.name} did not write records`);
|
||||
|
||||
for (const reader of readers) {
|
||||
const read = await reader.read(file);
|
||||
assert.equal(read.documentId, written.documentId, `${reader.name} failed to read ${writer.name}`);
|
||||
assert.equal(read.authorRuntimeId, written.authorRuntimeId);
|
||||
assert.equal(read.verseId, "verse:interop");
|
||||
assert.equal(read.body, INTEROP_BODY);
|
||||
assert.ok(read.tags.includes("interop"));
|
||||
assert.ok(read.tags.includes("cultmesh"));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function writeTsInteropStore(file: string, runtimeId: string): Promise<InteropNote> {
|
||||
const node = await CultMesh.startNode(file, {
|
||||
documents: [interopNoteDocument],
|
||||
});
|
||||
const note = buildInteropNote(runtimeId, "ts");
|
||||
await node.put(interopNoteDocument, note.documentId, note);
|
||||
await node.flush();
|
||||
return note;
|
||||
}
|
||||
|
||||
async function readTsInteropStore(file: string): Promise<InteropNote> {
|
||||
const node = await CultMesh.startNode(file, {
|
||||
documents: [interopNoteDocument],
|
||||
});
|
||||
const note = node.cache.getAll(interopNoteDocument)[0];
|
||||
if (!note) {
|
||||
throw new Error("No cultmesh.interop-note records found.");
|
||||
}
|
||||
return note;
|
||||
}
|
||||
|
||||
async function buildInteropPeers(): Promise<void> {
|
||||
if (!(await exists(rustInteropBinary))) {
|
||||
await execAsync(`"${cargoCommand}" build --quiet --example cultmesh_interop`, {
|
||||
cwd: cultmeshRsRoot,
|
||||
});
|
||||
}
|
||||
if (!(await exists(csharpInteropDll))) {
|
||||
await execAsync(`"${dotnetCommand}" build "${csharpInteropProject}" -nologo`, {
|
||||
cwd: cultLibRoot,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function exists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function runJsonCommand(
|
||||
name: string,
|
||||
command: string,
|
||||
args: string[],
|
||||
cwd: string,
|
||||
): Promise<InteropNote> {
|
||||
const { stdout, stderr } = await execFileAsync(command, args, { cwd, timeout: 30_000 });
|
||||
const trimmed = stdout.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error(`${name} produced no stdout.\n${stderr}`);
|
||||
}
|
||||
|
||||
return JSON.parse(trimmed.split(/\r?\n/).at(-1) as string) as InteropNote;
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>GameCult.Mesh.InteropPeer</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\GameCult.Mesh\GameCult.Mesh.csproj" />
|
||||
<ProjectReference Include="..\..\src\GameCult.Caching.MessagePack.Generator\GameCult.Caching.MessagePack.Generator.csproj"
|
||||
OutputItemType="Analyzer"
|
||||
ReferenceOutputAssembly="false" />
|
||||
<PackageReference Include="MessagePack" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
146
tests/GameCult.Mesh.InteropPeer/Program.cs
Normal file
146
tests/GameCult.Mesh.InteropPeer/Program.cs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using GameCult.Mesh;
|
||||
using GameCult.Networking;
|
||||
using MessagePack;
|
||||
|
||||
return await ProgramMainAsync(args);
|
||||
|
||||
static async Task<int> ProgramMainAsync(string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (args.Length == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Expected mode: write | read");
|
||||
}
|
||||
|
||||
var mode = args[0];
|
||||
var options = ParseArgs(args.Skip(1).ToArray());
|
||||
var file = RequireArg(options, "file");
|
||||
switch (mode)
|
||||
{
|
||||
case "write":
|
||||
await WriteAsync(file, RequireArg(options, "runtime-id"));
|
||||
return 0;
|
||||
case "read":
|
||||
await ReadAsync(file);
|
||||
return 0;
|
||||
default:
|
||||
throw new InvalidOperationException($"Unknown mode {mode}.");
|
||||
}
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
Console.Error.WriteLine(error);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
static async Task WriteAsync(string file, string runtimeId)
|
||||
{
|
||||
using var node = await CreateNodeAsync(file, runtimeId);
|
||||
var note = new CultMeshInteropNote
|
||||
{
|
||||
DocumentId = $"note:{runtimeId}",
|
||||
AuthorRuntimeId = runtimeId,
|
||||
VerseId = "verse:interop",
|
||||
Body = "CultMesh local node state uses the shared CultCache wire store.",
|
||||
Tags = [runtimeId, "csharp", "interop", "cultmesh"]
|
||||
};
|
||||
await node.Database.PutAsync(new CultRecordKey(note.DocumentId), note);
|
||||
await node.FlushAsync();
|
||||
WriteJsonLine(note);
|
||||
}
|
||||
|
||||
static async Task ReadAsync(string file)
|
||||
{
|
||||
using var node = await CreateNodeAsync(file, "csharp-reader");
|
||||
var note = node.Cache.AllEntries
|
||||
.OfType<CultMeshInteropNote>()
|
||||
.FirstOrDefault()
|
||||
?? throw new InvalidOperationException("No cultmesh.interop-note records found.");
|
||||
WriteJsonLine(note);
|
||||
}
|
||||
|
||||
static async Task<CultMeshNode> CreateNodeAsync(string file, string runtimeId)
|
||||
{
|
||||
var registry = new CultDocumentRegistry();
|
||||
registry.GetRequired<CultMeshInteropNote>();
|
||||
var documentRegistry = new CultNetDocumentRegistry(registry);
|
||||
return await CultMesh.CreateNodeAsync(file, new CultMeshNodeOptions
|
||||
{
|
||||
StartServer = false,
|
||||
CacheOptions = new CultCacheOpenOptions
|
||||
{
|
||||
Registry = registry
|
||||
},
|
||||
DatabaseOptions = new CultNetDatabaseOptions
|
||||
{
|
||||
RuntimeId = runtimeId,
|
||||
DocumentRegistry = documentRegistry
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static Dictionary<string, string> ParseArgs(string[] args)
|
||||
{
|
||||
var parsed = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var index = 0; index < args.Length; index += 2)
|
||||
{
|
||||
var token = args[index];
|
||||
if (!token.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (index + 1 >= args.Length)
|
||||
{
|
||||
throw new InvalidOperationException($"Missing value for {token}.");
|
||||
}
|
||||
|
||||
parsed[token[2..]] = args[index + 1];
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
static string RequireArg(Dictionary<string, string> options, string name)
|
||||
{
|
||||
if (!options.TryGetValue(name, out var value) || string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
throw new InvalidOperationException($"Missing required argument --{name}.");
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
static void WriteJsonLine(CultMeshInteropNote note)
|
||||
{
|
||||
Console.Out.WriteLine(JsonSerializer.Serialize(new
|
||||
{
|
||||
schemaVersion = note.SchemaVersion,
|
||||
documentId = note.DocumentId,
|
||||
authorRuntimeId = note.AuthorRuntimeId,
|
||||
verseId = note.VerseId,
|
||||
body = note.Body,
|
||||
tags = note.Tags
|
||||
}));
|
||||
}
|
||||
|
||||
[CultDocument("cultmesh.interop-note", "cultmesh.interop_note.v0")]
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshInteropNote
|
||||
{
|
||||
[Key(0)] public string SchemaVersion { get; set; } = "cultmesh.interop_note.v0";
|
||||
[Key(1)] [CultName] public string DocumentId { get; set; } = string.Empty;
|
||||
[Key(2)] public string AuthorRuntimeId { get; set; } = string.Empty;
|
||||
[Key(3)] public string VerseId { get; set; } = string.Empty;
|
||||
[Key(4)] public string Body { get; set; } = string.Empty;
|
||||
[Key(5)] public string[] Tags { get; set; } = Array.Empty<string>();
|
||||
}
|
||||
Loading…
Reference in a new issue