Squashed 'crates/cultnet-rs/' content from commit ab86857a
git-subtree-dir: crates/cultnet-rs git-subtree-split: ab86857a687917f6383595a721ade0e1a7e247df
This commit is contained in:
commit
3905b9a01a
34 changed files with 5104 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
/target
|
||||
Cargo.lock
|
||||
32
Cargo.toml
Normal file
32
Cargo.toml
Normal file
|
|
@ -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"
|
||||
79
README.md
Normal file
79
README.md
Normal file
|
|
@ -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::<T>()`, 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.
|
||||
19
contracts/cultnet.document-delete.schema.json
Normal file
19
contracts/cultnet.document-delete.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
40
contracts/cultnet.document-mutation-contract.schema.json
Normal file
40
contracts/cultnet.document-mutation-contract.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
19
contracts/cultnet.document-put-raw.schema.json
Normal file
19
contracts/cultnet.document-put-raw.schema.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
19
contracts/cultnet.document-put.schema.json
Normal file
19
contracts/cultnet.document-put.schema.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
26
contracts/cultnet.document-record.schema.json
Normal file
26
contracts/cultnet.document-record.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
15
contracts/cultnet.error.schema.json
Normal file
15
contracts/cultnet.error.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
35
contracts/cultnet.hello.schema.json
Normal file
35
contracts/cultnet.hello.schema.json
Normal file
|
|
@ -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" }
|
||||
}
|
||||
}
|
||||
17
contracts/cultnet.login-success.schema.json
Normal file
17
contracts/cultnet.login-success.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
19
contracts/cultnet.login.schema.json
Normal file
19
contracts/cultnet.login.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
32
contracts/cultnet.raw-document-record.schema.json
Normal file
32
contracts/cultnet.raw-document-record.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
21
contracts/cultnet.register.schema.json
Normal file
21
contracts/cultnet.register.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
15
contracts/cultnet.sample-change-name.schema.json
Normal file
15
contracts/cultnet.sample-change-name.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
15
contracts/cultnet.sample-chat.schema.json
Normal file
15
contracts/cultnet.sample-chat.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
31
contracts/cultnet.schema-catalog-request.schema.json
Normal file
31
contracts/cultnet.schema-catalog-request.schema.json
Normal file
|
|
@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
22
contracts/cultnet.schema-catalog-response.schema.json
Normal file
22
contracts/cultnet.schema-catalog-response.schema.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
39
contracts/cultnet.schema-descriptor.schema.json
Normal file
39
contracts/cultnet.schema-descriptor.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
23
contracts/cultnet.snapshot-request.schema.json
Normal file
23
contracts/cultnet.snapshot-request.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
22
contracts/cultnet.snapshot-response-raw.schema.json
Normal file
22
contracts/cultnet.snapshot-response-raw.schema.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
22
contracts/cultnet.snapshot-response.schema.json
Normal file
22
contracts/cultnet.snapshot-response.schema.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
17
contracts/cultnet.verify.schema.json
Normal file
17
contracts/cultnet.verify.schema.json
Normal file
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
845
contracts/ghostlight.agent-state.schema.json
Normal file
845
contracts/ghostlight.agent-state.schema.json
Normal file
|
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
967
examples/cultnet_interop_peer.rs
Normal file
967
examples/cultnet_interop_peer.rs
Normal file
|
|
@ -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<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
tcp_host: String,
|
||||
tcp_port: u16,
|
||||
wire_contract: String,
|
||||
supported_document_types: Vec<String>,
|
||||
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::<CultNetInteropNote>()?;
|
||||
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<String, String>) -> 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::<String, serde_json::Value>::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::<DiscoveryMessage>(&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::<Vec<_>>(),
|
||||
}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn dial(config: DialConfig) -> Result<()> {
|
||||
let schema_registration = load_schema_registration(&config.schema_path)?;
|
||||
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<CultNetInteropNote>()?;
|
||||
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::<CultNetInteropNote>(&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<serde_json::Value> {
|
||||
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::<CultNetInteropMutationReceipt>(cache, &receipt_message)?;
|
||||
let mutated_message = read_message(stream)?;
|
||||
let mutated = document_registry
|
||||
.apply_raw_document_put_message::<CultNetInteropNote>(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<serde_json::Value> {
|
||||
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::<CultNetInteropFireReceipt>(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<PeerConfig>) -> 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::<DiscoveryMessage>(&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<PeerConfig>,
|
||||
cache: Arc<Mutex<CultCache>>,
|
||||
document_registry: Arc<CultNetDocumentRegistry>,
|
||||
schema_registry: Arc<CultNetSchemaRegistry>,
|
||||
) -> 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<PeerConfig>,
|
||||
cache: Arc<Mutex<CultCache>>,
|
||||
document_registry: Arc<CultNetDocumentRegistry>,
|
||||
schema_registry: Arc<CultNetSchemaRegistry>,
|
||||
) -> 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<Mutex<CultCache>>,
|
||||
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::<CultNetInteropMutationIntent>(&mut cache, message)?;
|
||||
let mut note = cache.get_required::<CultNetInteropNote>(&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::<CultNetInteropFireCommand>(&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<CultNetSchemaRegistration> {
|
||||
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::<CultNetInteropMutationIntent>()?;
|
||||
cache.register_entry_type::<CultNetInteropMutationReceipt>()?;
|
||||
cache.register_entry_type::<CultNetInteropFireCommand>()?;
|
||||
cache.register_entry_type::<CultNetInteropFireReceipt>()?;
|
||||
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<CultNetDocumentMutationContract> {
|
||||
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<CultNetMessage> {
|
||||
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::<std::io::Error>()
|
||||
.is_some_and(|io| io.kind() == std::io::ErrorKind::UnexpectedEof)
|
||||
}
|
||||
|
||||
fn create_discovery_socket(port: u16, _join_group: bool) -> Result<UdpSocket> {
|
||||
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<String, String>) -> Result<PeerConfig> {
|
||||
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<String, String>) -> Result<DialConfig> {
|
||||
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<String>) -> BTreeMap<String, String> {
|
||||
let mut parsed = BTreeMap::new();
|
||||
let mut index = 0;
|
||||
while index < args.len() {
|
||||
let token = &args[index];
|
||||
if !token.starts_with("--") {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
let name = token.trim_start_matches("--").to_string();
|
||||
let value = args
|
||||
.get(index + 1)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| panic!("missing value for --{name}"));
|
||||
parsed.insert(name, value);
|
||||
index += 2;
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
fn require_arg<'a>(options: &'a BTreeMap<String, String>, name: &str) -> Result<&'a str> {
|
||||
options
|
||||
.get(name)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| anyhow!("missing required argument --{name}"))
|
||||
}
|
||||
|
||||
fn parse_u16_arg(options: &BTreeMap<String, String>, name: &str) -> Result<u16> {
|
||||
require_arg(options, name)?
|
||||
.parse::<u16>()
|
||||
.with_context(|| format!("argument --{name} must be a u16"))
|
||||
}
|
||||
|
||||
fn parse_u64_arg(options: &BTreeMap<String, String>, name: &str) -> Option<u64> {
|
||||
options
|
||||
.get(name)
|
||||
.map(|value| value.parse::<u64>().expect("u64 arg"))
|
||||
}
|
||||
|
||||
fn parse_ipv4_arg(options: &BTreeMap<String, String>, name: &str) -> Result<Ipv4Addr> {
|
||||
require_arg(options, name)?
|
||||
.parse::<Ipv4Addr>()
|
||||
.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(())
|
||||
}
|
||||
1155
src/contracts.rs
Normal file
1155
src/contracts.rs
Normal file
File diff suppressed because it is too large
Load diff
49
src/framing.rs
Normal file
49
src/framing.rs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
|
||||
pub const FRAME_HEADER_BYTES: usize = 4;
|
||||
|
||||
pub fn encode_frame(payload: &[u8]) -> Result<Vec<u8>> {
|
||||
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<u8>,
|
||||
}
|
||||
|
||||
impl LengthPrefixedMessageFramer {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn push(&mut self, chunk: impl AsRef<[u8]>) -> Vec<Vec<u8>> {
|
||||
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
|
||||
}
|
||||
}
|
||||
11
src/lib.rs
Normal file
11
src/lib.rs
Normal file
|
|
@ -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::*;
|
||||
440
src/replication.rs
Normal file
440
src/replication.rs
Normal file
|
|
@ -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<String>,
|
||||
pub source_runtime_id: Option<String>,
|
||||
pub source_agent_id: Option<String>,
|
||||
pub source_role: Option<String>,
|
||||
pub tags: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CultNetDocumentBinding {
|
||||
pub schema_id: String,
|
||||
pub document_type: String,
|
||||
pub mutation_contract: Option<CultNetDocumentMutationContract>,
|
||||
pub payload_schema_version: Option<String>,
|
||||
}
|
||||
|
||||
impl CultNetDocumentBinding {
|
||||
pub fn for_entry<T: DatabaseEntry>(payload_schema_version: impl Into<Option<String>>) -> 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<T: DatabaseEntry>(
|
||||
schema_id: impl Into<String>,
|
||||
payload_schema_version: impl Into<Option<String>>,
|
||||
) -> 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<String, CultNetDocumentBinding>,
|
||||
bindings_by_schema_id: BTreeMap<String, CultNetDocumentBinding>,
|
||||
}
|
||||
|
||||
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<CultNetDocumentMutationContract> {
|
||||
self.bindings_by_type
|
||||
.values()
|
||||
.filter_map(|binding| binding.mutation_contract.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn create_document_put_message<T>(
|
||||
&self,
|
||||
message_id: impl Into<String>,
|
||||
record_key: impl Into<String>,
|
||||
value: &T,
|
||||
options: CultNetDocumentPutOptions,
|
||||
) -> Result<CultNetMessage>
|
||||
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<String>,
|
||||
schema_id: impl Into<String>,
|
||||
record_key: impl Into<String>,
|
||||
) -> 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<String>,
|
||||
envelope: &CultCacheEnvelope,
|
||||
) -> Result<CultNetMessage> {
|
||||
Ok(CultNetMessage::DocumentPutRaw {
|
||||
message_id: message_id.into(),
|
||||
document: self.raw_document_record_from_envelope(envelope)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_raw_document_put_message<T>(
|
||||
&self,
|
||||
message_id: impl Into<String>,
|
||||
record_key: impl Into<String>,
|
||||
value: &T,
|
||||
options: CultNetDocumentPutOptions,
|
||||
) -> Result<CultNetMessage>
|
||||
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<String>,
|
||||
schema_ids: Option<&[String]>,
|
||||
record_keys: Option<&[String]>,
|
||||
) -> Result<CultNetMessage> {
|
||||
let requested_schema_ids = schema_ids.map(|items| items.iter().collect::<BTreeSet<_>>());
|
||||
let requested_record_keys = record_keys.map(|items| items.iter().collect::<BTreeSet<_>>());
|
||||
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<String>,
|
||||
schema_ids: Option<&[String]>,
|
||||
record_keys: Option<&[String]>,
|
||||
) -> Result<CultNetMessage> {
|
||||
let requested_schema_ids = schema_ids.map(|items| items.iter().collect::<BTreeSet<_>>());
|
||||
let requested_record_keys = record_keys.map(|items| items.iter().collect::<BTreeSet<_>>());
|
||||
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<T>(
|
||||
&self,
|
||||
cache: &mut CultCache,
|
||||
message: &CultNetMessage,
|
||||
) -> Result<T>
|
||||
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<T>(
|
||||
&self,
|
||||
cache: &mut CultCache,
|
||||
message: &CultNetMessage,
|
||||
) -> Result<bool>
|
||||
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::<T>(record_key)
|
||||
}
|
||||
|
||||
pub fn apply_raw_document_put_message<T>(
|
||||
&self,
|
||||
cache: &mut CultCache,
|
||||
message: &CultNetMessage,
|
||||
) -> Result<T>
|
||||
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::<T>(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<T>(
|
||||
&self,
|
||||
cache: &mut CultCache,
|
||||
response: &CultNetMessage,
|
||||
) -> Result<Vec<T>>
|
||||
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::<T>(
|
||||
cache,
|
||||
&CultNetMessage::DocumentPut {
|
||||
message_id: "snapshot-apply".to_string(),
|
||||
document: document.clone(),
|
||||
},
|
||||
)?);
|
||||
}
|
||||
Ok(applied)
|
||||
}
|
||||
|
||||
pub fn apply_raw_snapshot_response<T>(
|
||||
&self,
|
||||
cache: &mut CultCache,
|
||||
response: &CultNetMessage,
|
||||
) -> Result<Vec<T>>
|
||||
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::<T>(
|
||||
cache,
|
||||
&CultNetMessage::DocumentPutRaw {
|
||||
message_id: "snapshot-apply-raw".to_string(),
|
||||
document: document.clone(),
|
||||
},
|
||||
)?);
|
||||
}
|
||||
Ok(applied)
|
||||
}
|
||||
|
||||
fn document_record_from_envelope(
|
||||
&self,
|
||||
envelope: &CultCacheEnvelope,
|
||||
) -> Result<CultNetDocumentRecord<Value>> {
|
||||
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<CultNetRawDocumentRecord> {
|
||||
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<T>(value: &T) -> Result<T>
|
||||
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)
|
||||
}
|
||||
389
src/schema_discovery.rs
Normal file
389
src/schema_discovery.rs
Normal file
|
|
@ -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<CultNetWireContract>,
|
||||
pub schema_version: Option<String>,
|
||||
pub document_type: Option<String>,
|
||||
pub title: Option<String>,
|
||||
pub schema_json: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct CultNetSchemaCatalogOptions {
|
||||
pub include_schema_json: bool,
|
||||
pub schema_ids: Option<Vec<String>>,
|
||||
pub kinds: Option<Vec<CultNetSchemaKind>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CultNetSchemaRegistry {
|
||||
entries: BTreeMap<String, CultNetSchemaDescriptor>,
|
||||
}
|
||||
|
||||
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<CultNetSchemaDescriptor> {
|
||||
self.entries
|
||||
.get(schema_id)
|
||||
.map(|entry| sanitize_descriptor(entry, include_schema_json))
|
||||
}
|
||||
|
||||
pub fn list(&self, options: &CultNetSchemaCatalogOptions) -> Vec<CultNetSchemaDescriptor> {
|
||||
let requested_ids = options
|
||||
.schema_ids
|
||||
.as_ref()
|
||||
.map(|values| values.iter().cloned().collect::<BTreeSet<_>>());
|
||||
let requested_kinds = options
|
||||
.kinds
|
||||
.as_ref()
|
||||
.map(|values| values.iter().copied().collect::<BTreeSet<_>>());
|
||||
|
||||
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<CultNetMessage> {
|
||||
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<String> {
|
||||
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::<Vec<_>>()
|
||||
.join(",")
|
||||
),
|
||||
Value::Object(values) => {
|
||||
let mut entries = values.iter().collect::<Vec<_>>();
|
||||
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::<Vec<_>>()
|
||||
.join(",")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn builtin_schema_registry() -> Result<CultNetSchemaRegistry> {
|
||||
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<CultNetWireContract>,
|
||||
schema_version: Option<&str>,
|
||||
document_type: Option<&str>,
|
||||
) -> Result<CultNetSchemaRegistration> {
|
||||
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()),
|
||||
})
|
||||
}
|
||||
270
src/security.rs
Normal file
270
src/security.rs
Normal file
|
|
@ -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<Sha256>;
|
||||
|
||||
#[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<String>) -> Result<Self> {
|
||||
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<String>,
|
||||
session_signing_secret: impl Into<String>,
|
||||
is_development: bool,
|
||||
) -> Result<Self> {
|
||||
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<Utc>,
|
||||
}
|
||||
|
||||
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<Option<Vec<u8>>> {
|
||||
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<Option<String>> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<Utc>,
|
||||
options: &CultNetServerSecurityOptions,
|
||||
) -> Result<String> {
|
||||
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<Option<ValidatedCultNetSessionToken>> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
let mut mac = <HmacSha256 as 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
|
||||
}
|
||||
397
tests/cultnet.rs
Normal file
397
tests/cultnet.rs
Normal file
|
|
@ -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::<GhostlightAgentStateFixture>(
|
||||
"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::<GhostlightAgentStateFixture>()?;
|
||||
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::<GhostlightAgentStateFixture>()?;
|
||||
target.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&target_store));
|
||||
target.pull_all_backing_stores()?;
|
||||
let applied =
|
||||
registry.apply_snapshot_response::<GhostlightAgentStateFixture>(&mut target, &snapshot)?;
|
||||
assert_eq!(applied, vec![payload.clone()]);
|
||||
assert_eq!(
|
||||
target.get_required::<GhostlightAgentStateFixture>("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::<GhostlightAgentStateFixture>(&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::<GhostlightAgentStateFixture>()?;
|
||||
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::<GhostlightAgentStateFixture>("epiphany.face")?;
|
||||
|
||||
let mut target = CultCache::new();
|
||||
target.register_entry_type::<GhostlightAgentStateFixture>()?;
|
||||
target.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&target_store));
|
||||
target.pull_all_backing_stores()?;
|
||||
let applied = registry
|
||||
.apply_raw_snapshot_response::<GhostlightAgentStateFixture>(&mut target, &raw_snapshot)?;
|
||||
let target_envelope =
|
||||
target.get_required_envelope::<GhostlightAgentStateFixture>("epiphany.face")?;
|
||||
|
||||
assert_eq!(applied, vec![payload.clone()]);
|
||||
assert_eq!(target_envelope.payload, source_envelope.payload);
|
||||
assert_eq!(
|
||||
target.get_required::<GhostlightAgentStateFixture>("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(())
|
||||
}
|
||||
BIN
tests/fixtures/cultnet-ts-hello.frame
vendored
Normal file
BIN
tests/fixtures/cultnet-ts-hello.frame
vendored
Normal file
Binary file not shown.
BIN
tests/fixtures/cultnet-ts-legacy-login.frame
vendored
Normal file
BIN
tests/fixtures/cultnet-ts-legacy-login.frame
vendored
Normal file
Binary file not shown.
Loading…
Reference in a new issue