From 3905b9a01aba86c5a7aa845b27961fa3aeb22c45 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 24 May 2026 11:35:08 +0100 Subject: [PATCH] Squashed 'crates/cultnet-rs/' content from commit ab86857a git-subtree-dir: crates/cultnet-rs git-subtree-split: ab86857a687917f6383595a721ade0e1a7e247df --- .gitignore | 2 + Cargo.toml | 32 + README.md | 79 ++ contracts/cultnet.document-delete.schema.json | 19 + ...net.document-mutation-contract.schema.json | 40 + .../cultnet.document-put-raw.schema.json | 19 + contracts/cultnet.document-put.schema.json | 19 + contracts/cultnet.document-record.schema.json | 26 + contracts/cultnet.error.schema.json | 15 + contracts/cultnet.hello.schema.json | 35 + contracts/cultnet.login-success.schema.json | 17 + contracts/cultnet.login.schema.json | 19 + .../cultnet.raw-document-record.schema.json | 32 + contracts/cultnet.register.schema.json | 21 + .../cultnet.sample-change-name.schema.json | 15 + contracts/cultnet.sample-chat.schema.json | 15 + ...cultnet.schema-catalog-request.schema.json | 31 + ...ultnet.schema-catalog-response.schema.json | 22 + .../cultnet.schema-descriptor.schema.json | 39 + .../cultnet.snapshot-request.schema.json | 23 + .../cultnet.snapshot-response-raw.schema.json | 22 + .../cultnet.snapshot-response.schema.json | 22 + contracts/cultnet.verify.schema.json | 17 + contracts/ghostlight.agent-state.schema.json | 845 ++++++++++++ examples/cultnet_interop_peer.rs | 967 ++++++++++++++ src/contracts.rs | 1155 +++++++++++++++++ src/framing.rs | 49 + src/lib.rs | 11 + src/replication.rs | 440 +++++++ src/schema_discovery.rs | 389 ++++++ src/security.rs | 270 ++++ tests/cultnet.rs | 397 ++++++ tests/fixtures/cultnet-ts-hello.frame | Bin 0 -> 160 bytes tests/fixtures/cultnet-ts-legacy-login.frame | Bin 0 -> 30 bytes 34 files changed, 5104 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 README.md create mode 100644 contracts/cultnet.document-delete.schema.json create mode 100644 contracts/cultnet.document-mutation-contract.schema.json create mode 100644 contracts/cultnet.document-put-raw.schema.json create mode 100644 contracts/cultnet.document-put.schema.json create mode 100644 contracts/cultnet.document-record.schema.json create mode 100644 contracts/cultnet.error.schema.json create mode 100644 contracts/cultnet.hello.schema.json create mode 100644 contracts/cultnet.login-success.schema.json create mode 100644 contracts/cultnet.login.schema.json create mode 100644 contracts/cultnet.raw-document-record.schema.json create mode 100644 contracts/cultnet.register.schema.json create mode 100644 contracts/cultnet.sample-change-name.schema.json create mode 100644 contracts/cultnet.sample-chat.schema.json create mode 100644 contracts/cultnet.schema-catalog-request.schema.json create mode 100644 contracts/cultnet.schema-catalog-response.schema.json create mode 100644 contracts/cultnet.schema-descriptor.schema.json create mode 100644 contracts/cultnet.snapshot-request.schema.json create mode 100644 contracts/cultnet.snapshot-response-raw.schema.json create mode 100644 contracts/cultnet.snapshot-response.schema.json create mode 100644 contracts/cultnet.verify.schema.json create mode 100644 contracts/ghostlight.agent-state.schema.json create mode 100644 examples/cultnet_interop_peer.rs create mode 100644 src/contracts.rs create mode 100644 src/framing.rs create mode 100644 src/lib.rs create mode 100644 src/replication.rs create mode 100644 src/schema_discovery.rs create mode 100644 src/security.rs create mode 100644 tests/cultnet.rs create mode 100644 tests/fixtures/cultnet-ts-hello.frame create mode 100644 tests/fixtures/cultnet-ts-legacy-login.frame diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..96ef6c0b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..41d14b52 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "cultnet-rs" +version = "0.1.0" +edition = "2024" +publish = false +license = "MIT" +description = "CultNet-style typed MessagePack messaging, direct-pipe framing, security helpers, and CultCache replication for Rust runtimes." + +[lib] +name = "cultnet_rs" +path = "src/lib.rs" + +[dependencies] +aes-gcm = "0.10" +anyhow = "1" +base64 = "0.22" +chrono = { version = "0.4", features = ["serde"] } +cultcache-rs = { path = "../cultcache-rs" } +hmac = "0.12" +rand = "0.9" +rmp-serde = "1.3" +rmpv = { version = "1.3", features = ["with-serde"] } +serde = { version = "1", features = ["derive"] } +serde_bytes = "0.11" +serde_json = "1" +sha2 = "0.10" +socket2 = "0.5" +uuid = { version = "1", features = ["v4"] } + +[dev-dependencies] +pretty_assertions = "1.4" +tempfile = "3" diff --git a/README.md b/README.md new file mode 100644 index 00000000..09ba4b0f --- /dev/null +++ b/README.md @@ -0,0 +1,79 @@ +# CultNet RS + +`cultnet-rs` is the Rust sibling of `cultnet-ts`: typed MessagePack messages, +4-byte length-prefixed direct-pipe framing, CultLib-shaped security helpers, and +CultCache replication without making callers paw through raw envelopes like we +lost a bet. + +The contract is intentionally boring: + +- `cultnet.schema.v0` sends schema-versioned MessagePack objects. +- `gamecult.networking.v0` maps the legacy C# union shape explicitly. +- schema discovery uses explicit catalog request/response messages; no inbound + auto-detect sludge. +- document put/delete/snapshot messages move typed CultCache entries. +- raw document put/snapshot messages preserve canonical MessagePack payload + bytes for bit-compatible neighbors. +- hello messages advertise `supportedMutationContracts`, so callers discover + which document types are read-only, which accept typed intents, which + authority owns the mutation, and which receipt documents prove the outcome. +- payloads are decoded through registered Rust types before entering the cache. + +This crate is not an HTTP wrapper. It is the wire vocabulary Epiphany, +Ghostlight, VoidBot, and the rest of the swarm can share. + +The public API surface is the schema plus its mutation contracts. A runtime does +not expose a pile of bespoke verbs and hope everyone remembers the ritual; it +advertises typed documents, typed intents, and typed receipts. Polite machines +knock on the contract before touching the furniture. + +## Receipts + +```powershell +cargo test +``` + +The initial tests prove: + +- CultLib-compatible AES-GCM string encryption and HMAC session tokens +- 4-byte big-endian MessagePack framing +- schema-versioned message round trips +- legacy `gamecult.networking.v0` login mapping +- schema discovery catalog responses with canonical JSON schema hashes +- CultCache snapshot replication through registered typed documents +- raw snapshot replication that preserves the original payload bytes +- document mutation contract advertisement through hello frames and registries + +## Schema Discovery + +`cultnet-rs` now ships a built-in schema registry for the shared swarm contract +surface: + +- core wire messages +- legacy `gamecult.networking.v0` auth/sample payloads +- schema catalog request/response messages +- the canonical `ghostlight.agent-state` document payload schema + +Use `builtin_schema_registry()` when you want the standard catalog, or register +your own closed-world schema set with `CultNetSchemaRegistry`. Discovery stays +explicit on purpose: peers advertise only the contracts they were compiled to +understand, the same way CultCache only consumes the document types you +registered instead of pretending polymorphism is a public park. + +## Local Fast Lane + +`cultnet-rs` now mirrors the raw replication seam from `cultnet-ts`: + +- `cultnet.document_put_raw.v0` +- `cultnet.snapshot_response_raw.v0` + +Those messages carry the exact persisted MessagePack payload bytes from +CultCache along with the typed envelope metadata. Combined with +`CultCache::put_envelope::()`, that lets a bit-compatible neighbor ingest the +document without re-encoding the payload first. + +That still is not zero-copy in the religious sense. Frames allocate, bytes move, +and the receiving cache still decodes once to keep typed reads and validation +honest. The win is narrower and realer: identical payload bytes stop getting +decoded into generic sludge and then encoded right back into the same bytes for +no reason. diff --git a/contracts/cultnet.document-delete.schema.json b/contracts/cultnet.document-delete.schema.json new file mode 100644 index 00000000..265bcaf2 --- /dev/null +++ b/contracts/cultnet.document-delete.schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-delete.schema.json", + "title": "CultNet Document Delete Message", + "type": "object", + "required": [ + "schemaVersion", + "messageId", + "schemaId", + "recordKey" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.document_delete.v0" }, + "messageId": { "type": "string", "minLength": 1 }, + "schemaId": { "type": "string", "minLength": 1 }, + "recordKey": { "type": "string", "minLength": 1 } + } +} diff --git a/contracts/cultnet.document-mutation-contract.schema.json b/contracts/cultnet.document-mutation-contract.schema.json new file mode 100644 index 00000000..e444fef0 --- /dev/null +++ b/contracts/cultnet.document-mutation-contract.schema.json @@ -0,0 +1,40 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-mutation-contract.schema.json", + "title": "CultNet Document Mutation Contract", + "type": "object", + "required": [ + "documentType", + "operations", + "authority" + ], + "additionalProperties": false, + "properties": { + "documentType": { "type": "string", "minLength": 1 }, + "payloadSchemaVersion": { "type": "string", "minLength": 1 }, + "operations": { + "type": "array", + "minItems": 1, + "items": { + "type": "string", + "enum": ["snapshot", "documentPut", "documentDelete", "intentSubmit", "receiptWatch"] + } + }, + "authority": { + "type": "string", + "enum": ["readOnly", "localUser", "coordinator", "runtime", "denied"] + }, + "intentDocumentTypes": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + }, + "receiptDocumentTypes": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + }, + "notes": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + } + } +} diff --git a/contracts/cultnet.document-put-raw.schema.json b/contracts/cultnet.document-put-raw.schema.json new file mode 100644 index 00000000..3c178d03 --- /dev/null +++ b/contracts/cultnet.document-put-raw.schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-put-raw.schema.json", + "title": "CultNet Raw Document Put Message", + "type": "object", + "required": [ + "schemaVersion", + "messageId", + "document" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.document_put_raw.v0" }, + "messageId": { "type": "string", "minLength": 1 }, + "document": { + "$ref": "./cultnet.raw-document-record.schema.json" + } + } +} diff --git a/contracts/cultnet.document-put.schema.json b/contracts/cultnet.document-put.schema.json new file mode 100644 index 00000000..a04f5fca --- /dev/null +++ b/contracts/cultnet.document-put.schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-put.schema.json", + "title": "CultNet Document Put Message", + "type": "object", + "required": [ + "schemaVersion", + "messageId", + "document" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.document_put.v0" }, + "messageId": { "type": "string", "minLength": 1 }, + "document": { + "$ref": "./cultnet.document-record.schema.json" + } + } +} diff --git a/contracts/cultnet.document-record.schema.json b/contracts/cultnet.document-record.schema.json new file mode 100644 index 00000000..94301dc5 --- /dev/null +++ b/contracts/cultnet.document-record.schema.json @@ -0,0 +1,26 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-record.schema.json", + "title": "CultNet Document Record", + "type": "object", + "required": [ + "schemaId", + "recordKey", + "storedAt", + "payload" + ], + "additionalProperties": false, + "properties": { + "schemaId": { "type": "string", "minLength": 1 }, + "recordKey": { "type": "string", "minLength": 1 }, + "storedAt": { "type": "string", "minLength": 1 }, + "payload": {}, + "sourceRuntimeId": { "type": "string", "minLength": 1 }, + "sourceAgentId": { "type": "string", "minLength": 1 }, + "sourceRole": { "type": "string", "minLength": 1 }, + "tags": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + } + } +} diff --git a/contracts/cultnet.error.schema.json b/contracts/cultnet.error.schema.json new file mode 100644 index 00000000..af6da9cf --- /dev/null +++ b/contracts/cultnet.error.schema.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.error.schema.json", + "title": "CultNet Error Message", + "type": "object", + "required": [ + "schemaVersion", + "error" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.error.v0" }, + "error": { "type": "string", "minLength": 1 } + } +} diff --git a/contracts/cultnet.hello.schema.json b/contracts/cultnet.hello.schema.json new file mode 100644 index 00000000..bced7577 --- /dev/null +++ b/contracts/cultnet.hello.schema.json @@ -0,0 +1,35 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.hello.schema.json", + "title": "CultNet Hello Message", + "type": "object", + "required": [ + "schemaVersion", + "runtimeId", + "runtimeKind" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.hello.v0" }, + "runtimeId": { "type": "string", "minLength": 1 }, + "runtimeKind": { "type": "string", "minLength": 1 }, + "agentId": { "type": "string", "minLength": 1 }, + "role": { "type": "string", "minLength": 1 }, + "displayName": { "type": "string", "minLength": 1 }, + "supportedDocumentTypes": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + }, + "supportedMutationContracts": { + "type": "array", + "items": { + "$ref": "./cultnet.document-mutation-contract.schema.json" + } + }, + "supportedMessageVersions": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + }, + "supportsSchemaCatalog": { "type": "boolean" } + } +} diff --git a/contracts/cultnet.login-success.schema.json b/contracts/cultnet.login-success.schema.json new file mode 100644 index 00000000..3d8a4591 --- /dev/null +++ b/contracts/cultnet.login-success.schema.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.login-success.schema.json", + "title": "CultNet Login Success Message", + "type": "object", + "required": [ + "schemaVersion", + "nonce", + "session" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.login_success.v0" }, + "nonce": { "type": "string", "minLength": 1 }, + "session": { "type": "string", "minLength": 1 } + } +} diff --git a/contracts/cultnet.login.schema.json b/contracts/cultnet.login.schema.json new file mode 100644 index 00000000..62f49599 --- /dev/null +++ b/contracts/cultnet.login.schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.login.schema.json", + "title": "CultNet Login Message", + "type": "object", + "required": [ + "schemaVersion", + "nonce", + "auth", + "password" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.login.v0" }, + "nonce": { "type": "string", "minLength": 1 }, + "auth": { "type": "string", "minLength": 1 }, + "password": { "type": "string", "minLength": 1 } + } +} diff --git a/contracts/cultnet.raw-document-record.schema.json b/contracts/cultnet.raw-document-record.schema.json new file mode 100644 index 00000000..3348a5fa --- /dev/null +++ b/contracts/cultnet.raw-document-record.schema.json @@ -0,0 +1,32 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.raw-document-record.schema.json", + "title": "CultNet Raw Document Record", + "type": "object", + "required": [ + "schemaId", + "recordKey", + "storedAt", + "payloadEncoding", + "payload" + ], + "additionalProperties": false, + "properties": { + "schemaId": { "type": "string", "minLength": 1 }, + "recordKey": { "type": "string", "minLength": 1 }, + "storedAt": { "type": "string", "minLength": 1 }, + "payloadEncoding": { "const": "messagepack" }, + "payload": { + "type": "string", + "contentEncoding": "base64", + "x-cult-runtime-type": "bytes" + }, + "sourceRuntimeId": { "type": "string", "minLength": 1 }, + "sourceAgentId": { "type": "string", "minLength": 1 }, + "sourceRole": { "type": "string", "minLength": 1 }, + "tags": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + } + } +} diff --git a/contracts/cultnet.register.schema.json b/contracts/cultnet.register.schema.json new file mode 100644 index 00000000..77286f3e --- /dev/null +++ b/contracts/cultnet.register.schema.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.register.schema.json", + "title": "CultNet Register Message", + "type": "object", + "required": [ + "schemaVersion", + "nonce", + "email", + "password", + "name" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.register.v0" }, + "nonce": { "type": "string", "minLength": 1 }, + "email": { "type": "string", "minLength": 1 }, + "password": { "type": "string", "minLength": 1 }, + "name": { "type": "string", "minLength": 1 } + } +} diff --git a/contracts/cultnet.sample-change-name.schema.json b/contracts/cultnet.sample-change-name.schema.json new file mode 100644 index 00000000..fc3fe057 --- /dev/null +++ b/contracts/cultnet.sample-change-name.schema.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.sample-change-name.schema.json", + "title": "CultNet Sample Change Name Message", + "type": "object", + "required": [ + "schemaVersion", + "name" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.sample.change_name.v0" }, + "name": { "type": "string", "minLength": 1 } + } +} diff --git a/contracts/cultnet.sample-chat.schema.json b/contracts/cultnet.sample-chat.schema.json new file mode 100644 index 00000000..8426fb57 --- /dev/null +++ b/contracts/cultnet.sample-chat.schema.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.sample-chat.schema.json", + "title": "CultNet Sample Chat Message", + "type": "object", + "required": [ + "schemaVersion", + "text" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.sample.chat.v0" }, + "text": { "type": "string", "minLength": 1 } + } +} diff --git a/contracts/cultnet.schema-catalog-request.schema.json b/contracts/cultnet.schema-catalog-request.schema.json new file mode 100644 index 00000000..611733d2 --- /dev/null +++ b/contracts/cultnet.schema-catalog-request.schema.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-catalog-request.schema.json", + "title": "CultNet Schema Catalog Request Message", + "type": "object", + "required": [ + "schemaVersion", + "messageId" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.schema_catalog_request.v0" }, + "messageId": { "type": "string", "minLength": 1 }, + "includeSchemaJson": { "type": "boolean" }, + "schemaIds": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + }, + "kinds": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "wire_message", + "document_payload", + "shared_contract" + ] + } + } + } +} diff --git a/contracts/cultnet.schema-catalog-response.schema.json b/contracts/cultnet.schema-catalog-response.schema.json new file mode 100644 index 00000000..fa371e48 --- /dev/null +++ b/contracts/cultnet.schema-catalog-response.schema.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-catalog-response.schema.json", + "title": "CultNet Schema Catalog Response Message", + "type": "object", + "required": [ + "schemaVersion", + "messageId", + "schemas" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.schema_catalog_response.v0" }, + "messageId": { "type": "string", "minLength": 1 }, + "schemas": { + "type": "array", + "items": { + "$ref": "./cultnet.schema-descriptor.schema.json" + } + } + } +} diff --git a/contracts/cultnet.schema-descriptor.schema.json b/contracts/cultnet.schema-descriptor.schema.json new file mode 100644 index 00000000..23796857 --- /dev/null +++ b/contracts/cultnet.schema-descriptor.schema.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-descriptor.schema.json", + "title": "CultNet Schema Descriptor", + "type": "object", + "required": [ + "schemaId", + "kind", + "wireContracts", + "contentHash" + ], + "additionalProperties": false, + "properties": { + "schemaId": { "type": "string", "minLength": 1 }, + "kind": { + "type": "string", + "enum": [ + "wire_message", + "document_payload", + "shared_contract" + ] + }, + "schemaVersion": { "type": "string", "minLength": 1 }, + "documentType": { "type": "string", "minLength": 1 }, + "title": { "type": "string", "minLength": 1 }, + "wireContracts": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "cultnet.schema.v0", + "gamecult.networking.v0" + ] + } + }, + "contentHash": { "type": "string", "minLength": 1 }, + "schemaJson": { "type": "string", "minLength": 1 } + } +} diff --git a/contracts/cultnet.snapshot-request.schema.json b/contracts/cultnet.snapshot-request.schema.json new file mode 100644 index 00000000..712d7059 --- /dev/null +++ b/contracts/cultnet.snapshot-request.schema.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-request.schema.json", + "title": "CultNet Snapshot Request Message", + "type": "object", + "required": [ + "schemaVersion", + "messageId" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.snapshot_request.v0" }, + "messageId": { "type": "string", "minLength": 1 }, + "schemaIds": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + }, + "recordKeys": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + } + } +} diff --git a/contracts/cultnet.snapshot-response-raw.schema.json b/contracts/cultnet.snapshot-response-raw.schema.json new file mode 100644 index 00000000..a84bc50d --- /dev/null +++ b/contracts/cultnet.snapshot-response-raw.schema.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-response-raw.schema.json", + "title": "CultNet Raw Snapshot Response Message", + "type": "object", + "required": [ + "schemaVersion", + "messageId", + "documents" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.snapshot_response_raw.v0" }, + "messageId": { "type": "string", "minLength": 1 }, + "documents": { + "type": "array", + "items": { + "$ref": "./cultnet.raw-document-record.schema.json" + } + } + } +} diff --git a/contracts/cultnet.snapshot-response.schema.json b/contracts/cultnet.snapshot-response.schema.json new file mode 100644 index 00000000..940822ce --- /dev/null +++ b/contracts/cultnet.snapshot-response.schema.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-response.schema.json", + "title": "CultNet Snapshot Response Message", + "type": "object", + "required": [ + "schemaVersion", + "messageId", + "documents" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.snapshot_response.v0" }, + "messageId": { "type": "string", "minLength": 1 }, + "documents": { + "type": "array", + "items": { + "$ref": "./cultnet.document-record.schema.json" + } + } + } +} diff --git a/contracts/cultnet.verify.schema.json b/contracts/cultnet.verify.schema.json new file mode 100644 index 00000000..1f992aa8 --- /dev/null +++ b/contracts/cultnet.verify.schema.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.verify.schema.json", + "title": "CultNet Verify Message", + "type": "object", + "required": [ + "schemaVersion", + "nonce", + "session" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.verify.v0" }, + "nonce": { "type": "string", "minLength": 1 }, + "session": { "type": "string", "minLength": 1 } + } +} diff --git a/contracts/ghostlight.agent-state.schema.json b/contracts/ghostlight.agent-state.schema.json new file mode 100644 index 00000000..6437cd01 --- /dev/null +++ b/contracts/ghostlight.agent-state.schema.json @@ -0,0 +1,845 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/Ghostlight/schemas/agent-state.schema.json", + "title": "Ghostlight Agent State Schema", + "description": "First canonical contract for Ghostlight agent, perception, relationship, event, scene, and dialogue-context state.", + "type": "object", + "required": [ + "schema_version", + "world", + "agents", + "relationships", + "events", + "scenes" + ], + "additionalProperties": false, + "properties": { + "schema_version": { + "const": "ghostlight.agent_state.v0" + }, + "world": { + "$ref": "#/$defs/world_state" + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/$defs/agent" + } + }, + "relationships": { + "type": "array", + "items": { + "$ref": "#/$defs/relationship" + } + }, + "events": { + "type": "array", + "items": { + "$ref": "#/$defs/event" + } + }, + "scenes": { + "type": "array", + "items": { + "$ref": "#/$defs/scene" + } + } + }, + "$defs": { + "world_state": { + "type": "object", + "required": [ + "world_id", + "setting", + "time", + "canon_context" + ], + "additionalProperties": false, + "properties": { + "world_id": { + "type": "string" + }, + "setting": { + "type": "string" + }, + "time": { + "type": "object", + "required": [ + "label" + ], + "additionalProperties": true, + "properties": { + "label": { + "type": "string" + } + } + }, + "canon_context": { + "type": "array", + "items": { + "type": "string" + } + }, + "ambient_pressures": { + "type": "array", + "items": { + "$ref": "#/$defs/pressure" + } + } + } + }, + "agent": { + "type": "object", + "required": [ + "agent_id", + "identity", + "canonical_state", + "goals", + "memories", + "perceived_state_overlays" + ], + "additionalProperties": false, + "properties": { + "agent_id": { + "type": "string" + }, + "identity": { + "$ref": "#/$defs/identity" + }, + "canonical_state": { + "$ref": "#/$defs/canonical_state" + }, + "goals": { + "type": "array", + "items": { + "$ref": "#/$defs/goal" + } + }, + "memories": { + "$ref": "#/$defs/memory_bundle" + }, + "perceived_state_overlays": { + "type": "array", + "items": { + "$ref": "#/$defs/perceived_state_overlay" + } + } + } + }, + "identity": { + "type": "object", + "required": [ + "name", + "roles", + "origin", + "public_description" + ], + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "roles": { + "type": "array", + "items": { + "type": "string" + } + }, + "origin": { + "type": "string" + }, + "public_description": { + "type": "string" + }, + "private_notes": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "canonical_state": { + "type": "object", + "required": [ + "underlying_organization", + "stable_dispositions", + "behavioral_dimensions", + "presentation_strategy", + "voice_style", + "situational_state", + "values" + ], + "additionalProperties": false, + "properties": { + "underlying_organization": { + "$ref": "#/$defs/variable_map" + }, + "stable_dispositions": { + "$ref": "#/$defs/variable_map" + }, + "behavioral_dimensions": { + "$ref": "#/$defs/variable_map" + }, + "presentation_strategy": { + "$ref": "#/$defs/variable_map" + }, + "situational_state": { + "$ref": "#/$defs/variable_map" + }, + "values": { + "type": "array", + "items": { + "$ref": "#/$defs/value_commitment" + } + }, + "voice_style": { + "$ref": "#/$defs/variable_map" + } + } + }, + "variable_map": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/state_variable" + } + }, + "state_variable": { + "type": "object", + "required": [ + "mean", + "plasticity", + "current_activation" + ], + "additionalProperties": false, + "properties": { + "mean": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "plasticity": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "current_activation": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "evidence": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "value_commitment": { + "type": "object", + "required": [ + "value_id", + "label", + "priority", + "unforgivable_if_betrayed" + ], + "additionalProperties": false, + "properties": { + "value_id": { + "type": "string" + }, + "label": { + "type": "string" + }, + "priority": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "unforgivable_if_betrayed": { + "type": "boolean" + } + } + }, + "goal": { + "type": "object", + "required": [ + "goal_id", + "description", + "scope", + "priority", + "emotional_stake", + "status" + ], + "additionalProperties": false, + "properties": { + "goal_id": { + "type": "string" + }, + "description": { + "type": "string" + }, + "scope": { + "enum": [ + "immediate", + "scene", + "case", + "arc", + "life" + ] + }, + "priority": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "emotional_stake": { + "type": "string" + }, + "blockers": { + "type": "array", + "items": { + "type": "string" + } + }, + "status": { + "enum": [ + "active", + "blocked", + "dormant", + "resolved", + "abandoned" + ] + } + } + }, + "memory_bundle": { + "type": "object", + "required": [ + "episodic", + "semantic", + "relationship_summaries" + ], + "additionalProperties": false, + "properties": { + "episodic": { + "type": "array", + "items": { + "$ref": "#/$defs/memory" + } + }, + "semantic": { + "type": "array", + "items": { + "$ref": "#/$defs/memory" + } + }, + "relationship_summaries": { + "type": "array", + "items": { + "$ref": "#/$defs/memory" + } + } + } + }, + "memory": { + "type": "object", + "required": [ + "memory_id", + "summary", + "salience", + "confidence" + ], + "additionalProperties": false, + "properties": { + "memory_id": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "salience": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "linked_event_ids": { + "type": "array", + "items": { + "type": "string" + } + }, + "linked_relationship_id": { + "type": "string" + } + } + }, + "perceived_state_overlay": { + "type": "object", + "required": [ + "observer_agent_id", + "target_agent_id", + "perceived_dimensions", + "beliefs", + "distortions" + ], + "additionalProperties": false, + "properties": { + "observer_agent_id": { + "type": "string" + }, + "target_agent_id": { + "type": "string" + }, + "perceived_dimensions": { + "$ref": "#/$defs/inferred_variable_map" + }, + "beliefs": { + "type": "array", + "items": { + "$ref": "#/$defs/belief" + } + }, + "distortions": { + "type": "array", + "items": { + "enum": [ + "hostile_attribution", + "false_reassurance", + "overread_warmth", + "underread_threat", + "false_mask_detection", + "missed_mask_detection", + "status_injury", + "threat_amplification", + "institutional_suspicion_transfer", + "care_underread", + "mask_overfocus" + ] + } + } + } + }, + "belief": { + "type": "object", + "required": [ + "belief_id", + "claim", + "confidence" + ], + "additionalProperties": false, + "properties": { + "belief_id": { + "type": "string" + }, + "claim": { + "type": "string" + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "subject_id": { + "type": "string" + }, + "claim_type": { + "enum": [ + "fact", + "identity_inference", + "motive_inference", + "prediction", + "norm", + "value_read", + "relationship_read" + ] + }, + "evidence_event_ids": { + "type": "array", + "items": { + "type": "string" + } + }, + "visibility": { + "enum": [ + "private", + "shared", + "public", + "rumor" + ] + }, + "emotional_charge": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + } + }, + "relationship": { + "type": "object", + "required": [ + "relationship_id", + "source_id", + "target_id", + "stance", + "summary" + ], + "additionalProperties": false, + "properties": { + "relationship_id": { + "type": "string" + }, + "source_id": { + "type": "string" + }, + "target_id": { + "type": "string" + }, + "stance": { + "$ref": "#/$defs/variable_map" + }, + "summary": { + "type": "string" + }, + "unresolved_incident_ids": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "event": { + "type": "object", + "required": [ + "event_id", + "kind", + "summary", + "participants", + "pressure_tags" + ], + "additionalProperties": false, + "properties": { + "event_id": { + "type": "string" + }, + "kind": { + "enum": [ + "dialogue", + "action", + "memory", + "relationship_shift", + "scene_outcome", + "author_note" + ] + }, + "summary": { + "type": "string" + }, + "participants": { + "type": "array", + "items": { + "type": "string" + } + }, + "pressure_tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "observed_exchange": { + "type": "array", + "items": { + "$ref": "#/$defs/event_exchange_turn" + } + }, + "private_interpretations": { + "type": "array", + "items": { + "$ref": "#/$defs/event_private_interpretation" + } + }, + "event_effects": { + "type": "array", + "items": { + "$ref": "#/$defs/event_effect" + } + } + } + }, + "scene": { + "type": "object", + "required": [ + "scene_id", + "location", + "participants", + "public_stakes", + "hidden_stakes", + "dialogue_context_packs" + ], + "additionalProperties": false, + "properties": { + "scene_id": { + "type": "string" + }, + "location": { + "type": "string" + }, + "participants": { + "type": "array", + "items": { + "type": "string" + } + }, + "public_stakes": { + "type": "array", + "items": { + "type": "string" + } + }, + "hidden_stakes": { + "type": "array", + "items": { + "type": "string" + } + }, + "dialogue_context_packs": { + "type": "array", + "items": { + "$ref": "#/$defs/dialogue_context_pack" + } + } + } + }, + "dialogue_context_pack": { + "type": "object", + "required": [ + "speaker_agent_id", + "listener_ids", + "speaker_local_truth", + "speaker_beliefs", + "active_memories", + "active_goals", + "presentation_constraints" + ], + "additionalProperties": false, + "properties": { + "speaker_agent_id": { + "type": "string" + }, + "listener_ids": { + "type": "array", + "items": { + "type": "string" + } + }, + "speaker_local_truth": { + "type": "array", + "items": { + "type": "string" + } + }, + "speaker_beliefs": { + "type": "array", + "items": { + "type": "string" + } + }, + "active_memories": { + "type": "array", + "items": { + "type": "string" + } + }, + "active_goals": { + "type": "array", + "items": { + "type": "string" + } + }, + "presentation_constraints": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "pressure": { + "type": "object", + "required": [ + "pressure_id", + "label", + "intensity" + ], + "additionalProperties": false, + "properties": { + "pressure_id": { + "type": "string" + }, + "label": { + "type": "string" + }, + "intensity": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + } + }, + "inferred_variable_map": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/inferred_state_variable" + } + }, + "inferred_state_variable": { + "type": "object", + "required": [ + "observed_activation", + "attributed_disposition", + "confidence" + ], + "additionalProperties": false, + "properties": { + "observed_activation": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "attributed_disposition": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "evidence": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "event_exchange_turn": { + "type": "object", + "required": [ + "speaker_id", + "utterance_summary", + "dialogue_function" + ], + "additionalProperties": false, + "properties": { + "speaker_id": { + "type": "string" + }, + "utterance_summary": { + "type": "string" + }, + "dialogue_function": { + "type": "string" + }, + "observable_cues": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "event_private_interpretation": { + "type": "object", + "required": [ + "agent_id", + "interpretation", + "confidence" + ], + "additionalProperties": false, + "properties": { + "agent_id": { + "type": "string" + }, + "interpretation": { + "type": "string" + }, + "attributed_motive": { + "type": "string" + }, + "appraisal_tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + } + }, + "event_effect": { + "type": "object", + "required": [ + "agent_id", + "summary" + ], + "additionalProperties": false, + "properties": { + "agent_id": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "state_deltas": { + "type": "array", + "items": { + "$ref": "#/$defs/state_delta" + } + }, + "new_belief_ids": { + "type": "array", + "items": { + "type": "string" + } + }, + "memory_update_ids": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "state_delta": { + "type": "object", + "required": [ + "path", + "delta" + ], + "additionalProperties": false, + "properties": { + "path": { + "type": "string" + }, + "delta": { + "type": "number", + "minimum": -1, + "maximum": 1 + } + } + } + } +} diff --git a/examples/cultnet_interop_peer.rs b/examples/cultnet_interop_peer.rs new file mode 100644 index 00000000..08a09909 --- /dev/null +++ b/examples/cultnet_interop_peer.rs @@ -0,0 +1,967 @@ +use anyhow::Context; +use anyhow::Result; +use anyhow::anyhow; +use cultcache_rs::CultCache; +use cultcache_rs::DatabaseEntry; +use cultcache_rs::SingleFileMessagePackBackingStore; +use cultnet_rs::CultNetDocumentBinding; +use cultnet_rs::CultNetDocumentMutationContract; +use cultnet_rs::CultNetDocumentOperation; +use cultnet_rs::CultNetDocumentPutOptions; +use cultnet_rs::CultNetDocumentRegistry; +use cultnet_rs::CultNetMessage; +use cultnet_rs::CultNetMutationAuthority; +use cultnet_rs::CultNetSchemaKind; +use cultnet_rs::CultNetSchemaRegistration; +use cultnet_rs::CultNetSchemaRegistry; +use cultnet_rs::CultNetWireContract; +use cultnet_rs::builtin_schema_registry; +use cultnet_rs::decode_cultnet_message_from_slice; +use cultnet_rs::encode_cultnet_message_to_vec; +use cultnet_rs::encode_frame; +use serde::Deserialize; +use serde::Serialize; +use socket2::Domain; +use socket2::Protocol; +use socket2::Socket; +use socket2::Type; +use std::collections::BTreeMap; +use std::fs; +use std::io::Read; +use std::io::Write; +use std::net::Ipv4Addr; +use std::net::SocketAddr; +use std::net::SocketAddrV4; +use std::net::TcpListener; +use std::net::TcpStream; +use std::net::UdpSocket; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread; +use std::time::Duration; + +const INTEROP_DOCUMENT_TYPE: &str = "cultnet.interop-note"; +const INTEROP_SCHEMA_VERSION: &str = "cultnet.interop_note.v0"; +const MUTATION_INTENT_TYPE: &str = "cultnet.interop-note-mutation-intent"; +const MUTATION_INTENT_SCHEMA_ID: &str = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-note-mutation-intent.schema.json"; +const MUTATION_INTENT_SCHEMA_VERSION: &str = "cultnet.interop_note_mutation_intent.v0"; +const MUTATION_RECEIPT_TYPE: &str = "cultnet.interop-note-mutation-receipt"; +const MUTATION_RECEIPT_SCHEMA_ID: &str = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-note-mutation-receipt.schema.json"; +const MUTATION_RECEIPT_SCHEMA_VERSION: &str = "cultnet.interop_note_mutation_receipt.v0"; +const FIRE_COMMAND_TYPE: &str = "cultnet.interop-fire-weapon-command"; +const FIRE_COMMAND_SCHEMA_ID: &str = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-fire-weapon-command.schema.json"; +const FIRE_COMMAND_SCHEMA_VERSION: &str = "cultnet.interop_fire_weapon_command.v0"; +const FIRE_RECEIPT_TYPE: &str = "cultnet.interop-fire-weapon-receipt"; +const FIRE_RECEIPT_SCHEMA_ID: &str = "https://github.com/GameCult/cultnet-ts/integration/contracts/cultnet.interop-fire-weapon-receipt.schema.json"; +const FIRE_RECEIPT_SCHEMA_VERSION: &str = "cultnet.interop_fire_weapon_receipt.v0"; +const DISCOVERY_ANNOUNCE_SCHEMA_VERSION: &str = "cultnet.discovery_announce.v0"; + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache(type = "cultnet.interop-note", schema = "CultNetInteropNote")] +struct CultNetInteropNote { + #[cultcache(key = 0)] + schema_version: String, + #[cultcache(key = 1)] + document_id: String, + #[cultcache(key = 2)] + author_runtime_id: String, + #[cultcache(key = 3)] + title: String, + #[cultcache(key = 4)] + body: String, + #[cultcache(key = 5)] + tags: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "cultnet.interop-note-mutation-intent", + schema = "CultNetInteropMutationIntent" +)] +struct CultNetInteropMutationIntent { + #[cultcache(key = 0)] + schema_version: String, + #[cultcache(key = 1)] + intent_id: String, + #[cultcache(key = 2)] + target_document_id: String, + #[cultcache(key = 3)] + append_body: String, + #[cultcache(key = 4)] + append_tag: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "cultnet.interop-note-mutation-receipt", + schema = "CultNetInteropMutationReceipt" +)] +struct CultNetInteropMutationReceipt { + #[cultcache(key = 0)] + schema_version: String, + #[cultcache(key = 1)] + intent_id: String, + #[cultcache(key = 2)] + accepted: bool, + #[cultcache(key = 3)] + document_id: String, + #[cultcache(key = 4)] + body: String, + #[cultcache(key = 5)] + tags: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "cultnet.interop-fire-weapon-command", + schema = "CultNetInteropFireCommand" +)] +struct CultNetInteropFireCommand { + #[cultcache(key = 0)] + schema_version: String, + #[cultcache(key = 1)] + command_id: String, + #[cultcache(key = 2)] + character_id: String, + #[cultcache(key = 3)] + weapon_id: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "cultnet.interop-fire-weapon-receipt", + schema = "CultNetInteropFireReceipt" +)] +struct CultNetInteropFireReceipt { + #[cultcache(key = 0)] + schema_version: String, + #[cultcache(key = 1)] + command_id: String, + #[cultcache(key = 2)] + accepted: bool, + #[cultcache(key = 3)] + character_id: String, + #[cultcache(key = 4)] + weapon_id: String, + #[cultcache(key = 5)] + shots_fired: u32, + #[cultcache(key = 6)] + ammo_remaining: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "schemaVersion", rename_all = "camelCase")] +enum DiscoveryMessage { + #[serde(rename = "cultnet.discovery_probe.v0", rename_all = "camelCase")] + Probe { + message_id: String, + requester_runtime_id: String, + }, + #[serde(rename = "cultnet.discovery_announce.v0", rename_all = "camelCase")] + Announce { + message_id: String, + runtime_id: String, + runtime_kind: String, + display_name: String, + agent_id: Option, + tcp_host: String, + tcp_port: u16, + wire_contract: String, + supported_document_types: Vec, + supports_schema_catalog: bool, + }, +} + +#[derive(Clone, Debug)] +struct PeerConfig { + runtime_id: String, + runtime_kind: String, + display_name: String, + agent_id: String, + bind_host: String, + advertise_host: String, + tcp_port: u16, + discovery_port: u16, + discovery_group: Ipv4Addr, + schema_path: String, +} + +#[derive(Clone, Debug)] +struct DialConfig { + runtime_id: String, + runtime_kind: String, + display_name: String, + agent_id: String, + target_host: String, + target_port: u16, + schema_path: String, +} + +fn main() -> Result<()> { + let mut args = std::env::args().skip(1); + let mode = args + .next() + .ok_or_else(|| anyhow!("expected mode: serve | probe | dial"))?; + let options = parse_args(args.collect()); + + match mode.as_str() { + "serve" => serve(parse_peer_config(&options)?)?, + "probe" => probe(&options)?, + "dial" => dial(parse_dial_config(&options)?)?, + _ => return Err(anyhow!("unknown mode {mode}")), + } + + Ok(()) +} + +fn serve(config: PeerConfig) -> Result<()> { + let schema_registration = load_schema_registration(&config.schema_path)?; + let mut schema_registry = builtin_schema_registry()?; + schema_registry.register(schema_registration.clone())?; + + let mut cache = CultCache::new(); + cache.register_entry_type::()?; + register_capability_entry_types(&mut cache)?; + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(runtime_store_path( + &config.runtime_id, + ))); + cache.pull_all_backing_stores()?; + let note = build_note(&config.runtime_id, &config.display_name); + cache.put(¬e.document_id, ¬e)?; + + let mut document_registry = CultNetDocumentRegistry::new(); + register_capability_bindings(&mut document_registry, &schema_registration.schema_id); + + let cache = Arc::new(Mutex::new(cache)); + let document_registry = Arc::new(document_registry); + let schema_registry = Arc::new(schema_registry); + let config = Arc::new(config); + + start_udp_discovery_server(config.clone())?; + start_tcp_server(config.clone(), cache, document_registry, schema_registry)?; + + print_json(&serde_json::json!({ + "status": "ready", + "mode": "serve", + "runtimeId": config.runtime_id, + "runtimeKind": config.runtime_kind, + "tcpPort": config.tcp_port, + "discoveryPort": config.discovery_port, + "discoveryGroup": config.discovery_group.to_string(), + }))?; + + loop { + thread::sleep(Duration::from_secs(3600)); + } +} + +fn probe(options: &BTreeMap) -> Result<()> { + let runtime_id = require_arg(options, "runtime-id")?.to_string(); + let discovery_port = parse_u16_arg(options, "discovery-port")?; + let discovery_group = parse_ipv4_arg(options, "discovery-group")?; + let timeout_ms = parse_u64_arg(options, "timeout-ms").unwrap_or(1_500); + let message_id = format!("{runtime_id}-{}", chrono::Utc::now().timestamp_millis()); + + let socket = create_discovery_socket(0, false)?; + socket.set_read_timeout(Some(Duration::from_millis(timeout_ms)))?; + + let probe_message = DiscoveryMessage::Probe { + message_id: message_id.clone(), + requester_runtime_id: runtime_id.clone(), + }; + let payload = rmp_serde::to_vec_named(&probe_message)?; + socket.send_to( + &payload, + SocketAddr::V4(SocketAddrV4::new(discovery_group, discovery_port)), + )?; + + let mut buffer = vec![0_u8; 4096]; + let mut found = BTreeMap::::new(); + loop { + match socket.recv_from(&mut buffer) { + Ok((len, _)) => { + if let Ok(DiscoveryMessage::Announce { + message_id: response_message_id, + runtime_id, + runtime_kind, + display_name, + agent_id, + tcp_host, + tcp_port, + wire_contract, + supported_document_types, + supports_schema_catalog, + }) = rmp_serde::from_slice::(&buffer[..len]) + { + if response_message_id == message_id { + found.insert( + runtime_id.clone(), + serde_json::json!({ + "schemaVersion": DISCOVERY_ANNOUNCE_SCHEMA_VERSION, + "messageId": response_message_id, + "runtimeId": runtime_id, + "runtimeKind": runtime_kind, + "displayName": display_name, + "agentId": agent_id, + "tcpHost": tcp_host, + "tcpPort": tcp_port, + "wireContract": wire_contract, + "supportedDocumentTypes": supported_document_types, + "supportsSchemaCatalog": supports_schema_catalog, + }), + ); + } + } + } + Err(error) + if error.kind() == std::io::ErrorKind::WouldBlock + || error.kind() == std::io::ErrorKind::TimedOut => + { + break; + } + Err(error) => return Err(error.into()), + } + } + + print_json(&serde_json::json!({ + "mode": "probe", + "runtimeId": runtime_id, + "peers": found.into_values().collect::>(), + }))?; + Ok(()) +} + +fn dial(config: DialConfig) -> Result<()> { + let schema_registration = load_schema_registration(&config.schema_path)?; + + let mut cache = CultCache::new(); + cache.register_entry_type::()?; + register_capability_entry_types(&mut cache)?; + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(runtime_store_path( + &format!("{}-dial", config.runtime_id), + ))); + cache.pull_all_backing_stores()?; + + let mut document_registry = CultNetDocumentRegistry::new(); + register_capability_bindings(&mut document_registry, &schema_registration.schema_id); + + let mut stream = TcpStream::connect((config.target_host.as_str(), config.target_port)) + .with_context(|| { + format!( + "failed to connect to {}:{}", + config.target_host, config.target_port + ) + })?; + + send_message( + &mut stream, + &CultNetMessage::Hello { + runtime_id: config.runtime_id.clone(), + runtime_kind: config.runtime_kind.clone(), + agent_id: Some(config.agent_id.clone()), + role: None, + display_name: Some(config.display_name.clone()), + supported_document_types: Some(vec![INTEROP_DOCUMENT_TYPE.to_string()]), + supported_mutation_contracts: Some(interaction_contracts()), + supported_message_versions: Some(vec![INTEROP_SCHEMA_VERSION.to_string()]), + supports_schema_catalog: Some(true), + }, + )?; + + let remote_hello = read_message(&mut stream)?; + let remote_runtime_id = match &remote_hello { + CultNetMessage::Hello { runtime_id, .. } => runtime_id.clone(), + other => return Err(anyhow!("expected hello response, got {other:?}")), + }; + + send_message( + &mut stream, + &CultNetMessage::SchemaCatalogRequest { + message_id: format!("{}-catalog", config.runtime_id), + include_schema_json: Some(true), + schema_ids: None, + kinds: None, + }, + )?; + let catalog_response = read_message(&mut stream)?; + let has_interop_schema = match &catalog_response { + CultNetMessage::SchemaCatalogResponse { schemas, .. } => schemas.iter().any(|schema| { + schema.schema_id == schema_registration.schema_id + && schema.document_type.as_deref() == Some(INTEROP_DOCUMENT_TYPE) + }), + other => return Err(anyhow!("expected catalog response, got {other:?}")), + }; + + send_message( + &mut stream, + &CultNetMessage::SnapshotRequest { + message_id: format!("{}-snapshot", config.runtime_id), + schema_ids: Some(vec![schema_registration.schema_id.clone()]), + record_keys: None, + }, + )?; + let snapshot_response = read_message(&mut stream)?; + let applied = document_registry + .apply_raw_snapshot_response::(&mut cache, &snapshot_response)?; + let note = applied + .into_iter() + .find(|candidate| candidate.author_runtime_id == remote_runtime_id) + .ok_or_else(|| anyhow!("did not receive an interop note from {remote_runtime_id}"))?; + + print_json(&serde_json::json!({ + "mode": "dial", + "runtimeId": config.runtime_id, + "targetHost": config.target_host, + "targetPort": config.target_port, + "remoteHello": { + "schemaVersion": "cultnet.hello.v0", + "runtimeId": remote_runtime_id, + }, + "hasInteropSchema": has_interop_schema, + "retrievedNote": { + "schemaVersion": note.schema_version, + "documentId": note.document_id, + "authorRuntimeId": note.author_runtime_id, + "title": note.title, + "body": note.body, + "tags": note.tags, + }, + "mutatedNote": mutate_remote_note(&mut stream, &mut cache, &document_registry, &schema_registration.schema_id, &config.runtime_id, ¬e)?, + "fireReceipt": fire_remote_weapon(&mut stream, &mut cache, &document_registry, &config.runtime_id, &remote_runtime_id)?, + }))?; + Ok(()) +} + +fn mutate_remote_note( + stream: &mut TcpStream, + cache: &mut CultCache, + document_registry: &CultNetDocumentRegistry, + note_schema_id: &str, + runtime_id: &str, + note: &CultNetInteropNote, +) -> Result { + let intent = CultNetInteropMutationIntent { + schema_version: MUTATION_INTENT_SCHEMA_VERSION.to_string(), + intent_id: format!("{runtime_id}-decorate"), + target_document_id: note.document_id.clone(), + append_body: format!(" Decorated by {runtime_id}."), + append_tag: format!("decorated:{runtime_id}"), + }; + let message = document_registry.create_raw_document_put_message( + format!("{runtime_id}-decorate-put"), + intent.intent_id.clone(), + &intent, + CultNetDocumentPutOptions::default(), + )?; + send_message(stream, &message)?; + + let receipt_message = read_message(stream)?; + let _receipt = document_registry + .apply_raw_document_put_message::(cache, &receipt_message)?; + let mutated_message = read_message(stream)?; + let mutated = document_registry + .apply_raw_document_put_message::(cache, &mutated_message)?; + if mutated_message_schema_id(&mutated_message) != Some(note_schema_id) { + return Err(anyhow!("mutation response used the wrong schema id")); + } + Ok(serde_json::json!({ + "schemaVersion": mutated.schema_version, + "documentId": mutated.document_id, + "authorRuntimeId": mutated.author_runtime_id, + "title": mutated.title, + "body": mutated.body, + "tags": mutated.tags, + })) +} + +fn fire_remote_weapon( + stream: &mut TcpStream, + cache: &mut CultCache, + document_registry: &CultNetDocumentRegistry, + runtime_id: &str, + remote_runtime_id: &str, +) -> Result { + let command = CultNetInteropFireCommand { + schema_version: FIRE_COMMAND_SCHEMA_VERSION.to_string(), + command_id: format!("{runtime_id}-fire"), + character_id: remote_runtime_id.to_string(), + weapon_id: "interop-rifle".to_string(), + }; + let message = document_registry.create_raw_document_put_message( + format!("{runtime_id}-fire-put"), + command.command_id.clone(), + &command, + CultNetDocumentPutOptions::default(), + )?; + send_message(stream, &message)?; + let receipt_message = read_message(stream)?; + let receipt = document_registry + .apply_raw_document_put_message::(cache, &receipt_message)?; + Ok(serde_json::json!({ + "schemaVersion": receipt.schema_version, + "commandId": receipt.command_id, + "accepted": receipt.accepted, + "characterId": receipt.character_id, + "weaponId": receipt.weapon_id, + "shotsFired": receipt.shots_fired, + "ammoRemaining": receipt.ammo_remaining, + })) +} + +fn start_udp_discovery_server(config: Arc) -> Result<()> { + let socket = create_discovery_socket(config.discovery_port, true)?; + socket.join_multicast_v4(&config.discovery_group, &Ipv4Addr::UNSPECIFIED)?; + socket.set_read_timeout(Some(Duration::from_millis(250)))?; + + thread::spawn(move || { + let mut buffer = vec![0_u8; 4096]; + loop { + match socket.recv_from(&mut buffer) { + Ok((len, remote)) => { + if let Ok(DiscoveryMessage::Probe { + message_id, + requester_runtime_id: _, + }) = rmp_serde::from_slice::(&buffer[..len]) + { + let announce = DiscoveryMessage::Announce { + message_id, + runtime_id: config.runtime_id.clone(), + runtime_kind: config.runtime_kind.clone(), + display_name: config.display_name.clone(), + agent_id: Some(config.agent_id.clone()), + tcp_host: config.advertise_host.clone(), + tcp_port: config.tcp_port, + wire_contract: "cultnet.schema.v0".to_string(), + supported_document_types: vec![INTEROP_DOCUMENT_TYPE.to_string()], + supports_schema_catalog: true, + }; + if let Ok(payload) = rmp_serde::to_vec_named(&announce) { + let _ = socket.send_to(&payload, remote); + } + } + } + Err(error) + if error.kind() == std::io::ErrorKind::WouldBlock + || error.kind() == std::io::ErrorKind::TimedOut => {} + Err(_) => break, + } + } + }); + + Ok(()) +} + +fn start_tcp_server( + config: Arc, + cache: Arc>, + document_registry: Arc, + schema_registry: Arc, +) -> Result<()> { + let listener = + TcpListener::bind((config.bind_host.as_str(), config.tcp_port)).with_context(|| { + format!( + "failed to bind TCP listener on {}:{}", + config.bind_host, config.tcp_port + ) + })?; + listener.set_nonblocking(false)?; + + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { + continue; + }; + let config = config.clone(); + let cache = cache.clone(); + let document_registry = document_registry.clone(); + let schema_registry = schema_registry.clone(); + thread::spawn(move || { + if let Err(error) = + handle_connection(stream, config, cache, document_registry, schema_registry) + { + eprintln!("{error:#}"); + } + }); + } + }); + + Ok(()) +} + +fn handle_connection( + mut stream: TcpStream, + config: Arc, + cache: Arc>, + document_registry: Arc, + schema_registry: Arc, +) -> Result<()> { + loop { + let message = match read_message(&mut stream) { + Ok(message) => message, + Err(error) if is_eof_like(&error) => break, + Err(error) => return Err(error), + }; + + match message { + CultNetMessage::Hello { .. } => { + send_message( + &mut stream, + &CultNetMessage::Hello { + runtime_id: config.runtime_id.clone(), + runtime_kind: config.runtime_kind.clone(), + agent_id: Some(config.agent_id.clone()), + role: None, + display_name: Some(config.display_name.clone()), + supported_document_types: Some(vec![INTEROP_DOCUMENT_TYPE.to_string()]), + supported_mutation_contracts: Some(interaction_contracts()), + supported_message_versions: Some(vec![INTEROP_SCHEMA_VERSION.to_string()]), + supports_schema_catalog: Some(true), + }, + )?; + } + request @ CultNetMessage::SchemaCatalogRequest { .. } => { + let response = schema_registry.create_catalog_response(&request)?; + send_message(&mut stream, &response)?; + } + CultNetMessage::SnapshotRequest { + message_id, + schema_ids, + record_keys, + } => { + let mut response = document_registry.create_raw_snapshot_response( + &cache.lock().expect("cache poisoned"), + message_id, + schema_ids.as_deref(), + record_keys.as_deref(), + )?; + if let CultNetMessage::SnapshotResponseRaw { documents, .. } = &mut response { + for document in documents.iter_mut() { + document.source_runtime_id = Some(config.runtime_id.clone()); + document.source_agent_id = Some(config.agent_id.clone()); + document.source_role = Some("peer".to_string()); + document.tags = + Some(vec!["interop".to_string(), config.runtime_id.clone()]); + } + } + send_message(&mut stream, &response)?; + } + message @ CultNetMessage::DocumentPutRaw { .. } => { + handle_raw_put(&mut stream, &config, &cache, &document_registry, &message)?; + } + _ => {} + } + } + + Ok(()) +} + +fn handle_raw_put( + stream: &mut TcpStream, + config: &PeerConfig, + cache: &Arc>, + document_registry: &CultNetDocumentRegistry, + message: &CultNetMessage, +) -> Result<()> { + let CultNetMessage::DocumentPutRaw { document, .. } = message else { + return Ok(()); + }; + if document.schema_id == MUTATION_INTENT_SCHEMA_ID { + let mut cache = cache.lock().expect("cache poisoned"); + let intent = document_registry + .apply_raw_document_put_message::(&mut cache, message)?; + let mut note = cache.get_required::(&intent.target_document_id)?; + note.body = format!("{}{}", note.body, intent.append_body); + note.tags.push(intent.append_tag); + cache.put(¬e.document_id, ¬e)?; + let receipt = CultNetInteropMutationReceipt { + schema_version: MUTATION_RECEIPT_SCHEMA_VERSION.to_string(), + intent_id: intent.intent_id.clone(), + accepted: true, + document_id: note.document_id.clone(), + body: note.body.clone(), + tags: note.tags.clone(), + }; + let options = response_options(config, "mutation"); + let receipt_message = document_registry.create_raw_document_put_message( + format!("{}-mutation-receipt", config.runtime_id), + receipt.intent_id.clone(), + &receipt, + options.clone(), + )?; + let note_message = document_registry.create_raw_document_put_message( + format!("{}-mutated-note", config.runtime_id), + note.document_id.clone(), + ¬e, + options, + )?; + send_message(stream, &receipt_message)?; + send_message(stream, ¬e_message)?; + } else if document.schema_id == FIRE_COMMAND_SCHEMA_ID { + let mut cache = cache.lock().expect("cache poisoned"); + let command = document_registry + .apply_raw_document_put_message::(&mut cache, message)?; + let receipt = CultNetInteropFireReceipt { + schema_version: FIRE_RECEIPT_SCHEMA_VERSION.to_string(), + command_id: command.command_id, + accepted: true, + character_id: command.character_id, + weapon_id: command.weapon_id, + shots_fired: 1, + ammo_remaining: 29, + }; + let receipt_message = document_registry.create_raw_document_put_message( + format!("{}-fire-receipt", config.runtime_id), + receipt.command_id.clone(), + &receipt, + response_options(config, "side-effect"), + )?; + send_message(stream, &receipt_message)?; + } + Ok(()) +} + +fn load_schema_registration(schema_path: &str) -> Result { + let schema_json = fs::read_to_string(schema_path) + .with_context(|| format!("failed to read schema {}", schema_path))?; + let parsed: serde_json::Value = serde_json::from_str(&schema_json) + .with_context(|| format!("failed to parse schema {}", schema_path))?; + let schema_id = parsed + .get("$id") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| anyhow!("schema {} is missing $id", schema_path))? + .to_string(); + let title = parsed + .get("title") + .and_then(serde_json::Value::as_str) + .map(ToString::to_string); + + Ok(CultNetSchemaRegistration { + schema_id, + kind: CultNetSchemaKind::DocumentPayload, + wire_contracts: vec![CultNetWireContract::CultNetSchemaV0], + schema_version: Some(INTEROP_SCHEMA_VERSION.to_string()), + document_type: Some(INTEROP_DOCUMENT_TYPE.to_string()), + title, + schema_json: Some(schema_json), + }) +} + +fn register_capability_entry_types(cache: &mut CultCache) -> Result<()> { + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + Ok(()) +} + +fn register_capability_bindings( + document_registry: &mut CultNetDocumentRegistry, + note_schema_id: &str, +) { + document_registry + .register(CultNetDocumentBinding::for_entry_with_schema_id::< + CultNetInteropNote, + >( + note_schema_id.to_string(), + INTEROP_SCHEMA_VERSION.to_string(), + )) + .register(CultNetDocumentBinding::for_entry_with_schema_id::< + CultNetInteropMutationIntent, + >( + MUTATION_INTENT_SCHEMA_ID.to_string(), + MUTATION_INTENT_SCHEMA_VERSION.to_string(), + )) + .register(CultNetDocumentBinding::for_entry_with_schema_id::< + CultNetInteropMutationReceipt, + >( + MUTATION_RECEIPT_SCHEMA_ID.to_string(), + MUTATION_RECEIPT_SCHEMA_VERSION.to_string(), + )) + .register(CultNetDocumentBinding::for_entry_with_schema_id::< + CultNetInteropFireCommand, + >( + FIRE_COMMAND_SCHEMA_ID.to_string(), + FIRE_COMMAND_SCHEMA_VERSION.to_string(), + )) + .register(CultNetDocumentBinding::for_entry_with_schema_id::< + CultNetInteropFireReceipt, + >( + FIRE_RECEIPT_SCHEMA_ID.to_string(), + FIRE_RECEIPT_SCHEMA_VERSION.to_string(), + )); +} + +fn interaction_contracts() -> Vec { + vec![CultNetDocumentMutationContract { + document_type: INTEROP_DOCUMENT_TYPE.to_string(), + payload_schema_version: Some(INTEROP_SCHEMA_VERSION.to_string()), + operations: vec![ + CultNetDocumentOperation::Snapshot, + CultNetDocumentOperation::DocumentPut, + CultNetDocumentOperation::IntentSubmit, + CultNetDocumentOperation::ReceiptWatch, + ], + authority: CultNetMutationAuthority::Runtime, + intent_document_types: Some(vec![ + MUTATION_INTENT_TYPE.to_string(), + FIRE_COMMAND_TYPE.to_string(), + ]), + receipt_document_types: Some(vec![ + MUTATION_RECEIPT_TYPE.to_string(), + FIRE_RECEIPT_TYPE.to_string(), + ]), + notes: None, + }] +} + +fn response_options(config: &PeerConfig, tag: &str) -> CultNetDocumentPutOptions { + CultNetDocumentPutOptions { + source_runtime_id: Some(config.runtime_id.clone()), + source_agent_id: Some(config.agent_id.clone()), + source_role: Some("peer".to_string()), + tags: Some(vec![tag.to_string(), config.runtime_id.clone()]), + ..CultNetDocumentPutOptions::default() + } +} + +fn mutated_message_schema_id(message: &CultNetMessage) -> Option<&str> { + match message { + CultNetMessage::DocumentPutRaw { document, .. } => Some(document.schema_id.as_str()), + _ => None, + } +} + +fn build_note(runtime_id: &str, display_name: &str) -> CultNetInteropNote { + CultNetInteropNote { + schema_version: INTEROP_SCHEMA_VERSION.to_string(), + document_id: format!("note:{runtime_id}"), + author_runtime_id: runtime_id.to_string(), + title: format!("{display_name} keeps a little note"), + body: format!( + "{runtime_id} can move CultNet state without begging the gods for translation." + ), + tags: vec![ + runtime_id.to_string(), + "interop".to_string(), + "cultnet".to_string(), + ], + } +} + +fn send_message(stream: &mut TcpStream, message: &CultNetMessage) -> Result<()> { + let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?; + let frame = encode_frame(&payload)?; + stream.write_all(&frame)?; + stream.flush()?; + Ok(()) +} + +fn read_message(stream: &mut TcpStream) -> Result { + let mut header = [0_u8; 4]; + stream.read_exact(&mut header)?; + let payload_len = u32::from_be_bytes(header) as usize; + let mut payload = vec![0_u8; payload_len]; + stream.read_exact(&mut payload)?; + decode_cultnet_message_from_slice(&payload, CultNetWireContract::CultNetSchemaV0) +} + +fn is_eof_like(error: &anyhow::Error) -> bool { + error + .downcast_ref::() + .is_some_and(|io| io.kind() == std::io::ErrorKind::UnexpectedEof) +} + +fn create_discovery_socket(port: u16, _join_group: bool) -> Result { + let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?; + socket.set_reuse_address(true)?; + socket.bind(&SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, port).into())?; + let socket = UdpSocket::from(socket); + socket.set_multicast_loop_v4(true)?; + socket.set_multicast_ttl_v4(1)?; + socket.set_nonblocking(false)?; + Ok(socket) +} + +fn parse_peer_config(options: &BTreeMap) -> Result { + Ok(PeerConfig { + runtime_id: require_arg(options, "runtime-id")?.to_string(), + runtime_kind: require_arg(options, "runtime-kind")?.to_string(), + display_name: require_arg(options, "display-name")?.to_string(), + agent_id: require_arg(options, "agent-id")?.to_string(), + bind_host: options + .get("bind-host") + .cloned() + .unwrap_or_else(|| "127.0.0.1".to_string()), + advertise_host: require_arg(options, "advertise-host")?.to_string(), + tcp_port: parse_u16_arg(options, "tcp-port")?, + discovery_port: parse_u16_arg(options, "discovery-port")?, + discovery_group: parse_ipv4_arg(options, "discovery-group")?, + schema_path: require_arg(options, "schema-path")?.to_string(), + }) +} + +fn parse_dial_config(options: &BTreeMap) -> Result { + Ok(DialConfig { + runtime_id: require_arg(options, "runtime-id")?.to_string(), + runtime_kind: require_arg(options, "runtime-kind")?.to_string(), + display_name: require_arg(options, "display-name")?.to_string(), + agent_id: require_arg(options, "agent-id")?.to_string(), + target_host: require_arg(options, "target-host")?.to_string(), + target_port: parse_u16_arg(options, "target-port")?, + schema_path: require_arg(options, "schema-path")?.to_string(), + }) +} + +fn parse_args(args: Vec) -> BTreeMap { + 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, name: &str) -> Result<&'a str> { + options + .get(name) + .map(String::as_str) + .ok_or_else(|| anyhow!("missing required argument --{name}")) +} + +fn parse_u16_arg(options: &BTreeMap, name: &str) -> Result { + require_arg(options, name)? + .parse::() + .with_context(|| format!("argument --{name} must be a u16")) +} + +fn parse_u64_arg(options: &BTreeMap, name: &str) -> Option { + options + .get(name) + .map(|value| value.parse::().expect("u64 arg")) +} + +fn parse_ipv4_arg(options: &BTreeMap, name: &str) -> Result { + require_arg(options, name)? + .parse::() + .with_context(|| format!("argument --{name} must be an IPv4 address")) +} + +fn runtime_store_path(runtime_id: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!("cultnet-rs-interop-{runtime_id}.msgpack")) +} + +fn print_json(value: &serde_json::Value) -> Result<()> { + println!("{}", serde_json::to_string(value)?); + Ok(()) +} diff --git a/src/contracts.rs b/src/contracts.rs new file mode 100644 index 00000000..24be7b48 --- /dev/null +++ b/src/contracts.rs @@ -0,0 +1,1155 @@ +use anyhow::Result; +use anyhow::anyhow; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde::Deserialize; +use serde::Serialize; +use serde_json::Value; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum CultNetWireContract { + #[serde(rename = "cultnet.schema.v0")] + CultNetSchemaV0, + #[serde(rename = "gamecult.networking.v0")] + GameCultNetworkingV0, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CultNetSchemaKind { + WireMessage, + DocumentPayload, + SharedContract, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CultNetRawPayloadEncoding { + Messagepack, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultNetDocumentRecord { + pub schema_id: String, + pub record_key: String, + pub stored_at: String, + pub payload: TPayload, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_runtime_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_agent_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_role: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tags: Option>, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CultNetDocumentOperation { + Snapshot, + DocumentPut, + DocumentDelete, + IntentSubmit, + ReceiptWatch, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CultNetMutationAuthority { + ReadOnly, + LocalUser, + Coordinator, + Runtime, + Denied, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultNetDocumentMutationContract { + pub document_type: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub payload_schema_version: Option, + pub operations: Vec, + pub authority: CultNetMutationAuthority, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub intent_document_types: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub receipt_document_types: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub notes: Option>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultNetRawDocumentRecord { + pub schema_id: String, + pub record_key: String, + pub stored_at: String, + pub payload_encoding: CultNetRawPayloadEncoding, + #[serde(with = "serde_bytes")] + pub payload: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_runtime_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_agent_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_role: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tags: Option>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultNetSchemaDescriptor { + pub schema_id: String, + pub kind: CultNetSchemaKind, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub schema_version: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub document_type: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + pub wire_contracts: Vec, + pub content_hash: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub schema_json: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "schemaVersion")] +pub enum CultNetMessage { + #[serde(rename = "cultnet.hello.v0", rename_all = "camelCase")] + Hello { + runtime_id: String, + runtime_kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + agent_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + role: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + display_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + supported_document_types: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + supported_mutation_contracts: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + supported_message_versions: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + supports_schema_catalog: Option, + }, + #[serde(rename = "cultnet.login.v0", rename_all = "camelCase")] + Login { + nonce: String, + auth: String, + password: String, + }, + #[serde(rename = "cultnet.register.v0", rename_all = "camelCase")] + Register { + nonce: String, + email: String, + password: String, + name: String, + }, + #[serde(rename = "cultnet.verify.v0", rename_all = "camelCase")] + Verify { nonce: String, session: String }, + #[serde(rename = "cultnet.login_success.v0", rename_all = "camelCase")] + LoginSuccess { nonce: String, session: String }, + #[serde(rename = "cultnet.error.v0", rename_all = "camelCase")] + Error { error: String }, + #[serde(rename = "cultnet.sample.change_name.v0", rename_all = "camelCase")] + SampleChangeName { name: String }, + #[serde(rename = "cultnet.sample.chat.v0", rename_all = "camelCase")] + SampleChat { text: String }, + #[serde(rename = "cultnet.document_put.v0", rename_all = "camelCase")] + DocumentPut { + message_id: String, + document: CultNetDocumentRecord, + }, + #[serde(rename = "cultnet.document_delete.v0", rename_all = "camelCase")] + DocumentDelete { + message_id: String, + schema_id: String, + record_key: String, + }, + #[serde(rename = "cultnet.document_put_raw.v0", rename_all = "camelCase")] + DocumentPutRaw { + message_id: String, + document: CultNetRawDocumentRecord, + }, + #[serde(rename = "cultnet.snapshot_request.v0", rename_all = "camelCase")] + SnapshotRequest { + message_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + schema_ids: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + record_keys: Option>, + }, + #[serde(rename = "cultnet.snapshot_response.v0", rename_all = "camelCase")] + SnapshotResponse { + message_id: String, + documents: Vec>, + }, + #[serde(rename = "cultnet.snapshot_response_raw.v0", rename_all = "camelCase")] + SnapshotResponseRaw { + message_id: String, + documents: Vec, + }, + #[serde(rename = "cultnet.schema_catalog_request.v0", rename_all = "camelCase")] + SchemaCatalogRequest { + message_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + include_schema_json: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + schema_ids: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + kinds: Option>, + }, + #[serde( + rename = "cultnet.schema_catalog_response.v0", + rename_all = "camelCase" + )] + SchemaCatalogResponse { + message_id: String, + schemas: Vec, + }, +} + +pub fn parse_cultnet_message( + wire_value: &rmpv::Value, + contract: CultNetWireContract, +) -> Result { + match contract { + CultNetWireContract::CultNetSchemaV0 => { + let message = match schema_version_from_wire_value(wire_value)? { + Some("cultnet.document_put_raw.v0" | "cultnet.snapshot_response_raw.v0") => { + parse_raw_cultnet_schema_message(wire_value)? + } + _ => { + let json_value: Value = rmp_serde::from_slice(&rmp_serde::to_vec(wire_value)?)?; + serde_json::from_value(json_value)? + } + }; + validate_message(&message)?; + Ok(message) + } + CultNetWireContract::GameCultNetworkingV0 => parse_gamecult_networking_message(wire_value), + } +} + +pub fn encode_cultnet_message_for_wire( + message: &CultNetMessage, + contract: CultNetWireContract, +) -> Result { + validate_message(message)?; + match contract { + CultNetWireContract::CultNetSchemaV0 => match message { + CultNetMessage::DocumentPutRaw { .. } | CultNetMessage::SnapshotResponseRaw { .. } => { + encode_raw_cultnet_schema_message(message) + } + _ => Ok(rmp_serde::from_slice(&rmp_serde::to_vec( + &serde_json::to_value(message)?, + )?)?), + }, + CultNetWireContract::GameCultNetworkingV0 => encode_gamecult_networking_message(message), + } +} + +pub fn encode_cultnet_message_to_vec( + message: &CultNetMessage, + contract: CultNetWireContract, +) -> Result> { + let wire_value = encode_cultnet_message_for_wire(message, contract)?; + Ok(rmp_serde::to_vec(&wire_value)?) +} + +pub fn decode_cultnet_message_from_slice( + bytes: &[u8], + contract: CultNetWireContract, +) -> Result { + if contract == CultNetWireContract::CultNetSchemaV0 { + let wire_value: rmpv::Value = rmp_serde::from_slice(bytes)?; + return parse_cultnet_message(&wire_value, contract); + } + let wire_value: rmpv::Value = rmp_serde::from_slice(bytes)?; + parse_cultnet_message(&wire_value, contract) +} + +fn validate_message(message: &CultNetMessage) -> Result<()> { + match message { + CultNetMessage::Hello { + runtime_id, + runtime_kind, + agent_id, + role, + display_name, + supported_document_types, + supported_mutation_contracts, + supported_message_versions, + supports_schema_catalog: _, + } => { + require_non_empty(runtime_id, "runtimeId")?; + require_non_empty(runtime_kind, "runtimeKind")?; + require_optional_non_empty(agent_id.as_deref(), "agentId")?; + require_optional_non_empty(role.as_deref(), "role")?; + require_optional_non_empty(display_name.as_deref(), "displayName")?; + require_optional_string_vec( + supported_document_types.as_deref(), + "supportedDocumentTypes", + )?; + if let Some(contracts) = supported_mutation_contracts { + for contract in contracts { + validate_mutation_contract(contract)?; + } + } + require_optional_string_vec( + supported_message_versions.as_deref(), + "supportedMessageVersions", + )?; + } + CultNetMessage::Login { + nonce, + auth, + password, + } => { + require_non_empty(nonce, "nonce")?; + require_non_empty(auth, "auth")?; + require_non_empty(password, "password")?; + } + CultNetMessage::Register { + nonce, + email, + password, + name, + } => { + require_non_empty(nonce, "nonce")?; + require_non_empty(email, "email")?; + require_non_empty(password, "password")?; + require_non_empty(name, "name")?; + } + CultNetMessage::Verify { nonce, session } + | CultNetMessage::LoginSuccess { nonce, session } => { + require_non_empty(nonce, "nonce")?; + require_non_empty(session, "session")?; + } + CultNetMessage::Error { error } => require_non_empty(error, "error")?, + CultNetMessage::SampleChangeName { name } => require_non_empty(name, "name")?, + CultNetMessage::SampleChat { text } => require_non_empty(text, "text")?, + CultNetMessage::DocumentPut { + message_id, + document, + } => { + require_non_empty(message_id, "messageId")?; + validate_document_record(document)?; + } + CultNetMessage::DocumentDelete { + message_id, + schema_id, + record_key, + } => { + require_non_empty(message_id, "messageId")?; + require_non_empty(schema_id, "schemaId")?; + require_non_empty(record_key, "recordKey")?; + } + CultNetMessage::DocumentPutRaw { + message_id, + document, + } => { + require_non_empty(message_id, "messageId")?; + validate_raw_document_record(document)?; + } + CultNetMessage::SnapshotRequest { + message_id, + schema_ids, + record_keys, + } => { + require_non_empty(message_id, "messageId")?; + require_optional_string_vec(schema_ids.as_deref(), "schemaIds")?; + require_optional_string_vec(record_keys.as_deref(), "recordKeys")?; + } + CultNetMessage::SnapshotResponse { + message_id, + documents, + } => { + require_non_empty(message_id, "messageId")?; + for document in documents { + validate_document_record(document)?; + } + } + CultNetMessage::SnapshotResponseRaw { + message_id, + documents, + } => { + require_non_empty(message_id, "messageId")?; + for document in documents { + validate_raw_document_record(document)?; + } + } + CultNetMessage::SchemaCatalogRequest { + message_id, + include_schema_json: _, + schema_ids, + kinds: _, + } => { + require_non_empty(message_id, "messageId")?; + require_optional_string_vec(schema_ids.as_deref(), "schemaIds")?; + } + CultNetMessage::SchemaCatalogResponse { + message_id, + schemas, + } => { + require_non_empty(message_id, "messageId")?; + for schema in schemas { + validate_schema_descriptor(schema)?; + } + } + } + Ok(()) +} + +fn validate_mutation_contract(contract: &CultNetDocumentMutationContract) -> Result<()> { + require_non_empty(&contract.document_type, "documentType")?; + require_optional_non_empty( + contract.payload_schema_version.as_deref(), + "payloadSchemaVersion", + )?; + if contract.operations.is_empty() { + return Err(anyhow!( + "CultNet mutation contract for {:?} must advertise at least one operation", + contract.document_type + )); + } + require_optional_string_vec( + contract.intent_document_types.as_deref(), + "intentDocumentTypes", + )?; + require_optional_string_vec( + contract.receipt_document_types.as_deref(), + "receiptDocumentTypes", + )?; + require_optional_string_vec(contract.notes.as_deref(), "notes")?; + Ok(()) +} + +fn validate_document_record(document: &CultNetDocumentRecord) -> Result<()> { + require_non_empty(&document.schema_id, "schemaId")?; + require_non_empty(&document.record_key, "recordKey")?; + require_non_empty(&document.stored_at, "storedAt")?; + require_optional_non_empty(document.source_runtime_id.as_deref(), "sourceRuntimeId")?; + require_optional_non_empty(document.source_agent_id.as_deref(), "sourceAgentId")?; + require_optional_non_empty(document.source_role.as_deref(), "sourceRole")?; + require_optional_string_vec(document.tags.as_deref(), "tags")?; + Ok(()) +} + +fn validate_raw_document_record(document: &CultNetRawDocumentRecord) -> Result<()> { + require_non_empty(&document.schema_id, "schemaId")?; + require_non_empty(&document.record_key, "recordKey")?; + require_non_empty(&document.stored_at, "storedAt")?; + if document.payload.is_empty() { + return Err(anyhow!( + "CultNet field payload must contain non-empty MessagePack bytes" + )); + } + require_optional_non_empty(document.source_runtime_id.as_deref(), "sourceRuntimeId")?; + require_optional_non_empty(document.source_agent_id.as_deref(), "sourceAgentId")?; + require_optional_non_empty(document.source_role.as_deref(), "sourceRole")?; + require_optional_string_vec(document.tags.as_deref(), "tags")?; + Ok(()) +} + +fn validate_schema_descriptor(schema: &CultNetSchemaDescriptor) -> Result<()> { + require_non_empty(&schema.schema_id, "schemaId")?; + require_optional_non_empty(schema.schema_version.as_deref(), "schemaVersion")?; + require_optional_non_empty(schema.document_type.as_deref(), "documentType")?; + require_optional_non_empty(schema.title.as_deref(), "title")?; + require_non_empty(&schema.content_hash, "contentHash")?; + require_optional_non_empty(schema.schema_json.as_deref(), "schemaJson")?; + + if schema.wire_contracts.is_empty() { + return Err(anyhow!( + "CultNet field wireContracts must contain at least one supported contract" + )); + } + + Ok(()) +} + +fn require_non_empty(value: &str, field: &str) -> Result<()> { + if value.trim().is_empty() { + return Err(anyhow!("CultNet field {field} must be non-empty")); + } + Ok(()) +} + +fn require_optional_non_empty(value: Option<&str>, field: &str) -> Result<()> { + if let Some(value) = value { + require_non_empty(value, field)?; + } + Ok(()) +} + +fn require_optional_string_vec(value: Option<&[String]>, field: &str) -> Result<()> { + if let Some(values) = value { + for item in values { + require_non_empty(item, field)?; + } + } + Ok(()) +} + +fn schema_version_from_wire_value(input: &rmpv::Value) -> Result> { + let Some(object) = input.as_map() else { + return Ok(None); + }; + + Ok(object.iter().find_map(|(key, value)| { + key.as_str() + .filter(|candidate| *candidate == "schemaVersion") + .and_then(|_| value.as_str()) + })) +} + +fn parse_raw_cultnet_schema_message(input: &rmpv::Value) -> Result { + let object = input + .as_map() + .ok_or_else(|| anyhow!("cultnet.schema.v0 raw messages must be objects"))?; + + let get = |name: &str| -> Option<&rmpv::Value> { + object.iter().find_map(|(key, value)| { + key.as_str() + .filter(|candidate| *candidate == name) + .map(|_| value) + }) + }; + + let schema_version = require_legacy_string(get("schemaVersion"), "schemaVersion")?; + match schema_version.as_str() { + "cultnet.document_put_raw.v0" => Ok(CultNetMessage::DocumentPutRaw { + message_id: require_legacy_string(get("messageId"), "messageId")?, + document: require_raw_document_record(get("document"), "document")?, + }), + "cultnet.snapshot_response_raw.v0" => { + let documents = get("documents") + .and_then(rmpv::Value::as_array) + .ok_or_else(|| anyhow!("documents must be an array"))? + .iter() + .enumerate() + .map(|(index, value)| { + require_raw_document_record(value.into(), &format!("documents[{index}]")) + }) + .collect::>>()?; + + Ok(CultNetMessage::SnapshotResponseRaw { + message_id: require_legacy_string(get("messageId"), "messageId")?, + documents, + }) + } + _ => Err(anyhow!( + "Unsupported raw cultnet.schema.v0 schemaVersion {schema_version}" + )), + } +} + +fn encode_raw_cultnet_schema_message(message: &CultNetMessage) -> Result { + Ok(rmpv::Value::Map(match message { + CultNetMessage::DocumentPutRaw { + message_id, + document, + } => vec![ + ( + rmpv::Value::from("schemaVersion"), + rmpv::Value::from("cultnet.document_put_raw.v0"), + ), + ( + rmpv::Value::from("messageId"), + rmpv::Value::from(message_id.as_str()), + ), + ( + rmpv::Value::from("document"), + encode_raw_document_record(document), + ), + ], + CultNetMessage::SnapshotResponseRaw { + message_id, + documents, + } => vec![ + ( + rmpv::Value::from("schemaVersion"), + rmpv::Value::from("cultnet.snapshot_response_raw.v0"), + ), + ( + rmpv::Value::from("messageId"), + rmpv::Value::from(message_id.as_str()), + ), + ( + rmpv::Value::from("documents"), + rmpv::Value::Array(documents.iter().map(encode_raw_document_record).collect()), + ), + ], + _ => { + return Err(anyhow!( + "Message is not a raw cultnet.schema.v0 binary replication message" + )); + } + })) +} + +fn require_raw_document_record( + value: Option<&rmpv::Value>, + field_name: &str, +) -> Result { + let object = value + .and_then(rmpv::Value::as_map) + .ok_or_else(|| anyhow!("{field_name} must be an object"))?; + + let get = |name: &str| -> Option<&rmpv::Value> { + object.iter().find_map(|(key, value)| { + key.as_str() + .filter(|candidate| *candidate == name) + .map(|_| value) + }) + }; + + let payload_encoding = require_legacy_string( + get("payloadEncoding"), + &format!("{field_name}.payloadEncoding"), + )?; + + Ok(CultNetRawDocumentRecord { + schema_id: require_legacy_string(get("schemaId"), &format!("{field_name}.schemaId"))?, + record_key: require_legacy_string(get("recordKey"), &format!("{field_name}.recordKey"))?, + stored_at: require_legacy_string(get("storedAt"), &format!("{field_name}.storedAt"))?, + payload_encoding: match payload_encoding.as_str() { + "messagepack" => CultNetRawPayloadEncoding::Messagepack, + _ => { + return Err(anyhow!( + "{field_name}.payloadEncoding has unsupported value {payload_encoding}" + )); + } + }, + payload: get("payload") + .and_then(rmpv::Value::as_slice) + .map(|bytes| bytes.to_vec()) + .ok_or_else(|| anyhow!("{field_name}.payload must be binary MessagePack bytes"))?, + source_runtime_id: require_legacy_optional_string( + get("sourceRuntimeId"), + &format!("{field_name}.sourceRuntimeId"), + )?, + source_agent_id: require_legacy_optional_string( + get("sourceAgentId"), + &format!("{field_name}.sourceAgentId"), + )?, + source_role: require_legacy_optional_string( + get("sourceRole"), + &format!("{field_name}.sourceRole"), + )?, + tags: require_legacy_optional_string_array(get("tags"), &format!("{field_name}.tags"))?, + }) +} + +fn encode_raw_document_record(document: &CultNetRawDocumentRecord) -> rmpv::Value { + rmpv::Value::Map(vec![ + ( + rmpv::Value::from("schemaId"), + rmpv::Value::from(document.schema_id.as_str()), + ), + ( + rmpv::Value::from("recordKey"), + rmpv::Value::from(document.record_key.as_str()), + ), + ( + rmpv::Value::from("storedAt"), + rmpv::Value::from(document.stored_at.as_str()), + ), + ( + rmpv::Value::from("payloadEncoding"), + rmpv::Value::from(match document.payload_encoding { + CultNetRawPayloadEncoding::Messagepack => "messagepack", + }), + ), + ( + rmpv::Value::from("payload"), + rmpv::Value::Binary(document.payload.clone()), + ), + ( + rmpv::Value::from("sourceRuntimeId"), + document + .source_runtime_id + .as_deref() + .map(rmpv::Value::from) + .unwrap_or(rmpv::Value::Nil), + ), + ( + rmpv::Value::from("sourceAgentId"), + document + .source_agent_id + .as_deref() + .map(rmpv::Value::from) + .unwrap_or(rmpv::Value::Nil), + ), + ( + rmpv::Value::from("sourceRole"), + document + .source_role + .as_deref() + .map(rmpv::Value::from) + .unwrap_or(rmpv::Value::Nil), + ), + ( + rmpv::Value::from("tags"), + legacy_optional_string_array(document.tags.as_deref()), + ), + ]) +} + +fn parse_gamecult_networking_message(input: &rmpv::Value) -> Result { + let items = input.as_array().ok_or_else(|| { + anyhow!("gamecult.networking.v0 messages must be a 2-element union array") + })?; + if items.len() != 2 { + return Err(anyhow!( + "gamecult.networking.v0 messages must be a 2-element union array" + )); + } + let tag = items[0] + .as_i64() + .ok_or_else(|| anyhow!("gamecult.networking.v0 message tag must be an integer"))?; + let payload = items[1] + .as_array() + .ok_or_else(|| anyhow!("gamecult.networking.v0 message payload must be an array"))?; + match tag { + 0 => Ok(CultNetMessage::Login { + nonce: require_legacy_bytes(payload.first(), "LoginMessage.Nonce")?, + auth: require_legacy_bytes(payload.get(1), "LoginMessage.Auth")?, + password: require_legacy_bytes(payload.get(2), "LoginMessage.Password")?, + }), + 1 => Ok(CultNetMessage::Register { + nonce: require_legacy_bytes(payload.first(), "RegisterMessage.Nonce")?, + email: require_legacy_bytes(payload.get(1), "RegisterMessage.Email")?, + password: require_legacy_bytes(payload.get(2), "RegisterMessage.Password")?, + name: require_legacy_bytes(payload.get(3), "RegisterMessage.Name")?, + }), + 2 => Ok(CultNetMessage::Verify { + nonce: require_legacy_bytes(payload.first(), "VerifyMessage.Nonce")?, + session: require_legacy_bytes(payload.get(1), "VerifyMessage.Session")?, + }), + 3 => Ok(CultNetMessage::LoginSuccess { + nonce: require_legacy_bytes(payload.first(), "LoginSuccessMessage.Nonce")?, + session: require_legacy_bytes(payload.get(1), "LoginSuccessMessage.Session")?, + }), + 4 => Ok(CultNetMessage::Error { + error: require_legacy_string(payload.first(), "ErrorMessage.Error")?, + }), + 5 => Ok(CultNetMessage::SampleChangeName { + name: require_legacy_string(payload.first(), "ChangeNameMessage.Name")?, + }), + 6 => Ok(CultNetMessage::SampleChat { + text: require_legacy_string(payload.first(), "ChatMessage.Text")?, + }), + 7 => Ok(CultNetMessage::SchemaCatalogRequest { + message_id: require_legacy_string( + payload.first(), + "SchemaCatalogRequestMessage.MessageId", + )?, + include_schema_json: Some(require_legacy_bool( + payload.get(1), + "SchemaCatalogRequestMessage.IncludeSchemaJson", + )?), + schema_ids: require_legacy_optional_string_array( + payload.get(2), + "SchemaCatalogRequestMessage.SchemaIds", + )?, + kinds: require_legacy_optional_schema_kind_array( + payload.get(3), + "SchemaCatalogRequestMessage.Kinds", + )?, + }), + 8 => Ok(CultNetMessage::SchemaCatalogResponse { + message_id: require_legacy_string( + payload.first(), + "SchemaCatalogResponseMessage.MessageId", + )?, + schemas: require_legacy_schema_descriptor_array( + payload.get(1), + "SchemaCatalogResponseMessage.Schemas", + )?, + }), + _ => Err(anyhow!( + "Unsupported gamecult.networking.v0 union tag {tag}" + )), + } +} + +fn encode_gamecult_networking_message(message: &CultNetMessage) -> Result { + let pair = match message { + CultNetMessage::Login { + nonce, + auth, + password, + } => vec![ + rmpv::Value::from(0), + rmpv::Value::Array(vec![ + legacy_bytes(nonce, "LoginMessage.Nonce")?, + legacy_bytes(auth, "LoginMessage.Auth")?, + legacy_bytes(password, "LoginMessage.Password")?, + ]), + ], + CultNetMessage::Register { + nonce, + email, + password, + name, + } => vec![ + rmpv::Value::from(1), + rmpv::Value::Array(vec![ + legacy_bytes(nonce, "RegisterMessage.Nonce")?, + legacy_bytes(email, "RegisterMessage.Email")?, + legacy_bytes(password, "RegisterMessage.Password")?, + legacy_bytes(name, "RegisterMessage.Name")?, + ]), + ], + CultNetMessage::Verify { nonce, session } => vec![ + rmpv::Value::from(2), + rmpv::Value::Array(vec![ + legacy_bytes(nonce, "VerifyMessage.Nonce")?, + legacy_bytes(session, "VerifyMessage.Session")?, + ]), + ], + CultNetMessage::LoginSuccess { nonce, session } => vec![ + rmpv::Value::from(3), + rmpv::Value::Array(vec![ + legacy_bytes(nonce, "LoginSuccessMessage.Nonce")?, + legacy_bytes(session, "LoginSuccessMessage.Session")?, + ]), + ], + CultNetMessage::Error { error } => { + vec![ + rmpv::Value::from(4), + rmpv::Value::Array(vec![error.as_str().into()]), + ] + } + CultNetMessage::SampleChangeName { name } => { + vec![ + rmpv::Value::from(5), + rmpv::Value::Array(vec![name.as_str().into()]), + ] + } + CultNetMessage::SampleChat { text } => { + vec![ + rmpv::Value::from(6), + rmpv::Value::Array(vec![text.as_str().into()]), + ] + } + CultNetMessage::SchemaCatalogRequest { + message_id, + include_schema_json, + schema_ids, + kinds, + } => vec![ + rmpv::Value::from(7), + rmpv::Value::Array(vec![ + message_id.as_str().into(), + rmpv::Value::from(include_schema_json.unwrap_or(false)), + legacy_optional_string_array(schema_ids.as_deref()), + legacy_optional_schema_kind_array(kinds.as_deref()), + ]), + ], + CultNetMessage::SchemaCatalogResponse { + message_id, + schemas, + } => vec![ + rmpv::Value::from(8), + rmpv::Value::Array(vec![ + message_id.as_str().into(), + rmpv::Value::Array( + schemas + .iter() + .map(legacy_schema_descriptor) + .collect::>>()?, + ), + ]), + ], + _ => { + return Err(anyhow!( + "Message is not defined in the gamecult.networking.v0 contract" + )); + } + }; + Ok(rmpv::Value::Array(pair)) +} + +fn require_legacy_bytes(value: Option<&rmpv::Value>, field_name: &str) -> Result { + let bytes = value + .and_then(rmpv::Value::as_slice) + .ok_or_else(|| anyhow!("{field_name} must be binary data in gamecult.networking.v0"))?; + Ok(URL_SAFE_NO_PAD.encode(bytes)) +} + +fn require_legacy_string(value: Option<&rmpv::Value>, field_name: &str) -> Result { + let value = value + .and_then(rmpv::Value::as_str) + .ok_or_else(|| anyhow!("{field_name} must be a string in gamecult.networking.v0"))?; + Ok(value.to_string()) +} + +fn require_legacy_bool(value: Option<&rmpv::Value>, field_name: &str) -> Result { + value + .and_then(rmpv::Value::as_bool) + .ok_or_else(|| anyhow!("{field_name} must be a boolean in gamecult.networking.v0")) +} + +fn require_legacy_optional_string_array( + value: Option<&rmpv::Value>, + field_name: &str, +) -> Result>> { + let Some(value) = value else { + return Ok(None); + }; + if value.is_nil() { + return Ok(None); + } + let items = value + .as_array() + .ok_or_else(|| anyhow!("{field_name} must be an array in gamecult.networking.v0"))?; + let values = items + .iter() + .map(|item| { + item.as_str() + .map(ToString::to_string) + .ok_or_else(|| anyhow!("{field_name} must contain only strings")) + }) + .collect::>>()?; + Ok(Some(values)) +} + +fn require_legacy_optional_schema_kind_array( + value: Option<&rmpv::Value>, + field_name: &str, +) -> Result>> { + let Some(values) = require_legacy_optional_string_array(value, field_name)? else { + return Ok(None); + }; + values + .into_iter() + .map(|value| match value.as_str() { + "wire_message" => Ok(CultNetSchemaKind::WireMessage), + "document_payload" => Ok(CultNetSchemaKind::DocumentPayload), + "shared_contract" => Ok(CultNetSchemaKind::SharedContract), + _ => Err(anyhow!("{field_name} has unsupported schema kind {value}")), + }) + .collect::>>() + .map(Some) +} + +fn require_legacy_schema_descriptor_array( + value: Option<&rmpv::Value>, + field_name: &str, +) -> Result> { + let items = value + .and_then(rmpv::Value::as_array) + .ok_or_else(|| anyhow!("{field_name} must be an array in gamecult.networking.v0"))?; + items + .iter() + .enumerate() + .map(|(index, item)| { + require_legacy_schema_descriptor(item, &format!("{field_name}[{index}]")) + }) + .collect() +} + +fn require_legacy_schema_descriptor( + value: &rmpv::Value, + field_name: &str, +) -> Result { + let object = value + .as_map() + .ok_or_else(|| anyhow!("{field_name} must be an object in gamecult.networking.v0"))?; + + let get = |name: &str| -> Option<&rmpv::Value> { + object.iter().find_map(|(key, value)| { + key.as_str() + .filter(|candidate| *candidate == name) + .map(|_| value) + }) + }; + + let schema_id = require_legacy_string(get("schemaId"), &format!("{field_name}.SchemaId"))?; + let kind = require_legacy_string(get("kind"), &format!("{field_name}.Kind"))?; + let schema_version = require_legacy_optional_string( + get("schemaVersion"), + &format!("{field_name}.SchemaVersion"), + )?; + let document_type = + require_legacy_optional_string(get("documentType"), &format!("{field_name}.DocumentType"))?; + let title = require_legacy_optional_string(get("title"), &format!("{field_name}.Title"))?; + let wire_contracts = require_legacy_optional_wire_contracts( + get("wireContracts"), + &format!("{field_name}.WireContracts"), + )?; + let content_hash = + require_legacy_string(get("contentHash"), &format!("{field_name}.ContentHash"))?; + let schema_json = + require_legacy_optional_string(get("schemaJson"), &format!("{field_name}.SchemaJson"))?; + + let kind = match kind.as_str() { + "wire_message" => CultNetSchemaKind::WireMessage, + "document_payload" => CultNetSchemaKind::DocumentPayload, + "shared_contract" => CultNetSchemaKind::SharedContract, + _ => { + return Err(anyhow!( + "{field_name}.Kind has unsupported schema kind {kind}" + )); + } + }; + + Ok(CultNetSchemaDescriptor { + schema_id, + kind, + schema_version, + document_type, + title, + wire_contracts, + content_hash, + schema_json, + }) +} + +fn require_legacy_optional_string( + value: Option<&rmpv::Value>, + field_name: &str, +) -> Result> { + let Some(value) = value else { + return Ok(None); + }; + if value.is_nil() { + return Ok(None); + } + Ok(Some(require_legacy_string(Some(value), field_name)?)) +} + +fn require_legacy_optional_wire_contracts( + value: Option<&rmpv::Value>, + field_name: &str, +) -> Result> { + let Some(values) = require_legacy_optional_string_array(value, field_name)? else { + return Ok(Vec::new()); + }; + + values + .into_iter() + .map(|value| match value.as_str() { + "cultnet.schema.v0" => Ok(CultNetWireContract::CultNetSchemaV0), + "gamecult.networking.v0" => Ok(CultNetWireContract::GameCultNetworkingV0), + _ => Err(anyhow!( + "{field_name} contains unsupported wire contract {value}" + )), + }) + .collect() +} + +fn legacy_bytes(input: &str, field_name: &str) -> Result { + if input.trim().is_empty() { + return Err(anyhow!("{field_name} must be a non-empty base64url string")); + } + Ok(rmpv::Value::Binary(URL_SAFE_NO_PAD.decode(input)?)) +} + +fn legacy_optional_string_array(input: Option<&[String]>) -> rmpv::Value { + match input { + Some(values) => rmpv::Value::Array( + values + .iter() + .map(|value| rmpv::Value::from(value.as_str())) + .collect(), + ), + None => rmpv::Value::Nil, + } +} + +fn legacy_optional_schema_kind_array(input: Option<&[CultNetSchemaKind]>) -> rmpv::Value { + match input { + Some(values) => rmpv::Value::Array( + values + .iter() + .map(|value| { + rmpv::Value::from(match value { + CultNetSchemaKind::WireMessage => "wire_message", + CultNetSchemaKind::DocumentPayload => "document_payload", + CultNetSchemaKind::SharedContract => "shared_contract", + }) + }) + .collect(), + ), + None => rmpv::Value::Nil, + } +} + +fn legacy_schema_descriptor(schema: &CultNetSchemaDescriptor) -> Result { + Ok(rmpv::Value::Map(vec![ + ( + rmpv::Value::from("schemaId"), + rmpv::Value::from(schema.schema_id.as_str()), + ), + ( + rmpv::Value::from("kind"), + rmpv::Value::from(match schema.kind { + CultNetSchemaKind::WireMessage => "wire_message", + CultNetSchemaKind::DocumentPayload => "document_payload", + CultNetSchemaKind::SharedContract => "shared_contract", + }), + ), + ( + rmpv::Value::from("schemaVersion"), + schema + .schema_version + .as_deref() + .map(rmpv::Value::from) + .unwrap_or(rmpv::Value::Nil), + ), + ( + rmpv::Value::from("documentType"), + schema + .document_type + .as_deref() + .map(rmpv::Value::from) + .unwrap_or(rmpv::Value::Nil), + ), + ( + rmpv::Value::from("title"), + schema + .title + .as_deref() + .map(rmpv::Value::from) + .unwrap_or(rmpv::Value::Nil), + ), + ( + rmpv::Value::from("wireContracts"), + rmpv::Value::Array( + schema + .wire_contracts + .iter() + .map(|value| { + rmpv::Value::from(match value { + CultNetWireContract::CultNetSchemaV0 => "cultnet.schema.v0", + CultNetWireContract::GameCultNetworkingV0 => "gamecult.networking.v0", + }) + }) + .collect(), + ), + ), + ( + rmpv::Value::from("contentHash"), + rmpv::Value::from(schema.content_hash.as_str()), + ), + ( + rmpv::Value::from("schemaJson"), + schema + .schema_json + .as_deref() + .map(rmpv::Value::from) + .unwrap_or(rmpv::Value::Nil), + ), + ])) +} diff --git a/src/framing.rs b/src/framing.rs new file mode 100644 index 00000000..01578818 --- /dev/null +++ b/src/framing.rs @@ -0,0 +1,49 @@ +use anyhow::Result; +use anyhow::anyhow; + +pub const FRAME_HEADER_BYTES: usize = 4; + +pub fn encode_frame(payload: &[u8]) -> Result> { + let len: u32 = payload + .len() + .try_into() + .map_err(|_| anyhow!("CultNet frame payload is too large"))?; + let mut frame = Vec::with_capacity(FRAME_HEADER_BYTES + payload.len()); + frame.extend_from_slice(&len.to_be_bytes()); + frame.extend_from_slice(payload); + Ok(frame) +} + +#[derive(Clone, Debug, Default)] +pub struct LengthPrefixedMessageFramer { + buffer: Vec, +} + +impl LengthPrefixedMessageFramer { + pub fn new() -> Self { + Self::default() + } + + pub fn push(&mut self, chunk: impl AsRef<[u8]>) -> Vec> { + self.buffer.extend_from_slice(chunk.as_ref()); + let mut frames = Vec::new(); + loop { + if self.buffer.len() < FRAME_HEADER_BYTES { + break; + } + let payload_len = u32::from_be_bytes([ + self.buffer[0], + self.buffer[1], + self.buffer[2], + self.buffer[3], + ]) as usize; + let total_len = FRAME_HEADER_BYTES + payload_len; + if self.buffer.len() < total_len { + break; + } + frames.push(self.buffer[FRAME_HEADER_BYTES..total_len].to_vec()); + self.buffer.drain(0..total_len); + } + frames + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 00000000..7ac7bf92 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,11 @@ +mod contracts; +mod framing; +mod replication; +mod schema_discovery; +mod security; + +pub use contracts::*; +pub use framing::*; +pub use replication::*; +pub use schema_discovery::*; +pub use security::*; diff --git a/src/replication.rs b/src/replication.rs new file mode 100644 index 00000000..492cf317 --- /dev/null +++ b/src/replication.rs @@ -0,0 +1,440 @@ +use anyhow::Context; +use anyhow::Result; +use anyhow::anyhow; +use cultcache_rs::CultCache; +use cultcache_rs::CultCacheEnvelope; +use cultcache_rs::DatabaseEntry; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::Value; +use std::collections::BTreeMap; +use std::collections::BTreeSet; + +use crate::CultNetDocumentMutationContract; +use crate::CultNetDocumentRecord; +use crate::CultNetMessage; +use crate::CultNetRawDocumentRecord; +use crate::CultNetRawPayloadEncoding; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CultNetDocumentPutOptions { + pub stored_at: Option, + pub source_runtime_id: Option, + pub source_agent_id: Option, + pub source_role: Option, + pub tags: Option>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultNetDocumentBinding { + pub schema_id: String, + pub document_type: String, + pub mutation_contract: Option, + pub payload_schema_version: Option, +} + +impl CultNetDocumentBinding { + pub fn for_entry(payload_schema_version: impl Into>) -> Self { + Self { + document_type: T::TYPE.to_string(), + schema_id: T::TYPE.to_string(), + mutation_contract: None, + payload_schema_version: payload_schema_version.into(), + } + } + + pub fn for_entry_with_schema_id( + schema_id: impl Into, + payload_schema_version: impl Into>, + ) -> Self { + Self { + document_type: T::TYPE.to_string(), + schema_id: schema_id.into(), + mutation_contract: None, + payload_schema_version: payload_schema_version.into(), + } + } + + pub fn with_mutation_contract(mut self, contract: CultNetDocumentMutationContract) -> Self { + self.mutation_contract = Some(contract); + self + } +} + +#[derive(Clone, Debug, Default)] +pub struct CultNetDocumentRegistry { + bindings_by_type: BTreeMap, + bindings_by_schema_id: BTreeMap, +} + +impl CultNetDocumentRegistry { + pub fn new() -> Self { + Self::default() + } + + pub fn register(&mut self, binding: CultNetDocumentBinding) -> &mut Self { + self.bindings_by_schema_id + .insert(binding.schema_id.clone(), binding.clone()); + self.bindings_by_type + .insert(binding.document_type.clone(), binding); + self + } + + pub fn binding(&self, document_type: &str) -> Option<&CultNetDocumentBinding> { + self.bindings_by_type.get(document_type) + } + + pub fn binding_by_schema_id(&self, schema_id: &str) -> Option<&CultNetDocumentBinding> { + self.bindings_by_schema_id.get(schema_id) + } + + pub fn mutation_contracts(&self) -> Vec { + self.bindings_by_type + .values() + .filter_map(|binding| binding.mutation_contract.clone()) + .collect() + } + + pub fn create_document_put_message( + &self, + message_id: impl Into, + record_key: impl Into, + value: &T, + options: CultNetDocumentPutOptions, + ) -> Result + where + T: DatabaseEntry + Serialize + DeserializeOwned, + { + let binding = self.require_binding(T::TYPE)?; + let payload = serde_json::to_value(round_trip_typed(value)?)?; + Ok(CultNetMessage::DocumentPut { + message_id: message_id.into(), + document: CultNetDocumentRecord { + schema_id: binding.schema_id.clone(), + record_key: record_key.into(), + stored_at: options.stored_at.unwrap_or_else(now_utc_second), + payload, + source_runtime_id: options.source_runtime_id, + source_agent_id: options.source_agent_id, + source_role: options.source_role, + tags: options.tags, + }, + }) + } + + pub fn create_document_delete_message( + &self, + message_id: impl Into, + schema_id: impl Into, + record_key: impl Into, + ) -> CultNetMessage { + CultNetMessage::DocumentDelete { + message_id: message_id.into(), + schema_id: schema_id.into(), + record_key: record_key.into(), + } + } + + pub fn create_raw_document_put_message_from_envelope( + &self, + message_id: impl Into, + envelope: &CultCacheEnvelope, + ) -> Result { + Ok(CultNetMessage::DocumentPutRaw { + message_id: message_id.into(), + document: self.raw_document_record_from_envelope(envelope)?, + }) + } + + pub fn create_raw_document_put_message( + &self, + message_id: impl Into, + record_key: impl Into, + value: &T, + options: CultNetDocumentPutOptions, + ) -> Result + where + T: DatabaseEntry + Serialize, + { + let binding = self.require_binding(T::TYPE)?; + Ok(CultNetMessage::DocumentPutRaw { + message_id: message_id.into(), + document: CultNetRawDocumentRecord { + schema_id: binding.schema_id.clone(), + record_key: record_key.into(), + stored_at: options.stored_at.unwrap_or_else(now_utc_second), + payload_encoding: CultNetRawPayloadEncoding::Messagepack, + payload: rmp_serde::to_vec(value)?, + source_runtime_id: options.source_runtime_id, + source_agent_id: options.source_agent_id, + source_role: options.source_role, + tags: options.tags, + }, + }) + } + + pub fn create_snapshot_response( + &self, + cache: &CultCache, + message_id: impl Into, + schema_ids: Option<&[String]>, + record_keys: Option<&[String]>, + ) -> Result { + let requested_schema_ids = schema_ids.map(|items| items.iter().collect::>()); + let requested_record_keys = record_keys.map(|items| items.iter().collect::>()); + let mut documents = Vec::new(); + for envelope in cache.snapshot() { + let binding = self.require_binding(&envelope.r#type)?; + if requested_schema_ids + .as_ref() + .is_some_and(|ids| !ids.contains(&binding.schema_id)) + { + continue; + } + if requested_record_keys + .as_ref() + .is_some_and(|keys| !keys.contains(&envelope.key)) + { + continue; + } + documents.push(self.document_record_from_envelope(&envelope)?); + } + Ok(CultNetMessage::SnapshotResponse { + message_id: message_id.into(), + documents, + }) + } + + pub fn create_raw_snapshot_response( + &self, + cache: &CultCache, + message_id: impl Into, + schema_ids: Option<&[String]>, + record_keys: Option<&[String]>, + ) -> Result { + let requested_schema_ids = schema_ids.map(|items| items.iter().collect::>()); + let requested_record_keys = record_keys.map(|items| items.iter().collect::>()); + let mut documents = Vec::new(); + for envelope in cache.snapshot() { + let binding = self.require_binding(&envelope.r#type)?; + if requested_schema_ids + .as_ref() + .is_some_and(|ids| !ids.contains(&binding.schema_id)) + { + continue; + } + if requested_record_keys + .as_ref() + .is_some_and(|keys| !keys.contains(&envelope.key)) + { + continue; + } + documents.push(self.raw_document_record_from_envelope(&envelope)?); + } + Ok(CultNetMessage::SnapshotResponseRaw { + message_id: message_id.into(), + documents, + }) + } + + pub fn apply_document_put_message( + &self, + cache: &mut CultCache, + message: &CultNetMessage, + ) -> Result + where + T: DatabaseEntry + Serialize + DeserializeOwned, + { + let CultNetMessage::DocumentPut { document, .. } = message else { + return Err(anyhow!("expected cultnet.document_put.v0")); + }; + let binding = self.require_binding(T::TYPE)?; + if document.schema_id != binding.schema_id { + return Err(anyhow!( + "schema id {:?} does not match registered Rust type {:?} schema {:?}", + document.schema_id, + T::TYPE, + binding.schema_id + )); + } + let value: T = serde_json::from_value(document.payload.clone()).with_context(|| { + format!( + "failed to decode CultNet payload schema {:?} as {}", + binding.schema_id, + T::SCHEMA_NAME + ) + })?; + cache.put(&document.record_key, &value) + } + + pub fn apply_document_delete_message( + &self, + cache: &mut CultCache, + message: &CultNetMessage, + ) -> Result + where + T: DatabaseEntry, + { + let CultNetMessage::DocumentDelete { + schema_id, + record_key, + .. + } = message + else { + return Err(anyhow!("expected cultnet.document_delete.v0")); + }; + let binding = self.require_binding(T::TYPE)?; + if schema_id != &binding.schema_id { + return Err(anyhow!( + "schema id {:?} does not match registered Rust type {:?} schema {:?}", + schema_id, + T::TYPE, + binding.schema_id + )); + } + cache.delete::(record_key) + } + + pub fn apply_raw_document_put_message( + &self, + cache: &mut CultCache, + message: &CultNetMessage, + ) -> Result + where + T: DatabaseEntry + Serialize + DeserializeOwned, + { + let CultNetMessage::DocumentPutRaw { document, .. } = message else { + return Err(anyhow!("expected cultnet.document_put_raw.v0")); + }; + let binding = self.require_binding(T::TYPE)?; + if document.schema_id != binding.schema_id { + return Err(anyhow!( + "schema id {:?} does not match registered Rust type {:?} schema {:?}", + document.schema_id, + T::TYPE, + binding.schema_id + )); + } + cache.put_envelope::(CultCacheEnvelope { + key: document.record_key.clone(), + r#type: binding.document_type.clone(), + payload: document.payload.clone(), + stored_at: document.stored_at.clone(), + schema_id: Some(binding.schema_id.clone()), + }) + } + + pub fn apply_snapshot_response( + &self, + cache: &mut CultCache, + response: &CultNetMessage, + ) -> Result> + where + T: DatabaseEntry + Serialize + DeserializeOwned, + { + let CultNetMessage::SnapshotResponse { documents, .. } = response else { + return Err(anyhow!("expected cultnet.snapshot_response.v0")); + }; + let mut applied = Vec::new(); + let binding = self.require_binding(T::TYPE)?; + for document in documents { + if document.schema_id != binding.schema_id { + continue; + } + applied.push(self.apply_document_put_message::( + cache, + &CultNetMessage::DocumentPut { + message_id: "snapshot-apply".to_string(), + document: document.clone(), + }, + )?); + } + Ok(applied) + } + + pub fn apply_raw_snapshot_response( + &self, + cache: &mut CultCache, + response: &CultNetMessage, + ) -> Result> + where + T: DatabaseEntry + Serialize + DeserializeOwned, + { + let CultNetMessage::SnapshotResponseRaw { documents, .. } = response else { + return Err(anyhow!("expected cultnet.snapshot_response_raw.v0")); + }; + let mut applied = Vec::new(); + let binding = self.require_binding(T::TYPE)?; + for document in documents { + if document.schema_id != binding.schema_id { + continue; + } + applied.push(self.apply_raw_document_put_message::( + cache, + &CultNetMessage::DocumentPutRaw { + message_id: "snapshot-apply-raw".to_string(), + document: document.clone(), + }, + )?); + } + Ok(applied) + } + + fn document_record_from_envelope( + &self, + envelope: &CultCacheEnvelope, + ) -> Result> { + let binding = self.require_binding(&envelope.r#type)?; + let payload: Value = rmp_serde::from_slice(&envelope.payload).with_context(|| { + format!( + "failed to decode CultCache envelope {:?} at {:?} as generic CultNet payload", + envelope.r#type, envelope.key + ) + })?; + Ok(CultNetDocumentRecord { + schema_id: binding.schema_id.clone(), + record_key: envelope.key.clone(), + stored_at: envelope.stored_at.clone(), + payload, + source_runtime_id: None, + source_agent_id: None, + source_role: None, + tags: None, + }) + } + + fn raw_document_record_from_envelope( + &self, + envelope: &CultCacheEnvelope, + ) -> Result { + let binding = self.require_binding(&envelope.r#type)?; + Ok(CultNetRawDocumentRecord { + schema_id: binding.schema_id.clone(), + record_key: envelope.key.clone(), + stored_at: envelope.stored_at.clone(), + payload_encoding: CultNetRawPayloadEncoding::Messagepack, + payload: envelope.payload.clone(), + source_runtime_id: None, + source_agent_id: None, + source_role: None, + tags: None, + }) + } + + fn require_binding(&self, document_type: &str) -> Result<&CultNetDocumentBinding> { + self.binding(document_type).ok_or_else(|| { + anyhow!("No CultNet document binding is registered for {document_type:?}") + }) + } +} + +fn round_trip_typed(value: &T) -> Result +where + T: Serialize + DeserializeOwned, +{ + Ok(rmp_serde::from_slice(&rmp_serde::to_vec(value)?)?) +} + +fn now_utc_second() -> String { + chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) +} diff --git a/src/schema_discovery.rs b/src/schema_discovery.rs new file mode 100644 index 00000000..15ea9fb9 --- /dev/null +++ b/src/schema_discovery.rs @@ -0,0 +1,389 @@ +use anyhow::Result; +use anyhow::anyhow; +use serde_json::Value; +use sha2::Digest; +use sha2::Sha256; +use std::collections::BTreeMap; +use std::collections::BTreeSet; + +use crate::CultNetMessage; +use crate::CultNetSchemaDescriptor; +use crate::CultNetSchemaKind; +use crate::CultNetWireContract; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultNetSchemaRegistration { + pub schema_id: String, + pub kind: CultNetSchemaKind, + pub wire_contracts: Vec, + pub schema_version: Option, + pub document_type: Option, + pub title: Option, + pub schema_json: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CultNetSchemaCatalogOptions { + pub include_schema_json: bool, + pub schema_ids: Option>, + pub kinds: Option>, +} + +#[derive(Clone, Debug, Default)] +pub struct CultNetSchemaRegistry { + entries: BTreeMap, +} + +impl CultNetSchemaRegistry { + pub fn new() -> Self { + Self::default() + } + + pub fn register(&mut self, registration: CultNetSchemaRegistration) -> Result<()> { + if registration.schema_id.trim().is_empty() { + return Err(anyhow!("schema_id must be non-empty")); + } + if registration.wire_contracts.is_empty() { + return Err(anyhow!("wire_contracts must contain at least one entry")); + } + + let content_hash = if let Some(schema_json) = registration.schema_json.as_deref() { + canonical_schema_hash(schema_json)? + } else { + return Err(anyhow!( + "schema_json is required so discovery can advertise canonical hashes" + )); + }; + + self.entries.insert( + registration.schema_id.clone(), + CultNetSchemaDescriptor { + schema_id: registration.schema_id, + kind: registration.kind, + schema_version: registration.schema_version, + document_type: registration.document_type, + title: registration.title, + wire_contracts: registration.wire_contracts, + content_hash, + schema_json: registration.schema_json, + }, + ); + + Ok(()) + } + + pub fn get( + &self, + schema_id: &str, + include_schema_json: bool, + ) -> Option { + self.entries + .get(schema_id) + .map(|entry| sanitize_descriptor(entry, include_schema_json)) + } + + pub fn list(&self, options: &CultNetSchemaCatalogOptions) -> Vec { + let requested_ids = options + .schema_ids + .as_ref() + .map(|values| values.iter().cloned().collect::>()); + let requested_kinds = options + .kinds + .as_ref() + .map(|values| values.iter().copied().collect::>()); + + self.entries + .values() + .filter(|entry| { + if let Some(requested_ids) = &requested_ids + && !requested_ids.contains(&entry.schema_id) + { + return false; + } + + if let Some(requested_kinds) = &requested_kinds + && !requested_kinds.contains(&entry.kind) + { + return false; + } + + true + }) + .map(|entry| sanitize_descriptor(entry, options.include_schema_json)) + .collect() + } + + pub fn create_catalog_response(&self, request: &CultNetMessage) -> Result { + let CultNetMessage::SchemaCatalogRequest { + message_id, + include_schema_json, + schema_ids, + kinds, + } = request + else { + return Err(anyhow!( + "expected cultnet.schema_catalog_request.v0 for schema discovery" + )); + }; + + Ok(CultNetMessage::SchemaCatalogResponse { + message_id: message_id.clone(), + schemas: self.list(&CultNetSchemaCatalogOptions { + include_schema_json: include_schema_json.unwrap_or(false), + schema_ids: schema_ids.clone(), + kinds: kinds.clone(), + }), + }) + } +} + +fn sanitize_descriptor( + descriptor: &CultNetSchemaDescriptor, + include_schema_json: bool, +) -> CultNetSchemaDescriptor { + let mut clone = descriptor.clone(); + if !include_schema_json { + clone.schema_json = None; + } + clone +} + +fn canonical_schema_hash(schema_json: &str) -> Result { + let value: Value = serde_json::from_str(schema_json)?; + let canonical = stable_stringify(&value); + Ok(format!("{:x}", Sha256::digest(canonical.as_bytes()))) +} + +fn stable_stringify(value: &Value) -> String { + match value { + Value::Null => "null".to_string(), + Value::Bool(value) => value.to_string(), + Value::Number(value) => value.to_string(), + Value::String(value) => serde_json::to_string(value).expect("string serialization"), + Value::Array(values) => format!( + "[{}]", + values + .iter() + .map(stable_stringify) + .collect::>() + .join(",") + ), + Value::Object(values) => { + let mut entries = values.iter().collect::>(); + entries.sort_by(|(left, _), (right, _)| left.cmp(right)); + format!( + "{{{}}}", + entries + .into_iter() + .map(|(key, value)| { + format!( + "{}:{}", + serde_json::to_string(key).expect("key serialization"), + stable_stringify(value) + ) + }) + .collect::>() + .join(",") + ) + } + } +} + +pub fn builtin_schema_registry() -> Result { + let mut registry = CultNetSchemaRegistry::new(); + + for registration in [ + schema_registration( + include_str!("../contracts/cultnet.hello.schema.json"), + CultNetSchemaKind::WireMessage, + vec![CultNetWireContract::CultNetSchemaV0], + Some("cultnet.hello.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.document-mutation-contract.schema.json"), + CultNetSchemaKind::SharedContract, + vec![CultNetWireContract::CultNetSchemaV0], + None, + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.login.schema.json"), + CultNetSchemaKind::WireMessage, + vec![ + CultNetWireContract::CultNetSchemaV0, + CultNetWireContract::GameCultNetworkingV0, + ], + Some("cultnet.login.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.register.schema.json"), + CultNetSchemaKind::WireMessage, + vec![ + CultNetWireContract::CultNetSchemaV0, + CultNetWireContract::GameCultNetworkingV0, + ], + Some("cultnet.register.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.verify.schema.json"), + CultNetSchemaKind::WireMessage, + vec![ + CultNetWireContract::CultNetSchemaV0, + CultNetWireContract::GameCultNetworkingV0, + ], + Some("cultnet.verify.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.login-success.schema.json"), + CultNetSchemaKind::WireMessage, + vec![ + CultNetWireContract::CultNetSchemaV0, + CultNetWireContract::GameCultNetworkingV0, + ], + Some("cultnet.login_success.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.error.schema.json"), + CultNetSchemaKind::WireMessage, + vec![ + CultNetWireContract::CultNetSchemaV0, + CultNetWireContract::GameCultNetworkingV0, + ], + Some("cultnet.error.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.sample-change-name.schema.json"), + CultNetSchemaKind::WireMessage, + vec![ + CultNetWireContract::CultNetSchemaV0, + CultNetWireContract::GameCultNetworkingV0, + ], + Some("cultnet.sample.change_name.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.sample-chat.schema.json"), + CultNetSchemaKind::WireMessage, + vec![ + CultNetWireContract::CultNetSchemaV0, + CultNetWireContract::GameCultNetworkingV0, + ], + Some("cultnet.sample.chat.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.document-put.schema.json"), + CultNetSchemaKind::WireMessage, + vec![CultNetWireContract::CultNetSchemaV0], + Some("cultnet.document_put.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.document-delete.schema.json"), + CultNetSchemaKind::WireMessage, + vec![CultNetWireContract::CultNetSchemaV0], + Some("cultnet.document_delete.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.raw-document-record.schema.json"), + CultNetSchemaKind::SharedContract, + vec![CultNetWireContract::CultNetSchemaV0], + None, + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.document-put-raw.schema.json"), + CultNetSchemaKind::WireMessage, + vec![CultNetWireContract::CultNetSchemaV0], + Some("cultnet.document_put_raw.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.snapshot-request.schema.json"), + CultNetSchemaKind::WireMessage, + vec![CultNetWireContract::CultNetSchemaV0], + Some("cultnet.snapshot_request.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.snapshot-response.schema.json"), + CultNetSchemaKind::WireMessage, + vec![CultNetWireContract::CultNetSchemaV0], + Some("cultnet.snapshot_response.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.snapshot-response-raw.schema.json"), + CultNetSchemaKind::WireMessage, + vec![CultNetWireContract::CultNetSchemaV0], + Some("cultnet.snapshot_response_raw.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.schema-catalog-request.schema.json"), + CultNetSchemaKind::WireMessage, + vec![ + CultNetWireContract::CultNetSchemaV0, + CultNetWireContract::GameCultNetworkingV0, + ], + Some("cultnet.schema_catalog_request.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/cultnet.schema-catalog-response.schema.json"), + CultNetSchemaKind::WireMessage, + vec![ + CultNetWireContract::CultNetSchemaV0, + CultNetWireContract::GameCultNetworkingV0, + ], + Some("cultnet.schema_catalog_response.v0"), + None, + )?, + schema_registration( + include_str!("../contracts/ghostlight.agent-state.schema.json"), + CultNetSchemaKind::DocumentPayload, + vec![CultNetWireContract::CultNetSchemaV0], + Some("ghostlight.agent_state.v0"), + Some("ghostlight.agent-state"), + )?, + ] { + registry.register(registration)?; + } + + Ok(registry) +} + +fn schema_registration( + schema_json: &str, + kind: CultNetSchemaKind, + wire_contracts: Vec, + schema_version: Option<&str>, + document_type: Option<&str>, +) -> Result { + let value: Value = serde_json::from_str(schema_json)?; + let schema_id = value + .get("$id") + .and_then(Value::as_str) + .ok_or_else(|| anyhow!("schema is missing $id"))?; + let title = value + .get("title") + .and_then(Value::as_str) + .map(str::to_string); + + Ok(CultNetSchemaRegistration { + schema_id: schema_id.to_string(), + kind, + wire_contracts, + schema_version: schema_version.map(str::to_string), + document_type: document_type.map(str::to_string), + title, + schema_json: Some(schema_json.to_string()), + }) +} diff --git a/src/security.rs b/src/security.rs new file mode 100644 index 00000000..30aa841b --- /dev/null +++ b/src/security.rs @@ -0,0 +1,270 @@ +use aes_gcm::Aes256Gcm; +use aes_gcm::KeyInit; +use aes_gcm::Nonce; +use aes_gcm::aead::Aead; +use aes_gcm::aead::Payload; +use anyhow::Result; +use anyhow::anyhow; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use chrono::DateTime; +use chrono::TimeZone; +use chrono::Utc; +use hmac::Hmac; +use hmac::Mac; +use rand::RngCore; +use sha2::Digest; +use sha2::Sha256; + +const NONCE_LENGTH: usize = 12; +type HmacSha256 = Hmac; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultNetClientSecurityOptions { + pub connection_key: String, + encryption_key: [u8; 32], +} + +impl CultNetClientSecurityOptions { + pub fn new(connection_key: impl Into) -> Result { + let connection_key = connection_key.into(); + if connection_key.trim().is_empty() { + return Err(anyhow!("Connection key must be provided")); + } + let encryption_key = sha256(connection_key.as_bytes()); + Ok(Self { + connection_key, + encryption_key, + }) + } + + pub fn development() -> Self { + Self::new("gamecult-dev-connection-key").expect("development key is valid") + } + + pub fn encryption_key(&self) -> [u8; 32] { + self.encryption_key + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultNetServerSecurityOptions { + client: CultNetClientSecurityOptions, + pub session_signing_secret: String, + session_signing_key: [u8; 32], + pub is_development: bool, +} + +impl CultNetServerSecurityOptions { + pub fn new( + connection_key: impl Into, + session_signing_secret: impl Into, + is_development: bool, + ) -> Result { + let session_signing_secret = session_signing_secret.into(); + if session_signing_secret.trim().is_empty() { + return Err(anyhow!("Session signing secret must be provided")); + } + Ok(Self { + client: CultNetClientSecurityOptions::new(connection_key)?, + session_signing_key: sha256(session_signing_secret.as_bytes()), + session_signing_secret, + is_development, + }) + } + + pub fn development() -> Self { + Self::new( + "gamecult-dev-connection-key", + "gamecult-dev-session-signing-secret", + true, + ) + .expect("development security config is valid") + } + + pub fn to_client_options(&self) -> CultNetClientSecurityOptions { + self.client.clone() + } + + pub fn encryption_key(&self) -> [u8; 32] { + self.client.encryption_key() + } + + pub fn session_signing_key(&self) -> [u8; 32] { + self.session_signing_key + } +} + +pub trait CultNetEncryptionOptions { + fn encryption_key(&self) -> [u8; 32]; +} + +impl CultNetEncryptionOptions for CultNetClientSecurityOptions { + fn encryption_key(&self) -> [u8; 32] { + self.encryption_key() + } +} + +impl CultNetEncryptionOptions for CultNetServerSecurityOptions { + fn encryption_key(&self) -> [u8; 32] { + self.encryption_key() + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ValidatedCultNetSessionToken { + pub user_id: String, + pub expires_at_utc: DateTime, +} + +pub struct CultNetSecret; + +impl CultNetSecret { + pub fn new_nonce() -> [u8; NONCE_LENGTH] { + let mut nonce = [0_u8; NONCE_LENGTH]; + rand::rng().fill_bytes(&mut nonce); + nonce + } + + pub fn encrypt_string( + input: Option<&str>, + nonce: &[u8], + options: &impl CultNetEncryptionOptions, + ) -> Result>> { + let Some(input) = input.filter(|value| !value.is_empty()) else { + return Ok(None); + }; + Ok(Some(Self::encrypt_bytes(input.as_bytes(), nonce, options)?)) + } + + pub fn decrypt_string( + encrypted: Option<&[u8]>, + nonce: Option<&[u8]>, + options: &impl CultNetEncryptionOptions, + ) -> Result> { + let (Some(encrypted), Some(nonce)) = (encrypted, nonce) else { + return Ok(None); + }; + let bytes = Self::decrypt_bytes(encrypted, nonce, options)?; + Ok(Some(String::from_utf8(bytes)?)) + } + + pub fn encrypt_bytes( + input: &[u8], + nonce: &[u8], + options: &impl CultNetEncryptionOptions, + ) -> Result> { + let nonce = validate_nonce(nonce)?; + let cipher = Aes256Gcm::new_from_slice(&options.encryption_key())?; + let encrypted = cipher + .encrypt( + Nonce::from_slice(nonce), + Payload { + msg: input, + aad: &[], + }, + ) + .map_err(|_| anyhow!("AES-GCM encryption failed"))?; + Ok(encrypted) + } + + pub fn decrypt_bytes( + encrypted: &[u8], + nonce: &[u8], + options: &impl CultNetEncryptionOptions, + ) -> Result> { + let nonce = validate_nonce(nonce)?; + let cipher = Aes256Gcm::new_from_slice(&options.encryption_key())?; + cipher + .decrypt( + Nonce::from_slice(nonce), + Payload { + msg: encrypted, + aad: &[], + }, + ) + .map_err(|_| anyhow!("AES-GCM decryption failed")) + } + + pub fn create_session_token( + user_id: &str, + expires_at_utc: DateTime, + options: &CultNetServerSecurityOptions, + ) -> Result { + let payload = format!("{}|{}", user_id, expires_at_utc.timestamp()); + let signature = hmac_sha256(&options.session_signing_key(), payload.as_bytes())?; + Ok(format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(payload.as_bytes()), + URL_SAFE_NO_PAD.encode(signature) + )) + } + + pub fn try_validate_session_token( + token: Option<&str>, + options: &CultNetServerSecurityOptions, + ) -> Result> { + let Some(token) = token.filter(|value| !value.trim().is_empty()) else { + return Ok(None); + }; + let Some((payload_part, signature_part)) = token.split_once('.') else { + return Ok(None); + }; + let payload = URL_SAFE_NO_PAD.decode(payload_part)?; + let signature = URL_SAFE_NO_PAD.decode(signature_part)?; + let expected = hmac_sha256(&options.session_signing_key(), &payload)?; + if !constant_time_eq(&signature, &expected) { + return Ok(None); + } + let payload = String::from_utf8(payload)?; + let Some((user_id, expires_at)) = payload.split_once('|') else { + return Ok(None); + }; + let expires_at_seconds: i64 = expires_at.parse()?; + let Some(expires_at_utc) = Utc.timestamp_opt(expires_at_seconds, 0).single() else { + return Ok(None); + }; + if expires_at_utc <= Utc::now() { + return Ok(None); + } + Ok(Some(ValidatedCultNetSessionToken { + user_id: user_id.to_string(), + expires_at_utc, + })) + } + + pub fn to_base64_url(input: &[u8]) -> String { + URL_SAFE_NO_PAD.encode(input) + } + + pub fn from_base64_url(input: &str) -> Result> { + Ok(URL_SAFE_NO_PAD.decode(input)?) + } +} + +fn validate_nonce(nonce: &[u8]) -> Result<&[u8]> { + if nonce.len() != NONCE_LENGTH { + return Err(anyhow!("Invalid nonce")); + } + Ok(nonce) +} + +fn sha256(input: &[u8]) -> [u8; 32] { + Sha256::digest(input).into() +} + +fn hmac_sha256(key: &[u8], input: &[u8]) -> Result> { + let mut mac = ::new_from_slice(key)?; + mac.update(input); + Ok(mac.finalize().into_bytes().to_vec()) +} + +fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + if left.len() != right.len() { + return false; + } + left.iter() + .zip(right) + .fold(0_u8, |acc, (left, right)| acc | (left ^ right)) + == 0 +} diff --git a/tests/cultnet.rs b/tests/cultnet.rs new file mode 100644 index 00000000..347b3132 --- /dev/null +++ b/tests/cultnet.rs @@ -0,0 +1,397 @@ +use anyhow::Result; +use chrono::Duration; +use cultcache_rs::CultCache; +use cultcache_rs::DatabaseEntry; +use cultcache_rs::SingleFileMessagePackBackingStore; +use cultnet_rs::CultNetClientSecurityOptions; +use cultnet_rs::CultNetDocumentBinding; +use cultnet_rs::CultNetDocumentMutationContract; +use cultnet_rs::CultNetDocumentOperation; +use cultnet_rs::CultNetDocumentPutOptions; +use cultnet_rs::CultNetDocumentRegistry; +use cultnet_rs::CultNetMessage; +use cultnet_rs::CultNetMutationAuthority; +use cultnet_rs::CultNetSchemaKind; +use cultnet_rs::CultNetSchemaRegistry; +use cultnet_rs::CultNetSecret; +use cultnet_rs::CultNetServerSecurityOptions; +use cultnet_rs::CultNetWireContract; +use cultnet_rs::LengthPrefixedMessageFramer; +use cultnet_rs::builtin_schema_registry; +use cultnet_rs::decode_cultnet_message_from_slice; +use cultnet_rs::encode_cultnet_message_for_wire; +use cultnet_rs::encode_cultnet_message_to_vec; +use cultnet_rs::encode_frame; +use pretty_assertions::assert_eq; + +const TS_HELLO_FRAME: &[u8] = include_bytes!("fixtures/cultnet-ts-hello.frame"); +const TS_LEGACY_LOGIN_FRAME: &[u8] = include_bytes!("fixtures/cultnet-ts-legacy-login.frame"); + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "ghostlight.agent-state", + schema = "GhostlightAgentStateFixture" +)] +struct GhostlightAgentStateFixture { + #[cultcache(key = 0)] + schema_version: String, + #[cultcache(key = 1)] + agent_id: String, + #[cultcache(key = 2)] + display_name: String, +} + +#[test] +fn security_helpers_round_trip_encrypted_strings_and_validate_sessions() -> Result<()> { + let server_security = CultNetServerSecurityOptions::development(); + let client_security = server_security.to_client_options(); + let nonce = CultNetSecret::new_nonce(); + let encrypted = CultNetSecret::encrypt_string(Some("hello"), &nonce, &client_security)? + .expect("non-empty input encrypts"); + assert_eq!( + CultNetSecret::decrypt_string(Some(&encrypted), Some(&nonce), &server_security)?, + Some("hello".to_string()) + ); + + let token = CultNetSecret::create_session_token( + "runtime-face", + chrono::Utc::now() + Duration::minutes(1), + &server_security, + )?; + let validated = CultNetSecret::try_validate_session_token(Some(&token), &server_security)? + .expect("token validates before expiry"); + assert_eq!(validated.user_id, "runtime-face"); + Ok(()) +} + +#[test] +fn cultnet_schema_messages_round_trip_through_messagepack_frames() -> Result<()> { + let message = CultNetMessage::Hello { + runtime_id: "voidbot-main".to_string(), + runtime_kind: "rust-worker".to_string(), + agent_id: Some("void".to_string()), + role: None, + display_name: Some("Void".to_string()), + supported_document_types: Some(vec!["ghostlight.agent-state".to_string()]), + supported_mutation_contracts: Some(vec![CultNetDocumentMutationContract { + document_type: "ghostlight.agent-state".to_string(), + payload_schema_version: Some("ghostlight.agent_state.v0".to_string()), + operations: vec![ + CultNetDocumentOperation::Snapshot, + CultNetDocumentOperation::DocumentPut, + ], + authority: CultNetMutationAuthority::Coordinator, + intent_document_types: Some(vec!["ghostlight.agent-state.intent.v0".to_string()]), + receipt_document_types: Some(vec!["ghostlight.agent-state.receipt.v0".to_string()]), + notes: Some(vec![ + "Face may request bounded memory mutation; coordinator reviews authority." + .to_string(), + ]), + }]), + supported_message_versions: None, + supports_schema_catalog: Some(true), + }; + let payload = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0)?; + let frame = encode_frame(&payload)?; + assert_eq!(&frame[..4], &(payload.len() as u32).to_be_bytes()); + + let mut framer = LengthPrefixedMessageFramer::new(); + assert!(framer.push(&frame[..2]).is_empty()); + let frames = framer.push(&frame[2..]); + assert_eq!(frames.len(), 1); + let decoded = + decode_cultnet_message_from_slice(&frames[0], CultNetWireContract::CultNetSchemaV0)?; + assert_eq!(decoded, message); + Ok(()) +} + +#[test] +fn legacy_gamecult_networking_contract_round_trips_login_union() -> Result<()> { + let message = CultNetMessage::Login { + nonce: CultNetSecret::to_base64_url(b"nonce"), + auth: CultNetSecret::to_base64_url(b"auth"), + password: CultNetSecret::to_base64_url(b"password"), + }; + let wire = + encode_cultnet_message_for_wire(&message, CultNetWireContract::GameCultNetworkingV0)?; + let items = wire.as_array().expect("legacy union is an array"); + assert_eq!(items[0].as_i64(), Some(0)); + assert_eq!( + items[1].as_array().unwrap()[0].as_slice(), + Some(&b"nonce"[..]) + ); + + let bytes = rmp_serde::to_vec(&wire)?; + let decoded = + decode_cultnet_message_from_slice(&bytes, CultNetWireContract::GameCultNetworkingV0)?; + assert_eq!(decoded, message); + Ok(()) +} + +#[test] +fn rust_decodes_typescript_generated_cultnet_frames() -> Result<()> { + let mut framer = LengthPrefixedMessageFramer::new(); + let hello_frames = framer.push(TS_HELLO_FRAME); + assert_eq!(hello_frames.len(), 1); + let hello = + decode_cultnet_message_from_slice(&hello_frames[0], CultNetWireContract::CultNetSchemaV0)?; + assert_eq!( + hello, + CultNetMessage::Hello { + runtime_id: "voidbot-main".to_string(), + runtime_kind: "node-worker".to_string(), + agent_id: Some("void".to_string()), + role: None, + display_name: Some("Void".to_string()), + supported_document_types: Some(vec!["ghostlight.agent-state".to_string()]), + supported_mutation_contracts: None, + supported_message_versions: None, + supports_schema_catalog: None, + } + ); + + let mut framer = LengthPrefixedMessageFramer::new(); + let login_frames = framer.push(TS_LEGACY_LOGIN_FRAME); + assert_eq!(login_frames.len(), 1); + let login = decode_cultnet_message_from_slice( + &login_frames[0], + CultNetWireContract::GameCultNetworkingV0, + )?; + assert_eq!( + login, + CultNetMessage::Login { + nonce: "bm9uY2U".to_string(), + auth: "YXV0aA".to_string(), + password: "cGFzc3dvcmQ".to_string(), + } + ); + Ok(()) +} + +#[test] +fn document_registry_advertises_mutation_contracts_with_bindings() -> Result<()> { + let mut registry = CultNetDocumentRegistry::new(); + let contract = CultNetDocumentMutationContract { + document_type: "ghostlight.agent-state".to_string(), + payload_schema_version: Some("ghostlight.agent_state.v0".to_string()), + operations: vec![ + CultNetDocumentOperation::Snapshot, + CultNetDocumentOperation::IntentSubmit, + CultNetDocumentOperation::ReceiptWatch, + ], + authority: CultNetMutationAuthority::Coordinator, + intent_document_types: Some(vec!["ghostlight.agent-state.intent.v0".to_string()]), + receipt_document_types: Some(vec!["ghostlight.agent-state.receipt.v0".to_string()]), + notes: Some(vec![ + "Intent documents are reviewed before cache mutation.".to_string(), + ]), + }; + registry.register( + CultNetDocumentBinding::for_entry::( + "ghostlight.agent_state.v0".to_string(), + ) + .with_mutation_contract(contract.clone()), + ); + + assert_eq!(registry.mutation_contracts(), vec![contract]); + Ok(()) +} + +#[test] +fn document_registry_replicates_typed_cultcache_state() -> Result<()> { + let temp = tempfile::tempdir()?; + let origin_store = temp.path().join("origin.msgpack"); + let target_store = temp.path().join("target.msgpack"); + let payload = GhostlightAgentStateFixture { + schema_version: "ghostlight.agent_state.v0".to_string(), + agent_id: "epiphany.face".to_string(), + display_name: "Face".to_string(), + }; + + let mut registry = CultNetDocumentRegistry::new(); + registry.register(CultNetDocumentBinding::for_entry::< + GhostlightAgentStateFixture, + >("ghostlight.agent_state.v0".to_string())); + + let mut origin = CultCache::new(); + origin.register_entry_type::()?; + origin.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&origin_store)); + origin.pull_all_backing_stores()?; + origin.put("epiphany.face", &payload)?; + + let snapshot = registry.create_snapshot_response(&origin, "snapshot-1", None, None)?; + + let mut target = CultCache::new(); + target.register_entry_type::()?; + target.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&target_store)); + target.pull_all_backing_stores()?; + let applied = + registry.apply_snapshot_response::(&mut target, &snapshot)?; + assert_eq!(applied, vec![payload.clone()]); + assert_eq!( + target.get_required::("epiphany.face")?, + payload + ); + + let direct_put = registry.create_document_put_message( + "put-1", + "epiphany.face", + &GhostlightAgentStateFixture { + display_name: "Face Prime".to_string(), + ..payload + }, + CultNetDocumentPutOptions::default(), + )?; + let updated = registry + .apply_document_put_message::(&mut target, &direct_put)?; + assert_eq!(updated.display_name, "Face Prime"); + Ok(()) +} + +#[test] +fn raw_snapshot_replication_preserves_messagepack_payload_bytes() -> Result<()> { + let temp = tempfile::tempdir()?; + let origin_store = temp.path().join("origin-raw.msgpack"); + let target_store = temp.path().join("target-raw.msgpack"); + let payload = GhostlightAgentStateFixture { + schema_version: "ghostlight.agent_state.v0".to_string(), + agent_id: "epiphany.face".to_string(), + display_name: "Face".to_string(), + }; + + let mut registry = CultNetDocumentRegistry::new(); + registry.register(CultNetDocumentBinding::for_entry::< + GhostlightAgentStateFixture, + >("ghostlight.agent_state.v0".to_string())); + + let mut origin = CultCache::new(); + origin.register_entry_type::()?; + origin.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&origin_store)); + origin.pull_all_backing_stores()?; + origin.put("epiphany.face", &payload)?; + + let raw_snapshot = + registry.create_raw_snapshot_response(&origin, "raw-snapshot-1", None, None)?; + let source_envelope = + origin.get_required_envelope::("epiphany.face")?; + + let mut target = CultCache::new(); + target.register_entry_type::()?; + target.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&target_store)); + target.pull_all_backing_stores()?; + let applied = registry + .apply_raw_snapshot_response::(&mut target, &raw_snapshot)?; + let target_envelope = + target.get_required_envelope::("epiphany.face")?; + + assert_eq!(applied, vec![payload.clone()]); + assert_eq!(target_envelope.payload, source_envelope.payload); + assert_eq!( + target.get_required::("epiphany.face")?, + payload + ); + Ok(()) +} + +#[test] +fn client_security_keeps_the_connection_key_visible_without_exposing_cipher_logic() -> Result<()> { + let options = CultNetClientSecurityOptions::development(); + assert_eq!(options.connection_key, "gamecult-dev-connection-key"); + assert_ne!(options.encryption_key(), [0_u8; 32]); + Ok(()) +} + +#[test] +fn builtin_schema_registry_advertises_canonical_ghostlight_schema_without_inline_body_by_default() +-> Result<()> { + let registry = builtin_schema_registry()?; + let response = registry.create_catalog_response(&CultNetMessage::SchemaCatalogRequest { + message_id: "catalog-1".to_string(), + include_schema_json: None, + schema_ids: None, + kinds: None, + })?; + + let CultNetMessage::SchemaCatalogResponse { schemas, .. } = response else { + panic!("expected catalog response"); + }; + + let ghostlight = schemas + .iter() + .find(|schema| schema.document_type.as_deref() == Some("ghostlight.agent-state")) + .expect("ghostlight agent-state schema is advertised"); + + assert_eq!(ghostlight.kind, CultNetSchemaKind::DocumentPayload); + assert_eq!( + ghostlight.schema_version.as_deref(), + Some("ghostlight.agent_state.v0") + ); + assert_eq!(ghostlight.schema_json, None); + assert!(!ghostlight.content_hash.is_empty()); + Ok(()) +} + +#[test] +fn schema_discovery_round_trips_over_legacy_gamecult_contract_when_inline_schemas_are_requested() +-> Result<()> { + let registry = { + let mut registry = CultNetSchemaRegistry::new(); + registry.register(cultnet_rs::CultNetSchemaRegistration { + schema_id: "https://example.test/contracts/example.schema.json".to_string(), + kind: CultNetSchemaKind::SharedContract, + wire_contracts: vec![ + CultNetWireContract::CultNetSchemaV0, + CultNetWireContract::GameCultNetworkingV0, + ], + schema_version: None, + document_type: None, + title: Some("Example Schema".to_string()), + schema_json: Some( + r#"{ + "$schema":"https://json-schema.org/draft/2020-12/schema", + "$id":"https://example.test/contracts/example.schema.json", + "title":"Example Schema", + "type":"object", + "properties":{"value":{"type":"string"}}, + "required":["value"], + "additionalProperties":false + }"# + .to_string(), + ), + })?; + registry + }; + + let response = registry.create_catalog_response(&CultNetMessage::SchemaCatalogRequest { + message_id: "catalog-legacy".to_string(), + include_schema_json: Some(true), + schema_ids: None, + kinds: None, + })?; + let wire = + encode_cultnet_message_for_wire(&response, CultNetWireContract::GameCultNetworkingV0)?; + let bytes = rmp_serde::to_vec(&wire)?; + let decoded = + decode_cultnet_message_from_slice(&bytes, CultNetWireContract::GameCultNetworkingV0)?; + + let CultNetMessage::SchemaCatalogResponse { + message_id, + schemas, + } = decoded + else { + panic!("expected legacy schema catalog response"); + }; + + assert_eq!(message_id, "catalog-legacy"); + assert_eq!( + schemas[0].schema_id, + "https://example.test/contracts/example.schema.json" + ); + assert!( + schemas[0] + .schema_json + .as_deref() + .is_some_and(|schema| schema.contains("\"value\"")) + ); + Ok(()) +} diff --git a/tests/fixtures/cultnet-ts-hello.frame b/tests/fixtures/cultnet-ts-hello.frame new file mode 100644 index 0000000000000000000000000000000000000000..e2b22d50048ca9f140927ecaa1a9f5ec70affe1d GIT binary patch literal 160 zcmXZUu?oU45P;#nP>T=YQUoXI9-E^%OzuMNQt1o0yE_&{qTtl$vx@7_$6r;|?edb| zK`9voKBGLW&qOG&R<+C oO7v#hn*ejShDCCWoD}Sq`y5tzm?Fq^861mx9Go`4K`m+&KGeNK7ytkO literal 0 HcmV?d00001 diff --git a/tests/fixtures/cultnet-ts-legacy-login.frame b/tests/fixtures/cultnet-ts-legacy-login.frame new file mode 100644 index 0000000000000000000000000000000000000000..c6f335d37783e6ab66bf1cdfa02137995209a860 GIT binary patch literal 30 lcmZQzV33-`F!=~;UVdJ3>JgU2(vplL90iHR#pU@$DFBis3e^Ar literal 0 HcmV?d00001