diff --git a/contracts/cultnet/cultnet-distributed-database.md b/contracts/cultnet/cultnet-distributed-database.md index 686f4892..932ba861 100644 --- a/contracts/cultnet/cultnet-distributed-database.md +++ b/contracts/cultnet/cultnet-distributed-database.md @@ -115,6 +115,7 @@ copies), the C# `CultNetErrorMessage` factory, the Rust `CultNetErrorCode`, and `unowned_schema` (a write, or a remote put or delete, for a schema and key no shard owns), `write_not_authorized` (a peer's put or delete its server's remote write authority did not grant) and `unsupported_schema_version` (a message whose `schemaVersion` the peer does not speak; `details` names `schemaVersion` and the offered value) and +`limit_reached` (a receipt-capable server's per-session remembered-write table is full, so a new write is refused; `details` all null) and `message_invalid` (a request that lacks a required field or carries an ill-typed one: a document-put or delete, or a subscription without an id; `details.field` names the request field, or `message` when the whole frame cannot be read). A malformed put or delete is `message_invalid`, not a per-operation code: the peer knows which operation it sent. diff --git a/contracts/cultnet/interop/cultnet.error.v1.schema.json b/contracts/cultnet/interop/cultnet.error.v1.schema.json new file mode 100644 index 00000000..60f24a56 --- /dev/null +++ b/contracts/cultnet/interop/cultnet.error.v1.schema.json @@ -0,0 +1,122 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/CultLib/contracts/cultnet/interop/cultnet.error.v1.schema.json", + "title": "CultNet Error Message v1", + "description": "cultnet.error.v0 plus messageId (write-receipt.md). Sent in place of cultnet.error.v0 only to a connection that declared the write-receipt capability. v0 is unchanged: its schema is closed (additionalProperties false), so an extra key would make a v0 peer reject the frame instead of ignoring it. Map-mode: every key is written, messageId nil when the error answers no readable message. The code enum is the v0 enum plus limit_reached (write-receipt.md, Remembered-write limits).", + "type": "object", + "required": [ + "schemaVersion", + "error", + "routingHint", + "code", + "details", + "messageId" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { + "const": "cultnet.error.v1" + }, + "error": { + "type": "string", + "minLength": 1 + }, + "routingHint": { + "description": "Optional shard routing detail for an authority failure. Null for every selection/cursor refusal code (R-N).", + "type": [ + "object", + "null" + ], + "additionalProperties": false, + "required": [ + "shard", + "reason" + ], + "properties": { + "shard": { + "type": [ + "object", + "null" + ] + }, + "reason": { + "type": "string" + } + } + }, + "code": { + "description": "Machine-readable refusal code (R-N). Additive: a v0 peer that does not know this field ignores it. The set is a closed enum: Rust and TypeScript refuse a message whose code is not listed, so adding a code is one coordinated change across every runtime (this schema, the C# factory, the Rust CultNetErrorCode, and a captured-bytes case for each). limit_reached: a receipt-capable server refuses a NEW write because its per-session remembered-write table (1024 entries) or its server-wide memory budget is full; messageId is the write's id.", + "type": [ + "string", + "null" + ], + "enum": [ + null, + "selection_invalid", + "cursor_stale", + "cursor_invalid", + "reference_outside_target", + "variant_unsupported", + "unowned_schema", + "write_not_authorized", + "unsupported_schema_version", + "message_invalid", + "limit_reached" + ] + }, + "details": { + "description": "Code-specific structured detail (R-N). Every field is populated only for the code that defines it; the others are null, not omitted.", + "type": [ + "object", + "null" + ], + "additionalProperties": false, + "required": [ + "field", + "value", + "asOf", + "current" + ], + "properties": { + "field": { + "description": "selection_invalid: the selection field that failed. variant_unsupported: \"subscriptionId\", when a subscription was ended. unowned_schema: \"schemaId\". write_not_authorized: \"recordKey\". unsupported_schema_version: \"schemaVersion\". message_invalid: the request field that is missing or ill-typed (\"message\" when the whole frame cannot be read). limit_reached: no field; details stay all null. message_invalid also names \"messageId\" (over 256 bytes), \"document\", \"schemaId\" or \"channel\" (write on an unreliable channel).", + "type": [ + "string", + "null" + ] + }, + "value": { + "description": "selection_invalid: the offending value, when there is one string worth naming. variant_unsupported: the id of the subscription that ended. unowned_schema: the schema id no shard owns. write_not_authorized: the key of the refused write. unsupported_schema_version: the schemaVersion the peer does not speak.", + "type": [ + "string", + "null" + ] + }, + "asOf": { + "description": "cursor_stale: the cursor's own minted asOf.", + "type": [ + "integer", + "null" + ], + "minimum": 0 + }, + "current": { + "description": "cursor_stale: the answering server's current asOf.", + "type": [ + "integer", + "null" + ], + "minimum": 0 + } + } + }, + "messageId": { + "description": "The messageId of the write (or other request) this error answers, echoed byte for byte. Null only when the frame was unreadable or carried no messageId.", + "type": [ + "string", + "null" + ], + "minLength": 1 + } + } +} diff --git a/contracts/cultnet/interop/cultnet.write-admitted.schema.json b/contracts/cultnet/interop/cultnet.write-admitted.schema.json new file mode 100644 index 00000000..42e86a2e --- /dev/null +++ b/contracts/cultnet/interop/cultnet.write-admitted.schema.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/GameCult/CultLib/contracts/cultnet/interop/cultnet.write-admitted.schema.json", + "title": "CultNet Write Admitted", + "description": "The receipt for one admitted document put or delete (write-receipt.md). Sent only after the write's commit point, only to a connection that declared the write-receipt capability, once per messageId. Map-mode: every key is written, none is nil. A receipt never carries an error, and an error.v1 never carries admission.", + "type": "object", + "required": ["schemaVersion", "messageId", "operation", "schemaId", "recordKey"], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "cultnet.write_admitted.v0" }, + "messageId": { "description": "The messageId of the put or delete this admits, echoed byte for byte.", "type": "string", "minLength": 1 }, + "operation": { "enum": ["put", "delete"] }, + "schemaId": { "description": "The schemaId of the admitted write, echoed.", "type": "string", "minLength": 1 }, + "recordKey": { "description": "The recordKey of the admitted write, echoed.", "type": "string", "minLength": 1 } + } +} diff --git a/contracts/cultnet/interop/write-receipt-vectors.json b/contracts/cultnet/interop/write-receipt-vectors.json new file mode 100644 index 00000000..397fbad6 --- /dev/null +++ b/contracts/cultnet/interop/write-receipt-vectors.json @@ -0,0 +1,1366 @@ +{ + "provenance": "Spec-authored with msgpack-python 1.2.4 (str keys in schema order, use_bin_type). Not yet a C# capture: the first conformance PR for each runtime re-captures these with its own encoder and the bytes must match, as error-vectors.json does. Every schema case is checked against cultnet.write-admitted.schema.json / cultnet.error.v1.schema.json in this directory.", + "specification": "write-receipt.md", + "wire": [ + { + "name": "write_admitted_put", + "messagePackHex": "85AD736368656D6156657273696F6EB963756C746E65742E77726974655F61646D69747465642E7630A96D6573736167654964A57075742D31A96F7065726174696F6EA3707574A8736368656D614964A76E6F74652E7630A97265636F72644B6579A66E6F74653A31", + "message": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "put-1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + }, + { + "name": "write_admitted_delete", + "messagePackHex": "85AD736368656D6156657273696F6EB963756C746E65742E77726974655F61646D69747465642E7630A96D6573736167654964A564656C2D31A96F7065726174696F6EA664656C657465A8736368656D614964A76E6F74652E7630A97265636F72644B6579A66E6F74653A31", + "message": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "del-1", + "operation": "delete", + "schemaId": "note.v0", + "recordKey": "note:1" + } + }, + { + "name": "error_v1_write_not_authorized_echoes_id", + "messagePackHex": "86AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7631A56572726F72D93677726974655F6E6F745F617574686F72697A65643A2074686520636174616C6F6720726566757365642074686520646F63756D656E74AB726F7574696E6748696E74C0A4636F6465B477726974655F6E6F745F617574686F72697A6564A764657461696C7384A56669656C64A97265636F72644B6579A576616C7565A66E6F74653A32A461734F66C0A763757272656E74C0A96D6573736167654964A57075742D32", + "message": { + "schemaVersion": "cultnet.error.v1", + "error": "write_not_authorized: the catalog refused the document", + "routingHint": null, + "code": "write_not_authorized", + "details": { + "field": "recordKey", + "value": "note:2", + "asOf": null, + "current": null + }, + "messageId": "put-2" + } + }, + { + "name": "error_v1_message_invalid_names_member_of_a_batch", + "messagePackHex": "86AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7631A56572726F72D9256D6573736167655F696E76616C69643A207265636F72644B6579206973206D697373696E67AB726F7574696E6748696E74C0A4636F6465AF6D6573736167655F696E76616C6964A764657461696C7384A56669656C64A97265636F72644B6579A576616C7565C0A461734F66C0A763757272656E74C0A96D6573736167654964B062617463682D312D6D656D6265722D33", + "message": { + "schemaVersion": "cultnet.error.v1", + "error": "message_invalid: recordKey is missing", + "routingHint": null, + "code": "message_invalid", + "details": { + "field": "recordKey", + "value": null, + "asOf": null, + "current": null + }, + "messageId": "batch-1-member-3" + } + }, + { + "name": "error_v1_unreadable_frame_has_null_message_id", + "messagePackHex": "86AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7631A56572726F72D92E6D6573736167655F696E76616C69643A20746865206D65737361676520636F756C64206E6F742062652072656164AB726F7574696E6748696E74C0A4636F6465AF6D6573736167655F696E76616C6964A764657461696C7384A56669656C64A76D657373616765A576616C7565C0A461734F66C0A763757272656E74C0A96D6573736167654964C0", + "message": { + "schemaVersion": "cultnet.error.v1", + "error": "message_invalid: the message could not be read", + "routingHint": null, + "code": "message_invalid", + "details": { + "field": "message", + "value": null, + "asOf": null, + "current": null + }, + "messageId": null + } + }, + { + "name": "error_v1_empty_schema_id_is_unreadable_and_names_the_write", + "messagePackHex": "86AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7631A56572726F72D92E6D6573736167655F696E76616C69643A20746865206D65737361676520636F756C64206E6F742062652072656164AB726F7574696E6748696E74C0A4636F6465AF6D6573736167655F696E76616C6964A764657461696C7384A56669656C64A76D657373616765A576616C7565C0A461734F66C0A763757272656E74C0A96D6573736167654964A57075742D31", + "message": { + "schemaVersion": "cultnet.error.v1", + "error": "message_invalid: the message could not be read", + "routingHint": null, + "code": "message_invalid", + "details": { + "field": "message", + "value": null, + "asOf": null, + "current": null + }, + "messageId": "put-1" + } + }, + { + "name": "error_v1_limit_reached", + "messagePackHex": "86AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7631A56572726F72D93B6C696D69745F726561636865643A207468652073657373696F6E27732072656D656D62657265642D7772697465206C696D69742069732066756C6CAB726F7574696E6748696E74C0A4636F6465AD6C696D69745F72656163686564A764657461696C7384A56669656C64C0A576616C7565C0A461734F66C0A763757272656E74C0A96D6573736167654964A87075742D31303235", + "message": { + "schemaVersion": "cultnet.error.v1", + "error": "limit_reached: the session's remembered-write limit is full", + "routingHint": null, + "code": "limit_reached", + "details": { + "field": null, + "value": null, + "asOf": null, + "current": null + }, + "messageId": "put-1025" + } + } + ], + "blankFields": { + "semantics": "A put whose document 'names nothing' is refused like a frame that does not read (error.v1 message_invalid, details.field \"message\", the write's id, the fixed text of error_v1_empty_schema_id_is_unreadable_and_names_the_write) and never applied, on every connection, receipt-capable or not. Each case starts from this valid document: schemaId note.v0, recordKey note:1, storedAt 2026-11-08T00:00:00Z, payload 81A16101 (hex), no source ids, no tags; 'set' replaces or adds the named fields. A blank string is empty or made only of Unicode White_Space code points (the list in whiteSpaceCodePoints, the PropList property, the same in every runtime; U+200B, U+FEFF, U+180E and U+001C to U+001F are not White_Space, though some platforms' whitespace tests accept some of them). Fields not listed are valid. 'unset' means the key is absent or nil, which is not blank: those cases are admitted.", + "validPutPayloadHex": "81A16101", + "whiteSpaceCodePoints": ["0009","000A","000B","000C","000D","0020","0085","00A0","1680","2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","200A","2028","2029","202F","205F","3000"], + "notWhiteSpaceCodePoints": ["200B","200C","200D","2060","FEFF","180E","001C","001D","001E","001F"], + "codePointCases": "For every code point in whiteSpaceCodePoints, each of schemaId, recordKey, storedAt, sourceRuntimeId, sourceAgentId, sourceRole and one tags entry, set alone to a string of just that code point (and to that code point repeated three times), is refused; for every code point in notWhiteSpaceCodePoints the same string is not blank and the put is admitted.", + "cases": [ + { "name": "valid_document_is_admitted", "set": {}, "outcome": "admitted" }, + { "name": "empty_schema_id", "set": { "schemaId": "" }, "outcome": "refused" }, + { "name": "blank_schema_id", "set": { "schemaId": " " }, "outcome": "refused" }, + { "name": "empty_record_key", "set": { "recordKey": "" }, "outcome": "refused" }, + { "name": "blank_record_key", "set": { "recordKey": " " }, "outcome": "refused" }, + { "name": "empty_stored_at", "set": { "storedAt": "" }, "outcome": "refused" }, + { "name": "blank_stored_at", "set": { "storedAt": " " }, "outcome": "refused" }, + { "name": "empty_payload", "set": { "payloadHex": "" }, "outcome": "refused" }, + { "name": "blank_source_runtime_id", "set": { "sourceRuntimeId": "" }, "outcome": "refused" }, + { "name": "blank_source_agent_id", "set": { "sourceAgentId": " " }, "outcome": "refused" }, + { "name": "blank_source_role", "set": { "sourceRole": "" }, "outcome": "refused" }, + { "name": "blank_tag", "set": { "tags": ["a", " "] }, "outcome": "refused" }, + { "name": "nbsp_schema_id", "set": { "schemaId": "\u00a0" }, "outcome": "refused" }, + { "name": "em_space_record_key", "set": { "recordKey": "\u2003\u2003" }, "outcome": "refused" }, + { "name": "next_line_stored_at", "set": { "storedAt": "\u0085" }, "outcome": "refused" }, + { "name": "line_separator_source_runtime_id", "set": { "sourceRuntimeId": "\u2028" }, "outcome": "refused" }, + { "name": "ideographic_space_source_agent_id", "set": { "sourceAgentId": "\u3000" }, "outcome": "refused" }, + { "name": "nbsp_source_role", "set": { "sourceRole": " \u00a0 " }, "outcome": "refused" }, + { "name": "em_space_tag", "set": { "tags": ["a", "\u2003"] }, "outcome": "refused" }, + { "name": "next_line_tag", "set": { "tags": ["\u0085"] }, "outcome": "refused" }, + { "name": "zero_width_space_schema_id_is_a_name", "set": { "schemaId": "\u200b" }, "outcome": "admitted" }, + { "name": "zero_width_space_record_key_is_a_name", "set": { "recordKey": "\u200b" }, "outcome": "admitted" }, + { "name": "zero_width_space_tag_is_a_name", "set": { "tags": ["\u200b"] }, "outcome": "admitted" }, + { "name": "bom_stored_at_is_a_name", "set": { "storedAt": "\ufeff" }, "outcome": "admitted" }, + { "name": "mongolian_vowel_separator_source_role_is_a_name", "set": { "sourceRole": "\u180e" }, "outcome": "admitted" }, + { "name": "padded_name_is_a_name", "set": { "schemaId": "\u00a0a\u2003", "tags": [" a"] }, "outcome": "admitted" }, + { "name": "file_separator_schema_id_is_a_name", "set": { "schemaId": "\u001c" }, "outcome": "admitted" }, + { "name": "source_ids_and_tags_present_and_named", "set": { "sourceRuntimeId": "r", "sourceAgentId": "a", "sourceRole": "w", "tags": ["a"] }, "outcome": "admitted" }, + { "name": "source_ids_and_tags_nil", "set": { "sourceRuntimeId": null, "sourceAgentId": null, "sourceRole": null, "tags": null }, "outcome": "admitted" }, + { "name": "empty_tag_list", "set": { "tags": [] }, "outcome": "admitted" } + ] + }, + "schemaInvalid": [ + { + "name": "write_admitted_with_an_error_key", + "messagePackHex": "86AD736368656D6156657273696F6EB963756C746E65742E77726974655F61646D69747465642E7630A96D6573736167654964A57075742D31A96F7065726174696F6EA3707574A8736368656D614964A76E6F74652E7630A97265636F72644B6579A66E6F74653A31A56572726F72A46E6F7065", + "message": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "put-1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1", + "error": "nope" + }, + "why": "admission must not carry an error" + }, + { + "name": "write_admitted_empty_message_id", + "messagePackHex": "85AD736368656D6156657273696F6EB963756C746E65742E77726974655F61646D69747465642E7630A96D6573736167654964A0A96F7065726174696F6EA3707574A8736368656D614964A76E6F74652E7630A97265636F72644B6579A66E6F74653A31", + "message": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + }, + "why": "messageId is non-empty" + }, + { + "name": "write_admitted_unknown_operation", + "messagePackHex": "85AD736368656D6156657273696F6EB963756C746E65742E77726974655F61646D69747465642E7630A96D6573736167654964A57075742D31A96F7065726174696F6EA6757073657274A8736368656D614964A76E6F74652E7630A97265636F72644B6579A66E6F74653A31", + "message": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "put-1", + "operation": "upsert", + "schemaId": "note.v0", + "recordKey": "note:1" + }, + "why": "operation is put or delete" + }, + { + "name": "write_admitted_null_record_key", + "messagePackHex": "85AD736368656D6156657273696F6EB963756C746E65742E77726974655F61646D69747465642E7630A96D6573736167654964A57075742D31A96F7065726174696F6EA3707574A8736368656D614964A76E6F74652E7630A97265636F72644B6579C0", + "message": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "put-1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": null + }, + "why": "map-mode keys are never nil" + }, + { + "name": "error_v1_without_message_id", + "messagePackHex": "85AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7631A56572726F72AF6D6573736167655F696E76616C6964AB726F7574696E6748696E74C0A4636F6465AF6D6573736167655F696E76616C6964A764657461696C7384A56669656C64A76D657373616765A576616C7565C0A461734F66C0A763757272656E74C0", + "message": { + "schemaVersion": "cultnet.error.v1", + "error": "message_invalid", + "routingHint": null, + "code": "message_invalid", + "details": { + "field": "message", + "value": null, + "asOf": null, + "current": null + } + }, + "why": "messageId is required (null when unknown), never omitted" + }, + { + "name": "error_v1_empty_message_id", + "messagePackHex": "86AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7631A56572726F72AF6D6573736167655F696E76616C6964AB726F7574696E6748696E74C0A4636F6465AF6D6573736167655F696E76616C6964A764657461696C7384A56669656C64A76D657373616765A576616C7565C0A461734F66C0A763757272656E74C0A96D6573736167654964A0", + "message": { + "schemaVersion": "cultnet.error.v1", + "error": "message_invalid", + "routingHint": null, + "code": "message_invalid", + "details": { + "field": "message", + "value": null, + "asOf": null, + "current": null + }, + "messageId": "" + }, + "why": "null, not empty string, means unknown" + }, + { + "name": "error_v0_is_not_error_v1", + "messagePackHex": "86AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7630A56572726F72B477726974655F6E6F745F617574686F72697A6564AB726F7574696E6748696E74C0A4636F6465B477726974655F6E6F745F617574686F72697A6564A764657461696C7384A56669656C64A97265636F72644B6579A576616C7565A16BA461734F66C0A763757272656E74C0A96D6573736167654964A57075742D32", + "message": { + "schemaVersion": "cultnet.error.v0", + "error": "write_not_authorized", + "routingHint": null, + "code": "write_not_authorized", + "details": { + "field": "recordKey", + "value": "k", + "asOf": null, + "current": null + }, + "messageId": "put-2" + }, + "why": "v0 stays closed: a messageId key makes it invalid, which is why v1 exists" + } + ], + "scenarios": { + "semantics": "Each scenario replays events in atMs order against a client that sent each write at its send event; a tick advances the clock without a frame. An event is atMs plus exactly one of: send (a write goes out), frame (a decoded frame arrives), transportAck (delivery, never an answer; the tracker has no input for it), tick (the clock advances), sendFailed (the client's own send of that write failed), sessionEnd (the session ended). Any other key is a defect in the vectors or the runner. A window ends when a write's age reaches it, so an event at exactly sentAt+window finds the write already unconfirmed. 'window' names the constant in vectors.constants that applies (server receipt -> RECEIPT_RESULT_WINDOW_MS, legacy -> LEGACY_RESULT_WINDOW_MS); a tick at or after the window settles unanswered writes as unconfirmed. expect gives the outcome the caller was told per write id; recorded, when present, is the write handle's later state. admitted/refused/unconfirmed are three distinct results; no scenario may settle admitted without a write_admitted frame carrying the write's id.", + "cases": [ + { + "name": "receipt_admits", + "description": "A receipt with the id completes the write as admitted.", + "server": "receipt", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 5, + "transportAck": "w1" + }, + { + "atMs": 20, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + } + ], + "expect": { + "w1": { + "outcome": "admitted" + } + }, + "window": "RECEIPT_RESULT_WINDOW_MS" + }, + { + "name": "receipt_before_transport_ack", + "description": "Order against the transport ack is irrelevant.", + "server": "receipt", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 5, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + }, + { + "atMs": 9, + "transportAck": "w1" + } + ], + "expect": { + "w1": { + "outcome": "admitted" + } + }, + "window": "RECEIPT_RESULT_WINDOW_MS" + }, + { + "name": "refusal_after_ack", + "description": "A typed refusal after the transport ack refuses; the ack was not admission.", + "server": "receipt", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 5, + "transportAck": "w1" + }, + { + "atMs": 120, + "frame": { + "schemaVersion": "cultnet.error.v1", + "error": "write_not_authorized", + "routingHint": null, + "code": "write_not_authorized", + "details": null, + "messageId": "w1" + } + } + ], + "expect": { + "w1": { + "outcome": "refused", + "code": "write_not_authorized" + } + }, + "window": "RECEIPT_RESULT_WINDOW_MS" + }, + { + "name": "refusal_before_ack", + "description": "A typed refusal before the transport ack refuses.", + "server": "receipt", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 5, + "frame": { + "schemaVersion": "cultnet.error.v1", + "error": "message_invalid", + "routingHint": null, + "code": "message_invalid", + "details": null, + "messageId": "w1" + } + }, + { + "atMs": 9, + "transportAck": "w1" + } + ], + "expect": { + "w1": { + "outcome": "refused", + "code": "message_invalid" + } + }, + "window": "RECEIPT_RESULT_WINDOW_MS" + }, + { + "name": "ack_only_window_ends_unconfirmed", + "description": "The legacy fallback: an acked write that nothing answered ends unconfirmed, never admitted.", + "server": "legacy", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 5, + "transportAck": "w1" + }, + { + "atMs": 500, + "tick": true + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "window_elapsed" + } + }, + "window": "LEGACY_RESULT_WINDOW_MS" + }, + { + "name": "window_runs_from_send_not_from_ack", + "description": "A late transport ack does not extend the window.", + "server": "legacy", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 450, + "transportAck": "w1" + }, + { + "atMs": 500, + "tick": true + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "window_elapsed" + } + }, + "window": "LEGACY_RESULT_WINDOW_MS" + }, + { + "name": "silent_receipt_capable_server_is_unconfirmed_too", + "description": "A server that advertised receipts and stayed silent is still only unconfirmed, and the client reports the fault.", + "server": "receipt", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 5, + "transportAck": "w1" + }, + { + "atMs": 5000, + "tick": true + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "window_elapsed" + } + }, + "window": "RECEIPT_RESULT_WINDOW_MS" + }, + { + "name": "legacy_error_with_one_write_in_flight_refuses", + "description": "A pre-receipt server answers with error.v0 and no id: attributable only because one write is unanswered.", + "server": "legacy", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 30, + "frame": { + "schemaVersion": "cultnet.error.v0", + "error": "write_not_authorized", + "routingHint": null, + "code": "write_not_authorized", + "details": null + } + } + ], + "expect": { + "w1": { + "outcome": "refused", + "code": "write_not_authorized" + } + }, + "window": "LEGACY_RESULT_WINDOW_MS" + }, + { + "name": "legacy_error_with_two_writes_in_flight_is_unattributed", + "description": "An id-less error with two unanswered writes names neither: both stay pending and end unconfirmed.", + "server": "legacy", + "writes": [ + "w1", + "w2" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 1, + "send": "w2" + }, + { + "atMs": 30, + "frame": { + "schemaVersion": "cultnet.error.v0", + "error": "write_not_authorized", + "routingHint": null, + "code": "write_not_authorized", + "details": null + } + }, + { + "atMs": 501, + "tick": true + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "window_elapsed" + }, + "w2": { + "outcome": "unconfirmed", + "reason": "window_elapsed" + } + }, + "window": "LEGACY_RESULT_WINDOW_MS" + }, + { + "name": "batch_names_the_refused_member", + "description": "A batch is independent writes. The refusal names its member; the others keep their own outcomes.", + "server": "receipt", + "writes": [ + "b1", + "b2", + "b3" + ], + "events": [ + { + "atMs": 0, + "send": "b1" + }, + { + "atMs": 0, + "send": "b2" + }, + { + "atMs": 0, + "send": "b3" + }, + { + "atMs": 10, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "b1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + }, + { + "atMs": 11, + "frame": { + "schemaVersion": "cultnet.error.v1", + "error": "write_not_authorized", + "routingHint": null, + "code": "write_not_authorized", + "details": null, + "messageId": "b2" + } + }, + { + "atMs": 12, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "b3", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + } + ], + "expect": { + "b1": { + "outcome": "admitted" + }, + "b2": { + "outcome": "refused", + "code": "write_not_authorized" + }, + "b3": { + "outcome": "admitted" + } + }, + "window": "RECEIPT_RESULT_WINDOW_MS" + }, + { + "name": "batch_with_one_member_unanswered", + "description": "A member nothing answered is unconfirmed; the batch as a whole is admitted only if every member is.", + "server": "receipt", + "writes": [ + "b1", + "b2" + ], + "events": [ + { + "atMs": 0, + "send": "b1" + }, + { + "atMs": 0, + "send": "b2" + }, + { + "atMs": 10, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "b1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + }, + { + "atMs": 5000, + "tick": true + } + ], + "expect": { + "b1": { + "outcome": "admitted" + }, + "b2": { + "outcome": "unconfirmed", + "reason": "window_elapsed" + } + }, + "window": "RECEIPT_RESULT_WINDOW_MS" + }, + { + "name": "session_ends_before_an_answer", + "description": "A lost session leaves unanswered writes unconfirmed, not failed and not admitted.", + "server": "receipt", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 5, + "transportAck": "w1" + }, + { + "atMs": 40, + "sessionEnd": true + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "session_ended" + } + }, + "window": "RECEIPT_RESULT_WINDOW_MS" + }, + { + "name": "late_refusal_is_recorded_not_told", + "description": "An answer after the window does not change what the caller was told; the handle records refused_late.", + "server": "legacy", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 500, + "tick": true + }, + { + "atMs": 700, + "frame": { + "schemaVersion": "cultnet.error.v1", + "error": "write_not_authorized", + "routingHint": null, + "code": "write_not_authorized", + "details": null, + "messageId": "w1" + } + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "window_elapsed", + "recorded": "refused_late" + } + }, + "window": "LEGACY_RESULT_WINDOW_MS" + }, + { + "name": "duplicate_resend_of_an_admitted_write_is_admitted_again", + "description": "The server answers a re-sent admitted messageId with the receipt again, never an error.", + "server": "receipt", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 20, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + }, + { + "atMs": 30, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + } + ], + "expect": { + "w1": { + "outcome": "admitted" + } + }, + "window": "RECEIPT_RESULT_WINDOW_MS" + }, + { + "name": "an_answer_for_an_unknown_id_is_ignored", + "description": "A frame naming no write in flight settles nothing.", + "server": "receipt", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 10, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "other", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + }, + { + "atMs": 5000, + "tick": true + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "window_elapsed" + } + }, + "window": "RECEIPT_RESULT_WINDOW_MS" + }, + { + "name": "late_receipt_is_recorded_admitted_late", + "description": "A receipt after the window: the caller was told unconfirmed, the handle records admitted_late; a caller must consult it before resending.", + "server": "receipt", + "window": "RECEIPT_RESULT_WINDOW_MS", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 5000, + "tick": true + }, + { + "atMs": 6200, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "window_elapsed", + "recorded": "admitted_late" + } + } + }, + { + "name": "receipt_inside_the_receipt_window_is_not_late", + "description": "The receipt-capable window is 5 s: a receipt at 1.2 s admits.", + "server": "receipt", + "window": "RECEIPT_RESULT_WINDOW_MS", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 1200, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + } + ], + "expect": { + "w1": { + "outcome": "admitted" + } + } + }, + { + "name": "legacy_window_is_not_used_against_a_receipt_server", + "description": "At 500 ms a receipt-capable server's write is still pending, not unconfirmed.", + "server": "receipt", + "window": "RECEIPT_RESULT_WINDOW_MS", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 500, + "tick": true + }, + { + "atMs": 800, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + } + ], + "expect": { + "w1": { + "outcome": "admitted" + } + } + }, + { + "name": "error_v1_without_id_with_one_write_in_flight_refuses", + "description": "An error.v1 whose messageId is nil names no write: like error.v0 it is attributable only because one write is unanswered.", + "server": "receipt", + "window": "RECEIPT_RESULT_WINDOW_MS", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 30, + "frame": { + "schemaVersion": "cultnet.error.v1", + "error": "message_invalid", + "routingHint": null, + "code": "message_invalid", + "details": null, + "messageId": null + } + } + ], + "expect": { + "w1": { + "outcome": "refused", + "code": "message_invalid" + } + } + }, + { + "name": "error_v1_without_id_with_two_writes_in_flight_is_unattributed", + "description": "An error.v1 with a nil messageId settles neither of two unanswered writes; each ends unconfirmed at its window.", + "server": "receipt", + "window": "RECEIPT_RESULT_WINDOW_MS", + "writes": [ + "w1", + "w2" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 1, + "send": "w2" + }, + { + "atMs": 30, + "frame": { + "schemaVersion": "cultnet.error.v1", + "error": "message_invalid", + "routingHint": null, + "code": "message_invalid", + "details": null, + "messageId": null + } + }, + { + "atMs": 5001, + "tick": true + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "window_elapsed" + }, + "w2": { + "outcome": "unconfirmed", + "reason": "window_elapsed" + } + } + }, + { + "name": "send_failed_is_unconfirmed_and_touches_no_other_write", + "description": "The client's own send of w1 failed: w1 is unconfirmed local_send_failed, never refused; w2 is unaffected and settles on its own receipt.", + "server": "receipt", + "window": "RECEIPT_RESULT_WINDOW_MS", + "writes": [ + "w1", + "w2" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 1, + "send": "w2" + }, + { + "atMs": 2, + "sendFailed": "w1" + }, + { + "atMs": 20, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w2", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "local_send_failed" + }, + "w2": { + "outcome": "admitted" + } + } + }, + { + "name": "error_without_id_after_the_window_settles_nothing", + "description": "Once w1 is unconfirmed no write is unanswered, so an error that names no write is attributed to nothing and records nothing on w1.", + "server": "legacy", + "window": "LEGACY_RESULT_WINDOW_MS", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 500, + "tick": true + }, + { + "atMs": 600, + "frame": { + "schemaVersion": "cultnet.error.v0", + "error": "write_not_authorized", + "routingHint": null, + "code": "write_not_authorized", + "details": null + } + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "window_elapsed" + } + } + }, + { + "name": "receipt_one_millisecond_inside_the_window_admits", + "description": "A receipt 1 ms before the window ends settles the write admitted.", + "server": "receipt", + "window": "RECEIPT_RESULT_WINDOW_MS", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 4999, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + } + ], + "expect": { + "w1": { + "outcome": "admitted" + } + } + }, + { + "name": "receipt_at_the_exact_window_boundary_is_late", + "description": "The window ends when the write's age reaches it: a receipt at exactly that instant finds w1 already unconfirmed and is recorded admitted_late.", + "server": "receipt", + "window": "RECEIPT_RESULT_WINDOW_MS", + "writes": [ + "w1" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 5000, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + } + ], + "expect": { + "w1": { + "outcome": "unconfirmed", + "reason": "window_elapsed", + "recorded": "admitted_late" + } + } + }, + { + "name": "send_after_session_end_is_unconfirmed_at_once", + "description": "A write registered after the session ended can never be answered: it settles unconfirmed session_ended when sent, and the earlier write keeps its own receipt.", + "server": "receipt", + "window": "RECEIPT_RESULT_WINDOW_MS", + "writes": [ + "w1", + "w2" + ], + "events": [ + { + "atMs": 0, + "send": "w1" + }, + { + "atMs": 5, + "frame": { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "w1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1" + } + }, + { + "atMs": 40, + "sessionEnd": true + }, + { + "atMs": 50, + "send": "w2" + } + ], + "expect": { + "w1": { + "outcome": "admitted" + }, + "w2": { + "outcome": "unconfirmed", + "reason": "session_ended" + } + } + } + ] + }, + "constants": { + "RECEIPT_RESULT_WINDOW_MS": 5000, + "LEGACY_RESULT_WINDOW_MS": 500, + "DEDUPE_RETENTION_MS": 600000 + }, + "counts": { + "semantics": "How many of each a runner must have run. A runner that reads fewer (a parser that drops entries, a loop over nothing) fails instead of passing quietly; a runner that meets an event key outside scenarios.semantics fails too.", + "wire": 7, + "schemaInvalid": 7, + "contentHashCases": 4, + "scenarioCases": 25 + }, + "contentHash": { + "definition": "sha256(msgpack([operation, schemaId, recordKey, payload])), payload a msgpack bin for a put and nil for a delete; hex lowercase", + "cases": [ + { + "name": "put_note_1_payload_a", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1", + "payloadHex": "81A26964A131", + "sha256": "7051c10071123b6ade50fbd5075e3859cae4ea70ce358a24a0b0c6980090e95d" + }, + { + "name": "put_note_1_payload_b", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1", + "payloadHex": "81A26964A132", + "sha256": "58d3fc6b858d2605a68550c9d4811ccdca6b9db7a0c3bfebf304d279257f6f9f" + }, + { + "name": "put_note_2_payload_a", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:2", + "payloadHex": "81A26964A131", + "sha256": "a248cd920e58d41bc6ccca9e108030b1d491239000047fef088122364a32b6f8" + }, + { + "name": "delete_note_1", + "operation": "delete", + "schemaId": "note.v0", + "recordKey": "note:1", + "payloadHex": null, + "sha256": "232b0f96651b28aa8ab7673a6106944a9f6a8d66852b6e21291a23ed084b8b37" + } + ] + }, + "dedupe": { + "semantics": "Replay writes in order against a receipt-capable server whose actors are transport-authenticated. expect lists the answer per write in order and how many times a write was applied to the store in total. 'invalid' means error.v1 message_invalid with details.field messageId and the write's id.", + "cases": [ + { + "name": "resend_same_content_re_admits_without_reapplying", + "writes": [ + { + "actor": "alice", + "messageId": "m1", + "content": "put_note_1_payload_a" + }, + { + "actor": "alice", + "messageId": "m1", + "content": "put_note_1_payload_a" + } + ], + "answers": [ + "admitted", + "admitted" + ], + "applied": 1 + }, + { + "name": "same_id_different_payload_is_refused_not_re_receipted", + "writes": [ + { + "actor": "alice", + "messageId": "m1", + "content": "put_note_1_payload_a" + }, + { + "actor": "alice", + "messageId": "m1", + "content": "put_note_1_payload_b" + } + ], + "answers": [ + "admitted", + "refused:message_invalid" + ], + "applied": 1 + }, + { + "name": "same_id_different_record_key_is_refused", + "writes": [ + { + "actor": "alice", + "messageId": "m1", + "content": "put_note_1_payload_a" + }, + { + "actor": "alice", + "messageId": "m1", + "content": "put_note_2_payload_a" + } + ], + "answers": [ + "admitted", + "refused:message_invalid" + ], + "applied": 1 + }, + { + "name": "same_id_different_operation_is_refused", + "writes": [ + { + "actor": "alice", + "messageId": "m1", + "content": "put_note_1_payload_a" + }, + { + "actor": "alice", + "messageId": "m1", + "content": "delete_note_1" + } + ], + "answers": [ + "admitted", + "refused:message_invalid" + ], + "applied": 1 + }, + { + "name": "the_same_id_from_another_actor_is_an_independent_write", + "writes": [ + { + "actor": "alice", + "messageId": "m1", + "content": "put_note_1_payload_a" + }, + { + "actor": "bob", + "messageId": "m1", + "content": "put_note_1_payload_b" + } + ], + "answers": [ + "admitted", + "admitted" + ], + "applied": 2 + }, + { + "name": "resend_of_a_refused_write_is_refused_the_same_way", + "writes": [ + { + "actor": "mallory", + "messageId": "m1", + "content": "put_note_1_payload_a" + }, + { + "actor": "mallory", + "messageId": "m1", + "content": "put_note_1_payload_a" + } + ], + "answers": [ + "refused:write_not_authorized", + "refused:write_not_authorized" + ], + "applied": 0, + "note": "mallory is not authorized to write note.v0" + }, + { + "name": "the_capability_does_not_authorize", + "writes": [ + { + "actor": "mallory", + "messageId": "m2", + "content": "put_note_2_payload_a" + } + ], + "helloDeclaresReceipts": true, + "answers": [ + "refused:write_not_authorized" + ], + "applied": 0, + "note": "declaring the receipt capability changes the frame the refusal arrives in, never whether it is a refusal" + } + ] + } +} diff --git a/contracts/cultnet/interop/write-receipt.md b/contracts/cultnet/interop/write-receipt.md new file mode 100644 index 00000000..dc138452 --- /dev/null +++ b/contracts/cultnet/interop/write-receipt.md @@ -0,0 +1,85 @@ +# CultNet write receipt (specification) + +Status: specification. No runtime implements it yet; the conformance follow-ups below do. +Rules: Heimdall's ruling of 2026-11-08 (a write completes on its result frame; an ack or a return is not admission). +Files here: `cultnet.write-admitted.schema.json`, `cultnet.error.v1.schema.json`, `write-receipt-vectors.json`. They move to `contracts/cultnet/` when the first runtime implements them. + +## The problem + +A put or delete today has two answers on the wire: nothing (admitted, or the server never read it) and `cultnet.error.v0` (refused, with no id saying which write). A transport ack proves delivery. Clients that completed on the ack, or on a window with no refusal, reported refused writes as done (CultLib #55 to #58 bound this with a result window; this spec replaces the window with an answer). + +## Frames + +**`cultnet.write_admitted.v0`**: `{ schemaVersion, messageId, operation: "put"|"delete", schemaId, recordKey }`, every key written, none nil. Sent once a put or delete is admitted. The id echoes the write's `messageId` byte for byte; `operation`, `schemaId`, `recordKey` echo the write. + +**`cultnet.error.v1`**: `cultnet.error.v0` plus a required `messageId` (string or nil). The code enum is v0's plus `limit_reached` (see Remembered-write limits); `cultnet.error.v1.schema.json` is the authority for the closed set. Sent in place of `error.v0` to a receipt-capable connection. `messageId` is the id of the request the error answers; nil only when the frame was unreadable or carried no id. + +Why a new error version and not an extra key on v0: the v0 schema is closed (`additionalProperties: false`) and the TypeScript decoder (Ajv over the closed schemas) rejects unknown keys and unknown `schemaVersion`s, and `parseCultNetMessage` throws on an unknown version; Rust's decoder errors on an unknown version too. Unknown-key tolerance of the Rust, Python and Kotlin error decoders was not checked, so none is assumed, so a surprise key or frame breaks an old client's whole receive path. Old clients are therefore never sent either new frame. This reverses the "old clients ignore it" assumption, which is false for today's decoders. + +## Capability: opting in + +A connection is receipt-capable when its `cultnet.hello.v0` (sent before its first write; the schema channel is reliable and ordered) lists both `cultnet.write_admitted.v0` and `cultnet.error.v1` in `supportedMessageVersions`. A server MUST NOT send either new frame to any other connection, and answers it exactly as before (no receipt, `error.v0`). A receipt-capable server lists both in its own hello, so a client can tell a legacy server from a receipt server that has not answered yet. A client that sends no hello gets legacy behaviour. A server advertises the two frames in its hello only if it implements the receipt rules end to end. + +**The capability changes framing only; it never authorizes.** A hello authenticates nothing and grants nothing: who may write, and which keys, is decided by the server from the transport-authenticated actor exactly as without the capability. Declaring the capability never makes a refused write admitted, never widens an actor's authority, and never changes what a write does; it selects only which frame the answer arrives in. + +## Server rules + +1. **One answer.** For every put or delete on a receipt-capable connection the server sends exactly one of `write_admitted` or `error.v1`, carrying that write's `messageId`. Never both, never two different answers. +2. **After the commit point.** `write_admitted` is sent only after the write is committed by the same rule that makes it visible to readers. Receipt of the bytes, parse, or authorisation alone is not admission. +3. **Id on every refusal.** Every refusal of a write, whatever its code (`write_not_authorized`, `message_invalid`, `unowned_schema`, `unsupported_schema_version`, shard authority errors, ...), is an `error.v1` whose `messageId` is the write's id. When the frame is readable enough to find the id, it is found; `message_invalid` for a missing or ill-typed field still carries the id. Nil only when no id can be read. +4. **Batches.** There is no batch frame; a batch is N writes, each with its own `messageId`, each answered under rules 1 to 3. A failed batch names its member by that id. A server may not collapse a batch into one answer. +5. **Identity and idempotent resend.** A `messageId` is unique per authenticated actor and session: the client mints it, never reuses it for different content in that session, and a server never accepts the id of one actor as the id of another. The server's dedupe key is `(actor, messageId)`, where *actor* is the transport-authenticated identity, never a name the hello or the frame claims. Alongside the key it keeps the **content hash** of the write and the answer it gave. The content hash is SHA-256 of the MessagePack array `[operation, schemaId, recordKey, payload]`, where `payload` is the raw document payload as a MessagePack `bin` for a put and nil for a delete (the vectors give worked hashes). **Scope: at least the session.** The key lives for the life of the session it was made in, and a server may bound how many writes it remembers per session (see Remembered-write limits; a server never forgets an id it promised to answer). A server MAY keep the key longer for the same actor, up to `DEDUPE_RETENTION_MS` (10 minutes), but a client MUST NOT rely on it: **a reconnect is a new session, and a resend on the new session is a new write.** + - Same key, same content hash, answer was `write_admitted`: answer `write_admitted` again with the same body. The write is not applied twice. + - Same key, same content hash, answer was a refusal: the same refusal again. + - **Same key, different content hash: refuse `message_invalid` (details `field: "messageId"`) and never re-send the old receipt.** Old receipts are for the old content; showing one for new content would report an unapplied write as admitted. The original write's state is unchanged. + - **Id size.** A write's `messageId` is at most 256 bytes of UTF-8. A longer id is refused `message_invalid` (`details.field: "messageId"`, the refusal's `messageId` the id as received, text fixed per Fixed texts) BEFORE anything is remembered: no table entry, no digest, no budget charge. Such a refusal is therefore not replayed from the table; a resend is refused afresh, identically. + - **What is remembered.** Per entry a server keeps only fixed-size digests (SHA-256) of the `messageId` and of the content hash, plus the answer (`admitted`, or the refusal's code and details). Memory per entry is bounded independent of id length and payload size. Lookup compares digests. + - **Remembered-write limits.** The per-session table holds at most 1024 entries. A server MAY also enforce a server-wide memory budget across all sessions (reference: 32 MiB of remembered entries). A NEW write (a key not already in the table) that would exceed either bound is refused `limit_reached` for that write alone, `messageId` the write's id, `details` all null; the write is not applied and the session continues. A resend of a remembered key is still answered from the table. + - **Limit refusals are remembered.** A `limit_reached` refusal is remembered like any other: a resend of the same id and content hash replays `limit_reached`. No slot is freed mid-session, so an id refused at a bound never becomes admitted later in that session (a server at the cap keeps the refused digest pair in a bounded refusal set of at most 1024 per session, outside the entry budget; past it, a further new write is refused `limit_reached` without being remembered, and the session refuses every id it has not seen for the rest of its life, even if a server-wide budget has since freed, so a refusal that was not remembered is never followed by an admission of the same id). The client mints a new id on a new session. + - **Required fields.** A put or delete whose document or `schemaId` is null or missing is refused `message_invalid` with `details.field` `"document"` or `"schemaId"` (the first missing in that order) and fixed text; the write is not applied. A put or delete that is present but names nothing is not "missing": the write is refused `message_invalid` exactly as a frame that does not read, with `details.field` `"message"`, the fixed unreadable text and the write's id (vector `error_v1_empty_schema_id_is_unreadable_and_names_the_write`), and is never applied; a server must not hand it to its store. Names nothing means, on a put or delete, a `schemaId` or `recordKey` that is blank; on a put's document, also a `storedAt` that is blank, a `payload` of zero bytes (a MessagePack value is at least one byte, so an empty payload is no document), a `sourceRuntimeId`, `sourceAgentId` or `sourceRole` that is present and blank, and a `tags` entry that is blank. **Blank** means empty or made only of Unicode White_Space code points (the PropList property) and nothing else, in every runtime, whatever its platform's own whitespace test says. The set is exactly U+0009 to U+000D, U+0020, U+0085, U+00A0, U+1680, U+2000 to U+200A, U+2028, U+2029, U+202F, U+205F and U+3000. U+200B, U+200C, U+200D, U+2060, U+FEFF, U+180E and U+001C to U+001F are not White_Space (some platforms' whitespace tests accept U+001C to U+001F or U+180E, for example Java's `Character.isWhitespace` and older .NET, so a runtime must check the list, not its platform test): a string of them names something. The vectors list both sets (`whiteSpaceCodePoints`, `notWhiteSpaceCodePoints`) and a runtime checks every code point in every covered field. Absent or nil source ids and tags, and an empty `tags` list, are valid. The rule holds on every connection, receipt-capable or not (a legacy connection is refused with the `error.v0` of the same code, details and text); the vectors' `blankFields` section lists each case. + - **Fixed texts.** The `error` string of these refusals is fixed, so vectors can compare it: `message_invalid: messageId exceeds 256 bytes`, `message_invalid: document is required`, `message_invalid: schemaId is required`, `message_invalid: the message could not be read` (a frame that does not decode, or a write that names nothing; the text is the same for both and never carries a decoder's own wording), `message_invalid: receipt sessions require the reliable channel`, `limit_reached: the session's remembered-write limit is full`. + - **Reliable channel only.** A write is accepted on a receipt session only on a channel that is reliable and not sequenced (reliable ordered and reliable unordered both qualify; a sequenced channel drops superseded packets, so a write on it can vanish without trace). A write arriving on any other channel is refused `message_invalid` with `details.field: "channel"` (the transport profile's word for it) and fixed text. Receipts and refusals travel the reliable channel; a write that could be lost without trace cannot be answered once. The server refuses a sequenced write whenever it can read the write's id: from the delivered frame, and from a superseded packet that carries its whole frame. A write sent as several fragments whose frame is superseded is dropped whole and may go unanswered; the client's unconfirmed outcome covers it. A repeat of a packet the server already took, or a packet too far ahead to be taken, draws no further answer (rule 1). + - Past the session (or a server's longer retention, if it keeps one) a resend is a new write. +6. **Forwarded writes.** A server that forwards a non-primary write answers the original peer only with what the primary answered: the primary's receipt becomes `write_admitted` with the original id, its refusal becomes `error.v1` with the original id. If the forward gets no answer the server relays nothing: no receipt, no error, no synthesized refusal. The client's own rule below then reports the write as unconfirmed. A forwarder never turns an absent or ambiguous primary answer into an admission. +7. **Looks alike.** An admitted and a refused write differ in `schemaVersion`; a receipt has no `error`, an `error.v1` has no admission. A transport ack is neither. + +## Client rules: three outcomes + +A write settles as exactly one of: + +- **admitted**: a `write_admitted` whose `messageId` is the write's. +- **refused**: an `error.v1` whose `messageId` is the write's, carrying its `code` and `details` as the typed error. +- **unconfirmed**: nothing settled it. Reasons: `window_elapsed` (the result window ran from the *send* and passed with no answer; see Result window), `session_ended` (the peer closed the session, or it ended, before the write was answered; a write registered after the session ended settles this way when it is sent) and `local_send_failed` (the client's own send of this write failed). A local send failure is never reported as refused: no server answer exists, and the write may or may not have left the machine. Unconfirmed is not success and not refusal. APIs that return a value return the tri-state; APIs that throw throw a distinct refused error and a distinct unconfirmed error and return normally only for admitted. A caller that needs admission treats unconfirmed as not admitted. Resend with the same `messageId` and unchanged content, **on the same session**, is safe against a receipt-capable server (rule 5). After a reconnect the resend is a new write, and a legacy server may apply a resend twice: the caller resends only writes that are idempotent by record key (a put of the same content to the same key, a delete of a key), and reads the record back before resending any other. + +**Result window.** Two named constants (also in the vectors): `RECEIPT_RESULT_WINDOW_MS = 5000`, the default against a receipt-capable server (its hello lists both frames); `LEGACY_RESULT_WINDOW_MS = 500`, used only as the fallback against a server whose hello does not list them (or that sent none). The window runs from the send. It ends when the write's age reaches it: an answer arriving at exactly that instant is late. A receipt-capable server that has not answered within its window is reported as unconfirmed like any other; clients log it as a server that missed its window. + +**Late answers.** An answer for a write that already settled `unconfirmed` does not change what the caller was told, but the client records it on the write: a late `write_admitted` makes the write's recorded state `admitted_late`, a late refusal makes it `refused_late`. The write handle exposes that state, and a caller that got `unconfirmed` MUST consult it (and the record) before resending: it must not blind-resend a write that was admitted late. A resend on the same session with the same id and content is harmless on a receipt-capable server (rule 5); across a reconnect the caller follows the idempotence rule above. + +**Legacy answers.** An `error.v0`, or an `error.v1` with nil `messageId`, names no write. It is attributed to a write only when exactly one write on the connection is unanswered; it then refuses that write. With two or more unanswered writes it settles none of them and each ends unconfirmed at its window. A frame naming a `messageId` that is not in flight settles nothing. + +**Batches can commit partially.** A batch is N independent writes with no atomicity: some members may be admitted while others are refused or unanswered, and nothing is rolled back. The client reports each member's outcome and a batch result is only their set: admitted if every member is admitted, refused if any member is refused (naming the members), otherwise unconfirmed (naming the unanswered members). The caller owns retry: it resends exactly the members that are not admitted, with their original ids. + +## Changes to what #55 to #58 shipped + +Those clients complete *successfully* when the window ends with no refusal. Under this spec that case is `unconfirmed`. The TypeScript one-shot writer (#62) already reports it so: it resolves `admitted` only on a `write_admitted` carrying the put's id, and no other frame, a put echoed under the same id included, ever counts as admission. A caller whose server cannot answer a write yet (Odin, until it is receipt-capable) opts into the explicit send-only mode per call (`sendOnly: true`), which resolves the distinct outcome `sent` once the transport has acknowledged the put and never `admitted`. The Idunn presence publisher is send-only by its own function (`sendPresenceDocument`, not the `sendOnly` option): the same `sent` result, plus a rejection if a refusal naming the put (or naming nothing) arrives by the transport ack. Receipts and send-only are both opt-in, neither is the default. The C# and Rust clients of #55 to #58 keep the window-success until their conformance work lands, and callers of those must not read it as admission. + +## Vectors + +`write-receipt-vectors.json`: `constants` (the named windows and retention), `contentHash` (worked dedupe hashes), `dedupe` (server replay cases for rule 5), `wire` (MessagePack hex plus the decoded message for each new frame; the bytes are spec-authored with msgpack-python and every runtime's first conformance PR re-captures them with its own encoder and must match), `schemaInvalid` (frames that must be refused by a validator, each with why), and `blankFields` (server input cases for the Required fields rule: which document fields make a put unreadable, which are accepted), `scenarios` (event replays with the outcome each write must settle as; the clock is abstract; each case names its window constant). A conformant client passes every scenario; a conformant server's answers for the same inputs satisfy server rules 1 to 7. + +## Conformance status + +| Server class | Advertises both frames | Server-wide memory budget (MAY, Remembered-write limits) | +|---|---|---| +| `CultNetDatabaseServer` | yes | not implemented: only the per-session limit of 1024 applies | +| Shard write forwarder | yes | not implemented: only the per-session limit of 1024 applies | +| Rust RUDP document server | yes | implemented (32 MiB default, `max_remembered_write_bytes`) | +| C# RUDP schema server (`CultNetRudpSchemaServer`, `src/GameCult.Networking/CultNetRudpSchemaServer.cs`) | no | n/a | + +Advertising is per server class, not per transport. A class advertises both frames in its hello only if it implements the receipt rules end to end; the C# RUDP schema server stays "no" until it answers writes with receipts. + +Cross-runtime check: `packages/cultmesh-ts/test/interop/write-receipt-interop.test.ts` (`npm run test:interop` in `packages/cultmesh-ts`) runs the TypeScript client (`WriteTracker`, the decoder, the one-shot writer) against the real Rust RUDP document server and the real `CultNetDatabaseServer` over loopback, one scenario set against both. Known gap it records as a todo: the Rust RUDP document server refuses every delete (`write_not_authorized: the server does not take deletes`), where this spec has an admitted delete receipted like a put. + +## Conformance follow-ups (not in this PR) + +C# server and client, Rust, TypeScript, Python, Kotlin: emit and parse the two frames; hello capability; tri-state client outcome; replace the #55 to #58 window-success; re-capture the wire vectors in each runtime. Server write paths include the shard write forwarder (rule 6) and the Odin catalog. diff --git a/docs/cultnet-rudp-ack-cut.md b/docs/cultnet-rudp-ack-cut.md index 1b519484..47008c81 100644 --- a/docs/cultnet-rudp-ack-cut.md +++ b/docs/cultnet-rudp-ack-cut.md @@ -441,8 +441,8 @@ consumer that waits wants delivered, which is now just Acknowledged. | `cultmesh-rs/src/lib.rs:781-838` `request_raw_snapshot_from_rudp_catalog` (Idunn `src/drivers.rs:5527` uses it) | a hand-rolled loop until `Acknowledged`, then the response | Cut 4: `wait_acknowledged` | | `cultmesh-rs/src/lib.rs:870-900` `publish_cultnet_message_to_rudp_catalog` (Odin `odin-daemon`) | a hand-rolled loop until `Acknowledged`, then disconnect. The doc at `:869` claims "application admission" | Cut 4: `wait_acknowledged`; the doc says delivered to the document server's sink (`rudp_document_server.rs:343-372`) | | `cultmesh-rs/src/lib.rs:918-938` `publish_cultnet_messages_to_rudp_catalog` (Ghostlight `mesh.rs:323`) | `flush_reliable`, then drop. **Several ordered frames, then close** | None; flush now means it | -| `cultmesh-ts/src/index.ts:6070-6098` `publishRudpDocumentOnce` (Heimdall, StreamPixels, Stonks, weksa, Bifrost, VoidBot, Hermodr) | `peer.flush` (`cultnet-ts/src/peer.ts:109-110`), then close | None. Cut 5 moves its connect-and-wait helper (`index.ts:6603-6650`) into cultnet-ts | -| `cultnet-ts/src/idunn-odin-presence-publisher.ts:89-215` `publishDocument`, behind `createIdunnRuntimePresencePublisher`. **StreamPixels' service runs this**: `apps/service/scripts/idunn-entry.mjs` runs `deployment/idunn/runtime-presence.mjs`, which calls `createIdunnRuntimePresencePublisher` (`:46`) from its vendored CultLib `542ddd3` (StreamPixels `a49f7d8`; pass 2's `30ee8b9` is stale), where it lives under its older name `cultnet-ts/src/idunn-runtime-authority.ts:206` | a hand-rolled session loop (`:186-208`) until `outstandingReliablePacketCount === 0`. It does resend (`:205`). It drops `readyToSend` (`:198`), so promoted queued packets wait for the resend timer. It pins `initialSequence: 1` (`:103`) and never sends a Disconnect, so Odin's hub keeps each publish's peer until it times out (each publish binds a new port, so each is a new peer) | Cut 5: the socket transport, `connectAndWait`, `send("schema")`, `flush`, `close` (which sends the Disconnect, `rudp.ts:956-969`) | +| `cultmesh-ts/src/index.ts:6211-6303` `publishRudpDocumentOnce` (Heimdall, StreamPixels, Stonks, weksa, Bifrost, VoidBot, Hermodr) | `peer.flush` (`cultnet-ts/src/peer.ts:109-110`), then close | None. Cut 5 moves its connect-and-wait helper (`index.ts:6603-6650`) into cultnet-ts | +| `cultnet-ts/src/idunn-odin-presence-publisher.ts:97-136` `sendPresenceDocument` (formerly `publishDocument`), behind `createIdunnRuntimePresencePublisher`. **StreamPixels' service runs this**: `apps/service/scripts/idunn-entry.mjs` runs `deployment/idunn/runtime-presence.mjs`, which calls `createIdunnRuntimePresencePublisher` (`:46`) from its vendored CultLib `542ddd3` (StreamPixels `a49f7d8`; pass 2's `30ee8b9` is stale), where it lives under its older name `cultnet-ts/src/idunn-runtime-authority.ts:206` | a hand-rolled session loop (`:186-208`) until `outstandingReliablePacketCount === 0`. It does resend (`:205`). It drops `readyToSend` (`:198`), so promoted queued packets wait for the resend timer. It pins `initialSequence: 1` (`:103`) and never sends a Disconnect, so Odin's hub keeps each publish's peer until it times out (each publish binds a new port, so each is a new peer) | Cut 5: the socket transport, `connectAndWait`, `send("schema")`, `flush`, `close` (which sends the Disconnect, `rudp.ts:956-969`) | | `cultnet-ts/src/signed-daemon-health.ts:104-162` `publishSignedDaemonHealth` (Hermodr, Odin `idunn-rudp.cjs`) | a hand-rolled loop: sends the packets `sendMany` admitted, waits up to 500 ms for the **first** Ack packet of any content (`:146-153`), swallows the timeout, closes. Resends run inside that wait (`:303`) but promoted queued packets are never sent | Cut 5, as above. Today a write not acked within 500 ms, or any payload over 32 packets, is reported published | | `cultnet-ts/src/operation-service.ts` | the operation response | none (the response is the proof) | | C# `FlushReliable` callers: Gjallar `Program.cs:3055-3080` (two ordered frames, flush, dispose) | flush | None | diff --git a/packages/cultmesh-kotlin/README.md b/packages/cultmesh-kotlin/README.md index 3da68679..ff69c346 100644 --- a/packages/cultmesh-kotlin/README.md +++ b/packages/cultmesh-kotlin/README.md @@ -474,3 +474,14 @@ powershell -ExecutionPolicy Bypass -File .\packages\cultmesh-kotlin\build.ps1 The build writes `artifacts/cultmesh-kotlin/cultmesh-kotlin.jar`. It also runs the built-in RUDP packet fixture and localhost UDP socket self-test. + +## Write Receipt + +`WriteReceipt.kt` decodes `cultnet.write_admitted.v0` and `cultnet.error.v1` (and `error.v0`) strictly against their +closed schemas (`decodeWriteAdmitted`, `decodeErrorFrame`), computes the dedupe `writeContentHash`, tests a hello with +`helloAdvertisesWriteReceipts`, and settles sent writes as admitted, refused or unconfirmed in `WriteTracker` +(pure state machine, abstract clock; the caller owns transport and timers). Kotlin has no write client yet, so nothing +sends a put and waits on this. `WriteReceiptVectors.kt` replays +`contracts/cultnet/interop/write-receipt-vectors.json` (constants, contentHash, wire, schemaInvalid, scenarios; the +server-side `dedupe` and `blankFields` sections are not run); `build.ps1` runs it after the self-test, or run +`CultMeshKt write-receipt-vectors `. diff --git a/packages/cultmesh-kotlin/build.ps1 b/packages/cultmesh-kotlin/build.ps1 index aabacbcd..42c22358 100644 --- a/packages/cultmesh-kotlin/build.ps1 +++ b/packages/cultmesh-kotlin/build.ps1 @@ -26,4 +26,7 @@ $sources = Get-ChildItem $src -Recurse -Filter *.kt | Select-Object -ExpandPrope if ($LASTEXITCODE -ne 0) { throw "kotlinc failed with exit code $LASTEXITCODE" } & $java -cp "$jarPath;$kotlinStdlib" org.gamecult.cultmesh.CultMeshKt if ($LASTEXITCODE -ne 0) { throw "cultmesh-kotlin self-test failed with exit code $LASTEXITCODE" } +$vectors = Join-Path $repoRoot "contracts\cultnet\interop\write-receipt-vectors.json" +& $java -cp "$jarPath;$kotlinStdlib" org.gamecult.cultmesh.CultMeshKt write-receipt-vectors $vectors +if ($LASTEXITCODE -ne 0) { throw "write-receipt vector replay failed with exit code $LASTEXITCODE" } Write-Host "Built $jarPath" diff --git a/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt index 7d052785..4a06d7f5 100644 --- a/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt +++ b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt @@ -1100,9 +1100,9 @@ data class CultNetRawDocumentRecord( "payloadEncoding" to payloadEncoding, "payload" to payload.copyOf(), ) - if (!sourceRuntimeId.isNullOrBlank()) wire["sourceRuntimeId"] = sourceRuntimeId - if (!sourceAgentId.isNullOrBlank()) wire["sourceAgentId"] = sourceAgentId - if (!sourceRole.isNullOrBlank()) wire["sourceRole"] = sourceRole + if (!isBlankText(sourceRuntimeId)) wire["sourceRuntimeId"] = sourceRuntimeId + if (!isBlankText(sourceAgentId)) wire["sourceAgentId"] = sourceAgentId + if (!isBlankText(sourceRole)) wire["sourceRole"] = sourceRole if (tags.isNotEmpty()) wire["tags"] = tags return wire } @@ -3413,6 +3413,7 @@ fun main(args: Array) { rudpClientBindsLoopbackOnlyForALoopbackEndpoint() rudpSocketTransportHandshakesAndCarriesReliableOrderedSchemaFrames() rudpSocketTransportCarriesFragmentedReliableOrderedSchemaFrames() + rawDocumentRecordDropsOnlyWhiteSpaceSourceIds() return } @@ -3424,6 +3425,7 @@ fun main(args: Array) { "rudp-dial-message-once" -> rudpDialSchemaMessageOnce(options) "serve" -> interopServe(options) "dial" -> interopDial(options) + "write-receipt-vectors" -> if (!replayWriteReceiptVectors(args.getOrNull(1) ?: error("usage: write-receipt-vectors "))) kotlin.system.exitProcess(1) else -> error("Unknown mode ${args[0]}") } } diff --git a/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/WriteReceipt.kt b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/WriteReceipt.kt new file mode 100644 index 00000000..4b38d942 --- /dev/null +++ b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/WriteReceipt.kt @@ -0,0 +1,257 @@ +package org.gamecult.cultmesh + +// The write receipt (contracts/cultnet/interop/write-receipt.md): the two frames, their strict decode, the dedupe +// content hash, the hello capability test and the client settle rules. Mirrors packages/cultnet-ts (contracts.ts, +// write-tracker.ts) and packages/cultnet-rs (write_content_hash). The replay of write-receipt-vectors.json lives in +// WriteReceiptVectors.kt. Server rules (dedupe, limits, blank fields) are not a decoder's business and are not here. + +import java.io.IOException +import java.security.MessageDigest + +const val WRITE_ADMITTED_VERSION = "cultnet.write_admitted.v0" +const val ERROR_V1_VERSION = "cultnet.error.v1" +const val ERROR_V0_VERSION = "cultnet.error.v0" + +/** A connection is receipt-capable only when its hello lists both frames. */ +val CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS: List = listOf(WRITE_ADMITTED_VERSION, ERROR_V1_VERSION) + +const val RECEIPT_RESULT_WINDOW_MS = 5000L +const val LEGACY_RESULT_WINDOW_MS = 500L + +fun resultWindowMs(serverAdvertisesReceipts: Boolean): Long = + if (serverAdvertisesReceipts) RECEIPT_RESULT_WINDOW_MS else LEGACY_RESULT_WINDOW_MS + +/** The closed refusal-code set of error.v0; error.v1 adds `limit_reached`. */ +val CULTNET_ERROR_V0_CODES: Set = setOf( + "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target", "variant_unsupported", + "unowned_schema", "write_not_authorized", "unsupported_schema_version", "message_invalid", +) +val CULTNET_ERROR_V1_CODES: Set = CULTNET_ERROR_V0_CODES + "limit_reached" + +fun helloAdvertisesWriteReceipts(hello: CultNetMessage): Boolean { + val versions = hello.body["supportedMessageVersions"] as? List<*> ?: return false + return CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS.all { it in versions } +} + +data class CultNetWriteAdmitted(val messageId: String, val operation: String, val schemaId: String, val recordKey: String) { + fun toMessage() = CultNetMessage( + WRITE_ADMITTED_VERSION, + linkedMapOf("messageId" to messageId, "operation" to operation, "schemaId" to schemaId, "recordKey" to recordKey), + ) +} + +data class CultNetErrorDetails(val field: String?, val value: String?, val asOf: Long?, val current: Long?) + +/** error.v0 (`messageId` always null, `version` 0) or error.v1 (`version` 1). */ +data class CultNetErrorFrame( + val version: Int, + val error: String, + val routingHint: Map?, + val code: String?, + val details: CultNetErrorDetails?, + val messageId: String?, +) { + fun toMessage(): CultNetMessage { + val body = linkedMapOf( + "error" to error, + "routingHint" to routingHint, + "code" to code, + "details" to details?.let { + linkedMapOf("field" to it.field, "value" to it.value, "asOf" to it.asOf, "current" to it.current) + }, + ) + if (version == 1) body["messageId"] = messageId + return CultNetMessage(if (version == 1) ERROR_V1_VERSION else ERROR_V0_VERSION, body) + } +} + +/** + * Strict decode of a write_admitted.v0 message against its closed schema: exactly five keys, a non-empty string each, + * operation put|delete. + */ +fun decodeWriteAdmitted(message: CultNetMessage): CultNetWriteAdmitted { + if (message.schemaVersion != WRITE_ADMITTED_VERSION) throw IOException("not a $WRITE_ADMITTED_VERSION message") + closedKeys(message, setOf("messageId", "operation", "schemaId", "recordKey")) + val operation = nonEmpty(message, "operation") + if (operation != "put" && operation != "delete") throw IOException("operation must be put or delete") + return CultNetWriteAdmitted(nonEmpty(message, "messageId"), operation, nonEmpty(message, "schemaId"), nonEmpty(message, "recordKey")) +} + +/** Strict decode of error.v0 (no messageId, no limit_reached) or error.v1 (messageId required, string or nil, never empty). */ +fun decodeErrorFrame(message: CultNetMessage): CultNetErrorFrame { + val version = when (message.schemaVersion) { + ERROR_V1_VERSION -> 1 + ERROR_V0_VERSION -> 0 + else -> throw IOException("not an error message") + } + closedKeys(message, setOf("error", "routingHint", "code", "details") + if (version == 1) setOf("messageId") else emptySet()) + val error = nonEmpty(message, "error") + val codeValue = message.body["code"] + if (codeValue != null && (codeValue !is String || codeValue !in (if (version == 1) CULTNET_ERROR_V1_CODES else CULTNET_ERROR_V0_CODES))) { + throw IOException("unknown error code") + } + var messageId: String? = null + if (version == 1) { + val id = message.body["messageId"] + if (id != null && (id !is String || id.isEmpty())) throw IOException("messageId must be a non-empty string or nil") + messageId = id as String? + } + return CultNetErrorFrame(version, error, routingHintOf(message.body["routingHint"]), codeValue as String?, detailsOf(message.body["details"]), messageId) +} + +private fun closedKeys(message: CultNetMessage, required: Set) { + if (!message.body.keys.containsAll(required)) throw IOException("${message.schemaVersion} is missing ${required - message.body.keys}") + val unknown = message.body.keys - required + if (unknown.isNotEmpty()) throw IOException("${message.schemaVersion} carries unknown keys $unknown") +} + +private fun nonEmpty(message: CultNetMessage, key: String): String { + val value = message.body[key] + if (value !is String || value.isEmpty()) throw IOException("$key must be a non-empty string") + return value +} + +private fun routingHintOf(value: Any?): Map? { + if (value == null) return null + if (value !is Map<*, *> || value.keys != setOf("shard", "reason")) throw IOException("routingHint must be nil or {shard, reason}") + if (value["shard"] != null && value["shard"] !is Map<*, *>) throw IOException("routingHint.shard must be an object or nil") + if (value["reason"] !is String) throw IOException("routingHint.reason must be a string") + @Suppress("UNCHECKED_CAST") + return value as Map +} + +private fun detailsOf(value: Any?): CultNetErrorDetails? { + if (value == null) return null + if (value !is Map<*, *> || value.keys != setOf("field", "value", "asOf", "current")) { + throw IOException("details must be nil or {field, value, asOf, current}") + } + fun text(key: String): String? = value[key].let { if (it == null || it is String) it as String? else throw IOException("details.$key must be a string or nil") } + fun cursor(key: String): Long? = value[key].let { + if (it == null) null else if (it is Long && it >= 0) it else throw IOException("details.$key must be a non-negative integer or nil") + } + return CultNetErrorDetails(text("field"), text("value"), cursor("asOf"), cursor("current")) +} + +/** sha256 of the MessagePack array [operation, schemaId, recordKey, payload]: payload a bin for a put, nil for a delete. Lowercase hex. */ +fun writeContentHash(operation: String, schemaId: String, recordKey: String, payload: ByteArray?): String { + val writer = MessagePackWriter().array(4).string(operation).string(schemaId).string(recordKey) + if (payload == null) writer.nil() else writer.binary(payload) + return MessageDigest.getInstance("SHA-256").digest(writer.toByteArray()).joinToString("") { "%02x".format(it) } +} + +/** Why nothing settled a write. */ +enum class WriteUnconfirmedReason(val wire: String) { WINDOW_ELAPSED("window_elapsed"), SESSION_ENDED("session_ended"), LOCAL_SEND_FAILED("local_send_failed") } + +/** What a late answer is recorded as on a write that already settled unconfirmed. */ +enum class WriteRecorded(val wire: String) { ADMITTED_LATE("admitted_late"), REFUSED_LATE("refused_late") } + +/** What the caller was told. Settled once; never changed by a later frame. */ +sealed class WriteSettlement { + object Admitted : WriteSettlement() + data class Refused(val code: String?, val error: String, val response: CultNetErrorFrame) : WriteSettlement() + data class Unconfirmed(val reason: WriteUnconfirmedReason) : WriteSettlement() +} + +/** + * The client half of the receipt rules: a pure state machine with an abstract clock, one decision, how each sent write + * settles. Transport, timers and decoding belong to the caller; `frame` takes a message and decodes it strictly. + */ +class WriteTracker(private val windowMs: Long, private val onSettle: (String, WriteSettlement) -> Unit = { _, _ -> }) { + private class Entry(val sentAtMs: Long) { + var settlement: WriteSettlement? = null + var recorded: WriteRecorded? = null + } + + private val writes = linkedMapOf() + private var ended = false + + /** Registers a write sent at [atMs]. Re-sending a known id is the same write and does not restart its window. */ + fun send(messageId: String, atMs: Long) { + tick(atMs) + if (messageId in writes) return + val entry = Entry(atMs) + writes[messageId] = entry + // On a session that already ended nothing can answer this write. + if (ended) settle(messageId, entry, WriteSettlement.Unconfirmed(WriteUnconfirmedReason.SESSION_ENDED)) + } + + /** Feeds one received message. Only write_admitted, error.v1 and error.v0 answer; anything else is ignored. */ + fun frame(message: CultNetMessage, atMs: Long) { + tick(atMs) + when (message.schemaVersion) { + WRITE_ADMITTED_VERSION -> { + answer(decodeWriteAdmitted(message).messageId, WriteSettlement.Admitted, WriteRecorded.ADMITTED_LATE) + return + } + ERROR_V1_VERSION, ERROR_V0_VERSION -> { + val error = decodeErrorFrame(message) + val refusal = WriteSettlement.Refused(error.code, error.error, error) + if (error.messageId != null) { + answer(error.messageId, refusal, WriteRecorded.REFUSED_LATE) + return + } + // An error that names no write is attributable only when exactly one write is unanswered. + val unanswered = writes.filterValues { it.settlement == null } + if (unanswered.size == 1) settle(unanswered.keys.first(), unanswered.values.first(), refusal) + } + else -> return + } + } + + /** Every unanswered write whose window, counted from its own send, has run settles unconfirmed. */ + fun tick(atMs: Long) { + for ((id, entry) in writes) { + if (entry.settlement == null && atMs - entry.sentAtMs >= windowMs) settle(id, entry, WriteSettlement.Unconfirmed(WriteUnconfirmedReason.WINDOW_ELAPSED)) + } + } + + /** The session ended: every unanswered write settles unconfirmed, and so does any write sent afterwards. */ + fun sessionEnd(atMs: Long) { + tick(atMs) + ended = true + for ((id, entry) in writes) if (entry.settlement == null) settle(id, entry, WriteSettlement.Unconfirmed(WriteUnconfirmedReason.SESSION_ENDED)) + } + + /** This client's own send of [messageId] failed: that write settles unconfirmed; the others are untouched. */ + fun sendFailed(messageId: String, atMs: Long) { + val entry = writes[messageId] + if (entry != null && entry.settlement == null) settle(messageId, entry, WriteSettlement.Unconfirmed(WriteUnconfirmedReason.LOCAL_SEND_FAILED)) + tick(atMs) + } + + /** The settlement told to the caller, or null while unanswered or unknown. */ + fun settlement(messageId: String): WriteSettlement? = writes[messageId]?.settlement + + /** The late answer recorded on an unconfirmed write. */ + fun recorded(messageId: String): WriteRecorded? = writes[messageId]?.recorded + + private fun answer(messageId: String, settlement: WriteSettlement, late: WriteRecorded) { + val entry = writes[messageId] ?: return // names a write that is not in flight: settles nothing + val current = entry.settlement + if (current == null) settle(messageId, entry, settlement) + else if (current is WriteSettlement.Unconfirmed && entry.recorded == null) entry.recorded = late + } + + private fun settle(messageId: String, entry: Entry, settlement: WriteSettlement) { + entry.settlement = settlement + onSettle(messageId, settlement) + } +} + +/** Unicode White_Space (PropList), the one definition of "blank" in write-receipt.md rule 5; Kotlin's own isBlank takes U+001C to U+001F. */ +private val WHITE_SPACE_CODE_POINTS: Set = (0x0009..0x000D).toSet() + 0x0020 + 0x0085 + 0x00A0 + 0x1680 + + (0x2000..0x200A).toSet() + 0x2028 + 0x2029 + 0x202F + 0x205F + 0x3000 + +/** True for null, empty, or only White_Space code points. */ +fun isBlankText(text: String?): Boolean = text == null || text.codePoints().allMatch { it in WHITE_SPACE_CODE_POINTS } + +/** Self-test: blank is White_Space, not Kotlin's isBlank (rule 5): U+001C to U+001F name something, U+00A0 and U+0085 do not. */ +fun rawDocumentRecordDropsOnlyWhiteSpaceSourceIds() { + fun wireKeys(id: String) = CultNetRawDocumentRecord("note.v0", "note:1", "2026-11-08T00:00:00Z", payload = byteArrayOf(1), sourceRuntimeId = id, sourceAgentId = id, sourceRole = id).toWireMap().keys + for (blank in listOf("", "\u0085", "\u00a0\u2003", "\u3000", "\t\r\n ")) { + check(isBlankText(blank) && "sourceRuntimeId" !in wireKeys(blank)) { "blank ${blank.map { it.code }} must be dropped" } + } + for (named in listOf("\u001c", "\u001f", "\u200b", "\ufeff", "\u180e", "a")) { + check(!isBlankText(named) && "sourceRuntimeId" in wireKeys(named) && "sourceRole" in wireKeys(named)) { "${named.map { it.code }} names something and must be kept" } + } +} diff --git a/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/WriteReceiptVectors.kt b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/WriteReceiptVectors.kt new file mode 100644 index 00000000..e527692d --- /dev/null +++ b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/WriteReceiptVectors.kt @@ -0,0 +1,243 @@ +package org.gamecult.cultmesh + +// Replays contracts/cultnet/interop/write-receipt-vectors.json against this runtime: constants, contentHash, every +// `wire` frame (decode to the vector's fields, re-encode to its bytes), every `schemaInvalid` frame (must be refused), +// and every `scenarios` event replay through WriteTracker. `dedupe` and `blankFields` are server inputs and are not +// run here. Mode: `java -cp ... org.gamecult.cultmesh.CultMeshKt write-receipt-vectors `. + +import java.io.File +import java.io.IOException + +// The event actions scenarios.semantics names; anything else is refused, not skipped. +private val EVENT_KEYS = listOf("send", "frame", "tick", "sessionEnd", "sendFailed", "transportAck") + +fun replayWriteReceiptVectors(path: String): Boolean { + @Suppress("UNCHECKED_CAST") + val vectors = JsonReader(File(path).readText(Charsets.UTF_8)).readDocument() as Map + val results = linkedMapOf>() + fun check(name: String, run: () -> List) { + results[name] = try { run() } catch (e: Throwable) { listOf("threw: $e") } + } + + val constants = obj(vectors["constants"]) + check("constants") { + listOfNotNull( + "RECEIPT window".takeIf { constants["RECEIPT_RESULT_WINDOW_MS"] != RECEIPT_RESULT_WINDOW_MS }, + "LEGACY window".takeIf { constants["LEGACY_RESULT_WINDOW_MS"] != LEGACY_RESULT_WINDOW_MS }, + ) + } + + for (case in list(obj(vectors["contentHash"])["cases"])) { + val c = obj(case) + check("contentHash/${c["name"]}") { + val got = writeContentHash(c["operation"] as String, c["schemaId"] as String, c["recordKey"] as String, (c["payloadHex"] as String?)?.let(::unhex)) + if (got == c["sha256"]) emptyList() else listOf("$got != ${c["sha256"]}") + } + } + + for (case in list(vectors["wire"])) { + val c = obj(case) + check("wire/${c["name"]}") { + val bytes = unhex(c["messagePackHex"] as String) + val problems = mutableListOf() + val message = decodeReceiptFrame(parseCultNetMessage(bytes)) + if (message.toWireMap() != c["message"]) problems += "decoded ${message.toWireMap()} != ${c["message"]}" + val again = message.toBytes().joinToString("") { "%02X".format(it) } + if (again != (c["messagePackHex"] as String).uppercase()) problems += "re-encoded bytes $again != captured ${c["messagePackHex"]}" + problems + } + } + + for (case in list(vectors["schemaInvalid"])) { + val c = obj(case) + check("schemaInvalid/${c["name"]}") { + try { + decodeReceiptFrame(parseCultNetMessage(unhex(c["messagePackHex"] as String))) + listOf("accepted a frame that must be refused (${c["why"]})") + } catch (_: IOException) { + emptyList() + } + } + } + + // Not a vector: `limit_reached` is in error.v1's enum only (write-receipt.md), as the TS and Rust suites also pin. + check("error_v0_refuses_the_v1_only_limit_reached_code") { + val body = linkedMapOf("error" to "x", "routingHint" to null, "code" to "limit_reached", "details" to null) + val v1 = decodeErrorFrame(CultNetMessage(ERROR_V1_VERSION, body + ("messageId" to null))).code + try { + decodeErrorFrame(CultNetMessage(ERROR_V0_VERSION, body)) + listOf("error.v0 accepted limit_reached") + } catch (_: IOException) { + if (v1 == "limit_reached") emptyList() else listOf("error.v1 lost limit_reached") + } + } + + for (case in list(obj(vectors["scenarios"])["cases"])) { + val scenario = obj(case) + check("scenario/${scenario["name"]}") { + val problems = mutableListOf() + // The fake server states its capability the only way a real one does: in its hello. + val hello = cultNetHello( + "fake-server", "fake", + supportedMessageVersions = if (scenario["server"] == "receipt") CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS else emptyList(), + ) + val windowMs = resultWindowMs(helloAdvertisesWriteReceipts(hello)) + if (windowMs != constants[scenario["window"] as String]) problems += "window $windowMs != ${scenario["window"]}" + val told = linkedMapOf() + val tracker = WriteTracker(windowMs) { id, settlement -> + if (id in told) problems += "$id settled twice" + told[id] = settlement + } + for (event in list(scenario["events"]).map(::obj).sortedBy { it["atMs"] as Long }) { + val at = event["atMs"] as Long + val actions = event.keys - "atMs" + if (actions.size != 1 || actions.first() !in EVENT_KEYS) { problems += "event at $at has keys $actions, wanted atMs and exactly one of $EVENT_KEYS"; continue } + when { + "send" in event -> tracker.send(event["send"] as String, at) + // A frame reaches the client as bytes: the fake server encodes it, the client decodes it. + "frame" in event -> tracker.frame(parseCultNetMessage(MessagePackWriter().value(event["frame"]).toByteArray()), at) + "tick" in event -> tracker.tick(at) + "sessionEnd" in event -> tracker.sessionEnd(at) + "sendFailed" in event -> tracker.sendFailed(event["sendFailed"] as String, at) + // transportAck: delivery is not an answer; the tracker has no such input and must not need one. + } + } + val expect = obj(scenario["expect"]) + for ((id, wantAny) in expect) { + val want = obj(wantAny) + val got = told[id] + if (got == null) { problems += "$id: never settled, wanted ${want["outcome"]}"; continue } + val (outcome, code, reason) = when (got) { + is WriteSettlement.Admitted -> Triple("admitted", null, null) + is WriteSettlement.Refused -> Triple("refused", got.code, null) + is WriteSettlement.Unconfirmed -> Triple("unconfirmed", null, got.reason.wire) + } + if (outcome != want["outcome"]) problems += "$id: told $outcome, wanted ${want["outcome"]}" + if ("code" in want && code != want["code"]) problems += "$id: code $code, wanted ${want["code"]}" + if ("reason" in want && reason != want["reason"]) problems += "$id: reason $reason, wanted ${want["reason"]}" + if (tracker.recorded(id)?.wire != want["recorded"]) problems += "$id: recorded ${tracker.recorded(id)?.wire}, wanted ${want["recorded"]}" + } + for (id in told.keys) if (id !in expect) problems += "$id: settled but the scenario expects nothing for it" + problems + } + } + + // A runner that read fewer vectors than the file declares has silently skipped some. + check("counts") { + val declared = obj(vectors["counts"]) + fun ran(prefix: String) = results.keys.count { it.startsWith(prefix) } + val loaded = mapOf( + "wire" to list(vectors["wire"]).size, "schemaInvalid" to list(vectors["schemaInvalid"]).size, + "contentHashCases" to list(obj(vectors["contentHash"])["cases"]).size, "scenarioCases" to list(obj(vectors["scenarios"])["cases"]).size, + ) + val executed = mapOf("wire" to ran("wire/"), "schemaInvalid" to ran("schemaInvalid/"), "contentHashCases" to ran("contentHash/"), "scenarioCases" to ran("scenario/")) + loaded.keys.filter { loaded[it] != (declared[it] as Long).toInt() || executed[it] != loaded[it] } + .map { "$it: declared ${declared[it]}, loaded ${loaded[it]}, ran ${executed[it]}" } + } + + for ((name, problems) in results) { + println(if (problems.isEmpty()) "PASS $name" else "FAIL $name") + problems.forEach { println(" $it") } + } + val failed = results.values.count { it.isNotEmpty() } + println("${results.size - failed}/${results.size} passed") + return failed == 0 +} + +/** Strict decode of whichever receipt-family frame this is, returned as the message its typed form encodes; anything else is refused. */ +private fun decodeReceiptFrame(message: CultNetMessage): CultNetMessage = when (message.schemaVersion) { + WRITE_ADMITTED_VERSION -> decodeWriteAdmitted(message).toMessage() + ERROR_V1_VERSION, ERROR_V0_VERSION -> decodeErrorFrame(message).toMessage() + else -> throw IOException("not a receipt frame: ${message.schemaVersion}") +} + +@Suppress("UNCHECKED_CAST") +private fun obj(value: Any?): Map = value as Map +private fun list(value: Any?): List = value as List + +private fun unhex(text: String): ByteArray = ByteArray(text.length / 2) { text.substring(it * 2, it * 2 + 2).toInt(16).toByte() } + +/** A small JSON reader for the vector file: objects, arrays, strings, integers, true/false/null. */ +private class JsonReader(private val text: String) { + private var at = 0 + + fun readDocument(): Any? = readValue().also { skipSpace(); if (at != text.length) throw IOException("trailing JSON") } + + private fun skipSpace() { while (at < text.length && text[at] in " \t\r\n") at++ } + + private fun readValue(): Any? { + skipSpace() + return when (val c = text[at]) { + '{' -> { + at++ + val map = linkedMapOf() + skipSpace() + if (text[at] == '}') { at++; return map } + do { + skipSpace() + val key = readString() + skipSpace(); expect(':') + map[key] = readValue() + skipSpace() + } while (closes('}')) + map + } + '[' -> { + at++ + val items = mutableListOf() + skipSpace() + if (text[at] == ']') { at++; return items } + do { + items += readValue() + skipSpace() + } while (closes(']')) + items + } + '"' -> readString() + 't' -> literal("true", true) + 'f' -> literal("false", false) + 'n' -> literal("null", null) + else -> { + if (c != '-' && !c.isDigit()) throw IOException("unexpected '$c' at $at") + val start = at++ + while (at < text.length && text[at].isDigit()) at++ + text.substring(start, at).toLong() + } + } + } + + /** After an element: false when [close] ends the container, true after a comma. */ + private fun closes(close: Char): Boolean { + val c = text[at++] + if (c == close) return false + if (c != ',') throw IOException("expected , or $close at ${at - 1}") + return true + } + + private fun literal(word: String, value: Any?): Any? { + if (!text.startsWith(word, at)) throw IOException("bad literal at $at") + at += word.length + return value + } + + private fun expect(c: Char) { if (text[at++] != c) throw IOException("expected $c at ${at - 1}") } + + private fun readString(): String { + expect('"') + val out = StringBuilder() + while (true) { + val c = text[at++] + when (c) { + '"' -> return out.toString() + '\\' -> when (val e = text[at++]) { + 'n' -> out.append('\n'); 't' -> out.append('\t'); 'r' -> out.append('\r') + 'b' -> out.append('\b'); 'f' -> out.append('\u000c') + 'u' -> { out.append(text.substring(at, at + 4).toInt(16).toChar()); at += 4 } + '"', '\\', '/' -> out.append(e) + else -> throw IOException("bad escape \\$e") + } + else -> out.append(c) + } + } + } +} diff --git a/packages/cultmesh-rs/examples/receipt_interop_server.rs b/packages/cultmesh-rs/examples/receipt_interop_server.rs new file mode 100644 index 00000000..b8c66fd9 --- /dev/null +++ b/packages/cultmesh-rs/examples/receipt_interop_server.rs @@ -0,0 +1,77 @@ +//! The real Rust RUDP document server on an ephemeral loopback port, for the cross-runtime write-receipt interop +//! harness (packages/cultmesh-ts/test/interop/write-receipt-interop.test.ts). It is the production server with a +//! recording sink and nothing else: stdout carries one JSON line per fact the harness asserts on, and the server runs +//! until stdin closes. +//! +//! {"event":"listening","port":N} +//! {"event":"applied","op":"put","messageId":"...","schemaId":"...","recordKey":"..."} +//! +//! Record keys that start with `refuse:` are refused by the sink (authorize and commit), which is how the harness +//! asks for a refused write. +use anyhow::Result; +use cultmesh_rs::{ + CultMeshRudpDocumentServer, CultMeshRudpRawDocumentReceipt, CultMeshRudpRawDocumentSink, + CultMeshRudpSnapshotQuery, CultMeshSystemClock, +}; +use cultnet_rs::CultNetRawDocumentRecord; +use serde_json::json; +use std::io::Read; +use std::net::UdpSocket; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread; +use std::time::Duration; + +const REFUSED_PREFIX: &str = "refuse:"; + +struct RecordingSink; + +impl CultMeshRudpRawDocumentSink for RecordingSink { + fn authorize_raw_document(&mut self, receipt: &CultMeshRudpRawDocumentReceipt) -> Result<()> { + if receipt.document.record_key.starts_with(REFUSED_PREFIX) { + anyhow::bail!("not authorized"); + } + Ok(()) + } + + fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()> { + if receipt.document.record_key.starts_with(REFUSED_PREFIX) { + anyhow::bail!("not authorized"); + } + println!( + "{}", + json!({ + "event": "applied", + "op": "put", + "messageId": receipt.message_id, + "schemaId": receipt.document.schema_id, + "recordKey": receipt.document.record_key, + }) + ); + Ok(()) + } +} + +fn main() -> Result<()> { + let source = |_: &CultMeshRudpSnapshotQuery| -> Result> { Ok(Vec::new()) }; + let mut server = CultMeshRudpDocumentServer::new( + UdpSocket::bind("127.0.0.1:0")?, + RecordingSink, + source, + CultMeshSystemClock::default(), + Default::default(), + )?; + println!("{}", json!({ "event": "listening", "port": server.local_addr()?.port() })); + let stop = Arc::new(AtomicBool::new(false)); + let watcher = Arc::clone(&stop); + thread::spawn(move || { + let mut sink = Vec::new(); + let _ = std::io::stdin().read_to_end(&mut sink); + watcher.store(true, Ordering::SeqCst); + }); + while !stop.load(Ordering::SeqCst) { + server.poll_once()?; + thread::sleep(Duration::from_millis(1)); + } + Ok(()) +} diff --git a/packages/cultmesh-rs/src/rudp_document_server.rs b/packages/cultmesh-rs/src/rudp_document_server.rs index f97b2578..9aae5be9 100644 --- a/packages/cultmesh-rs/src/rudp_document_server.rs +++ b/packages/cultmesh-rs/src/rudp_document_server.rs @@ -780,6 +780,13 @@ where return Ok(CultMeshRudpPollOutcome::Handled); } + // Whether this packet is the first the session takes for its sequence: a repeat of an answered write, or a + // packet too far ahead to be remembered, is not, and the write is not answered for it again. + let first_receipt = packet.reliable + && self + .sessions + .get(&key) + .is_some_and(|entry| !entry.session.has_received(packet.sequence)); let result = { let entry = self .sessions @@ -821,11 +828,28 @@ where } let mut kept_rejection = None; + // A superseded packet delivers no frame, yet it was acknowledged and will not be resent, so its write would + // go unanswered. A packet that carries its whole frame is answered from its own payload. A superseded + // fragment cannot be: the write's id may lie in a fragment this packet does not hold. + if refuse_sequenced + && first_receipt + && self.sessions.get(&key).is_some_and(|entry| entry.session.has_received(packet.sequence)) + && packet.fragment_count == 0 + && !result.delivered.iter().any(|frame| frame.channel_id == "schema" && frame.sequence == packet.sequence) + { + if let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = + self.refuse_unreliable_write(key, &packet.payload)? + { + kept_rejection = Some(rejection); + } + } for frame in result.delivered { if frame.channel_id != "schema" { continue; } - if refuse_sequenced { + // `delivered` also holds the ordered frames this packet's arrival released from the hold; those were + // not sent on the sequenced channel. They sit above the packet's own sequence, its own frame at or below. + if refuse_sequenced && sequence_at_or_before(frame.sequence, packet.sequence) { if let CultMeshRudpPollOutcome::ApplicationRejected(rejection) = self.refuse_unreliable_write(key, &frame.payload)? { @@ -1814,6 +1838,13 @@ where #[cfg(test)] mod send_failure_tests; +/// Whether `sequence` is at or before `mark` in serial order (RFC 1982): the 32-bit space is compared modulo 2^32, +/// so a frame that began before the wrap and a packet after it still order correctly. The receive window of +/// `cultnet_rs`' duplicate test does not belong here: a frame's first fragment may lie any distance back. +fn sequence_at_or_before(sequence: u32, mark: u32) -> bool { + mark.wrapping_sub(sequence) < 1 << 31 +} + fn validate_options(options: &CultMeshRudpDocumentServerOptions) -> Result<()> { if options.max_sessions == 0 { return Err(anyhow!("max_sessions must be greater than zero")); @@ -1929,4 +1960,17 @@ mod tests { .unwrap(); assert_eq!(hex(&bytes), MESSAGE_INVALID_HEX); } + + #[test] + fn sequence_order_holds_across_the_wrap_and_beyond_the_receive_window() { + assert!(sequence_at_or_before(7, 7)); + assert!(sequence_at_or_before(100, 5_200), "further back than the receive window"); + assert!(!sequence_at_or_before(5_200, 100)); + assert!(sequence_at_or_before(u32::MAX - 1, 1), "begun before the wrap, ended after it"); + assert!(!sequence_at_or_before(1, u32::MAX - 1), "after the wrap is later than before it"); + assert!(sequence_at_or_before(u32::MAX, 0), "the wrap itself"); + assert!(!sequence_at_or_before(0, u32::MAX)); + assert!(sequence_at_or_before(0, (1 << 31) - 1), "just inside half the space"); + assert!(!sequence_at_or_before(0, 1 << 31), "half the space away is not before"); + } } diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index cccff92f..60596ee5 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -2983,6 +2983,324 @@ fn only_reliable_non_sequenced_writes_are_accepted_on_a_receipt_session() -> Res Ok(()) } +/// `bytes` with the MessagePack fixstr `from` replaced by the fixstr `to`, which may be blank. +fn swap_fixstr(bytes: &[u8], from: &str, to: &str) -> Vec { + assert!(from.len() < 32 && to.len() < 32); + let mut needle = vec![0xa0 | from.len() as u8]; + needle.extend_from_slice(from.as_bytes()); + let at = bytes.windows(needle.len()).position(|window| window == needle).expect("marker is in the frame"); + let mut out = bytes[..at].to_vec(); + out.push(0xa0 | to.len() as u8); + out.extend_from_slice(to.as_bytes()); + out.extend_from_slice(&bytes[at + needle.len()..]); + out +} + +/// A `schemaId` or `recordKey` that is present but empty or only whitespace names nothing: the write is refused +/// `message_invalid` like a frame that does not read (field "message", the write's id), never reaches the store, +/// and the session goes on (write-receipt.md, rule 5; vector `error_v1_empty_schema_id_is_unreadable_and_names_the_write`). +#[test] +fn a_write_whose_schema_id_or_record_key_names_nothing_is_refused_and_never_handed_to_the_store() -> Result<()> { + let blanks = ["", " ", "\t \n"]; + let mut connection_id = 300; + for blank in blanks { + for blank_field in ["schemaId", "recordKey"] { + for operation in ["put", "delete"] { + connection_id += 1; + let (schema_id, record_key) = match blank_field { + "schemaId" => (blank, "note:1"), + _ => ("test.raw.v1", blank), + }; + // The encoder refuses a blank field, so encode a marker and swap the blank into the bytes. + let bad = if operation == "put" { + let mut record = document("zz-key-zz", vec![1, 2, 3]); + record.schema_id = "zz-schema-zz".into(); + encode_cultnet_message_to_vec( + &CultNetMessage::DocumentPutRaw { message_id: "bad-1".into(), document: record }, + CultNetWireContract::CultNetSchemaV0, + )? + } else { + encode_cultnet_message_to_vec( + &CultNetMessage::DocumentDelete { + message_id: "bad-1".into(), + schema_id: "zz-schema-zz".into(), + record_key: "zz-key-zz".into(), + }, + CultNetWireContract::CultNetSchemaV0, + )? + }; + let bad = swap_fixstr(&bad, "zz-schema-zz", schema_id); + let bad = swap_fixstr(&bad, "zz-key-zz", record_key); + let label = format!("{operation} with {blank_field} {blank:?}"); + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = client(server.local_addr()?, connection_id)?; + connect(&mut server, &mut [&mut peer])?; + send_reliable(&mut peer, &receipt_hello())?; + peer.send_reliable("schema", bad)?; + send_reliable(&mut peer, &put("good-1", "note:2", vec![1]))?; + let answers = answers_after(&mut server, &mut peer, 2)?; + assert_eq!(refusal_of(&answers[0]), (Some(CultNetErrorCode::MessageInvalid), Some("bad-1".into())), "{label}"); + assert_eq!(error_text_and_field(&answers[0]).1, Some("message".into()), "{label}"); + assert_eq!(answers[1], admitted("good-1", "note:2"), "{label}: the session goes on"); + let state = sink.0.lock().unwrap(); + assert_eq!(state.authorized, vec!["good-1".to_string()], "{label}: the store was never asked about the blank write"); + assert_eq!(state.receipts.len(), 1, "{label}: only the good write was applied"); + } + } + } + Ok(()) +} + +/// The sequenced-channel refusal belongs to the frame that arrived sequenced. A reliable-sequenced packet that +/// fills the gap an earlier ordered packet was held behind delivers both frames in one go: the sequenced write is +/// refused, the ordered write it released is admitted. +#[test] +fn a_sequenced_packet_releasing_a_held_ordered_write_refuses_only_its_own() -> Result<()> { + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = RawPeer::connect(&mut server, 250)?; + peer.send(&receipt_hello())?; + server.poll_once()?; + let mut packet_for = |peer: &mut RawPeer, id: &str, ordered: bool, sequenced: bool| -> Result> { + let payload = encode_cultnet_message_to_vec(&put(id, &format!("note:{id}"), vec![1]), CultNetWireContract::CultNetSchemaV0)?; + peer.session.send_many( + "schema", + payload, + cultnet_rs::CultNetRudpSendOptions { reliable: true, ordered, sequenced, now_ms: 3, reliable_expire_after_ms: None }, + Some(1200), + ) + }; + let sequenced = packet_for(&mut peer, "s1", false, true)?; + let ordered = packet_for(&mut peer, "o1", true, false)?; + // The ordered write arrives first, one sequence ahead of the gap, and is held. + for packet in &ordered { + peer.send_packet(packet)?; + } + server.poll_once()?; + assert_eq!(sink.0.lock().unwrap().receipts.len(), 0, "the ordered write waits behind the gap"); + for packet in &sequenced { + peer.send_packet(packet)?; + } + server.poll_once()?; + let mut answers = Vec::new(); + for packet in peer.drain() { + for frame in peer.session.receive(&packet, 4)?.delivered { + answers.push(decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)?); + } + } + let refusals: Vec<_> = answers.iter().filter(|a| matches!(a, CultNetMessage::ErrorV1 { .. })).collect(); + assert_eq!(refusals.len(), 1, "only the sequenced write is refused: {answers:?}"); + assert_eq!(refusal_of(refusals[0]), (Some(CultNetErrorCode::MessageInvalid), Some("s1".into()))); + assert!(answers.contains(&admitted("o1", "note:o1")), "the released ordered write is admitted: {answers:?}"); + assert_eq!(sink.0.lock().unwrap().receipts.len(), 1, "and applied"); + Ok(()) +} + +/// The refusal of a write on a sequenced channel does not depend on the packet being the newest. A reliable-sequenced +/// packet that arrives after a newer one on its channel is superseded: the session delivers no frame for it, yet +/// the packet was acknowledged and will not be resent, so the server answers it from the packet's own payload. +#[test] +fn a_superseded_sequenced_write_is_still_refused() -> Result<()> { + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = RawPeer::connect(&mut server, 253)?; + peer.send(&receipt_hello())?; + server.poll_once()?; + let packet_for = |peer: &mut RawPeer, id: &str| -> Result> { + let payload = encode_cultnet_message_to_vec(&put(id, &format!("note:{id}"), vec![1]), CultNetWireContract::CultNetSchemaV0)?; + peer.session.send_many( + "schema", + payload, + cultnet_rs::CultNetRudpSendOptions { reliable: true, ordered: false, sequenced: true, now_ms: 3, reliable_expire_after_ms: None }, + Some(1200), + ) + }; + let older = packet_for(&mut peer, "old")?; + let newer = packet_for(&mut peer, "new")?; + let mut refused_ids = Vec::new(); + for packets in [&newer, &older] { + for packet in packets { + peer.send_packet(packet)?; + } + server.poll_once()?; + for packet in peer.drain() { + for frame in peer.session.receive(&packet, 4)?.delivered { + let answer = decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)?; + if matches!(answer, CultNetMessage::ErrorV1 { .. }) { + refused_ids.push(refusal_of(&answer).1.expect("a refusal names its write")); + } + } + } + } + assert_eq!(refused_ids, vec!["new".to_string(), "old".to_string()], "the superseded write is answered too"); + assert_eq!(sink.0.lock().unwrap().receipts.len(), 0, "and nothing was applied"); + Ok(()) +} + +/// One answer per write (write-receipt.md, rule 1): a sequenced packet the server already answered is answered +/// once, however often the peer sends it again, and a packet too far ahead to be received draws nothing until it +/// is received (the peer resends it, and the answer comes then). +#[test] +fn a_repeated_or_far_ahead_sequenced_write_draws_one_answer_not_one_per_send() -> Result<()> { + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = RawPeer::connect(&mut server, 256)?; + peer.send(&receipt_hello())?; + server.poll_once()?; + let packet_for = |peer: &mut RawPeer, id: &str| -> Result> { + let payload = encode_cultnet_message_to_vec(&put(id, &format!("note:{id}"), vec![1]), CultNetWireContract::CultNetSchemaV0)?; + peer.session.send_many( + "schema", + payload, + cultnet_rs::CultNetRudpSendOptions { reliable: true, ordered: false, sequenced: true, now_ms: 3, reliable_expire_after_ms: None }, + Some(1200), + ) + }; + let refusals_of = |peer: &mut RawPeer| -> Result> { + let mut ids = Vec::new(); + for packet in peer.drain() { + for frame in peer.session.receive(&packet, 4)?.delivered { + let answer = decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)?; + if matches!(answer, CultNetMessage::ErrorV1 { .. }) { + ids.push(refusal_of(&answer).1.expect("a refusal names its write")); + } + } + } + Ok(ids) + }; + // The same packet, sent three times (a resend whose acknowledgement was lost), is refused once. + let once = packet_for(&mut peer, "dup")?; + let mut refused = Vec::new(); + for _ in 0..3 { + for packet in &once { + peer.send_packet(packet)?; + } + server.poll_once()?; + refused.extend(refusals_of(&mut peer)?); + } + assert_eq!(refused, vec!["dup".to_string()], "a repeat of an answered write is not answered again"); + + // A packet far past the receive window is not received: no answer yet, and none per resend. + let ahead = packet_for(&mut peer, "ahead")?; + let mut far = ahead[0].clone(); + far.sequence = once[0].sequence + 5_000; + let mut refused = Vec::new(); + for _ in 0..3 { + peer.send_packet(&far)?; + server.poll_once()?; + refused.extend(refusals_of(&mut peer)?); + } + assert_eq!(refused, Vec::::new(), "an unreceived packet draws no answer"); + assert_eq!(sink.0.lock().unwrap().receipts.len(), 0); + Ok(()) +} + +/// A superseded sequenced packet is answered even when its arrival fills a gap and releases another write: the +/// frames that arrive with it do not stand in for its own. +#[test] +fn a_superseded_sequenced_write_is_refused_while_it_releases_a_held_ordered_write() -> Result<()> { + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = RawPeer::connect(&mut server, 255)?; + peer.send(&receipt_hello())?; + server.poll_once()?; + let packet_for = |peer: &mut RawPeer, id: &str, ordered: bool, sequenced: bool| -> Result> { + let payload = encode_cultnet_message_to_vec(&put(id, &format!("note:{id}"), vec![1]), CultNetWireContract::CultNetSchemaV0)?; + peer.session.send_many( + "schema", + payload, + cultnet_rs::CultNetRudpSendOptions { reliable: true, ordered, sequenced, now_ms: 3, reliable_expire_after_ms: None }, + Some(1200), + ) + }; + let older = packet_for(&mut peer, "old", false, true)?; + let ordered = packet_for(&mut peer, "o1", true, false)?; + let newer = packet_for(&mut peer, "new", false, true)?; + let mut answers = Vec::new(); + for packets in [&newer, &ordered, &older] { + for packet in packets { + peer.send_packet(packet)?; + } + server.poll_once()?; + for packet in peer.drain() { + for frame in peer.session.receive(&packet, 4)?.delivered { + answers.push(decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)?); + } + } + } + let mut refused: Vec = answers + .iter() + .filter(|a| matches!(a, CultNetMessage::ErrorV1 { .. })) + .map(|a| refusal_of(a).1.expect("a refusal names its write")) + .collect(); + refused.sort(); + assert_eq!(refused, vec!["new".to_string(), "old".to_string()], "{answers:?}"); + assert!(answers.contains(&admitted("o1", "note:o1")), "the released ordered write is admitted: {answers:?}"); + Ok(()) +} + +/// The refusal reaches a sequenced write however far apart its fragments' sequences sit: other traffic can take the +/// sequences between the first fragment and the last, further back than the duplicate test's receive window. +#[test] +fn a_sequenced_write_whose_fragments_span_more_than_the_receive_window_is_refused() -> Result<()> { + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = RawPeer::connect(&mut server, 254)?; + peer.send(&receipt_hello())?; + server.poll_once()?; + let payload = encode_cultnet_message_to_vec(&put("far", "note:far", vec![1; 64]), CultNetWireContract::CultNetSchemaV0)?; + let mut packets = peer.session.send_many( + "schema", + payload, + cultnet_rs::CultNetRudpSendOptions { reliable: true, ordered: false, sequenced: true, now_ms: 3, reliable_expire_after_ms: None }, + Some(32), + )?; + let last = packets.pop().expect("the write is fragmented"); + assert!(!packets.is_empty()); + let mut next = last.sequence; + let mut refused_ids = Vec::new(); + for packet in &packets { + peer.send_packet(packet)?; + server.poll_once()?; + } + // 5,000 reliable packets on another channel, in order, take the sequences between the fragments. + for count in 0..5_000 { + let mut filler = packets[0].clone(); + filler.channel_id = "filler".into(); + filler.sequenced = false; + filler.fragment_id = 0; + filler.fragment_index = 0; + filler.fragment_count = 0; + filler.payload = vec![0]; + filler.sequence = next; + next += 1; + peer.send_packet(&filler)?; + server.poll_once()?; + if count % 100 == 99 { + // Read what the server sent, so the socket buffer never holds back the refusal. + for packet in peer.drain() { + peer.session.receive(&packet, 4)?; + } + } + } + let mut last = last; + last.sequence = next; + peer.send_packet(&last)?; + server.poll_once()?; + for packet in peer.drain() { + for frame in peer.session.receive(&packet, 4)?.delivered { + let answer = decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0)?; + if matches!(answer, CultNetMessage::ErrorV1 { .. }) { + refused_ids.push(refusal_of(&answer).1.expect("a refusal names its write")); + } + } + } + assert_eq!(refused_ids, vec!["far".to_string()]); + assert_eq!(sink.0.lock().unwrap().receipts.len(), 0, "and nothing was applied"); + Ok(()) +} + /// A refused write is traffic: the peer that sends it is not idle, so its session outlives the idle timeout measured /// from the refusal and not from the packet before it. #[test] @@ -3122,3 +3440,189 @@ fn an_unreliable_refusal_that_cannot_be_queued_ends_the_session_as_a_local_failu assert_eq!(goodbye.payload, b"server could not answer a write".to_vec()); Ok(()) } + +fn vectors() -> serde_json::Value { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../contracts/cultnet/interop/write-receipt-vectors.json"); + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() +} + +/// The spec's one fixed text for a frame that does not read or a write that names nothing, read from the vector +/// that carries it, so a server and the spec cannot drift apart unseen. +fn unreadable_vector_text(vectors: &serde_json::Value) -> String { + let name = "error_v1_empty_schema_id_is_unreadable_and_names_the_write"; + let vector = vectors["wire"].as_array().unwrap().iter().find(|v| v["name"] == name).unwrap(); + vector["message"]["error"].as_str().unwrap().to_string() +} + +/// The put frame of a `blankFields` case: the valid document with the case's `set` applied. Serialized without the +/// typed encoder, because that refuses what the case is about. +fn blank_field_put(vectors: &serde_json::Value, set: &serde_json::Value) -> Vec { + blank_field_put_with_id(vectors, set, "m1") +} + +fn blank_field_put_with_id(vectors: &serde_json::Value, set: &serde_json::Value, message_id: &str) -> Vec { + #[derive(serde::Serialize)] + #[serde(rename_all = "camelCase")] + struct Put { + schema_version: &'static str, + message_id: String, + document: CultNetRawDocumentRecord, + } + let hex = set.get("payloadHex").and_then(|v| v.as_str()).unwrap_or(vectors["blankFields"]["validPutPayloadHex"].as_str().unwrap()); + let field = |name: &str, default: &str| set.get(name).and_then(|v| v.as_str()).unwrap_or(default).to_string(); + let optional = |name: &str| set.get(name).and_then(|v| v.as_str()).map(str::to_string); + let document = CultNetRawDocumentRecord { + schema_id: field("schemaId", "note.v0"), + record_key: field("recordKey", "note:1"), + stored_at: field("storedAt", "2026-11-08T00:00:00Z"), + payload_encoding: CultNetRawPayloadEncoding::Messagepack, + payload: (0..hex.len()).step_by(2).map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap()).collect(), + source_runtime_id: optional("sourceRuntimeId"), + source_agent_id: optional("sourceAgentId"), + source_role: optional("sourceRole"), + tags: set.get("tags").and_then(|v| v.as_array()).map(|tags| tags.iter().map(|t| t.as_str().unwrap().to_string()).collect()), + }; + rmp_serde::to_vec_named(&Put { schema_version: "cultnet.document_put_raw.v0", message_id: message_id.to_string(), document }).unwrap() +} + +/// Each `blankFields` case: a receipt-capable connection is answered with the admitted receipt, or with the one fixed +/// unreadable text naming the write, and the sink sees a document only when the case is admitted. +#[test] +fn a_put_that_names_nothing_is_refused_as_unreadable_naming_the_write_and_a_named_one_is_admitted() -> Result<()> { + let vectors = vectors(); + let fixed = unreadable_vector_text(&vectors); + assert_eq!(fixed, "message_invalid: the message could not be read"); + let cases = vectors["blankFields"]["cases"].as_array().unwrap(); + assert!(cases.len() >= 10); + for (index, case) in cases.iter().enumerate() { + let name = case["name"].as_str().unwrap(); + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = client(server.local_addr()?, 400 + index as u32)?; + connect(&mut server, &mut [&mut peer])?; + send_reliable(&mut peer, &receipt_hello())?; + peer.send_reliable("schema", blank_field_put(&vectors, &case["set"]))?; + let answers = answers_after(&mut server, &mut peer, 1)?; + match case["outcome"].as_str().unwrap() { + "admitted" => { + assert_eq!( + answers, + vec![CultNetMessage::WriteAdmitted { + message_id: "m1".into(), + operation: "put".into(), + schema_id: case["set"]["schemaId"].as_str().unwrap_or("note.v0").into(), + record_key: case["set"]["recordKey"].as_str().unwrap_or("note:1").into(), + }], + "{name}" + ); + assert_eq!(sink.0.lock().unwrap().receipts.len(), 1, "{name}"); + } + "refused" => { + assert_eq!(refusal_of(&answers[0]), (Some(CultNetErrorCode::MessageInvalid), Some("m1".into())), "{name}"); + assert_eq!(error_text_and_field(&answers[0]), (fixed.clone(), Some("message".into())), "{name}"); + assert_eq!(sink.0.lock().unwrap().receipts.len(), 0, "{name}: never applied"); + } + other => panic!("{name}: unknown outcome {other}"), + } + assert_eq!(server.session_count(), 1, "{name}: the session is kept"); + } + Ok(()) +} + +fn code_point_string(hex: &str, times: usize) -> String { + std::char::from_u32(u32::from_str_radix(hex, 16).unwrap()).unwrap().to_string().repeat(times) +} + +/// The Unicode White_Space set is the one blank rule: every listed code point, alone or repeated, blanks every field +/// the rule covers; U+200B, U+FEFF, U+180E and the other listed non-White_Space code points name something. +#[test] +fn blank_means_exactly_the_unicode_white_space_code_points_in_every_field() -> Result<()> { + let vectors = vectors(); + let fixed = unreadable_vector_text(&vectors); + let fields = ["schemaId", "recordKey", "storedAt", "sourceRuntimeId", "sourceAgentId", "sourceRole", "tags"]; + let space = vectors["blankFields"]["whiteSpaceCodePoints"].as_array().unwrap(); + let not_space = vectors["blankFields"]["notWhiteSpaceCodePoints"].as_array().unwrap(); + assert_eq!(space.len(), 25); + for (index, (hex, blank)) in space.iter().map(|h| (h, true)).chain(not_space.iter().map(|h| (h, false))).enumerate() { + let hex = hex.as_str().unwrap(); + for (field_index, field) in fields.iter().enumerate() { + // A session that is sent refusals is allowed to end, so each code point and field gets its own. + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = client(server.local_addr()?, 600 + (index * fields.len() + field_index) as u32)?; + connect(&mut server, &mut [&mut peer])?; + send_reliable(&mut peer, &receipt_hello())?; + assert_eq!(frames_after(&mut server, &mut peer, 1)?, vec![server_hello()]); + let mut admitted = 0; + for times in [1, 3] { + let text = code_point_string(hex, times); + let value = if *field == "tags" { serde_json::json!(["a", text]) } else { serde_json::json!(text) }; + let set = serde_json::json!({ *field: value }); + let id = format!("{hex}-{field}-{times}"); + peer.send_reliable("schema", blank_field_put_with_id(&vectors, &set, &id))?; + let answers = frames_after(&mut server, &mut peer, 1)?; + let what = format!("U+{hex} in {field} x{times}"); + assert!(!answers.is_empty(), "{what}: no answer"); + if blank { + assert_eq!(refusal_of(&answers[0]), (Some(CultNetErrorCode::MessageInvalid), Some(id)), "{what}"); + assert_eq!(error_text_and_field(&answers[0]), (fixed.clone(), Some("message".into())), "{what}"); + } else { + assert!(matches!(answers[0], CultNetMessage::WriteAdmitted { .. }), "{what} is a name: {:?}", answers[0]); + admitted += 1; + } + } + assert_eq!(sink.0.lock().unwrap().receipts.len(), admitted, "U+{hex} in {field}: only named writes are applied"); + } + } + Ok(()) +} + +/// The same cases on a connection that never opted in: the same refusal as `error.v0`, the same text, nothing applied. +#[test] +fn a_put_that_names_nothing_is_refused_the_same_way_on_a_legacy_connection() -> Result<()> { + let vectors = vectors(); + let fixed = unreadable_vector_text(&vectors); + for (index, case) in vectors["blankFields"]["cases"].as_array().unwrap().iter().enumerate() { + let name = case["name"].as_str().unwrap(); + let sink = Sink::default(); + let mut server = server(Default::default(), Clock::new(70_000), sink.clone(), Source::default())?; + let mut peer = client(server.local_addr()?, 500 + index as u32)?; + connect(&mut server, &mut [&mut peer])?; + let bytes = blank_field_put(&vectors, &case["set"]); + if case["outcome"] == "refused" { + let (code, details, error) = refusal_on_live_session(&mut server, &mut peer, bytes)?; + assert_eq!(code, Some(CultNetErrorCode::MessageInvalid), "{name}"); + assert_eq!(details.and_then(|d| d.field), Some("message".into()), "{name}"); + assert_eq!(error, fixed, "{name}"); + assert_eq!(sink.0.lock().unwrap().receipts.len(), 0, "{name}"); + } else { + peer.send_reliable("schema", bytes)?; + for _ in 0..2_000 { + server.poll_once()?; + if !sink.0.lock().unwrap().receipts.is_empty() { + break; + } + thread::sleep(Duration::from_millis(1)); + } + assert_eq!(sink.0.lock().unwrap().receipts.len(), 1, "{name}"); + } + } + Ok(()) +} + +/// An unreadable frame from a receipt connection is sent the one fixed text, with no decoder wording in it. +#[test] +fn an_unreadable_frame_on_a_receipt_connection_is_sent_exactly_the_fixed_text() -> Result<()> { + let vectors = vectors(); + let mut server = server(Default::default(), Clock::new(70_000), Sink::default(), Source::default())?; + let mut peer = client(server.local_addr()?, 450)?; + connect(&mut server, &mut [&mut peer])?; + send_reliable(&mut peer, &receipt_hello())?; + peer.send_reliable("schema", garbage())?; + let answers = answers_after(&mut server, &mut peer, 1)?; + assert_eq!( + error_text_and_field(&answers[0]), + (unreadable_vector_text(&vectors), Some("message".into())) + ); + Ok(()) +} diff --git a/packages/cultmesh-ts/CHANGELOG.md b/packages/cultmesh-ts/CHANGELOG.md index d06e753b..5df85ad3 100644 --- a/packages/cultmesh-ts/CHANGELOG.md +++ b/packages/cultmesh-ts/CHANGELOG.md @@ -5,8 +5,13 @@ All notable changes to `@gamecult/cultmesh-ts` are recorded here, following ## Unreleased +### Added + +- `publishRudpDocumentOnce` takes `writeReceipts: true`: it sends a hello listing `cultnet.write_admitted.v0` and `cultnet.error.v1` and, against a server that lists both back, resolves only on that write's `write_admitted`, rejects with `CultMeshRudpWriteRefusedError` (now also carrying an `error.v1`) on its refusal and with the new `CultMeshRudpWriteUnconfirmedError` (`reason`: `window_elapsed` after 5000 ms, `session_ended`, or `local_send_failed`) when nothing settles it. Without the option, or against a server that did not advertise, there is no hello and the window is 500 ms; a put nothing settled in it is unconfirmed too, no longer "published" (**behaviour change**: a server that applies a put but answers nothing now yields `CultMeshRudpWriteUnconfirmedError`, as the spec requires). A legacy server's echo of the put's id is not admission: only `write_admitted` is. The flush that sends the put is bounded by the result window, and a send not acknowledged by then is `local_send_failed`. `resultWindowMs` overrides either window. `publishRudpDocumentAndWaitForReceipt` is not changed. + ### Breaking +- `publishRudpDocumentOnce` no longer treats a window with no refusal as published: a put nothing settled in its result window (500 ms, or 5000 ms against a receipt-capable server) rejects `CultMeshRudpWriteUnconfirmedError`, and a legacy server's echo of the put's id is not admission. It now resolves `"admitted"` (only on a `write_admitted`) or `"sent"`. **Migration:** a caller whose server cannot answer a write yet (for example Odin, until it is receipt-capable) passes `sendOnly: true` per call and treats `"sent"` as "sent", never as admitted. Receipts stay opt-in (`writeReceipts: true`); neither mode is the default. - The package is renamed `cultmesh-ts` to `@gamecult/cultmesh-ts` (the repo already scopes `@gamecult/cultcache-ts`), so the unscoped name cannot be claimed by someone else. Import from `@gamecult/cultmesh-ts` and its subpaths; the API is unchanged. Depends on `@gamecult/cultnet-ts`. - `asSchemaAlias` is removed from `CultMeshDocumentHandle`, `CultMeshCollectionHandle` and their bound forms. Read the handle by the schema you mean. - `CultMeshDocumentCatalog` (`document`, `tryDocument`, `latest`, `replace`, `submitPrediction`, `authoritativeWriter`, `predictionWriter`, `watch`) and `CultMeshCollectionCatalog` (`collection`, `tryCollection`, `latest`, `watchChanges`) take `` and yield `CultMeshCatalogValue`: an explicit type argument wins, a CultCache document definition names its own value type, and a bare schema descriptor yields `unknown`. A value type is no longer inferred from a value or an expected result. The `parse` option is removed from these calls, and a lookup by type answers with that type's handle or none, not an alias of a compatible schema. diff --git a/packages/cultmesh-ts/package.json b/packages/cultmesh-ts/package.json index 92962cbc..39e0abba 100644 --- a/packages/cultmesh-ts/package.json +++ b/packages/cultmesh-ts/package.json @@ -24,7 +24,8 @@ "build": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json", "prepack": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json", "typecheck": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json --pretty false", - "test": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.test.json && node --expose-gc --test dist-test/test/*.test.js" + "test": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.test.json && node --expose-gc --test dist-test/test/*.test.js", + "test:interop": "npm --prefix ../.. run build --workspace @gamecult/cultcache-ts --workspace @gamecult/cultnet-ts && node ../../node_modules/typescript/bin/tsc -p tsconfig.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.test.json && node --test --test-force-exit dist-test/test/interop/write-receipt-interop.test.js" }, "keywords": [ "cultmesh", diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index f065dd83..2f734cfd 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -20,6 +20,10 @@ import { CultNetRudpSocketTransportConnection, rudpClientBindHost, CultNetSchemaCatalog, + CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS, + WriteTracker, + helloAdvertisesWriteReceipts, + resultWindowMs, cultNetMessageInvalidError, cultNetTextError, cultNetWriteNotAuthorizedError, @@ -44,6 +48,8 @@ import { type CultNetSchemaCatalogOptions, type CultNetSnapshotResponseRawMessage, type CultNetWireContract, + type WriteSettlement, + type WriteUnconfirmedReason, } from "@gamecult/cultnet-ts"; import { @@ -4189,8 +4195,8 @@ export interface CultMeshRudpDocumentServer { */ export class CultMeshRudpWriteRefusedError extends Error { readonly code: string | undefined; - readonly response: Extract; - constructor(response: Extract) { + readonly response: Extract; + constructor(response: Extract) { super(response.error); this.name = "CultMeshRudpWriteRefusedError"; this.code = response.code ?? undefined; @@ -4198,14 +4204,49 @@ export class CultMeshRudpWriteRefusedError extends Error { } } +/** + * Nothing settled the write (write-receipt.md, "unconfirmed"): the result window ran out with no answer, the + * session ended first, or the client's own send failed. Not success and not refusal; a caller that needs admission treats it as not admitted. + */ +export class CultMeshRudpWriteUnconfirmedError extends Error { + readonly reason: WriteUnconfirmedReason; + readonly messageId: string; + constructor(messageId: string, reason: WriteUnconfirmedReason) { + super(`Write ${messageId} was not confirmed: ${reason}.`); + this.name = "CultMeshRudpWriteUnconfirmedError"; + this.reason = reason; + this.messageId = messageId; + } +} + export interface CultMeshRudpDocumentPublishOptions extends CultMeshRudpPeerOptions { /** - * How long after the put's transport ack a refusal may still arrive. A reliable-transport ack is not - * admission; the outcome is the peer's result frame. A server that answers a put only on refusal sends no - * success frame, so the put is reported published once this window passes with no refusal; a success reply - * ends the wait early. Default 500 ms. + * How long, counted from the send, the put may wait for its result frame. A reliable-transport ack is not + * admission; the outcome is the peer's result frame. Default: 5000 ms against a server whose hello lists the + * write-receipt frames, 500 ms otherwise. A put nothing settled within the window is unconfirmed, never + * published, whatever the server advertised: only a `write_admitted` is admission. The send itself is also + * bounded by the window (`flushTimeoutMs` is the upper bound); a send not acknowledged by then is + * unconfirmed as `local_send_failed`. */ resultWindowMs?: number; + /** + * Declare the write-receipt capability: send a hello listing `cultnet.write_admitted.v0` and `cultnet.error.v1` + * before the put. A server that lists both back is receipt-capable: the put then resolves only on its + * `write_admitted`, rejects with `CultMeshRudpWriteRefusedError` on its `error.v1`, and rejects with + * `CultMeshRudpWriteUnconfirmedError` when nothing settles it. Unset, no hello is sent and the server answers + * as it always did. + */ + writeReceipts?: boolean; + /** With `writeReceipts`, how long to wait for the server's hello before treating it as legacy. Default 500 ms. */ + helloWaitMs?: number; + /** + * Send the put and report only that it was sent: no hello, no wait for a result frame. Resolves `"sent"` once the + * transport has acknowledged the put (`flushTimeoutMs`), rejects `CultMeshRudpWriteUnconfirmedError` + * (`local_send_failed`) if it cannot be sent, and never resolves `"admitted"`: whether the server applied or + * refused it is unknown. For callers whose server cannot answer a write yet. Opt-in per call; not combinable with + * `writeReceipts`. + */ + sendOnly?: boolean; messageId?: string; sourceRuntimeId?: string; sourceAgentId?: string; @@ -6175,44 +6216,88 @@ export class CultMesh { recordKey: string, value: CultCacheDocumentValue, options: CultMeshRudpDocumentPublishOptions = {}, - ): Promise { + ): Promise<"admitted" | "sent"> { requireNonEmpty(runtimeId, "runtimeId"); requireNonEmpty(recordKey, "recordKey"); + if (options.sendOnly && options.writeReceipts) throw new TypeError("sendOnly and writeReceipts cannot be combined."); const registry = new CultNetDocumentRegistry([binding]); const messageId = options.messageId ?? `${runtimeId}:${binding.definition.type}:${recordKey}`; + // Built before any connection and outside every try: a put that cannot be built is the caller's error, with its cause. + const put = registry.createRawDocumentPutMessage( + binding, + messageId, + recordKey, + value, + { + sourceRuntimeId: options.sourceRuntimeId ?? runtimeId, + sourceAgentId: options.sourceAgentId, + sourceRole: options.sourceRole, + tags: options.tags, + }, + ); const peer = await CultMesh.createRudpPeer(runtimeId, connectionId, endpoint, options); try { - // A transport ack is not admission: the put completes on its result frame. A refusal rejects with the - // typed error whether it arrives before the ack, after it, or inside the result window. - let refusal: CultMeshRudpWriteRefusedError | undefined; - let succeeded = false; + if (options.sendOnly) { + try { + peer.send(put); + await peer.flush(options.flushTimeoutMs ?? 30_000); + } catch { + throw new CultMeshRudpWriteUnconfirmedError(messageId, "local_send_failed"); + } + return "sent"; + } + // A transport ack is not admission: the put completes on its result frame, and the WriteTracker alone decides + // how it settles (write-receipt.md, "Client rules"). This function only maps the settlement to resolve/throw. + let receiptCapable = false; + let tracker: WriteTracker | undefined; + let settlement: WriteSettlement | undefined; let wake: (() => void) | undefined; + let serverHello: (() => void) | undefined; peer.on("message", (message: CultNetMessage) => { - if (message.schemaVersion === "cultnet.error.v0") refusal ??= new CultMeshRudpWriteRefusedError(message); - else if ("messageId" in message && message.messageId === messageId) succeeded = true; - else return; - wake?.(); + if (message.schemaVersion === "cultnet.hello.v0") { + receiptCapable = helloAdvertisesWriteReceipts(message); + serverHello?.(); + } else { + tracker?.frame(message, Date.now()); + } }); - peer.send(registry.createRawDocumentPutMessage( - binding, - messageId, - recordKey, - value, - { - sourceRuntimeId: options.sourceRuntimeId ?? runtimeId, - sourceAgentId: options.sourceAgentId, - sourceRole: options.sourceRole, - tags: options.tags, - }, - )); - await peer.flush(options.flushTimeoutMs ?? 30_000); - if (!refusal && !succeeded) { + peer.on("close", () => tracker?.sessionEnd(Date.now())); + if (options.writeReceipts) { + const answered = new Promise((resolve) => { serverHello = resolve; }); + peer.sendHello({ + schemaVersion: "cultnet.hello.v0", runtimeId, runtimeKind: "cultmesh-ts", + supportedMessageVersions: [...CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS], + }); + let helloTimer: NodeJS.Timeout | undefined; + await Promise.race([answered, new Promise((resolve) => { helloTimer = setTimeout(resolve, options.helloWaitMs ?? 500); })]); + clearTimeout(helloTimer); + } + const writeTracker = new WriteTracker({ + windowMs: options.resultWindowMs ?? resultWindowMs(receiptCapable), + onSettle: (_id, result) => { settlement = result; wake?.(); }, + }); + tracker = writeTracker; + writeTracker.send(messageId, Date.now()); + try { + peer.send(put); + // The flush may not outlast the result window: a send nobody acknowledged by then is a local send failure. + const windowRemaining = writeTracker.nextDeadlineMs(Date.now()) ?? 0; + await peer.flush(Math.min(options.flushTimeoutMs ?? 30_000, Math.max(windowRemaining, 1))); + } catch { + // Our own send failed or was never acknowledged: the put may or may not have left. Never a refusal. + writeTracker.sendFailed(messageId, Date.now()); + } + while (!settlement) { + const remaining = writeTracker.nextDeadlineMs(Date.now()) ?? 0; await new Promise((resolve) => { - const timer = setTimeout(resolve, options.resultWindowMs ?? 500); + const timer = setTimeout(resolve, remaining); wake = () => { clearTimeout(timer); resolve(); }; }); + writeTracker.tick(Date.now()); } - if (refusal) throw refusal; + if (settlement.outcome === "refused") throw new CultMeshRudpWriteRefusedError(settlement.response); + if (settlement.outcome === "unconfirmed") throw new CultMeshRudpWriteUnconfirmedError(messageId, settlement.reason); + return "admitted"; } finally { peer.close(); } diff --git a/packages/cultmesh-ts/test/client-write-completion.test.ts b/packages/cultmesh-ts/test/client-write-completion.test.ts index 8dd122ed..5c4a1eaa 100644 --- a/packages/cultmesh-ts/test/client-write-completion.test.ts +++ b/packages/cultmesh-ts/test/client-write-completion.test.ts @@ -16,7 +16,7 @@ import { encodeRudpPacket, } from "@gamecult/cultnet-ts"; import { encodeWireValue } from "@gamecult/cultnet-ts/wire"; -import { CultMesh, CultMeshGrantAllWrites, CultMeshRudpWriteRefusedError } from "../src/index"; +import { CultMesh, CultMeshGrantAllWrites, CultMeshRudpWriteRefusedError, CultMeshRudpWriteUnconfirmedError } from "../src/index"; const isTheRefusal = (error: unknown): boolean => error instanceof CultMeshRudpWriteRefusedError && error.code === "write_not_authorized"; @@ -100,7 +100,7 @@ for (const order of orders) { }); } -test("publishRudpDocumentOnce still publishes a put the server admitted", async () => { +test("a put the server applied but did not answer is unconfirmed, never published", async () => { const connectionId = nextConnection++; const puts: string[] = []; const server = CultMesh.createRudpDocumentServer("completion-admit", connectionId, { @@ -111,7 +111,10 @@ test("publishRudpDocumentOnce still publishes a put the server admitted", async }); await server.start(); try { - await CultMesh.publishRudpDocumentOnce("completion-admit-client", connectionId, `rudp://127.0.0.1:${server.bind.port}`, binding, "tests:completion:a", { noteId: "a", text: "x" }, { resendDelayMs: 50, resendPollMs: 5, resultWindowMs: 200 }); - assert.deepEqual(puts, ["tests:completion:a"]); + await assert.rejects( + CultMesh.publishRudpDocumentOnce("completion-admit-client", connectionId, `rudp://127.0.0.1:${server.bind.port}`, binding, "tests:completion:a", { noteId: "a", text: "x" }, { resendDelayMs: 50, resendPollMs: 5, resultWindowMs: 200 }), + (error: unknown) => error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed", + ); + assert.deepEqual(puts, ["tests:completion:a"], "the server did apply it; this server just does not answer"); } finally { server.close(); } }); diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index 90ff38f9..68429969 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -21,7 +21,7 @@ import { type CultNetMessage, type CultNetSnapshotResponseRawMessage, } from "@gamecult/cultnet-ts"; -import { CultMesh, CultMeshGrantAllWrites, CultMeshRudpUnservableDocumentError } from "../src/index"; +import { CultMesh, CultMeshGrantAllWrites, CultMeshRudpUnservableDocumentError, CultMeshRudpWriteUnconfirmedError } from "../src/index"; // A record's payload as the bytes a peer would put on the wire. const payloadOf = (value: unknown) => documentPayloadFromBytes(encodeWireValue(value)); @@ -2968,25 +2968,30 @@ test("CultMesh TS publishes one registered document to a RUDP catalog", async () try { await server.start(); - await CultMesh.publishRudpDocumentOnce( - "cultmesh-ts-muninn", - connectionId, - `rudp://127.0.0.1:${server.bind.port}`, - defineCultNetDocumentBinding({ definition: noteDocument }), - "note:odin", - { - noteId: "note:odin", - body: "pay respects once", - }, - { - resendDelayMs: 25, - resendPollMs: 5, - maxFragmentBytes: 1024, - maxPendingReliablePackets: 16, - connectTimeoutMs: 1_000, - flushTimeoutMs: 25, - sourceRole: "test-provider", - }, + // This server answers a put with nothing, so the writer cannot know the put landed: unconfirmed, though it did. + await assert.rejects( + CultMesh.publishRudpDocumentOnce( + "cultmesh-ts-muninn", + connectionId, + `rudp://127.0.0.1:${server.bind.port}`, + defineCultNetDocumentBinding({ definition: noteDocument }), + "note:odin", + { + noteId: "note:odin", + body: "pay respects once", + }, + { + resendDelayMs: 25, + resendPollMs: 5, + maxFragmentBytes: 1024, + maxPendingReliablePackets: 16, + connectTimeoutMs: 1_000, + flushTimeoutMs: 25, + resultWindowMs: 100, + sourceRole: "test-provider", + }, + ), + (error: unknown) => error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed", ); await waitFor(() => received !== undefined, "published RUDP document"); diff --git a/packages/cultmesh-ts/test/interop/write-receipt-interop.test.ts b/packages/cultmesh-ts/test/interop/write-receipt-interop.test.ts new file mode 100644 index 00000000..092d5ffb --- /dev/null +++ b/packages/cultmesh-ts/test/interop/write-receipt-interop.test.ts @@ -0,0 +1,434 @@ +// The TypeScript write-receipt client (cultnet-ts WriteTracker and decoder, cultmesh-ts one-shot writer) against the two real +// receipt servers over loopback, as child processes on ephemeral ports: +// +// rust packages/cultmesh-rs/examples/receipt_interop_server.rs, the RUDP document server, reached over RUDP. +// csharp tests/GameCult.Networking.InteropPeer `receipt-serve`, CultNetDatabaseServer on Server (LiteNetLib). TypeScript has no +// LiteNetLib client, so a second child, `receipt-relay`, carries bytes between the test and the server (4-byte +// big-endian length, then the CultNet frame: CultNetPeer's own stream framing). It decodes and judges nothing. +// +// Every scenario runs against both targets; its outcome is read from the WriteTracker (admitted, refused, unconfirmed), and the +// server's own stdout facts say what was committed. Contract: contracts/cultnet/interop/write-receipt.md and its vectors. +// +// Needs cargo and dotnet; run it with `npm run test:interop` in packages/cultmesh-ts (CARGO and DOTNET override the commands; +// RECEIPT_INTEROP_PREBUILT=1 skips the two builds). +import assert from "node:assert/strict"; +import { execFile, spawn, spawnSync, type ChildProcess } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { Duplex } from "node:stream"; +import { after, before, beforeEach, describe, test } from "node:test"; +import { promisify } from "node:util"; +import { encode } from "@msgpack/msgpack"; +import { z } from "zod"; +import { defineDocumentType } from "@gamecult/cultcache-ts"; +import { + CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS, + CultNetPeer, + WriteTracker, + defineCultNetDocumentBinding, + helloAdvertisesWriteReceipts, + resultWindowMs, + type CultNetErrorV1Message, + type CultNetHelloMessage, + type CultNetMessage, + type WriteSettlement, +} from "@gamecult/cultnet-ts"; +import { CultMesh, CultMeshRudpWriteRefusedError, CultMeshRudpWriteUnconfirmedError } from "../../src/index"; + +const execFileAsync = promisify(execFile); +// dist-test/test/interop -> the repository root +const repoRoot = resolve(__dirname, "..", "..", "..", "..", ".."); +const cargo = process.env.CARGO ?? "cargo"; +const dotnet = process.env.DOTNET ?? "dotnet"; +const rustManifestDir = join(repoRoot, "packages", "cultmesh-rs"); +const csharpProject = join(repoRoot, "tests", "GameCult.Networking.InteropPeer", "GameCult.Networking.InteropPeer.csproj"); +const csharpDll = join(repoRoot, "bin", "GameCult.Networking.InteropPeer", "Debug", "net10.0", "GameCult.Networking.InteropPeer.dll"); +// Set when the server binaries were built beforehand (the builds themselves cannot start under a tight address-space cap). +const prebuilt = process.env.RECEIPT_INTEROP_PREBUILT === "1"; +const vectors = JSON.parse(readFileSync(join(repoRoot, "contracts", "cultnet", "interop", "write-receipt-vectors.json"), "utf8")); + +const SCHEMA_ID = "receipt.interop_note.v1"; +const UNREADABLE = "message_invalid: the message could not be read"; +const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms)); + +async function waitFor(predicate: () => boolean, what: string, ms = 5_000): Promise { + const startedAt = Date.now(); + while (!predicate()) { + if (Date.now() - startedAt > ms) throw new Error(`timed out waiting for ${what}`); + await sleep(5); + } +} + +// ---- the servers ------------------------------------------------------------------------------------------------------- + +interface Fact { event: string; recordKey?: string; messageId?: string; [key: string]: unknown } + +/** A running server child and the JSON facts it prints on stdout. */ +class ServerProcess { + readonly facts: Fact[] = []; + stderr = ""; + port = 0; + constructor(readonly child: ChildProcess) { + let pending = ""; + child.stdout!.on("data", (chunk: Buffer) => { + pending += chunk.toString("utf8"); + for (let at = pending.indexOf("\n"); at >= 0; at = pending.indexOf("\n")) { + const line = pending.slice(0, at).trim(); + pending = pending.slice(at + 1); + if (line) this.facts.push(JSON.parse(line) as Fact); + } + }); + child.stderr!.on("data", (chunk: Buffer) => { this.stderr += chunk.toString("utf8"); }); + } + /** How many times `event` was printed for `recordKey`. */ + count(event: string, recordKey: string): number { + return this.facts.filter((fact) => fact.event === event && fact.recordKey === recordKey).length; + } + async stop(): Promise { + this.child.stdin!.end(); + await new Promise((done) => { + const killer = setTimeout(() => this.child.kill("SIGKILL"), 5_000); + this.child.once("exit", () => { clearTimeout(killer); done(); }); + if (this.child.exitCode !== null) done(); + }); + } +} + +async function launch(command: string, args: string[]): Promise { + const server = new ServerProcess(spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] })); + await waitFor(() => server.facts.some((fact) => fact.event === "listening") || server.child.exitCode !== null, "the server to listen", 60_000); + const listening = server.facts.find((fact) => fact.event === "listening"); + if (!listening) throw new Error(`the server exited before listening:\n${server.stderr}`); + server.port = listening.port as number; + return server; +} + +/** One connection to a server: the peer that speaks CultNet, and how to close it. */ +interface Connection { peer: CultNetPeer; close(): void } + +interface Target { + name: string; + /** Shard fields the server's database requires on a write, if any. */ + shard?: { shardId: string; shardEpoch: number }; + /** A document payload this target's store reads. */ + payload(text: string): Uint8Array; + start(): Promise; + connect(server: ServerProcess): Promise; +} + +let nextConnectionId = 0x20206000; + +const rust: Target = { + name: "rust", + payload: (text) => encode({ text }), + async start() { + if (!prebuilt) await execFileAsync(cargo, ["build", "--example", "receipt_interop_server", "--message-format", "short"], { cwd: rustManifestDir }); + const metadata = spawnSync(cargo, ["metadata", "--format-version", "1", "--no-deps"], { cwd: rustManifestDir, encoding: "utf8" }); + if (metadata.status !== 0) throw new Error(`cargo metadata failed: ${metadata.stderr}`); + const exe = join(JSON.parse(metadata.stdout).target_directory, "debug", "examples", `receipt_interop_server${process.platform === "win32" ? ".exe" : ""}`); + return launch(exe, []); + }, + async connect(server) { + const peer = await CultMesh.createRudpPeer("receipt-interop", nextConnectionId++, { host: "127.0.0.1", port: server.port, uri: `rudp://127.0.0.1:${server.port}` }); + return { peer, close: () => peer.close() }; + }, +}; + +// The C# server admits 30 connection requests per IP per minute (Server.MaxConnectionAttemptsPerMinute) and answers the rest with +// no hello. Every scenario wants a fresh session, so before each C# test the harness waits until the last minute holds at most +// CONNECTIONS_PER_MINUTE connections, leaving room for the two a test may open. The server's limit stays as it is. +const CONNECTIONS_PER_MINUTE = 24; +const connectedAt: number[] = []; +async function awaitConnectionBudget(): Promise { + for (;;) { + const now = Date.now(); + while (connectedAt.length > 0 && now - connectedAt[0] >= 61_000) connectedAt.shift(); + if (connectedAt.length <= CONNECTIONS_PER_MINUTE) return; + await sleep(connectedAt[0] + 61_000 - now); + } +} + +const csharp: Target = { + name: "csharp", + shard: { shardId: "receipt-interop-shard", shardEpoch: 1 }, + payload: (text) => encode([text]), + async start() { + if (!prebuilt) await execFileAsync(dotnet, ["build", csharpProject, "-nologo", "-v", "q"], { cwd: repoRoot, maxBuffer: 64 * 1024 * 1024 }); + return launch(dotnet, [csharpDll, "receipt-serve"]); + }, + async connect(server) { + connectedAt.push(Date.now()); + const relay = spawn(dotnet, [csharpDll, "receipt-relay", "--port", String(server.port)], { stdio: ["pipe", "pipe", "ignore"] }); + const peer = new CultNetPeer(Duplex.from({ readable: relay.stdout!, writable: relay.stdin! }), { wireContract: "cultnet.schema.v0" }); + return { peer, close: () => { relay.stdin!.end(); relay.kill(); } }; + }, +}; + +// ---- a client session: one connection, the frames it saw, one WriteTracker per write ----------------------------------------- + +class Session { + readonly frames: CultNetMessage[] = []; + readonly invalid: Error[] = []; + private readonly trackers = new Set(); + private serverReceipts = false; + private constructor(readonly target: Target, private readonly connection: Connection) { + connection.peer.on("message", (message: CultNetMessage) => { + if (message.schemaVersion === "cultnet.hello.v0") this.serverReceipts = helloAdvertisesWriteReceipts(message); + this.frames.push(message); + for (const tracker of this.trackers) tracker.frame(message, Date.now()); + }); + connection.peer.on("invalidMessage", (error: Error) => this.invalid.push(error)); + connection.peer.on("close", () => { for (const tracker of this.trackers) tracker.sessionEnd(Date.now()); }); + } + + static async open(target: Target, server: ServerProcess): Promise { + return new Session(target, await target.connect(server)); + } + + /** Declares the receipt capability and waits for the server's own hello. */ + async hello(versions: readonly string[] = CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS): Promise { + this.connection.peer.sendHello({ schemaVersion: "cultnet.hello.v0", runtimeId: "receipt-interop", runtimeKind: "cultmesh-ts", supportedMessageVersions: [...versions] }); + await waitFor(() => this.frames.some((frame) => frame.schemaVersion === "cultnet.hello.v0"), "the server's hello"); + return this.frames.find((frame) => frame.schemaVersion === "cultnet.hello.v0") as CultNetHelloMessage; + } + + put(messageId: string, recordKey: string, text: string, document: Record = {}): CultNetMessage { + return this.shard({ + schemaVersion: "cultnet.document_put_raw.v0", + messageId, + document: { + schemaId: SCHEMA_ID, recordKey, storedAt: new Date().toISOString(), payloadEncoding: "messagepack", + payload: this.target.payload(text), ...document, + }, + }); + } + + delete(messageId: string, recordKey: string): CultNetMessage { + return this.shard({ schemaVersion: "cultnet.document_delete.v0", messageId, schemaId: SCHEMA_ID, recordKey }); + } + + private shard(message: unknown): CultNetMessage { + return { ...(message as object), ...this.target.shard } as CultNetMessage; + } + + /** + * Sends one write and settles it with its own tracker, windowed by what the server advertised (5000 ms against a receipt + * server, 500 ms otherwise). Only the tracker decides the outcome. + */ + async write(message: CultNetMessage): Promise { + const messageId = (message as { messageId: string }).messageId; + const tracker = new WriteTracker({ windowMs: resultWindowMs(this.serverReceipts) }); + this.trackers.add(tracker); + tracker.send(messageId, Date.now()); + this.connection.peer.send(message); + for (;;) { + tracker.tick(Date.now()); + const state = tracker.state(messageId)!; + if (state.outcome !== "pending") return state; + await sleep(Math.min(20, tracker.nextDeadlineMs(Date.now()) ?? 20)); + } + } + + /** Frames of `schemaVersion` that name `messageId`. */ + answers(messageId: string, schemaVersion: string): CultNetMessage[] { + return this.frames.filter((frame) => frame.schemaVersion === schemaVersion && (frame as { messageId?: string }).messageId === messageId); + } + + close(): void { this.connection.close(); } +} + +function refusal(settlement: WriteSettlement): CultNetErrorV1Message { + assert.equal(settlement.outcome, "refused", JSON.stringify(settlement)); + return (settlement as Extract).response as CultNetErrorV1Message; +} + +// ---- the scenarios, run against each server ----------------------------------------------------------------------------------- + +for (const target of [rust, csharp]) { + describe(`write receipt, TypeScript client against the real ${target.name} server`, () => { + let server: ServerProcess; + let session: Session | undefined; + before(async () => { server = await target.start(); }, { timeout: 180_000 }); + after(async () => { session?.close(); await server?.stop(); }); + beforeEach(async () => { if (target === csharp) await awaitConnectionBudget(); }, { timeout: 90_000 }); + + /** A fresh receipt session (hello sent, the server's hello read) for a scenario. */ + async function receiptSession(): Promise { + session?.close(); + session = await Session.open(target, server); + const hello = await session.hello(); + assert.ok(helloAdvertisesWriteReceipts(hello), "the server's hello lists both receipt frames"); + return session; + } + + test("hello listing both frames: the server answers with its own hello listing both, then a put is receipted after it", { timeout: 30_000 }, async () => { + const s = await receiptSession(); + assert.equal(s.frames[0].schemaVersion, "cultnet.hello.v0"); + const settlement = await s.write(s.put("hello-1", "hello:a", "one")); + assert.deepEqual(settlement, { outcome: "admitted" }); + assert.deepEqual(s.frames.map((frame) => frame.schemaVersion), ["cultnet.hello.v0", "cultnet.write_admitted.v0"]); + }); + + test("a hello listing only one of the two frames does not opt in: no receipt, and the put is applied", { timeout: 30_000 }, async () => { + for (const listed of CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS) { + session?.close(); + session = await Session.open(target, server); + session.hello([listed]).catch(() => undefined); // a server may stay silent to a hello that does not opt in + await sleep(300); + const settlement = await session.write(session.put(`half-${listed}`, `half:${listed}`, "one")); + assert.deepEqual(settlement, { outcome: "unconfirmed", reason: "window_elapsed" }, `listing only ${listed}`); + assert.ok(!session.frames.some((frame) => frame.schemaVersion === "cultnet.write_admitted.v0" || frame.schemaVersion === "cultnet.error.v1")); + await waitFor(() => server.count("applied", `half:${listed}`) === 1, "the put to be applied"); + } + }); + + test("put admitted: the receipt echoes the write and the store has it once", { timeout: 30_000 }, async () => { + const s = await receiptSession(); + const settlement = await s.write(s.put("put-1", "put:a", "one")); + assert.deepEqual(settlement, { outcome: "admitted" }); + assert.deepEqual(s.answers("put-1", "cultnet.write_admitted.v0"), [ + { schemaVersion: "cultnet.write_admitted.v0", messageId: "put-1", operation: "put", schemaId: SCHEMA_ID, recordKey: "put:a" }, + ]); + await waitFor(() => server.count("applied", "put:a") === 1, "the put to be applied"); + }); + + // The Rust RUDP document server has no delete: its sink only accepts documents, and every delete on a receipt session is + // answered with a refusal (rudp_document_server.rs, deletes_on_a_receipt_session_are_refused_one_by_one). The spec + // (Server rules 1 to 3) has a delete admitted and receipted like a put. + test("delete admitted: the receipt says operation delete and the store drops the record", { + timeout: 30_000, + todo: target.name === "rust" ? "the Rust RUDP document server refuses every delete; there is no delete port in CultMeshRudpRawDocumentSink" : false, + }, async () => { + const s = await receiptSession(); + assert.deepEqual(await s.write(s.put("del-put", "del:a", "one")), { outcome: "admitted" }); + assert.deepEqual(await s.write(s.delete("del-1", "del:a")), { outcome: "admitted" }); + assert.deepEqual(s.answers("del-1", "cultnet.write_admitted.v0"), [ + { schemaVersion: "cultnet.write_admitted.v0", messageId: "del-1", operation: "delete", schemaId: SCHEMA_ID, recordKey: "del:a" }, + ]); + await waitFor(() => server.count("removed", "del:a") === 1, "the delete to be applied"); + }); + + test("refused write: an error.v1 carrying the write's id, and nothing is applied", { timeout: 30_000 }, async () => { + const s = await receiptSession(); + const response = refusal(await s.write(s.put("deny-1", "refuse:a", "one"))); + assert.equal(response.schemaVersion, "cultnet.error.v1"); + assert.equal(response.messageId, "deny-1"); + assert.equal(response.code, "write_not_authorized"); + // The session is kept: the next write on it is admitted. + assert.deepEqual(await s.write(s.put("deny-2", "deny:b", "one")), { outcome: "admitted" }); + assert.equal(server.count("applied", "refuse:a"), 0); + }); + + test("resend of the same id and content on the same session: re-receipted, applied once", { timeout: 30_000 }, async () => { + const s = await receiptSession(); + assert.deepEqual(await s.write(s.put("resend-1", "resend:a", "one")), { outcome: "admitted" }); + assert.deepEqual(await s.write(s.put("resend-1", "resend:a", "one")), { outcome: "admitted" }); + const receipts = s.answers("resend-1", "cultnet.write_admitted.v0"); + assert.equal(receipts.length, 2); + assert.deepEqual(receipts[0], receipts[1]); + await sleep(200); // a second application would be printed by now + assert.equal(server.count("applied", "resend:a"), 1); + }); + + test("same id with different content: message_invalid naming the id, never a receipt, the first write untouched", { timeout: 30_000 }, async () => { + const s = await receiptSession(); + assert.deepEqual(await s.write(s.put("clash-1", "clash:a", "one")), { outcome: "admitted" }); + const response = refusal(await s.write(s.put("clash-1", "clash:a", "other"))); + assert.equal(response.code, "message_invalid"); + assert.equal(response.messageId, "clash-1"); + assert.equal(response.details?.field, "messageId"); + assert.equal(s.answers("clash-1", "cultnet.write_admitted.v0").length, 1, "no receipt for the changed write"); + await sleep(200); + assert.equal(server.count("applied", "clash:a"), 1); + }); + + // Each case of the vectors' blankFields section: a document that names nothing is refused as an unreadable frame, with the + // write's id and the fixed text, and never applied; a document that is merely missing optional fields is admitted. + for (const blank of vectors.blankFields.cases as { name: string; set: Record; outcome: "admitted" | "refused" }[]) { + test(`blank-field vector ${blank.name}: ${blank.outcome}`, { timeout: 30_000 }, async () => { + const s = await receiptSession(); + const { payloadHex, ...fields } = blank.set; + // A case that sets recordKey replaces the harness key, so the store is read under the key the server actually saw. + const recordKey = typeof fields.recordKey === "string" ? fields.recordKey : `blank:${blank.name}`; + const message = s.put(`blank-${blank.name}`, recordKey, "one", fields); + const sent = (message as unknown as { document: Record }).document; + for (const [key, value] of Object.entries(fields)) if (value === null) delete sent[key]; // nil means absent on the wire here + if (payloadHex === "") sent.payload = new Uint8Array(); + const settlement = await s.write(message); + if (blank.outcome === "admitted") { + assert.deepEqual(settlement, { outcome: "admitted" }); + await waitFor(() => server.count("applied", recordKey) === 1, "the put to be applied"); + return; + } + const response = refusal(settlement); + assert.equal(response.code, "message_invalid"); + assert.equal(response.error, UNREADABLE); + assert.equal(response.details?.field, "message"); + assert.equal(response.messageId, `blank-${blank.name}`); + await sleep(200); + assert.equal(server.count("applied", recordKey), 0); + }); + } + + test("a delete that names nothing is refused as unreadable with its id", { timeout: 30_000 }, async () => { + const s = await receiptSession(); + const message = s.delete("blank-del", "blank:del"); + (message as unknown as { schemaId: string }).schemaId = ""; + const response = refusal(await s.write(message)); + assert.equal(response.code, "message_invalid"); + assert.equal(response.error, UNREADABLE); + assert.equal(response.details?.field, "message"); + assert.equal(response.messageId, "blank-del"); + }); + + test("legacy client (no hello): no receipt frames, the write is applied, and its refusal is the old error.v0", { timeout: 30_000 }, async () => { + session?.close(); + session = await Session.open(target, server); + assert.deepEqual(await session.write(session.put("legacy-1", "legacy:a", "one")), { outcome: "unconfirmed", reason: "window_elapsed" }); + await waitFor(() => server.count("applied", "legacy:a") === 1, "the put to be applied"); + const refused = (await session.write(session.put("legacy-2", "refuse:legacy", "one"))) as Extract; + assert.equal(refused.outcome, "refused"); + assert.equal(refused.response.schemaVersion, "cultnet.error.v0"); + assert.deepEqual(session.frames.map((frame) => frame.schemaVersion), ["cultnet.error.v0"]); + assert.equal(session.invalid.length, 0); + }); + }); +} + +// ---- the one-shot writer, which is the real cultmesh-ts client path, against the Rust RUDP server ---------------------------- +// (The C# server speaks LiteNetLib, not RUDP: no RUDP client path reaches it.) + +describe("write receipt, cultmesh-ts publishRudpDocumentOnce against the real rust server", () => { + const note = defineDocumentType({ type: "receipt.interop_note", schemaId: SCHEMA_ID, schema: z.object({ text: z.string() }), name: "text" }); + const binding = defineCultNetDocumentBinding({ definition: note }); + let server: ServerProcess; + before(async () => { server = await rust.start(); }, { timeout: 180_000 }); + after(async () => { await server?.stop(); }); + const endpoint = () => ({ host: "127.0.0.1", port: server.port, uri: `rudp://127.0.0.1:${server.port}` }); + + test("writeReceipts: the put resolves admitted on the receipt, after the server applied it", { timeout: 30_000 }, async () => { + const outcome = await CultMesh.publishRudpDocumentOnce("receipt-interop", nextConnectionId++, endpoint(), binding, "once:a", { text: "one" }, { writeReceipts: true, messageId: "once-1" }); + assert.equal(outcome, "admitted"); + await waitFor(() => server.count("applied", "once:a") === 1, "the put to be applied"); + }); + + test("writeReceipts: a refused put rejects with the server's error.v1 naming the put", { timeout: 30_000 }, async () => { + await assert.rejects( + CultMesh.publishRudpDocumentOnce("receipt-interop", nextConnectionId++, endpoint(), binding, "refuse:once", { text: "one" }, { writeReceipts: true, messageId: "once-2" }), + (error: unknown) => { + assert.ok(error instanceof CultMeshRudpWriteRefusedError); + assert.equal(error.response.schemaVersion, "cultnet.error.v1"); + assert.equal((error.response as CultNetErrorV1Message).messageId, "once-2"); + return true; + }, + ); + }); + + test("without writeReceipts the server stays silent: the put is unconfirmed, not admitted, though the server applied it", { timeout: 30_000 }, async () => { + await assert.rejects( + CultMesh.publishRudpDocumentOnce("receipt-interop", nextConnectionId++, endpoint(), binding, "once:legacy", { text: "one" }, { messageId: "once-3" }), + (error: unknown) => error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed", + ); + await waitFor(() => server.count("applied", "once:legacy") === 1, "the put to be applied"); + }); +}); diff --git a/packages/cultmesh-ts/test/write-receipt-client.test.ts b/packages/cultmesh-ts/test/write-receipt-client.test.ts new file mode 100644 index 00000000..072b89a3 --- /dev/null +++ b/packages/cultmesh-ts/test/write-receipt-client.test.ts @@ -0,0 +1,243 @@ +// Client side of contracts/cultnet/interop/write-receipt.md in the one-shot writer: with `writeReceipts` the put +// completes only on a write_admitted carrying its id; a refusal, a silent window and a legacy server each end as the +// spec says. Each test serves the client a fake RUDP peer that acknowledges the put and answers as scripted. +import assert from "node:assert/strict"; +import { createSocket, type Socket } from "node:dgram"; +import test from "node:test"; +import { z } from "zod"; +import { defineDocumentType } from "@gamecult/cultcache-ts"; +import { + CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS, + CultNetRudpSession, + decodeRudpPacket, + defineCultNetDocumentBinding, + encodeCultNetMessageForWire, + encodeRudpPacket, + type CultNetMessage, +} from "@gamecult/cultnet-ts"; +import { decodeWireValue, encodeWireValue } from "@gamecult/cultnet-ts/wire"; +import { CultMesh, CultMeshRudpWriteRefusedError, CultMeshRudpWriteUnconfirmedError } from "../src/index"; + +const note = defineDocumentType({ + type: "cultmesh.receipt_note", + schemaId: "cultmesh.receipt_note.v0", + schema: z.object({ noteId: z.string(), text: z.string() }), + name: "noteId", +}); +const binding = defineCultNetDocumentBinding({ definition: note }); +let nextConnection = 0x10206000; + +interface Script { + /** Does the server's hello list both receipt frames? */ + advertise: boolean; + /** What the server answers a put with, `delayMs` after it arrives. */ + answer: "admit" | "refuse" | "wrong-id" | "silence" | "goodbye" | "echo"; + delayMs?: number; + /** Acknowledge the reliable packets it receives? Default true. */ + ack?: boolean; +} + +async function fakeServer(connectionId: number, script: Script) { + const socket: Socket = createSocket("udp4"); + await new Promise((resolve) => socket.bind(0, "127.0.0.1", resolve)); + const session = new CultNetRudpSession({ connectionId, resendDelayMs: 50 }); + const timers = new Set(); + const seen: string[] = []; + let closed = false; + const send = (packet: Parameters[0], port: number, address: string) => { + if (!closed) socket.send(encodeRudpPacket(packet), port, address); + }; + const say = (message: CultNetMessage, port: number, address: string) => { + const packets = session.sendMany("schema", encodeWireValue(encodeCultNetMessageForWire(message)), { reliable: true, ordered: true, nowMs: Date.now() }); + packets.forEach((p) => send(p, port, address)); + }; + socket.on("message", (wire, remote) => { + const packet = decodeRudpPacket(wire); + const now = Date.now(); + if (packet.packetType === "connect") { + send(session.acceptConnect(packet, now), remote.port, remote.address); + return; + } + const result = session.receive(packet, now); + if (result.reply) send(result.reply, remote.port, remote.address); + for (const frame of result.delivered) { + if (frame.channelId !== "schema") continue; + const message = decodeWireValue(frame.payload) as { schemaVersion: string; messageId?: string }; + seen.push(message.schemaVersion); + if (message.schemaVersion === "cultnet.hello.v0") { + say({ + schemaVersion: "cultnet.hello.v0", runtimeId: "fake", runtimeKind: "fake", + ...(script.advertise ? { supportedMessageVersions: [...CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS] } : {}), + }, remote.port, remote.address); + continue; + } + if (message.schemaVersion !== "cultnet.document_put_raw.v0" || script.answer === "silence") continue; + const timer = setTimeout(() => { + timers.delete(timer); + if (script.answer === "echo") { + say({ schemaVersion: "cultnet.document_put_raw.v0", messageId: message.messageId!, document: { schemaId: "cultmesh.receipt_note.v0", recordKey: "tests:receipt:a", storedAt: "t", payloadEncoding: "messagepack", payload: new Uint8Array([1]) } } as unknown as CultNetMessage, remote.port, remote.address); + } else if (script.answer === "goodbye") { + send(session.endUnsendableSession(new Error("scripted goodbye")), remote.port, remote.address); + } else if (script.answer === "refuse") { + say({ schemaVersion: "cultnet.error.v1", error: "write_not_authorized", routingHint: null, code: "write_not_authorized", details: null, messageId: message.messageId! }, remote.port, remote.address); + } else { + const messageId = script.answer === "wrong-id" ? "someone-else" : message.messageId!; + say({ schemaVersion: "cultnet.write_admitted.v0", messageId, operation: "put", schemaId: "cultmesh.receipt_note.v0", recordKey: "tests:receipt:a" }, remote.port, remote.address); + } + }, script.delayMs ?? 20); + timers.add(timer); + } + if (packet.reliable && script.ack !== false) send(session.createAckForReceived(packet.sequence), remote.port, remote.address); + }); + return { endpoint: `rudp://127.0.0.1:${socket.address().port}`, seen, close: () => { closed = true; timers.forEach(clearTimeout); socket.close(); } }; +} + +const transport = { resendDelayMs: 50, resendPollMs: 5, flushTimeoutMs: 2_000 }; +const publish = (server: { endpoint: string }, options: Record) => + CultMesh.publishRudpDocumentOnce("receipt-client", nextConnection++, server.endpoint, binding, "tests:receipt:a", { noteId: "a", text: "x" }, { ...transport, ...options }); + +test("a receipt-capable server's write_admitted completes the put, past the legacy 500 ms window", async () => { + const server = await fakeServer(nextConnection, { advertise: true, answer: "admit", delayMs: 700 }); + try { + await publish(server, { writeReceipts: true }); + assert.deepEqual(server.seen.slice(0, 2), ["cultnet.hello.v0", "cultnet.document_put_raw.v0"]); + } finally { server.close(); } +}); + +test("a receipt-capable server's error.v1 refuses the put with its code", async () => { + const server = await fakeServer(nextConnection, { advertise: true, answer: "refuse" }); + try { + await assert.rejects(publish(server, { writeReceipts: true }), (error: unknown) => + error instanceof CultMeshRudpWriteRefusedError && error.code === "write_not_authorized" && error.response.schemaVersion === "cultnet.error.v1"); + } finally { server.close(); } +}); + +test("a receipt-capable server that stays silent leaves the put unconfirmed, never published", async () => { + const server = await fakeServer(nextConnection, { advertise: true, answer: "silence" }); + try { + await assert.rejects(publish(server, { writeReceipts: true, resultWindowMs: 250 }), (error: unknown) => + error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed"); + } finally { server.close(); } +}); + +test("a receipt for another id settles nothing", async () => { + const server = await fakeServer(nextConnection, { advertise: true, answer: "wrong-id" }); + try { + await assert.rejects(publish(server, { writeReceipts: true, resultWindowMs: 250 }), CultMeshRudpWriteUnconfirmedError); + } finally { server.close(); } +}); + +test("a server whose hello does not advertise leaves a silent put unconfirmed after the 500 ms window, never published", async () => { + const server = await fakeServer(nextConnection, { advertise: false, answer: "silence" }); + const started = Date.now(); + try { + await assert.rejects(publish(server, { writeReceipts: true }), (error: unknown) => + error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed"); + assert.ok(Date.now() - started >= 500, "the legacy window ran from the send"); + } finally { server.close(); } +}); + +test("a session that ends before any result leaves the put unconfirmed (session_ended), against a legacy server too", async () => { + for (const advertise of [false, true]) { + const server = await fakeServer(nextConnection, { advertise, answer: "goodbye" }); + try { + await assert.rejects(publish(server, { writeReceipts: true, resultWindowMs: 3_000 }), (error: unknown) => + error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "session_ended"); + } finally { server.close(); } + } +}); + +test("a put whose send is never acknowledged is unconfirmed as local_send_failed, not an untyped error", async () => { + const server = await fakeServer(nextConnection, { advertise: true, answer: "silence", ack: false }); + const started = Date.now(); + try { + await assert.rejects(publish(server, { writeReceipts: true, flushTimeoutMs: 300 }), (error: unknown) => + error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "local_send_failed"); + assert.ok(Date.now() - started < 2_500, "flushTimeoutMs bounds the send inside the 5 s window"); + } finally { server.close(); } +}); + +test("the flush is bounded by the result window: a send nobody acknowledges is local_send_failed at the window, not at the flush timeout", async () => { + const server = await fakeServer(nextConnection, { advertise: true, answer: "silence", ack: false }); + const started = Date.now(); + try { + await assert.rejects(publish(server, { writeReceipts: true, resultWindowMs: 300, flushTimeoutMs: 20_000 }), (error: unknown) => + error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "local_send_failed"); + assert.ok(Date.now() - started < 3_000, "it did not wait out the 20 s flush timeout"); + } finally { server.close(); } +}); + +test("a server that does not advertise receipts and echoes the put's id back has not admitted it", async () => { + const server = await fakeServer(nextConnection, { advertise: false, answer: "echo" }); + try { + await assert.rejects(publish(server, { writeReceipts: true, resultWindowMs: 300 }), (error: unknown) => + error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed"); + } finally { server.close(); } +}); + +test("a silent server never yields admitted, in either mode: the default is unconfirmed, sendOnly is the distinct outcome sent", async () => { + const dflt = await fakeServer(nextConnection, { advertise: false, answer: "silence" }); + try { + await assert.rejects(publish(dflt, { resultWindowMs: 200 }), CultMeshRudpWriteUnconfirmedError); + } finally { dflt.close(); } + const sendOnly = await fakeServer(nextConnection, { advertise: false, answer: "silence" }); + try { + const outcome = await publish(sendOnly, { sendOnly: true }); + assert.equal(outcome, "sent"); + assert.notEqual(outcome, "admitted"); + assert.deepEqual(sendOnly.seen, ["cultnet.document_put_raw.v0"], "sendOnly sends no hello"); + } finally { sendOnly.close(); } +}); + +test("only a write_admitted resolves admitted, and sendOnly does not wait for or act on an answer", async () => { + const admitting = await fakeServer(nextConnection, { advertise: true, answer: "admit" }); + try { + assert.equal(await publish(admitting, { writeReceipts: true }), "admitted"); + } finally { admitting.close(); } + const refusing = await fakeServer(nextConnection, { advertise: true, answer: "refuse", delayMs: 1 }); + try { + assert.equal(await publish(refusing, { sendOnly: true }), "sent", "a refusal is not awaited: sendOnly says only that the put was sent"); + } finally { refusing.close(); } +}); + +test("sendOnly fails local_send_failed when the send is never acknowledged", async () => { + const server = await fakeServer(nextConnection, { advertise: true, answer: "silence", ack: false }); + try { + await assert.rejects(publish(server, { sendOnly: true, flushTimeoutMs: 300 }), (error: unknown) => + error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "local_send_failed"); + } finally { server.close(); } +}); + +test("sendOnly keeps the cause of a put that cannot be built: it is not reported as local_send_failed", async () => { + const server = await fakeServer(nextConnection, { advertise: false, answer: "silence" }); + try { + await assert.rejects( + CultMesh.publishRudpDocumentOnce("receipt-client", nextConnection++, server.endpoint, binding, "tests:receipt:a", { noteId: 1 } as unknown as { noteId: string; text: string }, { ...transport, sendOnly: true }), + (error: unknown) => !(error instanceof CultMeshRudpWriteUnconfirmedError) && error instanceof Error, + ); + assert.deepEqual(server.seen, [], "nothing was sent"); + } finally { server.close(); } +}); + +test("the receipt path keeps the cause of a put that cannot be built: it is not reported as local_send_failed", async () => { + const server = await fakeServer(nextConnection, { advertise: true, answer: "admit" }); + try { + await assert.rejects( + CultMesh.publishRudpDocumentOnce("receipt-client", nextConnection++, server.endpoint, binding, "tests:receipt:a", { noteId: 1 } as unknown as { noteId: string; text: string }, { ...transport, writeReceipts: true }), + (error: unknown) => !(error instanceof CultMeshRudpWriteUnconfirmedError) && error instanceof Error, + ); + assert.ok(!server.seen.includes("cultnet.document_put_raw.v0"), "no put was sent"); + } finally { server.close(); } +}); + +test("sendOnly cannot be combined with writeReceipts", async () => { + await assert.rejects(publish({ endpoint: "rudp://127.0.0.1:9" }, { sendOnly: true, writeReceipts: true }), TypeError); +}); + +test("without writeReceipts no hello is sent and the receipt frames are never asked for", async () => { + const server = await fakeServer(nextConnection, { advertise: true, answer: "silence" }); + try { + await assert.rejects(publish(server, { resultWindowMs: 100 }), CultMeshRudpWriteUnconfirmedError); + assert.deepEqual(server.seen, ["cultnet.document_put_raw.v0"]); + } finally { server.close(); } +}); diff --git a/packages/cultnet-py/CHANGELOG.md b/packages/cultnet-py/CHANGELOG.md index b6bfa92b..5e4b0cfa 100644 --- a/packages/cultnet-py/CHANGELOG.md +++ b/packages/cultnet-py/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased (breaking; version 0.x, so the next minor) +- Decodes the write receipt frames of `contracts/cultnet/interop/write-receipt.md`: `parse_message` validates `cultnet.write_admitted.v0` and `cultnet.error.v1` against their closed schemas (unknown keys, empty or non-string ids, an unknown operation or code are refused; `error.v1` requires `messageId`, string or null; `limit_reached` is `error.v1` only). Added `CULTNET_ERROR_V1_CODES`, `CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS`, `write_content_hash` and `hello_advertises_write_receipts`; `hello` takes `supported_message_versions`. `tests/test_write_receipt.py` replays the vectors' `contentHash`, `wire` and `schemaInvalid` sections. Not implemented here: the client write tracker (`scenarios`) and the server rules (`dedupe`, `blankFields`); this package has no receipt server and no write client. - Added `message_invalid` to `CULTNET_ERROR_CODES` and `message_invalid_error(field, reason)`, byte-identical to the C# `ForMessageInvalid`. `cultmesh-py` refuses a malformed put or delete with it instead of the out-of-schema `malformed_document_put` and `malformed_document_delete`, which are removed. - Added `CultNetRudpSocketTransportServer` (`cultnet_py.rudp_server`): one UDP socket serving many RUDP peers, one session per remote endpoint, ported from the C# `CultNetRudpSocketTransportServer` and held to its bytes by diff --git a/packages/cultnet-py/src/cultnet_py/__init__.py b/packages/cultnet-py/src/cultnet_py/__init__.py index bcf2fcf0..e4a22779 100644 --- a/packages/cultnet-py/src/cultnet_py/__init__.py +++ b/packages/cultnet-py/src/cultnet_py/__init__.py @@ -39,6 +39,8 @@ from .cultmesh_contracts import ( from .framing import decode_frame, encode_frame, read_frame, write_frame from .messages import ( CULTNET_ERROR_CODES, + CULTNET_ERROR_V1_CODES, + CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS, CultNetMessage, CultNetWitnessArtifactBundle, compute_simulation_claim_hash, @@ -51,7 +53,9 @@ from .messages import ( error_message, message_invalid_error, unsupported_schema_version_error, + write_content_hash, hello, + hello_advertises_write_receipts, login, login_success, parse_message, @@ -176,6 +180,8 @@ __all__ = [ "verse_catalog_request", "verse_from_wire", "CULTNET_ERROR_CODES", + "CULTNET_ERROR_V1_CODES", + "CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS", "CultNetMessage", "CultNetWitnessArtifactBundle", "CultNetDatabaseSubscription", @@ -266,6 +272,8 @@ __all__ = [ "message_invalid_error", "unsupported_schema_version_error", "hello", + "hello_advertises_write_receipts", + "write_content_hash", "INTEROP_WIRE_CONTRACT", "login", "login_success", diff --git a/packages/cultnet-py/src/cultnet_py/messages.py b/packages/cultnet-py/src/cultnet_py/messages.py index 1a1f8e88..f2d89296 100644 --- a/packages/cultnet-py/src/cultnet_py/messages.py +++ b/packages/cultnet-py/src/cultnet_py/messages.py @@ -29,7 +29,11 @@ def parse_message(payload: bytes) -> CultNetMessage: body = dict(decoded) del body["schemaVersion"] if schema_version == "cultnet.error.v0": - _validate_error_body(body) + _validate_error_body(body, "cultnet.error.v0", CULTNET_ERROR_CODES) + elif schema_version == "cultnet.error.v1": + _validate_error_body(body, "cultnet.error.v1", CULTNET_ERROR_V1_CODES) + elif schema_version == "cultnet.write_admitted.v0": + _validate_write_admitted_body(body) return CultNetMessage(schema_version=schema_version, body=body) @@ -47,6 +51,13 @@ CULTNET_ERROR_CODES: tuple[str, ...] = ( "message_invalid", ) +# cultnet.error.v1 (contracts/cultnet/interop/cultnet.error.v1.schema.json): v0's codes plus limit_reached. +CULTNET_ERROR_V1_CODES: tuple[str, ...] = (*CULTNET_ERROR_CODES, "limit_reached") + +# The two frames a receipt-capable hello lists in supportedMessageVersions; a peer lists both or neither +# (contracts/cultnet/interop/write-receipt.md, "Capability: opting in"). +CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS: tuple[str, ...] = ("cultnet.write_admitted.v0", "cultnet.error.v1") + _ERROR_DETAILS_KEYS = ("field", "value", "asOf", "current") @@ -54,16 +65,48 @@ def _is_uint(value: Any) -> bool: return isinstance(value, int) and not isinstance(value, bool) and value >= 0 -def _validate_error_body(body: dict[str, Any]) -> None: - """Refuse a cultnet.error.v0 body that is not the full-key shape the schema requires.""" - expected = ("error", "routingHint", "code", "details") +def _is_name(value: Any) -> bool: + return isinstance(value, str) and value != "" + + +def _validate_write_admitted_body(body: dict[str, Any]) -> None: + """Refuse a cultnet.write_admitted.v0 body that is not exactly the five keys of its closed schema.""" + expected = ("messageId", "operation", "schemaId", "recordKey") if set(body) != set(expected): - raise ValueError(f"cultnet.error.v0 must carry exactly {list(expected)}, got {sorted(body)}") + raise ValueError(f"cultnet.write_admitted.v0 must carry exactly {list(expected)}, got {sorted(body)}") + for key in ("messageId", "schemaId", "recordKey"): + if not _is_name(body[key]): + raise ValueError(f"cultnet.write_admitted.v0 {key} must be a non-empty string") + if body["operation"] not in ("put", "delete"): + raise ValueError("cultnet.write_admitted.v0 operation must be put or delete") + + +def write_content_hash(operation: str, schema_id: str, record_key: str, payload: bytes | None) -> bytes: + """SHA-256 of the MessagePack array [operation, schemaId, recordKey, payload] (write-receipt.md, rule 5). + + payload is the raw document payload, packed as a MessagePack bin for a put and nil for a delete. + """ + return hashlib.sha256(msgpack.packb([operation, schema_id, record_key, payload], use_bin_type=True)).digest() + + +def hello_advertises_write_receipts(hello_message: CultNetMessage) -> bool: + """True when a hello lists both receipt frames: the only thing that makes a connection receipt-capable.""" + listed = hello_message.body.get("supportedMessageVersions") + return isinstance(listed, list) and all(version in listed for version in CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS) + + +def _validate_error_body(body: dict[str, Any], version: str, codes: tuple[str, ...]) -> None: + """Refuse a cultnet.error body that is not the full-key shape its closed schema requires.""" + expected = ("error", "routingHint", "code", "details") + (("messageId",) if version == "cultnet.error.v1" else ()) + if set(body) != set(expected): + raise ValueError(f"{version} must carry exactly {list(expected)}, got {sorted(body)}") if not isinstance(body["error"], str) or not body["error"]: - raise ValueError("cultnet.error.v0 error must be a non-empty string") + raise ValueError(f"{version} error must be a non-empty string") code = body["code"] - if code is not None and (not isinstance(code, str) or code not in CULTNET_ERROR_CODES): - raise ValueError(f"cultnet.error.v0 code {code!r} is not a recognized refusal code") + if code is not None and (not isinstance(code, str) or code not in codes): + raise ValueError(f"{version} code {code!r} is not a recognized refusal code") + if "messageId" in body and body["messageId"] is not None and not _is_name(body["messageId"]): + raise ValueError(f"{version} messageId must be a non-empty string or null") hint = body["routingHint"] if hint is not None: if ( @@ -72,17 +115,17 @@ def _validate_error_body(body: dict[str, Any]) -> None: or not isinstance(hint["reason"], str) or not (hint["shard"] is None or isinstance(hint["shard"], dict)) ): - raise ValueError("cultnet.error.v0 routingHint must be null or {shard, reason}") + raise ValueError(f"{version} routingHint must be null or {{shard, reason}}") details = body["details"] if details is not None: if not isinstance(details, dict) or set(details) != set(_ERROR_DETAILS_KEYS): - raise ValueError(f"cultnet.error.v0 details must be null or carry exactly {list(_ERROR_DETAILS_KEYS)}") + raise ValueError(f"{version} details must be null or carry exactly {list(_ERROR_DETAILS_KEYS)}") for key in ("field", "value"): if details[key] is not None and not isinstance(details[key], str): - raise ValueError(f"cultnet.error.v0 details.{key} must be a string or null") + raise ValueError(f"{version} details.{key} must be a string or null") for key in ("asOf", "current"): if details[key] is not None and not _is_uint(details[key]): - raise ValueError(f"cultnet.error.v0 details.{key} must be a non-negative integer or null") + raise ValueError(f"{version} details.{key} must be a non-negative integer or null") def hello( @@ -92,17 +135,18 @@ def hello( supported_schema_versions: list[str] | None = None, supported_mutation_contracts: list[dict[str, Any]] | None = None, transport_profiles: list[dict[str, Any]] | None = None, + supported_message_versions: list[str] | None = None, ) -> CultNetMessage: - return CultNetMessage( - "cultnet.hello.v0", - { - "runtimeId": runtime_id, - "supportedWireContracts": supported_wire_contracts or ["cultnet.schema.v0"], - "supportedSchemaVersions": supported_schema_versions or [], - "supportedMutationContracts": supported_mutation_contracts or [], - "transportProfiles": transport_profiles or [], - }, - ) + body: dict[str, Any] = { + "runtimeId": runtime_id, + "supportedWireContracts": supported_wire_contracts or ["cultnet.schema.v0"], + "supportedSchemaVersions": supported_schema_versions or [], + "supportedMutationContracts": supported_mutation_contracts or [], + "transportProfiles": transport_profiles or [], + } + if supported_message_versions is not None: + body["supportedMessageVersions"] = supported_message_versions + return CultNetMessage("cultnet.hello.v0", body) def login( @@ -172,7 +216,7 @@ def error_message( } if details is not None and set(details) - set(_ERROR_DETAILS_KEYS): raise ValueError(f"cultnet.error.v0 details has unknown keys {sorted(set(details) - set(_ERROR_DETAILS_KEYS))}") - _validate_error_body(body) + _validate_error_body(body, "cultnet.error.v0", CULTNET_ERROR_CODES) return CultNetMessage("cultnet.error.v0", body) diff --git a/packages/cultnet-py/tests/test_write_receipt.py b/packages/cultnet-py/tests/test_write_receipt.py new file mode 100644 index 00000000..98e74287 --- /dev/null +++ b/packages/cultnet-py/tests/test_write_receipt.py @@ -0,0 +1,247 @@ +from __future__ import annotations + +import json +import unittest +from pathlib import Path +from typing import Any + +import msgpack + +from cultnet_py import ( + CULTNET_ERROR_CODES, + CULTNET_ERROR_V1_CODES, + CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS, + error_message, + hello, + hello_advertises_write_receipts, + parse_message, + write_content_hash, +) + +# Decoder-side conformance with contracts/cultnet/interop/write-receipt-vectors.json: `contentHash`, `wire` and +# `schemaInvalid`. `dedupe` and `blankFields` are server obligations and `scenarios` is the client write tracker; `counts` is the file's own tally; +# this runtime has neither a receipt server nor a write client, so it replays none of them. +_INTEROP = Path(__file__).resolve().parents[3] / "contracts/cultnet/interop" +_VECTORS = json.loads((_INTEROP / "write-receipt-vectors.json").read_text(encoding="utf-8")) +_ERROR_V1_SCHEMA = json.loads((_INTEROP / "cultnet.error.v1.schema.json").read_text(encoding="utf-8")) + + +def _pack(wire: dict[str, Any]) -> bytes: + return msgpack.packb(wire, use_bin_type=True) + + +def _admitted(**override: Any) -> dict[str, Any]: + return { + "schemaVersion": "cultnet.write_admitted.v0", + "messageId": "put-1", + "operation": "put", + "schemaId": "note.v0", + "recordKey": "note:1", + **override, + } + + +def _refused(**override: Any) -> dict[str, Any]: + return { + "schemaVersion": "cultnet.error.v1", + "error": "write_not_authorized: no", + "routingHint": None, + "code": "write_not_authorized", + "details": None, + "messageId": "put-1", + **override, + } + + +class WriteReceiptVectorTests(unittest.TestCase): + def test_vector_sections_are_the_ones_this_file_accounts_for(self) -> None: + self.assertEqual( + set(_VECTORS) - {"provenance", "specification"}, + {"constants", "contentHash", "dedupe", "wire", "blankFields", "schemaInvalid", "scenarios", "counts"}, + ) + self.assertEqual(len(_VECTORS["contentHash"]["cases"]), 4) + self.assertEqual(len(_VECTORS["wire"]), 7) + self.assertEqual(len(_VECTORS["schemaInvalid"]), 7) + # The file declares how many of each it holds; a loader that drops entries disagrees with it. + counts = _VECTORS["counts"] + self.assertEqual(counts["wire"], len(_VECTORS["wire"])) + self.assertEqual(counts["schemaInvalid"], len(_VECTORS["schemaInvalid"])) + self.assertEqual(counts["contentHashCases"], len(_VECTORS["contentHash"]["cases"])) + self.assertEqual(counts["scenarioCases"], len(_VECTORS["scenarios"]["cases"])) + + def test_content_hash_matches_every_vector(self) -> None: + for case in _VECTORS["contentHash"]["cases"]: + payload = None if case["payloadHex"] is None else bytes.fromhex(case["payloadHex"]) + digest = write_content_hash(case["operation"], case["schemaId"], case["recordKey"], payload) + self.assertEqual(digest.hex(), case["sha256"], case["name"]) + + def test_wire_vectors_decode_to_their_fields_in_order_and_reencode_byte_identical(self) -> None: + for vector in _VECTORS["wire"]: + raw = bytes.fromhex(vector["messagePackHex"]) + message = parse_message(raw) + self.assertEqual(message.to_wire(), vector["message"], vector["name"]) + self.assertEqual(list(message.to_wire()), list(vector["message"]), vector["name"]) + self.assertEqual(message.to_bytes(), raw, vector["name"]) + + def test_schema_invalid_vectors_are_refused(self) -> None: + for vector in _VECTORS["schemaInvalid"]: + with self.assertRaises(ValueError, msg=vector["name"]): + parse_message(bytes.fromhex(vector["messagePackHex"])) + + def test_a_payload_that_is_not_bytes_changes_the_hash(self) -> None: + # The payload is a bin, not an str and not a re-parsed document. + as_bin = write_content_hash("put", "note.v0", "note:1", b"\x81\xa2id\xa11") + self.assertNotEqual(as_bin, write_content_hash("put", "note.v0", "note:1", None)) + self.assertEqual(len(as_bin), 32) + + +class ErrorV1Tests(unittest.TestCase): + def test_code_set_equals_the_schema_enum_and_v0_is_unchanged(self) -> None: + schema_codes = [c for c in _ERROR_V1_SCHEMA["properties"]["code"]["enum"] if c is not None] + self.assertEqual(sorted(CULTNET_ERROR_V1_CODES), sorted(schema_codes)) + self.assertNotIn("limit_reached", CULTNET_ERROR_CODES) + self.assertEqual(CULTNET_ERROR_V1_CODES[-1], "limit_reached") + + def test_every_v1_code_decodes_and_an_unknown_one_does_not(self) -> None: + for code in CULTNET_ERROR_V1_CODES: + self.assertEqual(parse_message(_pack(_refused(code=code))).body["code"], code) + parse_message(_pack(_refused(code=None))) + with self.assertRaises(ValueError): + parse_message(_pack(_refused(code="invented"))) + with self.assertRaises(ValueError): + parse_message(_pack(_refused(code=7))) + + def test_limit_reached_is_v1_only(self) -> None: + v0 = {k: v for k, v in _refused(code="limit_reached", schemaVersion="cultnet.error.v0").items() if k != "messageId"} + with self.assertRaises(ValueError): + parse_message(_pack(v0)) + with self.assertRaises(ValueError): + error_message("x", code="limit_reached") + + def test_message_id_is_required_and_is_a_nonempty_string_or_null(self) -> None: + self.assertEqual(parse_message(_pack(_refused(messageId="w-é 1"))).body["messageId"], "w-é 1") + self.assertIsNone(parse_message(_pack(_refused(messageId=None))).body["messageId"]) + omitted = {k: v for k, v in _refused().items() if k != "messageId"} + with self.assertRaises(ValueError): + parse_message(_pack(omitted)) + for bad in ("", 5, b"put-1", ["put-1"], True): + with self.assertRaises(ValueError, msg=repr(bad)): + parse_message(_pack(_refused(messageId=bad))) + + def test_v0_stays_closed_to_message_id(self) -> None: + v0 = _refused(schemaVersion="cultnet.error.v0", code="message_invalid") + with self.assertRaises(ValueError): + parse_message(_pack(v0)) + del v0["messageId"] + self.assertEqual(parse_message(_pack(v0)).schema_version, "cultnet.error.v0") + + def test_v1_is_closed_to_unknown_keys_and_keeps_the_shape_rules_of_v0(self) -> None: + for bad in ( + _refused(extra=1), + _refused(error=""), + _refused(error=3), + _refused(routingHint={"shard": None}), + _refused(routingHint={"shard": 1, "reason": "r"}), + _refused(routingHint={"shard": None, "reason": 1}), + _refused(details={"field": None, "value": None, "asOf": None}), + _refused(details={"field": 1, "value": None, "asOf": None, "current": None}), + _refused(details={"field": None, "value": None, "asOf": -1, "current": None}), + _refused(details={"field": None, "value": None, "asOf": None, "current": True}), + ): + with self.assertRaises(ValueError, msg=str(bad)): + parse_message(_pack(bad)) + for good in ( + _refused(routingHint={"shard": None, "reason": "r"}), + _refused(details={"field": "messageId", "value": "x", "asOf": 1, "current": 2}), + ): + parse_message(_pack(good)) + + def test_the_refusal_reason_names_its_version(self) -> None: + with self.assertRaisesRegex(ValueError, "cultnet.error.v1 code"): + parse_message(_pack(_refused(code="invented"))) + with self.assertRaisesRegex(ValueError, r"routingHint must be null or \{shard, reason\}"): + parse_message(_pack(_refused(routingHint={"shard": None}))) + + +class RefusalTextTests(unittest.TestCase): + """A refusal names its frame version and the rule it broke; a caller reads this text in a log.""" + + def assertRefused(self, wire: dict[str, Any], pattern: str) -> None: + with self.assertRaisesRegex(ValueError, pattern): + parse_message(_pack(wire)) + + def test_error_frames_name_their_own_version(self) -> None: + v0 = {k: v for k, v in _refused(schemaVersion="cultnet.error.v0").items() if k != "messageId"} + self.assertRefused({**v0, "code": "nope"}, r"^cultnet\.error\.v0 code") + self.assertRefused({**v0, "extra": 1}, r"^cultnet\.error\.v0 must carry exactly") + self.assertRefused(_refused(extra=1), r"^cultnet\.error\.v1 must carry exactly") + self.assertRefused(_refused(error=""), r"^cultnet\.error\.v1 error must be") + self.assertRefused(_refused(messageId=""), r"^cultnet\.error\.v1 messageId must be") + self.assertRefused(_refused(details={"field": None}), r"^cultnet\.error\.v1 details must be null or carry exactly") + self.assertRefused( + _refused(details={"field": 1, "value": None, "asOf": None, "current": None}), r"^cultnet\.error\.v1 details\.field must be" + ) + self.assertRefused( + _refused(details={"field": None, "value": None, "asOf": -1, "current": None}), r"^cultnet\.error\.v1 details\.asOf must be" + ) + with self.assertRaisesRegex(ValueError, r"^cultnet\.error\.v0 code"): + error_message("x", code="bogus") + + def test_write_admitted_names_the_broken_rule(self) -> None: + self.assertRefused(_admitted(extra=1), r"^cultnet\.write_admitted\.v0 must carry exactly") + self.assertRefused(_admitted(recordKey=""), r"^cultnet\.write_admitted\.v0 recordKey must be a non-empty string") + self.assertRefused(_admitted(operation="upsert"), r"^cultnet\.write_admitted\.v0 operation must be put or delete$") + + +class WriteAdmittedTests(unittest.TestCase): + def test_both_operations_decode(self) -> None: + for operation in ("put", "delete"): + self.assertEqual(parse_message(_pack(_admitted(operation=operation))).body["operation"], operation) + + def test_every_key_is_required_and_no_other_is_allowed(self) -> None: + for key in ("messageId", "operation", "schemaId", "recordKey"): + with self.assertRaises(ValueError, msg=key): + parse_message(_pack({k: v for k, v in _admitted().items() if k != key})) + for extra in ("error", "code", "details"): + with self.assertRaises(ValueError, msg=extra): + parse_message(_pack(_admitted(**{extra: "x"}))) + + def test_each_string_is_nonempty_and_a_string(self) -> None: + for key in ("messageId", "schemaId", "recordKey"): + for bad in ("", None, 3, b"x"): + with self.assertRaises(ValueError, msg=f"{key}={bad!r}"): + parse_message(_pack(_admitted(**{key: bad}))) + + def test_operation_is_put_or_delete(self) -> None: + for bad in ("upsert", "PUT", "", None, 1): + with self.assertRaises(ValueError, msg=repr(bad)): + parse_message(_pack(_admitted(operation=bad))) + + def test_message_id_is_echoed_byte_for_byte(self) -> None: + self.assertEqual(parse_message(_pack(_admitted(messageId=" w é 1 "))).body["messageId"], " w é 1 ") + + +class HelloCapabilityTests(unittest.TestCase): + def test_capability_needs_both_frames(self) -> None: + both = list(CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS) + self.assertEqual(both, ["cultnet.write_admitted.v0", "cultnet.error.v1"]) + self.assertTrue(hello_advertises_write_receipts(hello(runtime_id="r", supported_message_versions=both))) + self.assertTrue(hello_advertises_write_receipts(hello(runtime_id="r", supported_message_versions=[*both, "x"]))) + self.assertFalse(hello_advertises_write_receipts(hello(runtime_id="r", supported_message_versions=both[:1]))) + self.assertFalse(hello_advertises_write_receipts(hello(runtime_id="r", supported_message_versions=both[1:]))) + self.assertFalse(hello_advertises_write_receipts(hello(runtime_id="r", supported_message_versions=[]))) + self.assertFalse(hello_advertises_write_receipts(hello(runtime_id="r"))) + + def test_a_non_list_listing_is_not_a_capability(self) -> None: + wire = hello(runtime_id="r").to_wire() + wire["supportedMessageVersions"] = "cultnet.write_admitted.v0 cultnet.error.v1" + self.assertFalse(hello_advertises_write_receipts(parse_message(_pack(wire)))) + + def test_hello_writes_the_listing_only_when_given_and_round_trips(self) -> None: + self.assertNotIn("supportedMessageVersions", hello(runtime_id="r").body) + listed = hello(runtime_id="r", supported_message_versions=list(CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS)) + self.assertEqual(parse_message(listed.to_bytes()), listed) + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/cultnet-rs/src/rudp.rs b/packages/cultnet-rs/src/rudp.rs index eae7a2ee..427a38c1 100644 --- a/packages/cultnet-rs/src/rudp.rs +++ b/packages/cultnet-rs/src/rudp.rs @@ -1277,6 +1277,12 @@ impl CultNetRudpSession { } } + /// Whether `receive` has taken this reliable sequence: delivered, held, superseded or a duplicate. A packet + /// `receive` refused unremembered (too far ahead, or before the handshake) is not, and its sender resends it. + pub fn has_received(&self, sequence: u32) -> bool { + self.was_received(sequence) + } + /// The one duplicate test: true for a sequence in the window that was /// received, for one below the window, and for one at or before the /// watermark. The watermark starts at the handshake's seed, so a frame the diff --git a/packages/cultnet-rs/tests/write_receipt.rs b/packages/cultnet-rs/tests/write_receipt.rs index 6d06a68c..3d233a61 100644 --- a/packages/cultnet-rs/tests/write_receipt.rs +++ b/packages/cultnet-rs/tests/write_receipt.rs @@ -39,7 +39,7 @@ fn the_new_frames_decode_back_equal() { ); // error.v1 with a nil id round-trips as nil, and the code enum is v0's. let error = CultNetMessage::ErrorV1 { - error: "message_invalid: unreadable frame".into(), + error: "message_invalid: the message could not be read".into(), code: Some(CultNetErrorCode::MessageInvalid), details: None, message_id: None, diff --git a/packages/cultnet-ts/CHANGELOG.md b/packages/cultnet-ts/CHANGELOG.md index 739396cd..e7a5f1f1 100644 --- a/packages/cultnet-ts/CHANGELOG.md +++ b/packages/cultnet-ts/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to `@gamecult/cultnet-ts` are recorded here, following ### Added +- `WriteTracker`: a write sent after `sessionEnd` settles unconfirmed `session_ended` when it is sent (it stayed unanswered forever). The replay runner now fails on an event key outside `scenarios.semantics` and on a vector count that differs from the file's `counts`; seven tracker vectors are new. A blank text in a raw frame is Unicode White_Space, not `String.prototype.trim()`. +- Write receipt, client side (`contracts/cultnet/interop/write-receipt.md`): `cultnet.write_admitted.v0` and `cultnet.error.v1` (v0 plus `messageId`; its closed code set adds `limit_reached`, `CULTNET_ERROR_V1_CODES`) parse and encode, and `CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS` / `helloAdvertisesWriteReceipts` name the hello capability. `cultnet.error.v0` and its code set are unchanged. `WriteTracker` settles each write as admitted, refused or unconfirmed (windows `RECEIPT_RESULT_WINDOW_MS` 5000 and `LEGACY_RESULT_WINDOW_MS` 500, counted from the send; late answers recorded as `admitted_late` / `refused_late`), and `tools/replay-write-receipt-vectors.mjs` replays the vectors against it (see README, "Write receipt replay runner"). The interop schemas are read from `contracts/cultnet/interop/`. - `message_invalid` joins the closed `cultnet.error.v0` code set, with `cultNetMessageInvalidError(field, reason)` (`details.field` names the request field at fault), byte-identical to the C# `ForMessageInvalid`. - `cultNetWriteNotAuthorizedError(recordKey, reason?)`: the typed `write_not_authorized` refusal (code and `details.recordKey`), byte-identical to the C# `ForRemoteWriteRefused` vector in `error-vectors.json`. `CultNetDocumentRegistry.canonicalSchemaId(schemaId)` resolves the id a put or delete writes under, for a server's write authority. - `cultNetTextError(error)`: the text-only `cultnet.error.v0` refusal, with `routingHint`, `code` and `details` null. The legacy-union error decode uses it, so there is one place that spells the null members. @@ -16,6 +18,7 @@ All notable changes to `@gamecult/cultnet-ts` are recorded here, following ### Breaking +- The Idunn runtime presence publisher is send-only (`sendPresenceDocument`): it returns `"sent"` once Odin's transport has acknowledged the put and no longer waits up to 500 ms for a success reply, which was never admission. It rejects `IdunnPresenceRefusedError` for a `cultnet.error.v0`, or a `cultnet.error.v1` naming the put or nothing, that arrives by the ack; a refusal after the ack is not awaited, and no other frame, one carrying the put's id included, counts as success. - The package is renamed `cultnet-ts` to `@gamecult/cultnet-ts` (the repo already scopes `@gamecult/cultcache-ts`), so the unscoped name cannot be claimed by someone else. Import from `@gamecult/cultnet-ts` and its subpaths; the API is unchanged. - `CultNetErrorMessage` carries `routingHint`, `code` and `details` (null when absent), as the reference writes them and `cultnet.error.schema.json` requires; the interface previously dropped them. New `CultNetErrorCode`, `CultNetErrorDetails` and `CultNetShardRoutingHint` types. diff --git a/packages/cultnet-ts/README.md b/packages/cultnet-ts/README.md index 1fb37a3f..07996956 100644 --- a/packages/cultnet-ts/README.md +++ b/packages/cultnet-ts/README.md @@ -289,6 +289,33 @@ maps them back to the exact C# union payload shape at the wire boundary. serve and dial commands also exercise schema-v0 over the shared RUDP socket transport and advertise both transport profiles. +## Write receipt replay runner + +`WriteTracker` is the client half of `contracts/cultnet/interop/write-receipt.md`: a pure state machine on an abstract +clock that owns one decision, how each sent write settles. `tools/replay-write-receipt-vectors.mjs` replays +`write-receipt-vectors.json` against it (build first, then `node tools/replay-write-receipt-vectors.mjs`): it prints +`PASS`/`FAIL` per case and exits nonzero on any failure. Rust and C# port the same runner by implementing this interface +and replaying the same file. + +Tracker interface (times are integer milliseconds on the vector's clock; the constructor takes the window): + +| Call | Meaning | +| --- | --- | +| `new WriteTracker({ windowMs, onSettle })` | `windowMs` = 5000 when the server's hello lists both `cultnet.write_admitted.v0` and `cultnet.error.v1`, else 500. `onSettle(id, settlement)` fires once per write. | +| `send(id, atMs)` | A write with that `messageId` was sent. Its window runs from here, not from any transport ack. | +| `frame(message, atMs)` | A decoded frame arrived. `write_admitted` and `error.v1` settle the write they name; `error.v0`, or `error.v1` with nil `messageId`, refuses a write only when exactly one is unanswered; an id not in flight settles nothing. | +| `tick(atMs)` | Advance the clock. Every unanswered write with `atMs - sentAt >= windowMs` settles `unconfirmed(window_elapsed)`. `send`, `frame` and `sessionEnd` tick first. | +| `sessionEnd(atMs)` | Every unanswered write settles `unconfirmed(session_ended)`. | +| `state(id)` | `pending`, or the settlement plus `recorded`: `admitted_late` / `refused_late`, set by the first answer that arrives after `unconfirmed`. A settlement never changes. | + +Runner, per case in `scenarios.cases` (the transport ack is not an input: delivery is not an answer): + +1. The fake server states its capability the only way a real one does, in a hello (`server: "receipt"` lists both frames, `"legacy"` lists none); the window comes from that hello and must equal `constants[case.window]`. +2. Events run in `atMs` order: `send` -> `send(id)`, `frame` -> encode the frame to MessagePack, decode and validate it as the client would, then `frame(message)`, `tick` -> `tick`, `sessionEnd` -> `sessionEnd`, `transportAck` -> nothing. +3. For each id in `expect`, the settlement given to the caller has the expected `outcome` (and `code` or `reason` when given), `state(id).recorded` equals the expected `recorded` (absent when absent), and nothing settled twice or outside `expect`. + +The runner also decodes each `wire[].messagePackHex` and compares the fields and the re-encoded bytes to the vector, and requires every `schemaInvalid[]` frame to be refused by the decoder. `dedupe.cases` and `contentHash` are server vectors and not replayed here. + ## Development ```bash diff --git a/packages/cultnet-ts/src/contracts.ts b/packages/cultnet-ts/src/contracts.ts index d4bc1b19..3cc87dcd 100644 --- a/packages/cultnet-ts/src/contracts.ts +++ b/packages/cultnet-ts/src/contracts.ts @@ -9,6 +9,8 @@ import registerSchema from "../contracts/cultnet/cultnet.register.schema.json"; import verifySchema from "../contracts/cultnet/cultnet.verify.schema.json"; import loginSuccessSchema from "../contracts/cultnet/cultnet.login-success.schema.json"; import errorSchema from "../contracts/cultnet/cultnet.error.schema.json"; +import errorV1Schema from "../contracts/cultnet/interop/cultnet.error.v1.schema.json"; +import writeAdmittedSchema from "../contracts/cultnet/interop/cultnet.write-admitted.schema.json"; import sampleChangeNameSchema from "../contracts/cultnet/cultnet.sample-change-name.schema.json"; import sampleChatSchema from "../contracts/cultnet/cultnet.sample-chat.schema.json"; import documentPutSchema from "../contracts/cultnet/cultnet.document-put.schema.json"; @@ -62,6 +64,8 @@ export type CultNetSchemaVersion = | "cultnet.verify.v0" | "cultnet.login_success.v0" | "cultnet.error.v0" + | "cultnet.error.v1" + | "cultnet.write_admitted.v0" | "cultnet.sample.change_name.v0" | "cultnet.sample.chat.v0" | "cultnet.document_put.v0" @@ -201,6 +205,11 @@ export const CULTNET_ERROR_CODES = [ export type CultNetErrorCode = (typeof CULTNET_ERROR_CODES)[number]; +/** The closed refusal-code set of cultnet.error.v1 (contracts/cultnet/interop/cultnet.error.v1.schema.json): v0's codes plus `limit_reached`. */ +export const CULTNET_ERROR_V1_CODES = [...CULTNET_ERROR_CODES, "limit_reached"] as const; + +export type CultNetErrorV1Code = (typeof CULTNET_ERROR_V1_CODES)[number]; + /** A refusal that carries text only: `routingHint`, `code` and `details` are written as null, as the reference writes an absent member. */ export function cultNetTextError(error: string): CultNetErrorMessage { return { schemaVersion: "cultnet.error.v0", error, routingHint: null, code: null, details: null }; @@ -255,6 +264,34 @@ export interface CultNetErrorMessage { details: CultNetErrorDetails | null; } +/** + * cultnet.error.v0 plus the `messageId` of the request it answers (nil when no id could be read). Sent only to a + * connection whose hello listed both receipt frames (contracts/cultnet/interop/write-receipt.md). + */ +export interface CultNetErrorV1Message extends Omit { + schemaVersion: "cultnet.error.v1"; + code: CultNetErrorV1Code | null; + messageId: string | null; +} + +/** The receipt for one admitted put or delete: every key written, the write's `messageId` echoed byte for byte. */ +export interface CultNetWriteAdmittedMessage { + schemaVersion: "cultnet.write_admitted.v0"; + messageId: string; + operation: "put" | "delete"; + schemaId: string; + recordKey: string; +} + +/** The two frames a receipt-capable hello lists in `supportedMessageVersions`; a peer lists both or neither. */ +export const CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS = ["cultnet.write_admitted.v0", "cultnet.error.v1"] as const; + +/** True when a hello lists both receipt frames: the only thing that makes a connection receipt-capable. */ +export function helloAdvertisesWriteReceipts(hello: Pick): boolean { + const listed = hello.supportedMessageVersions ?? []; + return CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS.every((version) => listed.includes(version)); +} + export interface CultNetSampleChangeNameMessage { schemaVersion: "cultnet.sample.change_name.v0"; name: string; @@ -770,6 +807,8 @@ export interface GhostlightAgentStateDocument { export type CultNetMessage = | CultNetHelloMessage + | CultNetErrorV1Message + | CultNetWriteAdmittedMessage | CultNetLoginMessage | CultNetRegisterMessage | CultNetVerifyMessage @@ -812,6 +851,8 @@ const CULTNET_MESSAGE_SCHEMAS = [ verifySchema, loginSuccessSchema, errorSchema, + errorV1Schema, + writeAdmittedSchema, sampleChangeNameSchema, sampleChatSchema, documentPutSchema, @@ -1381,7 +1422,7 @@ function validateBinaryMessageRoot( if (candidate.schemaVersion !== schemaVersion) { throw new Error(`Validation failed for ${schemaVersion}: /schemaVersion: must equal ${schemaVersion}`); } - if (typeof candidate.messageId !== "string" || candidate.messageId.trim().length === 0) { + if (typeof candidate.messageId !== "string" || isBlank(candidate.messageId)) { throw new Error(`Validation failed for ${schemaVersion}: /messageId: must be a non-empty string`); } @@ -1419,8 +1460,13 @@ function validateRawDocumentRecord( requireOptionalStringArray(candidate.tags, `${instancePath}/tags`); } +/** Blank is empty or only Unicode White_Space (write-receipt.md, rule 5), not `trim()`: JS trims U+FEFF and keeps U+0085. */ +function isBlank(value: string): boolean { + return /^\p{White_Space}*$/u.test(value); +} + function requireNonEmptyString(input: unknown, instancePath: string): void { - if (typeof input !== "string" || input.trim().length === 0) { + if (typeof input !== "string" || isBlank(input)) { throw new Error(`Validation failed for raw CultNet document record: ${instancePath}: must be a non-empty string`); } } @@ -1436,7 +1482,7 @@ function requireOptionalStringArray(input: unknown, instancePath: string): void if (typeof input === "undefined" || input === null) { return; } - if (!Array.isArray(input) || input.some((item) => typeof item !== "string" || item.trim().length === 0)) { + if (!Array.isArray(input) || input.some((item) => typeof item !== "string" || isBlank(item))) { throw new Error(`Validation failed for raw CultNet document record: ${instancePath}: must be an array of non-empty strings`); } } @@ -1535,6 +1581,8 @@ export const cultNetSchemas = { verifySchema, loginSuccessSchema, errorSchema, + errorV1Schema, + writeAdmittedSchema, sampleChangeNameSchema, sampleChatSchema, documentPutSchema, diff --git a/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts b/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts index 209a2881..a5994f56 100644 --- a/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts +++ b/packages/cultnet-ts/src/idunn-odin-presence-publisher.ts @@ -52,7 +52,7 @@ export function createIdunnRuntimePresencePublisher( const publish = async (detail: string) => { const signed = signer.sign(detail); messageSequence += 1; - await publishDocument(endpoint, connectionId, { + await sendPresenceDocument(endpoint, connectionId, { schemaVersion: "cultnet.document_put_raw.v0", messageId: `runtime-presence:${signer.authority.expected.target}:${signer.runtimeInstanceId}:${messageSequence}`, document: signed.document, @@ -86,11 +86,19 @@ export function createIdunnRuntimePresencePublisher( }; } -async function publishDocument( +/** + * Sends one presence put and says only that it was sent (write-receipt.md: the explicit send-only mode). Odin does not + * answer a write with a receipt yet, so no frame, whatever id it carries, is admission; this never claims it. It returns + * once the transport has acknowledged the put, rejects `IdunnPresenceRefusedError` if a refusal arrives by then, and + * rejects if the put is never acknowledged. + * + * @internal exported for tests + */ +export async function sendPresenceDocument( endpoint: { host: string; port: number }, connectionId: number, message: Record, -): Promise { +): Promise<"sent"> { const socket = dgram.createSocket(endpoint.host.includes(":") ? "udp6" : "udp4"); await new Promise((resolve, reject) => { socket.once("error", reject); @@ -107,26 +115,24 @@ async function publishDocument( const wirePayload = encode(encodeCultNetMessageForWire(message as never, "cultnet.schema.v0")); const packets = session.sendMany("schema", wirePayload, { reliable: true, ordered: true, nowMs: Date.now() }); for (const packet of packets) await sendPacket(socket, endpoint, packet); - // The transport ack is not admission: the put completes on Odin's result frame. A refusal rejects whether - // it arrives before the ack, after it, or inside the result window; a success reply ends the wait early. - let succeeded = false; + // The transport ack is delivery, not admission. A refusal that arrives by then rejects; no other frame means anything. const onFrame = (frame: { channelId: string; payload: Uint8Array }) => { if (frame.channelId !== "schema") return; const response = parseCultNetMessage(decode(frame.payload)); if (response.schemaVersion === "cultnet.error.v0") throw new IdunnPresenceRefusedError(response); - succeeded = true; + // An error.v1 refuses this put only when it names it (or names nothing). + if (response.schemaVersion === "cultnet.error.v1" && (response.messageId === null || response.messageId === message.messageId)) { + throw new IdunnPresenceRefusedError(response); + } }; await receiveUntil(receiver, session, endpoint, () => session.outstandingReliablePacketCount === 0, 2000, onFrame); - if (!succeeded) await receiveUntil(receiver, session, endpoint, () => succeeded, RESULT_WINDOW_MS, onFrame, true); + return "sent"; } finally { receiver.close(); socket.close(); } } -/** How long after the transport ack Odin's refusal may still arrive; a success reply ends the wait early. */ -const RESULT_WINDOW_MS = 500; - /** Odin refused the presence put: the typed `cultnet.error.v0` it answered with. */ export class IdunnPresenceRefusedError extends Error { readonly code: string | undefined; @@ -200,7 +206,6 @@ async function receiveUntil( predicate: (packet: CultNetRudpPacket) => boolean, timeoutMs: number, onDelivered?: (frame: { channelId: string; payload: Uint8Array; sequence: number }) => void, - returnOnTimeout = false, ): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { @@ -215,7 +220,6 @@ async function receiveUntil( } for (const packet of session.dueResends(Date.now())) await sendPacket(receiver.socket, endpoint, packet); } - if (returnOnTimeout) return; throw new Error(`Timed out waiting for CultNet RUDP response after ${timeoutMs} ms.`); } diff --git a/packages/cultnet-ts/src/index.ts b/packages/cultnet-ts/src/index.ts index 4fd0014c..a8740cae 100644 --- a/packages/cultnet-ts/src/index.ts +++ b/packages/cultnet-ts/src/index.ts @@ -17,6 +17,12 @@ export { type CultNetRawDocumentRecord, type CultNetRawPayloadEncoding, CULTNET_ERROR_CODES, + CULTNET_ERROR_V1_CODES, + CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS, + helloAdvertisesWriteReceipts, + type CultNetErrorV1Code, + type CultNetErrorV1Message, + type CultNetWriteAdmittedMessage, cultNetTextError, cultNetMessageInvalidError, cultNetWriteNotAuthorizedError, @@ -249,3 +255,15 @@ export { type IdunnRuntimePresencePublisher, type IdunnRuntimePresencePublisherOptions, } from "./idunn-odin-presence-publisher"; + +export { + LEGACY_RESULT_WINDOW_MS, + RECEIPT_RESULT_WINDOW_MS, + WriteTracker, + resultWindowMs, + type WriteRecorded, + type WriteSettlement, + type WriteState, + type WriteTrackerOptions, + type WriteUnconfirmedReason, +} from "./write-tracker"; diff --git a/packages/cultnet-ts/src/write-tracker.ts b/packages/cultnet-ts/src/write-tracker.ts new file mode 100644 index 00000000..cedf877d --- /dev/null +++ b/packages/cultnet-ts/src/write-tracker.ts @@ -0,0 +1,150 @@ +// The client half of the write receipt (contracts/cultnet/interop/write-receipt.md, "Client rules"): a pure state +// machine with an abstract clock. It owns exactly one decision, how each sent write settles. Transport, timers and +// frame decoding belong to the caller; the replay runner (tools/replay-write-receipt-vectors.mjs) drives this same +// interface from write-receipt-vectors.json. + +import type { CultNetErrorMessage, CultNetErrorV1Message, CultNetMessage } from "./contracts"; + +/** The result window against a server whose hello lists both receipt frames. */ +export const RECEIPT_RESULT_WINDOW_MS = 5000; +/** The result window against a server whose hello does not list them (or that sent none). */ +export const LEGACY_RESULT_WINDOW_MS = 500; + +export function resultWindowMs(serverAdvertisesReceipts: boolean): number { + return serverAdvertisesReceipts ? RECEIPT_RESULT_WINDOW_MS : LEGACY_RESULT_WINDOW_MS; +} + +/** + * Why nothing settled a write: its window ran out, the session ended first, or the client's own send of it failed (it may or + * may not have left the machine, and is never a refusal). + */ +export type WriteUnconfirmedReason = "window_elapsed" | "session_ended" | "local_send_failed"; +/** What a late answer is recorded as on a write that already settled unconfirmed. */ +export type WriteRecorded = "admitted_late" | "refused_late"; + +/** What the caller was told. Settled once; never changed by a later frame. */ +export type WriteSettlement = + | { outcome: "admitted" } + | { outcome: "refused"; code: string | null; error: string; response: CultNetErrorMessage | CultNetErrorV1Message } + | { outcome: "unconfirmed"; reason: WriteUnconfirmedReason }; + +/** A write's state: unanswered, or its settlement plus (after unconfirmed only) the late answer. */ +export type WriteState = + | { outcome: "pending"; recorded?: undefined } + | (WriteSettlement & { recorded?: WriteRecorded }); + +export interface WriteTrackerOptions { + /** The result window, from the send. Use `resultWindowMs(serverAdvertisesReceipts)`. */ + windowMs: number; + /** Called once per write, at the moment it settles. */ + onSettle?: (messageId: string, settlement: WriteSettlement) => void; +} + +interface Entry { + sentAtMs: number; + state: WriteState; +} + +export class WriteTracker { + readonly #windowMs: number; + readonly #onSettle?: (messageId: string, settlement: WriteSettlement) => void; + readonly #writes = new Map(); + #ended = false; + + constructor(options: WriteTrackerOptions) { + this.#windowMs = options.windowMs; + this.#onSettle = options.onSettle; + } + + /** Registers a write sent at `atMs`. A messageId is minted once per session: re-sending a known id is the same write. */ + send(messageId: string, atMs: number): void { + this.tick(atMs); + if (this.#writes.has(messageId)) return; + const entry: Entry = { sentAtMs: atMs, state: { outcome: "pending" } }; + this.#writes.set(messageId, entry); + // On a session that already ended nothing can answer this write. + if (this.#ended) this.#settle(messageId, entry, { outcome: "unconfirmed", reason: "session_ended" }); + } + + /** Feeds one decoded frame received at `atMs`. Frames that are not answers to a write are ignored. */ + frame(message: CultNetMessage, atMs: number): void { + this.tick(atMs); + switch (message.schemaVersion) { + case "cultnet.write_admitted.v0": + this.#answer(message.messageId, { outcome: "admitted" }, "admitted_late"); + return; + case "cultnet.error.v1": + if (message.messageId !== null) { + this.#answer(message.messageId, refusalOf(message), "refused_late"); + return; + } + break; + case "cultnet.error.v0": + break; + default: + return; + } + // An error that names no write is attributable only when exactly one write is unanswered. + const unanswered = [...this.#writes].filter(([, entry]) => entry.state.outcome === "pending"); + if (unanswered.length === 1) this.#settle(unanswered[0][0], unanswered[0][1], refusalOf(message)); + } + + /** Advances the clock: every unanswered write whose window, counted from its send, has run settles unconfirmed. */ + tick(atMs: number): void { + for (const [messageId, entry] of this.#writes) { + if (entry.state.outcome === "pending" && atMs - entry.sentAtMs >= this.#windowMs) { + this.#settle(messageId, entry, { outcome: "unconfirmed", reason: "window_elapsed" }); + } + } + } + + /** The session ended: every unanswered write settles unconfirmed, and so does any write sent afterwards. */ + sessionEnd(atMs: number): void { + this.tick(atMs); + this.#ended = true; + for (const [messageId, entry] of this.#writes) { + if (entry.state.outcome === "pending") this.#settle(messageId, entry, { outcome: "unconfirmed", reason: "session_ended" }); + } + } + + /** This client's own send of `messageId` failed: that write settles unconfirmed; the others are untouched. */ + sendFailed(messageId: string, atMs: number): void { + const entry = this.#writes.get(messageId); + if (entry?.state.outcome === "pending") this.#settle(messageId, entry, { outcome: "unconfirmed", reason: "local_send_failed" }); + this.tick(atMs); + } + + state(messageId: string): WriteState | undefined { + return this.#writes.get(messageId)?.state; + } + + /** Milliseconds from `atMs` until the next unanswered write's window runs out; undefined when none is unanswered. */ + nextDeadlineMs(atMs: number): number | undefined { + let next: number | undefined; + for (const entry of this.#writes.values()) { + if (entry.state.outcome !== "pending") continue; + const remaining = Math.max(0, entry.sentAtMs + this.#windowMs - atMs); + if (next === undefined || remaining < next) next = remaining; + } + return next; + } + + #answer(messageId: string, settlement: WriteSettlement, late: WriteRecorded): void { + const entry = this.#writes.get(messageId); + if (!entry) return; // names a write that is not in flight: settles nothing + if (entry.state.outcome === "pending") { + this.#settle(messageId, entry, settlement); + } else if (entry.state.outcome === "unconfirmed" && entry.state.recorded === undefined) { + entry.state = { ...entry.state, recorded: late }; + } + } + + #settle(messageId: string, entry: Entry, settlement: WriteSettlement): void { + entry.state = settlement; + this.#onSettle?.(messageId, settlement); + } +} + +function refusalOf(message: CultNetErrorMessage | CultNetErrorV1Message): WriteSettlement { + return { outcome: "refused", code: message.code, error: message.error, response: message }; +} diff --git a/packages/cultnet-ts/test/idunn-odin-presence-send-only.test.ts b/packages/cultnet-ts/test/idunn-odin-presence-send-only.test.ts new file mode 100644 index 00000000..fff8e2d5 --- /dev/null +++ b/packages/cultnet-ts/test/idunn-odin-presence-send-only.test.ts @@ -0,0 +1,94 @@ +// The presence publisher is send-only (write-receipt.md): Odin answers no write with a receipt yet, so no frame, whatever +// id it carries, is admission. Each test serves it a fake Odin that acknowledges the put and answers as scripted. +import assert from "node:assert/strict"; +import { createSocket, type Socket } from "node:dgram"; +import test from "node:test"; +import { encode, decode } from "@msgpack/msgpack"; + +import { encodeCultNetMessageForWire, type CultNetMessage } from "../src/contracts"; +import { IdunnPresenceRefusedError, sendPresenceDocument } from "../src/idunn-odin-presence-publisher"; +import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "../src/rudp"; + +interface Script { + answer: "silence" | "echo" | "admitted" | "refuse-v0" | "refuse-v1-other" | "refuse-v1-same" | "refuse-v1-none"; + /** Acknowledge the put? Default true. */ + ack?: boolean; +} + +async function fakeOdin(connectionId: number, script: Script) { + const socket: Socket = createSocket("udp4"); + await new Promise((resolve) => socket.bind(0, "127.0.0.1", resolve)); + const session = new CultNetRudpSession({ connectionId, resendDelayMs: 50 }); + const send = (packet: Parameters[0], port: number, address: string) => { + try { socket.send(encodeRudpPacket(packet), port, address); } catch { /* closed */ } + }; + const say = (message: CultNetMessage, port: number, address: string) => { + const packets = session.sendMany("schema", encode(encodeCultNetMessageForWire(message, "cultnet.schema.v0")), { reliable: true, ordered: true, nowMs: Date.now() }); + packets.forEach((p) => send(p, port, address)); + }; + socket.on("message", (wire, remote) => { + const packet = decodeRudpPacket(wire); + const now = Date.now(); + if (packet.packetType === "connect") { + send(session.acceptConnect(packet, now), remote.port, remote.address); + return; + } + const result = session.receive(packet, now); + if (result.reply) send(result.reply, remote.port, remote.address); + for (const frame of result.delivered) { + if (frame.channelId !== "schema") continue; + const put = decode(frame.payload) as { messageId: string; document: unknown }; + if (script.answer === "echo") say({ schemaVersion: "cultnet.document_put_raw.v0", messageId: put.messageId, document: put.document } as unknown as CultNetMessage, remote.port, remote.address); + else if (script.answer === "admitted") say({ schemaVersion: "cultnet.write_admitted.v0", messageId: put.messageId, operation: "put", schemaId: "s", recordKey: "k" }, remote.port, remote.address); + else if (script.answer === "refuse-v0") say({ schemaVersion: "cultnet.error.v0", error: "no", routingHint: null, code: "write_not_authorized", details: null }, remote.port, remote.address); + else if (script.answer === "refuse-v1-other") say({ schemaVersion: "cultnet.error.v1", error: "no", routingHint: null, code: "write_not_authorized", details: null, messageId: "someone-else" }, remote.port, remote.address); + else if (script.answer === "refuse-v1-same") say({ schemaVersion: "cultnet.error.v1", error: "no", routingHint: null, code: "write_not_authorized", details: null, messageId: put.messageId }, remote.port, remote.address); + else if (script.answer === "refuse-v1-none") say({ schemaVersion: "cultnet.error.v1", error: "no", routingHint: null, code: "write_not_authorized", details: null, messageId: null }, remote.port, remote.address); + } + if (packet.reliable && script.ack !== false) send(session.createAckForReceived(packet.sequence), remote.port, remote.address); + }); + return { port: socket.address().port, close: () => socket.close() }; +} + +let nextConnection = 0x0d1d1000; +const put = (id: string) => ({ schemaVersion: "cultnet.document_put_raw.v0", messageId: id, document: { schemaId: "s", recordKey: "k", storedAt: "t", payloadEncoding: "messagepack", payload: new Uint8Array([1]) } }); +const sendTo = (server: { port: number }, id: string, connectionId: number) => + sendPresenceDocument({ host: "127.0.0.1", port: server.port }, connectionId, put(id)); + +for (const answer of ["silence", "echo", "admitted", "refuse-v1-other"] as const) { + test(`a ${answer} Odin yields sent, never admitted: no frame carrying the put's id is success`, async () => { + const connectionId = nextConnection++; + const server = await fakeOdin(connectionId, { answer }); + try { + const outcome = await sendTo(server, "presence-1", connectionId); + assert.equal(outcome, "sent"); + assert.notEqual(outcome as string, "admitted"); + } finally { server.close(); } + }); +} + +test("a refusal that arrives by the transport ack rejects the put", async () => { + const connectionId = nextConnection++; + const server = await fakeOdin(connectionId, { answer: "refuse-v0" }); + try { + await assert.rejects(sendTo(server, "presence-1", connectionId), IdunnPresenceRefusedError); + } finally { server.close(); } +}); + +for (const answer of ["refuse-v1-same", "refuse-v1-none"] as const) { + test(`an error.v1 refusal that ${answer === "refuse-v1-same" ? "names this put" : "names no put"} rejects the put`, async () => { + const connectionId = nextConnection++; + const server = await fakeOdin(connectionId, { answer }); + try { + await assert.rejects(sendTo(server, "presence-1", connectionId), IdunnPresenceRefusedError); + } finally { server.close(); } + }); +} + +test("a put the transport never acknowledges is an error, not sent", async () => { + const connectionId = nextConnection++; + const server = await fakeOdin(connectionId, { answer: "silence", ack: false }); + try { + await assert.rejects(sendTo(server, "presence-1", connectionId), /Timed out/); + } finally { server.close(); } +}); diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 2e05bbf4..50236782 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -345,18 +345,27 @@ test("the Odin publisher publishes the signer's document to the endpoint Expecte assert.equal(peer.failure, undefined, peer.failure?.message); }); -for (const order of ["ack-then-refusal", "refusal-then-ack"] as const) { - test(`the Odin publisher does not complete on the ack of a refused presence (${order})`, async (context) => { - const endpoint = expectedFacts("service").odinEndpoint!; - const peer = await startOdinPeer(context, endpoint); - peer.reject = true; - peer.order = order; - const signer = signerFor(context, "service"); - signer.reportHealth("active"); - const publisher = createIdunnRuntimePresencePublisher({ signer, endpoint }); - await assert.rejects(publisher.publish("denied presence"), /Odin rejected runtime presence: test admission denied/); - }); -} +test("the Odin publisher rejects a presence whose refusal arrives before the transport ack", async (context) => { + const endpoint = expectedFacts("service").odinEndpoint!; + const peer = await startOdinPeer(context, endpoint); + peer.reject = true; + peer.order = "refusal-then-ack"; + const signer = signerFor(context, "service"); + signer.reportHealth("active"); + const publisher = createIdunnRuntimePresencePublisher({ signer, endpoint }); + await assert.rejects(publisher.publish("denied presence"), /Odin rejected runtime presence: test admission denied/); +}); + +test("the Odin publisher is send-only: a refusal that follows the transport ack is not awaited", async (context) => { + const endpoint = expectedFacts("service").odinEndpoint!; + const peer = await startOdinPeer(context, endpoint); + peer.reject = true; + peer.order = "ack-then-refusal"; + const signer = signerFor(context, "service"); + signer.reportHealth("active"); + const publisher = createIdunnRuntimePresencePublisher({ signer, endpoint }); + await publisher.publish("denied presence"); +}); test("the Odin publisher leaves a capability shortfall to the Rust correlation instead of refusing to publish", async (context) => { const endpoint = expectedFacts("service").odinEndpoint!; diff --git a/packages/cultnet-ts/test/write-receipt.test.ts b/packages/cultnet-ts/test/write-receipt.test.ts new file mode 100644 index 00000000..6acb79cf --- /dev/null +++ b/packages/cultnet-ts/test/write-receipt.test.ts @@ -0,0 +1,282 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { + CULTNET_ERROR_CODES, + CULTNET_ERROR_V1_CODES, + CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS, + LEGACY_RESULT_WINDOW_MS, + RECEIPT_RESULT_WINDOW_MS, + WriteTracker, + cultNetSchemas, + helloAdvertisesWriteReceipts, + parseCultNetMessage, + resultWindowMs, + type CultNetErrorV1Message, + type CultNetMessage, + type CultNetWriteAdmittedMessage, + type WriteSettlement, +} from "../src"; + +const admitted = (messageId: string): CultNetWriteAdmittedMessage => + ({ schemaVersion: "cultnet.write_admitted.v0", messageId, operation: "put", schemaId: "note.v0", recordKey: "note:1" }); +const refusedV1 = (messageId: string | null, code: CultNetErrorV1Message["code"] = "write_not_authorized"): CultNetErrorV1Message => + ({ schemaVersion: "cultnet.error.v1", error: "no", routingHint: null, code, details: null, messageId }); +const errorV0 = (): CultNetMessage => + ({ schemaVersion: "cultnet.error.v0", error: "no", routingHint: null, code: "write_not_authorized", details: null }); + +test("error.v1 accepts every code of its closed enum, limit_reached included, and refuses any other", () => { + const schemaCodes = ((cultNetSchemas.errorV1Schema.properties.code as { enum: (string | null)[] }).enum).filter((c) => c !== null); + assert.deepEqual([...CULTNET_ERROR_V1_CODES].sort(), [...schemaCodes].sort()); + for (const code of CULTNET_ERROR_V1_CODES) parseCultNetMessage({ ...refusedV1("w1"), code }); + assert.throws(() => parseCultNetMessage({ ...refusedV1("w1"), code: "invented" })); +}); + +test("error.v1 echoes messageId byte for byte, allows nil, and requires the key", () => { + assert.equal((parseCultNetMessage(refusedV1("w-é 1")) as CultNetErrorV1Message).messageId, "w-é 1"); + assert.equal((parseCultNetMessage(refusedV1(null)) as CultNetErrorV1Message).messageId, null); + const { messageId: _omitted, ...withoutId } = refusedV1("w1"); + assert.throws(() => parseCultNetMessage(withoutId)); + assert.throws(() => parseCultNetMessage(refusedV1(""))); +}); + +test("error.v0 is unaffected: still closed, no messageId, no limit_reached", () => { + assert.deepEqual([...CULTNET_ERROR_CODES].includes("limit_reached" as never), false); + assert.throws(() => parseCultNetMessage({ ...errorV0(), code: "limit_reached" })); + assert.throws(() => parseCultNetMessage({ ...errorV0(), messageId: "w1" })); + assert.equal(parseCultNetMessage(errorV0()).schemaVersion, "cultnet.error.v0"); +}); + +test("write_admitted needs all five keys, a known operation and no error key", () => { + parseCultNetMessage(admitted("w1")); + parseCultNetMessage({ ...admitted("w1"), operation: "delete" }); + assert.throws(() => parseCultNetMessage({ ...admitted("w1"), operation: "upsert" })); + assert.throws(() => parseCultNetMessage({ ...admitted("w1"), error: "nope" })); + const { recordKey: _omitted, ...short } = admitted("w1"); + assert.throws(() => parseCultNetMessage(short)); +}); + +test("a hello is receipt-capable only when it lists both frames", () => { + assert.equal(helloAdvertisesWriteReceipts({ supportedMessageVersions: [...CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS] }), true); + assert.equal(helloAdvertisesWriteReceipts({ supportedMessageVersions: ["cultnet.write_admitted.v0"] }), false); + assert.equal(helloAdvertisesWriteReceipts({ supportedMessageVersions: ["cultnet.error.v1"] }), false); + assert.equal(helloAdvertisesWriteReceipts({}), false); + const hello = parseCultNetMessage({ schemaVersion: "cultnet.hello.v0", runtimeId: "r", runtimeKind: "k", supportedMessageVersions: [...CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS] }); + assert.equal(hello.schemaVersion, "cultnet.hello.v0"); +}); + +test("the window is 5000 ms for a receipt-capable server and 500 ms otherwise", () => { + assert.equal(resultWindowMs(true), RECEIPT_RESULT_WINDOW_MS); + assert.equal(resultWindowMs(false), LEGACY_RESULT_WINDOW_MS); + assert.equal(RECEIPT_RESULT_WINDOW_MS, 5000); + assert.equal(LEGACY_RESULT_WINDOW_MS, 500); +}); + +function tracker(windowMs = 500) { + const told: [string, WriteSettlement][] = []; + return { told, t: new WriteTracker({ windowMs, onSettle: (id, s) => told.push([id, s]) }) }; +} + +test("tracker: the window is inclusive at exactly windowMs and open one ms before", () => { + const { t, told } = tracker(); + t.send("w1", 100); + t.tick(599); + assert.equal(t.state("w1")?.outcome, "pending"); + t.tick(600); + assert.deepEqual(told, [["w1", { outcome: "unconfirmed", reason: "window_elapsed" }]]); +}); + +test("tracker: each write's window runs from its own send", () => { + const { t } = tracker(); + t.send("w1", 0); + t.send("w2", 300); + t.tick(500); + assert.equal(t.state("w1")?.outcome, "unconfirmed"); + assert.equal(t.state("w2")?.outcome, "pending"); +}); + +test("tracker: a frame arriving after the window cannot admit the write; it is recorded late", () => { + const { t, told } = tracker(); + t.send("w1", 0); + t.frame(admitted("w1"), 500); + assert.deepEqual(t.state("w1"), { outcome: "unconfirmed", reason: "window_elapsed", recorded: "admitted_late" }); + assert.equal(told.length, 1); +}); + +test("tracker: a write settles once; later frames neither change it nor flip a late record", () => { + const { t, told } = tracker(); + t.send("w1", 0); + t.frame(refusedV1("w1"), 10); + t.frame(admitted("w1"), 20); + t.frame(refusedV1("w1", "message_invalid"), 30); + t.sessionEnd(40); + assert.equal(told.length, 1); + assert.deepEqual(told[0][1], { outcome: "refused", code: "write_not_authorized", error: "no", response: refusedV1("w1") }); + t.send("w2", 100); + t.tick(600); + t.frame(refusedV1("w2"), 700); + t.frame(admitted("w2"), 800); + assert.equal(t.state("w2")?.outcome === "unconfirmed" && t.state("w2")?.recorded, "refused_late"); +}); + +test("tracker: an id-less error refuses the single unanswered write only, counting answered writes out", () => { + const { t } = tracker(); + t.send("w1", 0); + t.send("w2", 1); + t.frame(admitted("w1"), 5); + t.frame(refusedV1(null), 6); + assert.equal(t.state("w1")?.outcome, "admitted"); + assert.equal(t.state("w2")?.outcome, "refused"); +}); + +test("tracker: an id-less error never reaches a write that already ended unconfirmed", () => { + const { t } = tracker(); + t.send("w1", 0); + t.tick(500); + t.frame(errorV0(), 501); + assert.deepEqual(t.state("w1"), { outcome: "unconfirmed", reason: "window_elapsed" }); +}); + +test("tracker: sessionEnd settles unanswered writes only, and an expired window keeps its own reason", () => { + const { t } = tracker(); + t.send("w1", 0); + t.send("w2", 0); + t.send("w3", 400); + t.frame(admitted("w2"), 10); + t.sessionEnd(600); + assert.deepEqual(t.state("w1"), { outcome: "unconfirmed", reason: "window_elapsed" }); + assert.equal(t.state("w2")?.outcome, "admitted"); + assert.deepEqual(t.state("w3"), { outcome: "unconfirmed", reason: "session_ended" }); +}); + +test("tracker: re-sending a known id is the same write and does not restart its window", () => { + const { t } = tracker(); + t.send("w1", 0); + t.send("w1", 400); + t.tick(500); + assert.equal(t.state("w1")?.outcome, "unconfirmed"); +}); + +test("tracker: a send past another write's window settles that write at once", () => { + const { t, told } = tracker(); + t.send("w1", 0); + t.send("w2", 600); + assert.deepEqual(told, [["w1", { outcome: "unconfirmed", reason: "window_elapsed" }]]); +}); + +test("tracker: only receipt and error frames answer; any other frame naming the id settles nothing", () => { + const { t } = tracker(); + t.send("w1", 0); + t.frame({ schemaVersion: "cultnet.hello.v0", runtimeId: "r", runtimeKind: "k" }, 1); + t.frame({ schemaVersion: "cultnet.document_put_raw.v0", messageId: "w1" } as unknown as CultNetMessage, 2); + assert.equal(t.state("w1")?.outcome, "pending"); +}); + +test("tracker: nextDeadlineMs reports the nearest unanswered window, none when all settled", () => { + const { t } = tracker(); + assert.equal(t.nextDeadlineMs(0), undefined); + t.send("w1", 0); + t.send("w2", 100); + assert.equal(t.nextDeadlineMs(50), 450); + assert.equal(t.nextDeadlineMs(900), 0); + t.frame(admitted("w1"), 60); + assert.equal(t.nextDeadlineMs(150), 450); + t.frame(admitted("w2"), 160); + assert.equal(t.nextDeadlineMs(170), undefined); +}); + +test("the replay runner passes every vector against this runtime", () => { + const script = join(__dirname, "..", "..", "tools", "replay-write-receipt-vectors.mjs"); + const run = spawnSync(process.execPath, [script], { encoding: "utf8" }); + assert.equal(run.status, 0, run.stdout + run.stderr); + assert.match(run.stdout, /^PASS scenario\/receipt_admits$/m); + assert.doesNotMatch(run.stdout, /^FAIL/m); +}); + +// A runner that skips what it cannot read passes a file it did not replay. It must fail instead. +test("the replay runner fails on an unknown event key and on a vector count the file does not declare", () => { + const script = join(__dirname, "..", "..", "tools", "replay-write-receipt-vectors.mjs"); + const vectorsPath = join(__dirname, "..", "..", "..", "..", "contracts", "cultnet", "interop", "write-receipt-vectors.json"); + const dir = mkdtempSync(join(tmpdir(), "receipt-vectors-")); + const runWith = (edit: (vectors: any) => void) => { + const vectors = JSON.parse(readFileSync(vectorsPath, "utf8")); + edit(vectors); + const file = join(dir, "vectors.json"); + writeFileSync(file, JSON.stringify(vectors)); + return spawnSync(process.execPath, [script, file], { encoding: "utf8" }); + }; + const typo = runWith((v) => { v.scenarios.cases[0].events[0] = { atMs: 0, sendfailed: "w1" }; }); + assert.equal(typo.status, 1, typo.stdout); + assert.match(typo.stdout, /^FAIL scenario\/receipt_admits$/m); + const dropped = runWith((v) => { v.scenarios.cases.pop(); }); + assert.equal(dropped.status, 1, dropped.stdout); + assert.match(dropped.stdout, /^FAIL counts$/m); + const undeclared = runWith((v) => { v.wire.push(v.wire[0]); }); + assert.equal(undeclared.status, 1, undeclared.stdout); +}); + +test("a write sent after the session ended settles unconfirmed session_ended at once, and the earlier receipt stands", () => { + const settled: [string, WriteSettlement][] = []; + const tracker = new WriteTracker({ windowMs: 1000, onSettle: (id, settlement) => settled.push([id, settlement]) }); + tracker.send("w1", 0); + tracker.frame(admitted("w1"), 5); + tracker.sessionEnd(40); + tracker.send("w2", 50); + assert.deepEqual(settled, [["w1", { outcome: "admitted" }], ["w2", { outcome: "unconfirmed", reason: "session_ended" }]]); +}); + +test("a failed local send settles only that write unconfirmed as local_send_failed, and an answer after it is recorded late", () => { + const settled: [string, WriteSettlement][] = []; + const tracker = new WriteTracker({ windowMs: 1000, onSettle: (id, settlement) => settled.push([id, settlement]) }); + tracker.send("w1", 0); + tracker.send("w2", 0); + tracker.sendFailed("w1", 10); + assert.deepEqual(settled, [["w1", { outcome: "unconfirmed", reason: "local_send_failed" }]]); + assert.equal(tracker.state("w2")?.outcome, "pending"); + tracker.frame(admitted("w1"), 20); + assert.deepEqual(tracker.state("w1"), { outcome: "unconfirmed", reason: "local_send_failed", recorded: "admitted_late" }); + tracker.sendFailed("w2", 30); + tracker.sendFailed("w2", 31); + assert.equal(settled.length, 2, "a write settles once"); + tracker.sendFailed("unknown", 40); + assert.equal(tracker.state("unknown"), undefined); +}); + +test("a failed local send advances the clock: other writes whose windows have run settle window_elapsed", () => { + const tracker = new WriteTracker({ windowMs: 1000 }); + tracker.send("w1", 0); + tracker.send("w2", 500); + tracker.sendFailed("w2", 1200); + assert.deepEqual(tracker.state("w1"), { outcome: "unconfirmed", reason: "window_elapsed" }); + assert.deepEqual(tracker.state("w2"), { outcome: "unconfirmed", reason: "local_send_failed" }); +}); + +test("a write whose own send failed settles local_send_failed even when its window has also run", () => { + const tracker = new WriteTracker({ windowMs: 1000 }); + tracker.send("w1", 0); + tracker.sendFailed("w1", 1000); + assert.deepEqual(tracker.state("w1"), { outcome: "unconfirmed", reason: "local_send_failed" }); +}); + +// Blank is Unicode White_Space (write-receipt.md, rule 5), not what String.prototype.trim() trims: trim() takes U+FEFF and +// misses U+0085. Every frame decoder that rejects a blank text must agree with the servers that do. +test("a blank messageId, record key or tag is exactly Unicode White_Space, not trim()", () => { + const put = (document: Record, messageId = "p1") => ({ + schemaVersion: "cultnet.document_put_raw.v0", messageId, + document: { schemaId: "note.v0", recordKey: "note:1", storedAt: "2026-11-08T00:00:00Z", payloadEncoding: "messagepack", payload: Uint8Array.of(0x81, 0xa1, 0x61, 0x01), ...document }, + }); + for (const blank of ["\u0085", "  ", " "]) { + assert.throws(() => parseCultNetMessage(put({}, blank)), `messageId ${JSON.stringify(blank)}`); + assert.throws(() => parseCultNetMessage(put({ recordKey: blank })), `recordKey ${JSON.stringify(blank)}`); + assert.throws(() => parseCultNetMessage(put({ tags: [blank] })), `tag ${JSON.stringify(blank)}`); + } + for (const named of ["", "​", "\u001c", "᠎"]) { + parseCultNetMessage(put({}, named)); + parseCultNetMessage(put({ recordKey: named })); + parseCultNetMessage(put({ tags: [named] })); + } +}); diff --git a/packages/cultnet-ts/tools/replay-write-receipt-vectors.mjs b/packages/cultnet-ts/tools/replay-write-receipt-vectors.mjs new file mode 100644 index 00000000..87da14e9 --- /dev/null +++ b/packages/cultnet-ts/tools/replay-write-receipt-vectors.mjs @@ -0,0 +1,132 @@ +#!/usr/bin/env node +// Replays contracts/cultnet/interop/write-receipt-vectors.json against this runtime: every `scenarios.cases` event +// replay through a fake server and the WriteTracker, and every `wire` / `schemaInvalid` frame through the real +// decoder. Prints PASS/FAIL per case; exit 1 on any failure. Runs against the built package (`npm run build` first). +// +// node tools/replay-write-receipt-vectors.mjs [path/to/write-receipt-vectors.json] +// +// The runner interface a port (Rust, C#) must reproduce is documented in README.md, "Write receipt replay runner". + +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { createRequire } from "node:module"; + +const require = createRequire(import.meta.url); +const here = path.dirname(fileURLToPath(import.meta.url)); +const { decode, encode } = require("@msgpack/msgpack"); +const { + CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS, LEGACY_RESULT_WINDOW_MS, RECEIPT_RESULT_WINDOW_MS, WriteTracker, + encodeCultNetMessageForWire, helloAdvertisesWriteReceipts, parseCultNetMessage, resultWindowMs, +} = require(path.join(here, "..", "dist", "index.js")); + +const vectorsPath = process.argv[2] ?? path.join(here, "..", "..", "..", "contracts", "cultnet", "interop", "write-receipt-vectors.json"); +const vectors = JSON.parse(readFileSync(vectorsPath, "utf8")); + +// The event actions scenarios.semantics names; anything else is refused, not skipped. +const EVENT_KEYS = ["send", "frame", "tick", "sessionEnd", "sendFailed", "transportAck"]; + +const results = []; +const check = (name, run) => { + try { + const problems = run(); + results.push({ name, problems }); + } catch (error) { + results.push({ name, problems: [`threw: ${error instanceof Error ? error.message : String(error)}`] }); + } +}; +const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex, "hex")); +const hexOf = (bytes) => Buffer.from(bytes).toString("hex").toUpperCase(); +// A frame reaches the client as bytes: the fake server encodes it, the client decodes and validates it. +const delivered = (frame) => parseCultNetMessage(decode(encode(frame))); + +check("constants", () => [ + ...(vectors.constants.RECEIPT_RESULT_WINDOW_MS === RECEIPT_RESULT_WINDOW_MS ? [] : [`RECEIPT window ${RECEIPT_RESULT_WINDOW_MS} != ${vectors.constants.RECEIPT_RESULT_WINDOW_MS}`]), + ...(vectors.constants.LEGACY_RESULT_WINDOW_MS === LEGACY_RESULT_WINDOW_MS ? [] : [`LEGACY window ${LEGACY_RESULT_WINDOW_MS} != ${vectors.constants.LEGACY_RESULT_WINDOW_MS}`]), +]); + +for (const vector of vectors.wire) { + check(`wire/${vector.name}`, () => { + const problems = []; + const parsed = parseCultNetMessage(decode(bytesOf(vector.messagePackHex))); + if (JSON.stringify(sorted(parsed)) !== JSON.stringify(sorted(vector.message))) problems.push(`decoded ${JSON.stringify(parsed)} != ${JSON.stringify(vector.message)}`); + const reencoded = hexOf(encode(encodeCultNetMessageForWire(parsed))); + if (reencoded !== vector.messagePackHex.toUpperCase()) problems.push(`re-encoded bytes ${reencoded} != captured ${vector.messagePackHex}`); + return problems; + }); +} + +for (const vector of vectors.schemaInvalid) { + check(`schemaInvalid/${vector.name}`, () => { + try { + parseCultNetMessage(decode(bytesOf(vector.messagePackHex))); + } catch { + return []; + } + return [`accepted a frame that must be refused (${vector.why})`]; + }); +} + +for (const scenario of vectors.scenarios.cases) { + check(`scenario/${scenario.name}`, () => { + // The fake server states its capability the only way a real one does: in its hello. + const serverHello = { schemaVersion: "cultnet.hello.v0", runtimeId: "fake-server", runtimeKind: "fake", + ...(scenario.server === "receipt" ? { supportedMessageVersions: [...CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS] } : {}) }; + const windowMs = resultWindowMs(helloAdvertisesWriteReceipts(serverHello)); + const problems = []; + if (windowMs !== vectors.constants[scenario.window]) problems.push(`window ${windowMs} != ${scenario.window}`); + + const told = new Map(); // what the caller was told, at settle time + const tracker = new WriteTracker({ windowMs, onSettle: (id, settlement) => { + if (told.has(id)) problems.push(`${id} settled twice`); + told.set(id, settlement); + } }); + for (const event of [...scenario.events].sort((a, b) => a.atMs - b.atMs)) { + const actions = Object.keys(event).filter((key) => key !== "atMs"); + if (actions.length !== 1 || !EVENT_KEYS.includes(actions[0])) { problems.push(`event at ${event.atMs} has keys [${actions}], wanted atMs and exactly one of ${EVENT_KEYS}`); continue; } + if ("send" in event) tracker.send(event.send, event.atMs); + else if ("frame" in event) tracker.frame(delivered(event.frame), event.atMs); + else if ("tick" in event) tracker.tick(event.atMs); + else if ("sessionEnd" in event) tracker.sessionEnd(event.atMs); + else if ("sendFailed" in event) tracker.sendFailed(event.sendFailed, event.atMs); + // transportAck: delivery is not an answer; the tracker has no such input and must not need one. + } + for (const [id, want] of Object.entries(scenario.expect)) { + const got = told.get(id); + if (!got) { problems.push(`${id}: never settled, wanted ${want.outcome}`); continue; } + if (got.outcome !== want.outcome) problems.push(`${id}: told ${got.outcome}, wanted ${want.outcome}`); + if (want.code !== undefined && got.code !== want.code) problems.push(`${id}: code ${got.code}, wanted ${want.code}`); + if (want.reason !== undefined && got.reason !== want.reason) problems.push(`${id}: reason ${got.reason}, wanted ${want.reason}`); + const recorded = tracker.state(id)?.recorded; + if (recorded !== want.recorded) problems.push(`${id}: recorded ${recorded}, wanted ${want.recorded}`); + } + for (const id of told.keys()) if (!(id in scenario.expect)) problems.push(`${id}: settled but the scenario expects nothing for it`); + return problems; + }); +} + +// A runner that read fewer vectors than the file declares has silently skipped some. (contentHash is not replayed here.) +check("counts", () => { + const ran = (prefix) => results.filter((r) => r.name.startsWith(prefix)).length; + const loaded = { wire: vectors.wire.length, schemaInvalid: vectors.schemaInvalid.length, scenarioCases: vectors.scenarios.cases.length }; + const executed = { wire: ran("wire/"), schemaInvalid: ran("schemaInvalid/"), scenarioCases: ran("scenario/") }; + return Object.keys(executed) + .filter((key) => loaded[key] !== vectors.counts[key] || executed[key] !== vectors.counts[key]) + .map((key) => `${key}: declared ${vectors.counts[key]}, loaded ${loaded[key]}, ran ${executed[key]}`); +}); + +function sorted(value) { + if (Array.isArray(value)) return value.map(sorted); + if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((k) => [k, sorted(value[k])])); + return value; +} + +let failed = 0; +for (const { name, problems } of results) { + if (problems.length === 0) { console.log(`PASS ${name}`); continue; } + failed++; + console.log(`FAIL ${name}`); + for (const problem of problems) console.log(` ${problem}`); +} +console.log(`${results.length - failed}/${results.length} passed`); +process.exit(failed === 0 ? 0 : 1); diff --git a/src/GameCult.Networking/CultNetDatabase.cs b/src/GameCult.Networking/CultNetDatabase.cs index d9e7ec09..af561ea5 100644 --- a/src/GameCult.Networking/CultNetDatabase.cs +++ b/src/GameCult.Networking/CultNetDatabase.cs @@ -1017,6 +1017,8 @@ namespace GameCult.Networking /// /// Applies a raw document mutation after checking shard authority. This is the host's own door (and replication's): /// it asks no remote write authority. A peer's put goes through , which does. + /// Returning normally means the put is committed and visible to readers: a receipt-capable peer is told + /// write_admitted on the strength of it, so a write that has only been queued must not return. /// /// No shard owns the schema and key; nothing was written. /// The change committed and was published, but the shard log could not record it. @@ -1047,6 +1049,7 @@ namespace GameCult.Networking /// /// Applies a raw document delete after checking shard authority. This is the host's own door: it asks no remote /// write authority. A peer's delete goes through , which does. + /// Returning normally means the delete is committed and visible to readers (see ). /// /// No shard owns the schema and key; nothing was written. /// The change committed and was published, but the shard log could not record it. diff --git a/src/GameCult.Networking/CultNetDatabaseServer.cs b/src/GameCult.Networking/CultNetDatabaseServer.cs index 6433c6c3..e1694131 100644 --- a/src/GameCult.Networking/CultNetDatabaseServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseServer.cs @@ -22,6 +22,7 @@ namespace GameCult.Networking private readonly Func _snapshotHandlerV1; private readonly Func _putHandler; private readonly Func _deleteHandler; + private readonly Func _helloHandler; private readonly Func _shardCatalogHandler; private readonly Func _shardLogHandler; private readonly Func _subscribeHandler; @@ -45,6 +46,7 @@ namespace GameCult.Networking _snapshotHandlerV1 = HandleSnapshotRequestV1Async; _putHandler = HandlePutAsync; _deleteHandler = HandleDeleteAsync; + _helloHandler = HandleHelloAsync; _shardCatalogHandler = HandleShardCatalogRequestAsync; _shardLogHandler = HandleShardLogRequestAsync; _subscribeHandler = HandleSubscribeAsync; @@ -55,6 +57,7 @@ namespace GameCult.Networking _server.OnCultNet(_snapshotHandlerV1); _server.OnCultNet(_putHandler); _server.OnCultNet(_deleteHandler); + _server.OnCultNet(_helloHandler); _server.OnCultNet(_shardCatalogHandler); _server.OnCultNet(_shardLogHandler); _server.OnCultNet(_subscribeHandler); @@ -217,6 +220,7 @@ namespace GameCult.Networking _server.RemoveCultNetMessageListener(_snapshotHandlerV1); _server.RemoveCultNetMessageListener(_putHandler); _server.RemoveCultNetMessageListener(_deleteHandler); + _server.RemoveCultNetMessageListener(_helloHandler); _server.RemoveCultNetMessageListener(_shardCatalogHandler); _server.RemoveCultNetMessageListener(_shardLogHandler); _server.RemoveCultNetMessageListener(_subscribeHandler); @@ -262,7 +266,7 @@ namespace GameCult.Networking catch (Exception ex) { _server.Logger.LogError($"CultNet snapshot v1 request failed: {ex.Message}"); - peer.SendCultNet(new CultNetErrorMessage { Error = ex.Message }); + peer.SendCultNet(new CultNetErrorMessage { Error = "the snapshot request could not be answered" }); } return Task.CompletedTask; @@ -282,7 +286,8 @@ namespace GameCult.Networking } catch (Exception ex) { - peer.SendCultNet(new CultNetErrorMessage { Error = ex.Message }); + _server.Logger.LogError($"CultNet shard log request failed: {ex.Message}"); + peer.SendCultNet(new CultNetErrorMessage { Error = "the shard log request could not be answered" }); } return Task.CompletedTask; @@ -323,74 +328,273 @@ namespace GameCult.Networking }; } - private async Task HandlePutAsync(CultNetDocumentPutRawMessage message, CultNetServerPeer peer) + // A hello decides the connection's write framing if it is the first thing to (write-receipt.md, "Capability"). The + // server answers a receipt-capable hello with its own, so the client can tell a receipt server from a legacy one. + private Task HandleHelloAsync(CultNetHelloMessage hello, CultNetServerPeer peer) + { + if (peer.Transport != null && peer.Transport.SettleWriteFraming(hello)) + { + Answer(peer, new CultNetHelloMessage + { + RuntimeId = "gamecult-networking-database-server", + RuntimeKind = "dotnet", + SupportedMessageVersions = [CultNetSchemaVersions.WriteAdmitted, CultNetSchemaVersions.ErrorV1] + }); + } + + return Task.CompletedTask; + } + + // The write's receipt state, or null when its connection did not opt in (it is then answered exactly as before). + private CultNetReceiptedWrite? BeginReceipted( + CultNetServerPeer peer, + string operation, + string? messageId, + string? schemaId, + string? recordKey, + byte[]? payload) + { + var transport = peer.Transport; + if (transport == null) return null; + transport.SettleWriteFraming(null); + var session = transport.WriteReceipts; + return session == null + ? null + : new CultNetReceiptedWrite(session, message => Answer(peer, message), operation, messageId, schemaId, recordKey, payload); + } + + // Every frame a write can be answered with. Mock point for tests: the answer leaves through the peer's transport. An + // answer that cannot be queued ends the connection: the peer settles its write as session_ended, never as silence. + private void Answer(CultNetServerPeer peer, ICultNetSchemaMessage message) { try { - await _database.ApplyPutAsync(message, Authorize(peer, CultNetRemoteWriteOperation.Put, message.ShardId, message.ShardEpoch)) - .ConfigureAwait(false); + Send(peer, message); + } + catch (Exception ex) + { + _server.Logger.LogWarning($"CultNet write answer could not be sent; ending the connection: {ex.Message}"); + peer.Transport?.End(); + } + } + + private static void Send(CultNetServerPeer peer, ICultNetSchemaMessage message) + { + switch (message) + { + case CultNetWriteAdmittedMessage admitted: peer.SendCultNet(admitted); break; + case CultNetErrorV1Message error: peer.SendCultNet(error); break; + case CultNetErrorMessage error: peer.SendCultNet(error); break; + case CultNetHelloMessage hello: peer.SendCultNet(hello); break; + default: throw new ArgumentException($"{message.GetType().Name} is not a write answer.", nameof(message)); + } + } + + // A write that names nothing is refused as a frame that does not read, exactly as the Rust server's decoder refuses it + // (write-receipt.md, "Required fields"), never handed to the store: a blank schemaId, recordKey or storedAt, an empty + // payload, and a source id or tag that is present but blank. + private static bool IsUnreadableWriteTarget(string? schemaId, string? recordKey) => + IsBlank(schemaId) || IsBlank(recordKey); + + private static bool IsUnreadableDocument(CultNetRawDocumentRecord document) => + IsUnreadableWriteTarget(document.SchemaId, document.RecordKey) + || IsBlank(document.StoredAt) + || document.Payload == null || document.Payload.Length == 0 + || IsPresentButBlank(document.SourceRuntimeId) + || IsPresentButBlank(document.SourceAgentId) + || IsPresentButBlank(document.SourceRole) + || document.Tags != null && document.Tags.Any(IsBlank); + + private static bool IsPresentButBlank(string? value) => value != null && IsBlank(value); + + // Blank is the Unicode White_Space property, listed here and in write-receipt.md, not char.IsWhiteSpace: the platform's + // own test follows its Unicode tables (and has put U+180E in the set), the spec's does not move. A null is not text. + private static bool IsBlank(string? value) => value == null || value.All(IsWhiteSpaceCodePoint); + + private static bool IsWhiteSpaceCodePoint(char c) => + c is (>= '\u0009' and <= '\u000D') or '\u0020' or '\u0085' or '\u00A0' or '\u1680' + or (>= '\u2000' and <= '\u200A') or '\u2028' or '\u2029' or '\u202F' or '\u205F' or '\u3000'; + + // A refusal: error.v1 carrying the write's id for a receipt-capable connection, the v0 error for any other. + private static void Refuse(CultNetServerPeer peer, CultNetReceiptedWrite? write, CultNetErrorMessage error) + { + if (write != null) write.Refused(error); + else peer.SendCultNet(error); + } + + // Rule 6: a forward is answered with what the primary answered, under the original id. A refusal the primary sent is + // relayed; silence or any other failure relays nothing, so the client settles it unconfirmed. + private void RelayForwardFailure(CultNetReceiptedWrite write, Exception failure) + { + if (failure is CultNetWriteRefusedException refused) + { + write.Refused(refused.Refusal); + return; + } + + _server.Logger.LogWarning($"CultNet forwarded write was not answered by its primary: {failure.Message}"); + // Only a forward that provably never left (not sent) may be forwarded again. Every other failure, silence or not, is + // unconfirmed: the primary may have applied it, so the id is never forwarded again on this session. + if (failure is CultNetWriteNotSentException) write.NotSent(); + else write.LeftSilent(); + } + + private async Task HandlePutAsync(CultNetDocumentPutRawMessage message, CultNetServerPeer peer) + { + var write = BeginReceipted(peer, "put", message.MessageId, message.Document?.SchemaId, message.Document?.RecordKey, message.Document?.Payload); + var idRefusal = write?.IdRefusal; + if (idRefusal != null) + { + write!.Refused(idRefusal); + return; + } + + var missing = message.Document == null ? "document" : message.Document.SchemaId == null ? "schemaId" : null; + if (missing != null) + { + Refuse(peer, write, CultNetErrorMessage.ForMessageInvalid(missing, $"{missing} is required")); + return; + } + + if (IsUnreadableDocument(message.Document!)) + { + Refuse(peer, write, CultNetErrorMessage.ForUnreadableMessage()); + return; + } + + if (write != null && !write.Begin()) return; + + var authorize = Authorize(peer, CultNetRemoteWriteOperation.Put, message.ShardId, message.ShardEpoch); + try + { + await _database.ApplyPutAsync(message, authorize).ConfigureAwait(false); + write?.Admitted(); } catch (CultNetRemoteWriteRefusedException ex) { _server.Logger.LogWarning($"CultNet raw put refused: {ex.Message}"); - peer.SendCultNet(CultNetErrorMessage.ForRemoteWriteRefused(ex.Request, ex.Reason)); + Refuse(peer, write, CultNetErrorMessage.ForRemoteWriteRefused(ex.Request, ex.Reason)); } catch (CultNetShardAuthorityException ex) { - if (!await TryForwardPutAsync(ex, message).ConfigureAwait(false)) + bool forwarded; + try + { + forwarded = await TryForwardPutAsync(ex, message).ConfigureAwait(false); + } + catch (CultNetWriteUnconfirmedException) when (write == null) + { + // A peer that did not opt in is told nothing of a forward its primary left unanswered. + return; + } + catch (Exception failure) when (write != null) + { + RelayForwardFailure(write, failure); + return; + } + + if (forwarded) + { + write?.Admitted(); + } + else { _server.Logger.LogError($"CultNet raw put authority failed: {ex.Message}"); - peer.SendCultNet(CreateRoutingError(ex)); + Refuse(peer, write, CreateRoutingError(ex)); } } catch (CultNetUnownedSchemaException ex) { _server.Logger.LogWarning($"CultNet raw put refused: {ex.Message}"); - peer.SendCultNet(CultNetErrorMessage.ForUnownedSchema(ex)); + Refuse(peer, write, CultNetErrorMessage.ForUnownedSchema(ex)); } catch (Exception ex) when (CommittedWithLogFailure(ex)) { // The write committed and was published; only its shard log failed, so the peer is not told it was refused. _server.Logger.LogWarning($"CultNet raw put committed but its shard log failed: {ex.Message}"); + write?.Admitted(); } catch (Exception ex) { _server.Logger.LogError($"CultNet raw put failed: {ex.Message}"); - peer.SendCultNet(new CultNetErrorMessage { Error = ex.Message }); + Refuse(peer, write, new CultNetErrorMessage { Error = CultNetWriteReceiptSession.WriteFailedText }); } } private async Task HandleDeleteAsync(CultNetDocumentDeleteMessage message, CultNetServerPeer peer) { + var write = BeginReceipted(peer, "delete", message.MessageId, message.SchemaId, message.RecordKey, null); + var idRefusal = write?.IdRefusal; + if (idRefusal != null) + { + write!.Refused(idRefusal); + return; + } + + if (message.SchemaId == null) + { + Refuse(peer, write, CultNetErrorMessage.ForMessageInvalid("schemaId", "schemaId is required")); + return; + } + + if (IsUnreadableWriteTarget(message.SchemaId, message.RecordKey)) + { + Refuse(peer, write, CultNetErrorMessage.ForUnreadableMessage()); + return; + } + + if (write != null && !write.Begin()) return; + + var authorize = Authorize(peer, CultNetRemoteWriteOperation.Delete, message.ShardId, message.ShardEpoch); try { - await _database.ApplyDeleteAsync(message, Authorize(peer, CultNetRemoteWriteOperation.Delete, message.ShardId, message.ShardEpoch)) - .ConfigureAwait(false); + await _database.ApplyDeleteAsync(message, authorize).ConfigureAwait(false); + write?.Admitted(); } catch (CultNetRemoteWriteRefusedException ex) { _server.Logger.LogWarning($"CultNet raw delete refused: {ex.Message}"); - peer.SendCultNet(CultNetErrorMessage.ForRemoteWriteRefused(ex.Request, ex.Reason)); + Refuse(peer, write, CultNetErrorMessage.ForRemoteWriteRefused(ex.Request, ex.Reason)); } catch (CultNetShardAuthorityException ex) { - if (!await TryForwardDeleteAsync(ex, message).ConfigureAwait(false)) + bool forwarded; + try { - peer.SendCultNet(CreateRoutingError(ex)); + forwarded = await TryForwardDeleteAsync(ex, message).ConfigureAwait(false); + } + catch (CultNetWriteUnconfirmedException) when (write == null) + { + return; + } + catch (Exception failure) when (write != null) + { + RelayForwardFailure(write, failure); + return; + } + + if (forwarded) + { + write?.Admitted(); + } + else + { + Refuse(peer, write, CreateRoutingError(ex)); } } catch (CultNetUnownedSchemaException ex) { _server.Logger.LogWarning($"CultNet raw delete refused: {ex.Message}"); - peer.SendCultNet(CultNetErrorMessage.ForUnownedSchema(ex)); + Refuse(peer, write, CultNetErrorMessage.ForUnownedSchema(ex)); } catch (Exception ex) when (CommittedWithLogFailure(ex)) { _server.Logger.LogWarning($"CultNet raw delete committed but its shard log failed: {ex.Message}"); + write?.Admitted(); } catch (Exception ex) { - peer.SendCultNet(new CultNetErrorMessage { Error = ex.Message }); + Refuse(peer, write, new CultNetErrorMessage { Error = CultNetWriteReceiptSession.WriteFailedText }); } } @@ -588,7 +792,7 @@ namespace GameCult.Networking var refusedKey = change.GetType().GetProperty("Key")?.GetValue(change) is CultRecordKey changed ? changed.Value : string.Empty; lock (refused) refused.Add(refusedKey); - sendError(new CultNetErrorMessage { Error = refusal.Message }); + sendError(new CultNetErrorMessage { Error = "the record is a variant CultNet cannot carry" }); return null; } @@ -666,11 +870,14 @@ namespace GameCult.Networking exception is CultNetShardLogException || exception is AggregateException aggregate && aggregate.Flatten().InnerExceptions.Any(inner => inner is CultNetShardLogException); + // Fixed text: the routing refusal never carries an exception's own message (the shard and reason travel in the hint). + internal const string RoutingRefusalText = "the write belongs to another shard primary"; + private static CultNetErrorMessage CreateRoutingError(CultNetShardAuthorityException exception) { return new CultNetErrorMessage { - Error = exception.Message, + Error = RoutingRefusalText, RoutingHint = new CultNetShardRoutingHint { Reason = exception.Reason, diff --git a/src/GameCult.Networking/CultNetSchemaClient.cs b/src/GameCult.Networking/CultNetSchemaClient.cs index 83865e31..79f0ce20 100644 --- a/src/GameCult.Networking/CultNetSchemaClient.cs +++ b/src/GameCult.Networking/CultNetSchemaClient.cs @@ -27,7 +27,8 @@ namespace GameCult.Networking /// /// Sends one schema-v0 message through the transport. Fire-and-forget: an ack or a return is not admission; - /// read the result frame (). + /// read the result frame (). Throws only + /// when it can prove no byte was written; any other exception leaves the send ambiguous and a forwarded write unconfirmed. /// void SendCultNet(T message) where T : ICultNetSchemaMessage; diff --git a/src/GameCult.Networking/CultNetSchemaMessageSerialization.cs b/src/GameCult.Networking/CultNetSchemaMessageSerialization.cs index d098a923..cdcca912 100644 --- a/src/GameCult.Networking/CultNetSchemaMessageSerialization.cs +++ b/src/GameCult.Networking/CultNetSchemaMessageSerialization.cs @@ -53,6 +53,8 @@ namespace GameCult.Networking CultNetSchemaVersions.Verify => Deserialize(payload), CultNetSchemaVersions.LoginSuccess => Deserialize(payload), CultNetSchemaVersions.Error => Deserialize(payload), + CultNetSchemaVersions.ErrorV1 => Deserialize(payload), + CultNetSchemaVersions.WriteAdmitted => Deserialize(payload), CultNetSchemaVersions.SampleChangeName => Deserialize(payload), CultNetSchemaVersions.SampleChat => Deserialize(payload), CultNetSchemaVersions.OperationRequest => Deserialize(payload), diff --git a/src/GameCult.Networking/CultNetSchemaMessages.cs b/src/GameCult.Networking/CultNetSchemaMessages.cs index 5f37f150..a2211672 100644 --- a/src/GameCult.Networking/CultNetSchemaMessages.cs +++ b/src/GameCult.Networking/CultNetSchemaMessages.cs @@ -48,6 +48,14 @@ namespace GameCult.Networking /// public const string Error = "cultnet.error.v0"; /// + /// error v1 contract identifier: error v0 plus the id of the request it answers (write-receipt.md). + /// + public const string ErrorV1 = "cultnet.error.v1"; + /// + /// write admitted receipt contract identifier (write-receipt.md). + /// + public const string WriteAdmitted = "cultnet.write_admitted.v0"; + /// /// sample change name contract identifier. /// public const string SampleChangeName = "cultnet.sample.change_name.v0"; @@ -538,7 +546,7 @@ namespace GameCult.Networking public static CultNetErrorMessage ForUnownedSchema(CultNetUnownedSchemaException ex) => new CultNetErrorMessage { - Error = $"unowned_schema: {ex.Message}", + Error = "unowned_schema: no shard owns the schema and key", Code = "unowned_schema", Details = new CultNetErrorDetails { Field = "schemaId", Value = ex.SchemaId } }; @@ -579,6 +587,13 @@ namespace GameCult.Networking Details = new CultNetErrorDetails { Field = field } }; + /// + /// The refusal of a frame that does not read, or whose write names nothing (write-receipt.md, Fixed texts): + /// message_invalid, details { field: "message" }, and the one fixed text. A decoder's own text never reaches the wire. + /// + public static CultNetErrorMessage ForUnreadableMessage() => + ForMessageInvalid("message", "the message could not be read"); + /// /// Builds the wire error for a cursor refusal (R-N): code cursor_stale with details /// { asOf, current }, or code cursor_invalid with no details. @@ -621,6 +636,80 @@ namespace GameCult.Networking }; } + /// + /// cultnet.error.v1 (contracts/cultnet/interop/write-receipt.md): the v0 error plus , + /// the id of the request it answers. Sent only to a connection that declared the write-receipt capability. + /// + [MessagePackObject] + public class CultNetErrorV1Message : ICultNetSchemaMessage + { + /// Gets or sets the schema version. + [Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.ErrorV1; + /// Gets or sets the error. + [Key("error")] public string Error { get; set; } = string.Empty; + /// Gets or sets optional shard routing details for authority failures. + [Key("routingHint")] public CultNetShardRoutingHint? RoutingHint { get; set; } + /// Gets or sets the machine-readable refusal code (the v0 enum). + [Key("code")] public string? Code { get; set; } + /// Gets or sets the code-specific structured detail. + [Key("details")] public CultNetErrorDetails? Details { get; set; } + /// Gets or sets the id of the request this answers; null only when no id could be read. + [Key("messageId")] public string? MessageId { get; set; } + + /// Builds the v1 form of answering . + public static CultNetErrorV1Message From(CultNetErrorMessage error, string? messageId) + { + if (error == null) throw new ArgumentNullException(nameof(error)); + return new CultNetErrorV1Message + { + Error = error.Error, + RoutingHint = error.RoutingHint, + Code = error.Code, + Details = error.Details, + MessageId = string.IsNullOrEmpty(messageId) ? null : messageId + }; + } + + /// + /// The refusal of a write a session has no room to remember (write-receipt.md, rule 5): code limit_reached, + /// details present and all nil. Exists only as error.v1; v0 has no such code. + /// + public static CultNetErrorV1Message LimitReached(string? messageId) => new CultNetErrorV1Message + { + Error = "limit_reached: the session's remembered-write limit is full", + Code = "limit_reached", + Details = new CultNetErrorDetails(), + MessageId = string.IsNullOrEmpty(messageId) ? null : messageId + }; + + /// Gets the v0 form, dropping the id. + public CultNetErrorMessage ToV0() => new CultNetErrorMessage + { + Error = Error, + RoutingHint = RoutingHint, + Code = Code, + Details = Details + }; + } + + /// + /// cultnet.write_admitted.v0: the receipt for one admitted put or delete, sent after its commit point. + /// + [MessagePackObject] + public class CultNetWriteAdmittedMessage : ICultNetSchemaMessage + { + /// Gets or sets the schema version. + [Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.WriteAdmitted; + /// Gets or sets the messageId of the admitted write, echoed. + [Key("messageId")] public string MessageId { get; set; } = string.Empty; + /// Gets or sets put or delete. + [Key("operation")] public string Operation { get; set; } = string.Empty; + /// Gets or sets the schemaId of the admitted write, echoed. + [Key("schemaId")] public string SchemaId { get; set; } = string.Empty; + /// Gets or sets the recordKey of the admitted write, echoed. + [Key("recordKey")] public string RecordKey { get; set; } = string.Empty; + } + /// /// Code-specific structured detail carried on (R-N). Fields are /// populated only for the code that defines them; every field is otherwise omitted (nil on the wire). diff --git a/src/GameCult.Networking/CultNetShardWriteForwarding.cs b/src/GameCult.Networking/CultNetShardWriteForwarding.cs index 0fa6c4f7..e4e66298 100644 --- a/src/GameCult.Networking/CultNetShardWriteForwarding.cs +++ b/src/GameCult.Networking/CultNetShardWriteForwarding.cs @@ -10,12 +10,16 @@ namespace GameCult.Networking public interface ICultNetShardWriteForwarder { /// - /// Forwards a raw document put to the shard owner. + /// Forwards a raw document put to the shard owner. Completes only when the owner answered that it admitted the write; + /// throws when it refused, when + /// nothing could have reached it (the only failure after which the id may be forwarded again), and any other exception + /// when the frame may have gone out and was not answered (unconfirmed, including ). The server relays to the original peer exactly what the owner answered. /// Task ForwardPutAsync(CultNetShardDescriptor shard, CultNetDocumentPutRawMessage message); /// - /// Forwards a raw document delete to the shard owner. + /// Forwards a raw document delete to the shard owner; completes, refuses and goes unconfirmed as + /// does. /// Task ForwardDeleteAsync(CultNetShardDescriptor shard, CultNetDocumentDeleteMessage message); } @@ -70,10 +74,12 @@ namespace GameCult.Networking public Func? CreateClient { get; set; } /// - /// Gets or sets how long after a forwarded write the primary's refusal may still arrive; a refusal fails the - /// forward with . Defaults to . + /// Gets or sets how long the primary has to answer a forwarded write (from the send). Its receipt completes the forward, + /// its refusal fails it with , and silence fails it with + /// . Defaults to ; a + /// primary that predates write receipts never answers, so forwarding to one is unconfirmed after this window. /// - public TimeSpan ResultWindow { get; set; } = CultNetWriteCompletion.DefaultResultWindow; + public TimeSpan ResultWindow { get; set; } = CultNetWriteCompletion.ReceiptResultWindow; } /// @@ -92,29 +98,29 @@ namespace GameCult.Networking } /// - /// Forwards a put and completes on the primary's result frame: a refusal throws - /// , the same failure path as an unreachable primary. + /// Forwards a put under its original message id and completes on the primary's result frame: a receipt returns, a refusal + /// throws and silence throws . /// public async Task ForwardPutAsync(CultNetShardDescriptor shard, CultNetDocumentPutRawMessage message) { if (message == null) throw new ArgumentNullException(nameof(message)); - var endpoint = ResolvePrimaryEndpoint(shard); + if (shard == null) throw new ArgumentNullException(nameof(shard)); message.ShardId ??= shard.ShardId; message.ShardEpoch ??= shard.Epoch; - await SendAsync(endpoint, message).ConfigureAwait(false); + await SendAsync(shard, message, message.MessageId).ConfigureAwait(false); } /// - /// Forwards a delete and completes on the primary's result frame: a refusal throws - /// . + /// Forwards a delete under its original message id; completes, refuses and goes unconfirmed as + /// does. /// public async Task ForwardDeleteAsync(CultNetShardDescriptor shard, CultNetDocumentDeleteMessage message) { if (message == null) throw new ArgumentNullException(nameof(message)); - var endpoint = ResolvePrimaryEndpoint(shard); + if (shard == null) throw new ArgumentNullException(nameof(shard)); message.ShardId ??= shard.ShardId; message.ShardEpoch ??= shard.Epoch; - await SendAsync(endpoint, message).ConfigureAwait(false); + await SendAsync(shard, message, message.MessageId).ConfigureAwait(false); } /// @@ -138,19 +144,50 @@ namespace GameCult.Networking return (uri.Host, uri.IsDefaultPort ? 3075 : uri.Port); } - private async Task SendAsync(string endpoint, T message) where T : ICultNetSchemaMessage + // The write frame has not been handed to the transport until this returns: any failure here is CultNetWriteNotSentException, + // the one failure the caller may retry under the same id. + private async Task ConnectBeforeSendAsync(CultNetShardDescriptor shard, string messageId) { - var (host, port) = ParseEndpoint(endpoint); - using var client = CreateClient(endpoint); - client.Connect(host, port); - await WaitForConnectionAsync(client, endpoint).ConfigureAwait(false); - await CultNetWriteCompletion.SendAndAwaitResultAsync( - refuse => + ICultNetSchemaClient? client = null; + try + { + var endpoint = ResolvePrimaryEndpoint(shard); + var (host, port) = ParseEndpoint(endpoint); + client = CreateClient(endpoint); + client.Connect(host, port); + await WaitForConnectionAsync(client, endpoint).ConfigureAwait(false); + // The hello comes first on the ordered schema channel: it opts this connection in to the primary's receipts. + client.SendCultNet(new CultNetHelloMessage { + RuntimeId = "gamecult-networking-shard-forwarder", + RuntimeKind = "dotnet", + SupportedMessageVersions = [CultNetSchemaVersions.WriteAdmitted, CultNetSchemaVersions.ErrorV1] + }); + return client; + } + catch (Exception failure) + { + client?.Dispose(); + if (failure is CultNetWriteNotSentException) throw; + throw new CultNetWriteNotSentException(messageId, failure); + } + } + + private async Task SendAsync(CultNetShardDescriptor shard, T message, string messageId) where T : ICultNetSchemaMessage + { + using var client = await ConnectBeforeSendAsync(shard, messageId).ConfigureAwait(false); + // From the write's send on, every failure (timeout, reset, silence, an exception from the send itself) propagates as it + // is: the frame may have gone out, so the caller treats it as unconfirmed. + await CultNetWriteCompletion.SendAndAwaitReceiptAsync( + (admitted, refuse, refuseV1) => + { + client.OnCultNet(admitted); client.OnCultNet(refuse); + client.OnCultNet(refuseV1); return null; }, () => client.SendCultNet(message), + messageId, _options.ResultWindow).ConfigureAwait(false); } diff --git a/src/GameCult.Networking/CultNetTransport.cs b/src/GameCult.Networking/CultNetTransport.cs index da465326..d84b0263 100644 --- a/src/GameCult.Networking/CultNetTransport.cs +++ b/src/GameCult.Networking/CultNetTransport.cs @@ -3533,7 +3533,8 @@ namespace GameCult.Networking /// public sealed class LiteNetLibTransportConnection { - private readonly NetPeer? _peer; + private readonly Action? _deliver; + private readonly Action? _end; private readonly CultNetTransportStats _stats = new CultNetTransportStats(); /// @@ -3541,10 +3542,99 @@ namespace GameCult.Networking /// public LiteNetLibTransportConnection(NetPeer peer, CultNetTransportProfile? profile = null) { - _peer = peer ?? throw new ArgumentNullException(nameof(peer)); + if (peer == null) throw new ArgumentNullException(nameof(peer)); + _deliver = payload => peer.Send(payload, DeliveryMethod.ReliableOrdered); + _end = peer.Disconnect; Profile = profile ?? CultNetTransportProfiles.CreateLiteNetLib("csharp-litenetlib-peer"); } + // The mock point for what leaves the connection: the peer's reliable ordered send. + internal LiteNetLibTransportConnection(Action deliver, Action? end = null) + { + _deliver = deliver ?? throw new ArgumentNullException(nameof(deliver)); + _end = end; + Profile = CultNetTransportProfiles.CreateLiteNetLib("csharp-litenetlib-peer"); + } + + /// + /// Ends the connection. A write that can be neither answered nor refused is answered by this goodbye: the peer sees + /// its session end and settles the write as unconfirmed (session_ended), never as silence. + /// + internal void End() => _end?.Invoke(); + + /// + /// Answers a schema frame that did not decode with a message_invalid error.v1 naming its id when it holds one; + /// when that answer cannot be sent the connection ends instead. + /// + internal void AnswerUnreadableSchemaFrame(byte[] payload) + { + try + { + SendSchema(CultNetErrorV1Message.From( + CultNetErrorMessage.ForUnreadableMessage(), + CultNetReadableMessageId.From(payload))); + } + catch (Exception) + { + End(); + } + } + + /// + /// A put or delete that arrived on an unreliable or sequenced channel of a receipt session (write-receipt.md, Reliable channel only): + /// answered message_invalid, details channel, fixed text, carrying the write's id, and not applied. True when + /// the frame was such a write and has been answered here. + /// + internal bool RefuseUnreliableWrite(ICultNetSchemaMessage message, DeliveryMethod method) + { + if (WriteReceipts == null) return false; + if (method is DeliveryMethod.ReliableOrdered or DeliveryMethod.ReliableUnordered) return false; + var messageId = message switch + { + CultNetDocumentPutRawMessage put => put.MessageId, + CultNetDocumentDeleteMessage delete => delete.MessageId, + _ => null + }; + if (messageId == null && message is not (CultNetDocumentPutRawMessage or CultNetDocumentDeleteMessage)) return false; + try + { + SendSchema(CultNetErrorV1Message.From( + CultNetErrorMessage.ForMessageInvalid("channel", "receipt sessions require the reliable channel"), messageId)); + } + catch (Exception) + { + End(); + } + + return true; + } + + private readonly object _writeFramingGate = new(); + private bool _writeFramingSettled; + + /// + /// The write-receipt state of a connection that opted in (write-receipt.md); null for every other connection, which is + /// answered exactly as before. + /// + internal CultNetWriteReceiptSession? WriteReceipts { get; private set; } + + /// + /// Decides this connection's write framing once: by its first hello, or by its first write if no hello came first. A + /// later hello changes nothing. The capability changes framing only; it never authorizes. Returns true when this call + /// opted the connection in. + /// + internal bool SettleWriteFraming(CultNetHelloMessage? hello) + { + lock (_writeFramingGate) + { + if (_writeFramingSettled) return false; + _writeFramingSettled = true; + if (hello == null || !CultNetWriteReceiptCapability.Declares(hello)) return false; + WriteReceipts = new CultNetWriteReceiptSession(); + return true; + } + } + /// /// Initializes a receive-only channel-aware adapter for LiteNetLib payload classification. /// @@ -3580,14 +3670,14 @@ namespace GameCult.Networking public void Send(string channelId, byte[] payload) { if (payload == null) throw new ArgumentNullException(nameof(payload)); - if (_peer == null) throw new InvalidOperationException("A LiteNetLib peer is required to send through this transport."); + if (_deliver == null) throw new InvalidOperationException("A LiteNetLib peer is required to send through this transport."); if (!string.Equals(channelId, "schema", StringComparison.Ordinal) && !string.Equals(channelId, "legacy", StringComparison.Ordinal)) { throw new InvalidOperationException($"litenetlib transport only supports schema and legacy channels, got \"{channelId}\"."); } - _peer.Send(payload, DeliveryMethod.ReliableOrdered); + _deliver(payload); _stats.BytesSent += payload.Length; _stats.FramesSent++; } diff --git a/src/GameCult.Networking/CultNetWriteCompletion.cs b/src/GameCult.Networking/CultNetWriteCompletion.cs index 6d5c226d..8767be6e 100644 --- a/src/GameCult.Networking/CultNetWriteCompletion.cs +++ b/src/GameCult.Networking/CultNetWriteCompletion.cs @@ -24,6 +24,40 @@ namespace GameCult.Networking public CultNetErrorMessage Refusal { get; } } + /// + /// A write nothing answered within its window: neither admitted nor refused (write-receipt.md, "unconfirmed"). + /// + public sealed class CultNetWriteUnconfirmedException : Exception + { + /// Creates the exception for the write . + public CultNetWriteUnconfirmedException(string messageId) + : base($"No admission or refusal arrived for write '{messageId}'.") + { + MessageId = messageId; + } + + /// Gets the id of the unconfirmed write. + public string MessageId { get; } + } + + /// + /// A forwarded write that provably never left this process: the connection failed, or the send failed before any byte was + /// written. It is the only forwarding failure after which the same id may be forwarded again. A send port that cannot prove + /// nothing was written must not throw this; every other failure of a forward is unconfirmed. + /// + public sealed class CultNetWriteNotSentException : Exception + { + /// Creates the exception for the write ; is for logs only. + public CultNetWriteNotSentException(string messageId, Exception? cause = null) + : base($"Write '{messageId}' was not sent.", cause) + { + MessageId = messageId; + } + + /// Gets the id of the write that was not sent. + public string MessageId { get; } + } + /// /// Completes a write on the peer's result frame, never on a send's return or a transport acknowledgement: /// an ack proves delivery, not admission. @@ -33,6 +67,49 @@ namespace GameCult.Networking /// How long after a send a refusal may still arrive when the caller names no window. public static readonly TimeSpan DefaultResultWindow = TimeSpan.FromMilliseconds(500); + /// How long a receipt-capable peer has to answer a write (write-receipt.md, RECEIPT_RESULT_WINDOW_MS). + public static readonly TimeSpan ReceiptResultWindow = TimeSpan.FromMilliseconds(5000); + + /// + /// Sends one write to a receipt-capable peer and waits for its answer: a + /// write_admitted naming returns, an error.v1 naming it throws + /// , and an id-less error (v0, or v1 with no id) is attributed to this write + /// because it is the only one in flight on the connection. Silence throws . + /// + public static async Task SendAndAwaitReceiptAsync( + Func, Action, Action, IDisposable?> subscribe, + Action send, + string messageId, + TimeSpan resultWindow, + CancellationToken cancellationToken = default) + { + if (subscribe == null) throw new ArgumentNullException(nameof(subscribe)); + if (send == null) throw new ArgumentNullException(nameof(send)); + var answer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = subscribe( + admitted => + { + if (string.Equals(admitted.MessageId, messageId, StringComparison.Ordinal)) answer.TrySetResult(null); + }, + error => answer.TrySetResult(error), + error => + { + if (error.MessageId == null || string.Equals(error.MessageId, messageId, StringComparison.Ordinal)) + answer.TrySetResult(error.ToV0()); + }); + send(); + var window = Task.Delay(resultWindow, cancellationToken); + await Task.WhenAny(answer.Task, window).ConfigureAwait(false); + if (!answer.Task.IsCompleted) + { + await window.ConfigureAwait(false); + throw new CultNetWriteUnconfirmedException(messageId); + } + + var refusal = await answer.Task.ConfigureAwait(false); + if (refusal != null) throw new CultNetWriteRefusedException(refusal); + } + /// /// Sends one write and waits for the peer's answer. A refusal frame rejects with /// whatever its order against the transport acknowledgement. A peer diff --git a/src/GameCult.Networking/CultNetWriteReceipts.cs b/src/GameCult.Networking/CultNetWriteReceipts.cs new file mode 100644 index 00000000..2a90f35d --- /dev/null +++ b/src/GameCult.Networking/CultNetWriteReceipts.cs @@ -0,0 +1,396 @@ +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using GameCult.Caching; +using MessagePack; + +namespace GameCult.Networking +{ + /// + /// The content hash a write-receipt server binds to a (peer, messageId) dedupe key + /// (contracts/cultnet/interop/write-receipt.md, rule 5). + /// + public static class CultNetWriteContentHash + { + /// + /// SHA-256 of the MessagePack array [operation, schemaId, recordKey, payload], payload a bin + /// for a put and nil for a delete. + /// + public static byte[] Compute(string operation, string schemaId, string recordKey, byte[]? payload) + { + var buffer = new System.Buffers.ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteArrayHeader(4); + writer.Write(operation); + writer.Write(schemaId); + writer.Write(recordKey); + if (payload == null) writer.WriteNil(); + else writer.Write(payload); + writer.Flush(); + using var sha = SHA256.Create(); + return sha.ComputeHash(buffer.WrittenSpan.ToArray()); + } + } + + /// + /// Whether a peer's hello opted in to write receipts: it lists both cultnet.write_admitted.v0 and + /// cultnet.error.v1. The capability changes framing only; it never authorizes. + /// + internal static class CultNetWriteReceiptCapability + { + public static bool Declares(CultNetHelloMessage hello) + { + var versions = hello.SupportedMessageVersions; + return versions != null + && Array.IndexOf(versions, CultNetSchemaVersions.WriteAdmitted) >= 0 + && Array.IndexOf(versions, CultNetSchemaVersions.ErrorV1) >= 0; + } + } + + /// A SHA-256 digest held by value: the fixed-size stand-in for an id or a content hash. + internal readonly struct CultNetDigest : IEquatable + { + private readonly ulong _a, _b, _c, _d; + + private CultNetDigest(ulong a, ulong b, ulong c, ulong d) { _a = a; _b = b; _c = c; _d = d; } + + public static CultNetDigest Of(byte[] bytes) + { + using var sha = SHA256.Create(); + var hash = sha.ComputeHash(bytes); + return new CultNetDigest( + BitConverter.ToUInt64(hash, 0), BitConverter.ToUInt64(hash, 8), + BitConverter.ToUInt64(hash, 16), BitConverter.ToUInt64(hash, 24)); + } + + public bool Equals(CultNetDigest other) => _a == other._a && _b == other._b && _c == other._c && _d == other._d; + public override bool Equals(object? obj) => obj is CultNetDigest other && Equals(other); + public override int GetHashCode() => unchecked((int)_a ^ (int)(_a >> 32)); + public static bool operator ==(CultNetDigest left, CultNetDigest right) => left.Equals(right); + public static bool operator !=(CultNetDigest left, CultNetDigest right) => !left.Equals(right); + } + + /// + /// What a session keeps of a refusal (write-receipt.md, What is remembered): its code, the field its details name, and its + /// routing hint (a shard descriptor the server owns). Never the write's strings or an authority's reason: the replay is built + /// from fixed text and the fields of the resend, which carries the same content. + /// + internal readonly struct CultNetRememberedRefusal + { + public string? Code { get; } + public bool HasDetails { get; } + public string? Field { get; } + public CultNetShardRoutingHint? Hint { get; } + + public CultNetRememberedRefusal(string? code, bool hasDetails, string? field, CultNetShardRoutingHint? hint) + { + Code = code; HasDetails = hasDetails; Field = field; Hint = hint; + } + + public static CultNetRememberedRefusal Of(CultNetErrorMessage error) => + new(error.Code, error.Details != null, error.Details?.Field, error.RoutingHint); + + private static string? NullIfEmpty(string value) => value.Length == 0 ? null : value; + + /// The refusal, in fixed text, naming the write's own record key or schema id where its details do. + public CultNetErrorMessage ToError(string schemaId, string recordKey) => new() + { + Error = Code switch + { + "unowned_schema" => "unowned_schema: no shard owns the schema and key", + null => Hint != null ? CultNetDatabaseServer.RoutingRefusalText : CultNetWriteReceiptSession.WriteFailedText, + _ => Code + }, + Code = Code, + RoutingHint = Hint, + Details = HasDetails + ? new CultNetErrorDetails + { + Field = Field, + Value = Field switch { "recordKey" => NullIfEmpty(recordKey), "schemaId" => NullIfEmpty(schemaId), _ => null } + } + : null + }; + } + + /// + /// One receipt-capable peer's writes: message id to content hash and the answer given, refusals included, so a resend of the + /// same content is answered again without being decided again and the same id with other content is refused. Ids and content + /// hashes are held as fixed-size digests; the answer is held as its kind (and, for a refusal, its code and the field its details name), + /// never the strings of the write. + /// + internal sealed class CultNetWriteReceiptSession + { + /// The most writes a peer is remembered for, refused ones included; a peer at the limit has new writes refused. + internal const int MaxRememberedWrites = 1024; + + /// The most ids refused at the limit that are remembered, so their resend is judged the same way. + internal const int MaxRememberedLimitRefusals = 1024; + + /// The longest messageId a write may carry, in UTF-8 bytes (write-receipt.md, Id size). + internal const int MaxMessageIdBytes = 256; + + /// What a write is refused with when it failed for a reason no typed refusal names. Never an exception's own text. + internal const string WriteFailedText = "the write could not be applied"; + + private readonly object _gate = new(); + private readonly Dictionary _writes = new(); + private readonly Dictionary _limitRefusals = new(); + + private sealed class Entry + { + public Entry(CultNetDigest hash) { Hash = hash; } + public CultNetDigest Hash { get; set; } + public bool Abandoned { get; set; } + public bool Admitted { get; set; } + public CultNetRememberedRefusal? Refusal { get; set; } + } + + public enum Begin { New, ReplayAdmitted, ReplayRefusal, Unanswered, DifferentContent, Full } + + private static CultNetDigest IdDigest(string messageId) => CultNetDigest.Of(System.Text.Encoding.UTF8.GetBytes(messageId)); + + /// + /// Looks up first. An id not seen is claimed for this content (); + /// otherwise the outcome says what already holds it, and is the refusal to repeat. + /// + public Begin TryBegin(string messageId, byte[] hash, out CultNetRememberedRefusal? refusal) + { + var id = IdDigest(messageId); + var content = CultNetDigest.Of(hash); + lock (_gate) + { + refusal = null; + if (_writes.TryGetValue(id, out var entry)) + { + if (entry.Abandoned) + { + // Not sent, so judged afresh in the slot it already holds; no slot is ever freed. + entry.Abandoned = false; + entry.Hash = content; + return Begin.New; + } + + if (entry.Hash != content) return Begin.DifferentContent; + if (entry.Admitted) return Begin.ReplayAdmitted; + if (entry.Refusal != null) + { + refusal = entry.Refusal; + return Begin.ReplayRefusal; + } + + // No answer yet: the first attempt is still being applied, or its primary left it unanswered for good. + return Begin.Unanswered; + } + + if (_writes.Count >= MaxRememberedWrites) + { + if (_limitRefusals.TryGetValue(id, out var refused)) return refused == content ? Begin.Full : Begin.DifferentContent; + if (_limitRefusals.Count < MaxRememberedLimitRefusals) _limitRefusals[id] = content; + return Begin.Full; + } + + _writes[id] = new Entry(content); + return Begin.New; + } + } + + /// The write was admitted: remember it so a resend repeats the receipt. + public void Admitted(string messageId) + { + lock (_gate) + { + if (_writes.TryGetValue(IdDigest(messageId), out var entry)) entry.Admitted = true; + } + } + + /// The write was refused: remember the refusal so a resend repeats it. + public void Refused(string messageId, CultNetRememberedRefusal refusal) + { + lock (_gate) + { + if (_writes.TryGetValue(IdDigest(messageId), out var entry)) entry.Refusal = refusal; + } + } + + /// + /// The write never reached anyone who could have applied it: a repeat is judged afresh. The entry keeps its slot, so + /// forgetting a write never makes room for an id that was refused at the limit. + /// + public void Abandoned(string messageId) + { + lock (_gate) + { + if (_writes.TryGetValue(IdDigest(messageId), out var entry)) entry.Abandoned = true; + } + } + } + + /// + /// The messageId of a schema frame that does not decode (write-receipt.md, rule 3: a refusal carries the write's id whenever + /// the frame is readable enough to find it). + /// + internal static class CultNetReadableMessageId + { + /// The frame's top-level string messageId, or null when the bytes are not a map holding one. + public static string? From(byte[] payload) + { + try + { + var reader = new MessagePackReader(payload); + var entries = reader.ReadMapHeader(); + for (var index = 0; index < entries; index++) + { + var key = reader.NextMessagePackType == MessagePackType.String ? reader.ReadString() : null; + if (key == "messageId" && reader.NextMessagePackType == MessagePackType.String) + { + var id = reader.ReadString(); + return string.IsNullOrEmpty(id) ? null : id; + } + + if (key == null) reader.Skip(); + reader.Skip(); + } + } + catch (Exception) + { + // Not a readable map: no id. + } + + return null; + } + } + + /// + /// One write on a receipt-capable connection: its dedupe claim and its single answer (write-receipt.md, rules 1 to 5). + /// + internal sealed class CultNetReceiptedWrite + { + private readonly CultNetWriteReceiptSession _session; + private readonly Action _send; + private readonly string _operation; + private readonly string _messageId; + private readonly string _schemaId; + private readonly string _recordKey; + private readonly byte[]? _payload; + private bool _claimed; + private bool _answered; + + public CultNetReceiptedWrite( + CultNetWriteReceiptSession session, + Action send, + string operation, + string? messageId, + string? schemaId, + string? recordKey, + byte[]? payload) + { + _session = session; + _send = send; + _operation = operation; + _messageId = messageId ?? string.Empty; + _schemaId = schemaId ?? string.Empty; + _recordKey = recordKey ?? string.Empty; + _payload = payload; + } + + /// + /// Looks the write's id up before anything else is decided (rule 5). True when the id is new and the write should go on + /// to authorization and the commit; false when it was answered here (a replay, a reused id, a full table) or is owed no + /// further answer (still in flight, or left silent by its primary). + /// + public bool Begin() + { + var outcome = _session.TryBegin(_messageId, CultNetWriteContentHash.Compute(_operation, _schemaId, _recordKey, _payload), out var refusal); + switch (outcome) + { + case CultNetWriteReceiptSession.Begin.New: + _claimed = true; + return true; + case CultNetWriteReceiptSession.Begin.ReplayAdmitted: + _answered = true; + _send(AdmittedReceipt()); + return false; + case CultNetWriteReceiptSession.Begin.ReplayRefusal: + _answered = true; + _send(CultNetErrorV1Message.From(refusal!.Value.ToError(_schemaId, _recordKey), _messageId)); + return false; + case CultNetWriteReceiptSession.Begin.Unanswered: + // The first attempt is still being applied and will answer this id, or its primary left it unanswered: + // then the claim stays, so the id is never sent again on this session, and the write stays unconfirmed. + _answered = true; + return false; + case CultNetWriteReceiptSession.Begin.DifferentContent: + Refused(CultNetErrorMessage.ForMessageInvalid("messageId", "the message id was already used for different content")); + return false; + default: + _answered = true; + _send(CultNetErrorV1Message.LimitReached(_messageId)); + return false; + } + } + + private CultNetWriteAdmittedMessage AdmittedReceipt() => new() + { + MessageId = _messageId, + Operation = _operation, + SchemaId = _schemaId, + RecordKey = _recordKey + }; + + /// The write committed: remember the receipt and send it. + public void Admitted() + { + if (_answered) return; + _answered = true; + if (_claimed) _session.Admitted(_messageId); + _send(AdmittedReceipt()); + } + + /// The write was refused: remember the refusal (a resend repeats it) and send its one error.v1. + public void Refused(CultNetErrorMessage error) + { + if (_answered) return; + _answered = true; + if (_claimed) + { + // A remembered refusal is answered from what is remembered, so the replay is the refusal again. + var kept = CultNetRememberedRefusal.Of(error); + _session.Refused(_messageId, kept); + error = kept.ToError(_schemaId, _recordKey); + } + + _send(CultNetErrorV1Message.From(error, _messageId)); + } + + /// + /// A forward that may have reached its primary and is unconfirmed (silence, reset, timeout, an ambiguous send): no answer is + /// owed or possible, and the claim stays so the id is never forwarded again on this session. Sends nothing. + /// + public void LeftSilent() + { + if (_answered) return; + _answered = true; + } + + /// A forward that was provably not sent (connect failed, or the send failed before any byte was written): forget the claim, send nothing. + public void NotSent() + { + if (_answered) return; + _answered = true; + if (_claimed) _session.Abandoned(_messageId); + _claimed = false; + } + + /// + /// Why the write's id cannot be used at all, before anything is remembered: it is missing (refused with no id) or longer + /// than UTF-8 bytes. Null when the id is usable. + /// + public CultNetErrorMessage? IdRefusal => + _messageId.Length == 0 + ? CultNetErrorMessage.ForMessageInvalid("messageId", "a write needs a messageId") + : System.Text.Encoding.UTF8.GetByteCount(_messageId) > CultNetWriteReceiptSession.MaxMessageIdBytes + ? CultNetErrorMessage.ForMessageInvalid("messageId", "messageId exceeds 256 bytes") + : null; + } +} diff --git a/src/GameCult.Networking/Server.cs b/src/GameCult.Networking/Server.cs index 128eb47d..08af0cc4 100644 --- a/src/GameCult.Networking/Server.cs +++ b/src/GameCult.Networking/Server.cs @@ -23,7 +23,7 @@ namespace GameCult.Networking private const string EmailPattern = @"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$"; private const string UsernamePattern = @"^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$"; - private const int ServerPort = 3075; + private const int DefaultPort = 3075; private const float SessionTimeoutSeconds = 1800; // 30 minutes private const float SessionRefreshThresholdSeconds = 300; // 5 minutes private const int MaxConnectionAttemptsPerMinute = 30; @@ -63,6 +63,12 @@ namespace GameCult.Networking /// public bool LogSensitivePayloads { get; set; } + /// + /// Gets or sets the UDP port binds (default 3075; 0 asks the OS for a free one). After + /// it holds the port actually bound. + /// + public int Port { get; set; } = DefaultPort; + private float Time => (float)(_timer?.Elapsed.TotalSeconds ?? 0d); /// @@ -74,7 +80,7 @@ namespace GameCult.Networking { TransportId = "litenetlib-server", Host = "0.0.0.0", - Port = ServerPort + Port = Port }); /// @@ -357,7 +363,8 @@ namespace GameCult.Networking UnsyncedEvents = true, NatPunchEnabled = true }; - _netManager.Start(ServerPort); + _netManager.Start(Port); + Port = _netManager.LocalPort; listener.NetworkErrorEvent += (point, code) => Logger.LogInfo($"{point.Address}: Error {code}"); @@ -408,11 +415,25 @@ namespace GameCult.Networking { var cultNetMessage = LiteNetLibTransportConnection.DecodeSchema(frame); Logger.LogDebug($"Received CultNet schema message {cultNetMessage.SchemaVersion}"); + if (transport.RefuseUnreliableWrite(cultNetMessage, method)) return; await HandleCultNetSchemaMessageAsync(peer, user, cultNetMessage).ConfigureAwait(false); return; } - var message = LiteNetLibTransportConnection.DecodeLegacy(frame); + Message message; + try + { + message = LiteNetLibTransportConnection.DecodeLegacy(frame); + } + catch (Exception ex) when (transport.WriteReceipts != null) + { + // A frame that decodes on neither channel is classed legacy, so this is where an unreadable frame lands. + // A receipt-capable peer is told which frame was unreadable (by its id, if the frame still holds one). + Logger.LogWarning($"CultNet frame unreadable: {ex.Message}"); + transport.AnswerUnreadableSchemaFrame(frame.Payload); + return; + } + if (LogSensitivePayloads) { Logger.LogDebug($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory(frame.Payload))}"); @@ -507,7 +528,7 @@ namespace GameCult.Networking } }); - Logger.LogInfo($"Server started on port {ServerPort}."); + Logger.LogInfo($"Server started on port {Port}."); } private async Task HandleCultNetSchemaMessageAsync(NetPeer peer, User user, ICultNetSchemaMessage message) diff --git a/tests/GameCult.Networking.InteropPeer/Program.cs b/tests/GameCult.Networking.InteropPeer/Program.cs index 17a1ea89..fcfcf09c 100644 --- a/tests/GameCult.Networking.InteropPeer/Program.cs +++ b/tests/GameCult.Networking.InteropPeer/Program.cs @@ -25,7 +25,7 @@ static async Task ProgramMainAsync(string[] args) { if (args.Length == 0) { - throw new InvalidOperationException("Expected mode: serve | probe | dial | rudp-serve-once | rudp-dial-once | rudp-serve-message-once | rudp-dial-message-once | quic-realtime-serve"); + throw new InvalidOperationException("Expected mode: serve | probe | dial | rudp-serve-once | rudp-dial-once | rudp-serve-message-once | rudp-dial-message-once | quic-realtime-serve | receipt-serve | receipt-relay"); } var mode = args[0]; @@ -53,6 +53,12 @@ static async Task ProgramMainAsync(string[] args) case "rudp-dial-message-once": RudpDialMessageOnce(options); return 0; + case "receipt-serve": + await GameCult.Networking.InteropPeer.ReceiptHarness.ServeAsync(); + return 0; + case "receipt-relay": + await GameCult.Networking.InteropPeer.ReceiptHarness.RelayAsync(int.Parse(options["port"], CultureInfo.InvariantCulture)); + return 0; case "quic-realtime-serve": await QuicRealtimeServeAsync(ParseQuicRealtimeServeConfig(options)); return 0; diff --git a/tests/GameCult.Networking.InteropPeer/ReceiptHarness.cs b/tests/GameCult.Networking.InteropPeer/ReceiptHarness.cs new file mode 100644 index 00000000..6871ea00 --- /dev/null +++ b/tests/GameCult.Networking.InteropPeer/ReceiptHarness.cs @@ -0,0 +1,120 @@ +using System; +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Networking; +using LiteNetLib; +using R3; + +// The real C# receipt server (CultNetDatabaseServer on Server) and the one transport shim the TypeScript client needs to reach it, +// for the cross-runtime write-receipt interop harness (packages/cultmesh-ts/test/interop/write-receipt-interop.test.ts). +// TypeScript has no LiteNetLib client, so the shim moves bytes and nothing else: each CultNet frame is a LiteNetLib reliable +// ordered payload, and on the pipe it is a 4-byte big-endian length followed by the frame. +namespace GameCult.Networking.InteropPeer +{ + // CompatibleSchemaIds are the names the spec's blankFields vectors admit (U+200B, U+001C, and a name padded with NBSP and EM SPACE): + // a name is any string that is not blank, so the store must hold a record put under one of them. + [CultDocument("receipt.interop_note", ReceiptHarness.SchemaId, CompatibleSchemaIds = ["\u200b", "\u001c", "\u00a0a\u2003"])] + [MessagePack.MessagePackObject] + public sealed class ReceiptInteropNote + { + [MessagePack.Key(0)] + public string Text { get; set; } = string.Empty; + } + + internal static class ReceiptHarness + { + public const string SchemaId = "receipt.interop_note.v1"; + public const string ShardId = "receipt-interop-shard"; + // A record key with this prefix is refused by the authority: how the harness asks for a refused write. + public const string RefusedPrefix = "refuse:"; + + private sealed class Authority : ICultNetRemoteWriteAuthority + { + public CultNetRemoteWriteDecision Decide(CultNetRemoteWriteRequest request) => + request.RecordKey.ToString().StartsWith(RefusedPrefix, StringComparison.Ordinal) + ? CultNetRemoteWriteDecision.Refuse("denied") + : CultNetRemoteWriteDecision.Grant(); + } + + private static void Emit(object fact) + { + lock (Console.Out) Console.Out.WriteLine(JsonSerializer.Serialize(fact)); + } + + // stdout: {"event":"listening","port":N} then {"event":"applied"|"removed","recordKey":"..."} per committed change; runs until stdin closes. + public static async Task ServeAsync() + { + var cache = new CultCache(); + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions + { + Shards = [new CultNetShardDescriptor(ShardId, "primary", epoch: 1, isPrimary: true, schemaIds: [SchemaId])] + }); + using var server = new Server(cache, ServerSecurityOptions.Development()) { Port = 0 }; + using var databaseServer = new CultNetDatabaseServer(server, database, new CultNetDatabaseServerOptions + { + RemoteWriteAuthority = new Authority() + }); + using var watch = cache.Watch().Subscribe(change => + Emit(new { @event = change.Kind == CultCacheDocumentChangeKind.Removed ? "removed" : "applied", recordKey = change.Key.ToString() })); + server.Start(); + Emit(new { @event = "listening", port = server.Port, shardId = ShardId, schemaId = SchemaId }); + await Task.Run(() => Console.In.ReadToEnd()); + } + + // Connects to the server on `port` and relays frames between stdin/stdout and the connection; exits when either ends. + public static async Task RelayAsync(int port) + { + var listener = new EventBasedNetListener(); + var connected = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var output = Console.OpenStandardOutput(); + var gate = new object(); + listener.PeerConnectedEvent += _ => connected.TrySetResult(true); + listener.PeerDisconnectedEvent += (_, _) => ended.TrySetResult(true); + listener.NetworkReceiveEvent += (_, reader, _, _) => + { + var frame = reader.GetRemainingBytes(); + var header = new byte[] { (byte)(frame.Length >> 24), (byte)(frame.Length >> 16), (byte)(frame.Length >> 8), (byte)frame.Length }; + lock (gate) + { + output.Write(header); + output.Write(frame); + output.Flush(); + } + }; + var manager = new NetManager(listener) { UnsyncedEvents = true }; + manager.Start(0); + var peer = manager.Connect("127.0.0.1", port, ServerSecurityOptions.Development().ConnectionKey); + if (await Task.WhenAny(connected.Task, Task.Delay(TimeSpan.FromSeconds(10))) != connected.Task) + throw new InvalidOperationException("the relay did not connect"); + var input = Console.OpenStandardInput(); + var pump = Task.Run(() => + { + var header = new byte[4]; + while (ReadExactly(input, header)) + { + var frame = new byte[(header[0] << 24) | (header[1] << 16) | (header[2] << 8) | header[3]]; + if (!ReadExactly(input, frame)) break; + peer.Send(frame, DeliveryMethod.ReliableOrdered); + } + }); + await Task.WhenAny(pump, ended.Task); + manager.Stop(); + } + + private static bool ReadExactly(Stream stream, byte[] buffer) + { + var read = 0; + while (read < buffer.Length) + { + var count = stream.Read(buffer, read, buffer.Length - read); + if (count <= 0) return false; + read += count; + } + return true; + } + } +} diff --git a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs index 64de1093..5713b0da 100644 --- a/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetDocumentRegistryVariantTests.cs @@ -418,6 +418,7 @@ namespace GameCult.Networking.Tests CultNetDatabaseChangeKind.Added, VariantKey, schemaId, database.Shards[0], cache.Get(VariantKey)!, previousDocument: null); Assert.That(Deliver(databaseServer, added, selection, refused, errors), Is.Null); Assert.That(errors, Has.Count.EqualTo(1)); + Assert.That(errors[0].Error, Is.EqualTo("the record is a variant CultNet cannot carry")); var removed = new CultNetDatabaseChange( CultNetDatabaseChangeKind.Removed, VariantKey, schemaId, database.Shards[0], document: null, previousDocument: cache.Get(VariantKey)!); diff --git a/tests/GameCult.Networking.Tests/CultNetRudpSchemaServerPeerInputTests.cs b/tests/GameCult.Networking.Tests/CultNetRudpSchemaServerPeerInputTests.cs index e7900e7c..2bb59952 100644 --- a/tests/GameCult.Networking.Tests/CultNetRudpSchemaServerPeerInputTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetRudpSchemaServerPeerInputTests.cs @@ -178,6 +178,46 @@ namespace GameCult.Networking.Tests Assert.That(scene.Logger.Errors, Has.Count.EqualTo(1)); } + // The RUDP schema server implements no receipt rules, so it must not advertise them (write-receipt.md, Capability and the + // conformance table): whatever hello it sends lists neither frame. + [Test] + public async Task TheRudpSchemaServerNeverAdvertisesTheReceiptFrames() + { + using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions + { + RuntimeId = "csharp-rudp-no-receipts", + ConnectionId = ConnectionId + }); + var client = await Connect(server); + try + { + SendSchema(server, client, CultNetSchemaMessageSerialization.Serialize(new CultNetHelloMessage + { + RuntimeId = "receipt-client", + RuntimeKind = "test", + SupportedMessageVersions = [CultNetSchemaVersions.WriteAdmitted, CultNetSchemaVersions.ErrorV1] + })); + await server.PollAvailableAsync(16); + + var hellos = new List(); + foreach (var packet in Drain(client.Socket)) + foreach (var frame in client.Session.Receive(packet, 1).Delivered) + if (CultNetSchemaMessageSerialization.Deserialize(frame.Payload) is CultNetHelloMessage hello) + hellos.Add(hello); + + foreach (var hello in hellos) + { + var listed = hello.SupportedMessageVersions ?? Array.Empty(); + Assert.That(listed, Has.None.EqualTo(CultNetSchemaVersions.WriteAdmitted)); + Assert.That(listed, Has.None.EqualTo(CultNetSchemaVersions.ErrorV1)); + } + } + finally + { + client.Socket.Dispose(); + } + } + private static List ErrorsReceivedBy(Client client) { var errors = new List(); diff --git a/tests/GameCult.Networking.Tests/CultNetWriteReceiptLoopbackTests.cs b/tests/GameCult.Networking.Tests/CultNetWriteReceiptLoopbackTests.cs new file mode 100644 index 00000000..d5e32fa0 --- /dev/null +++ b/tests/GameCult.Networking.Tests/CultNetWriteReceiptLoopbackTests.cs @@ -0,0 +1,290 @@ +#nullable enable +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameCult.Caching; +using LiteNetLib; +using NUnit.Framework; +using static GameCult.Networking.Tests.NetworkingTests; + +namespace GameCult.Networking.Tests +{ + // The receipt server on a real socket: Server.Start on an ephemeral loopback port and real LiteNetLib clients. The + // handler-level tests (CultNetWriteReceiptServerTests) hand frames to the handlers; only a running server decides what + // a frame that does not decode is answered with. + public sealed class CultNetWriteReceiptLoopbackTests + { + private static readonly TimeSpan Cap = TimeSpan.FromSeconds(10); + private static readonly CultRecordKey KeyA = new("tests:loopback:a"); + private static readonly CultRecordKey KeyB = new("tests:loopback:b"); + private const string ShardId = "loopback-shard"; + + private sealed class Client : IDisposable + { + private readonly NetManager _manager; + private readonly NetPeer _peer; + private readonly BlockingCollection _received = new(); + public int Closed; + + public Client(int port, string key) + { + var listener = new EventBasedNetListener(); + var connected = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var decoder = new LiteNetLibTransportConnection(); + listener.PeerConnectedEvent += _ => connected.TrySetResult(true); + listener.PeerDisconnectedEvent += (_, _) => Interlocked.Increment(ref Closed); + listener.NetworkReceiveEvent += (_, reader, _, _) => + _received.Add(LiteNetLibTransportConnection.DecodeSchema(decoder.Receive(reader.GetRemainingBytes()))); + _manager = new NetManager(listener) { UnsyncedEvents = true }; + _manager.Start(0); + _peer = _manager.Connect("127.0.0.1", port, key); + if (!connected.Task.Wait(Cap)) Assert.Fail("the client did not connect"); + } + + public void Send(T message) where T : ICultNetSchemaMessage => + _peer.Send(CultNetSchemaMessageSerialization.Serialize(message), DeliveryMethod.ReliableOrdered); + + public void SendUnreliable(T message) where T : ICultNetSchemaMessage => + _peer.Send(CultNetSchemaMessageSerialization.Serialize(message), DeliveryMethod.Unreliable); + + public void Send(T message, DeliveryMethod method) where T : ICultNetSchemaMessage => + _peer.Send(CultNetSchemaMessageSerialization.Serialize(message), method); + + public void SendRaw(byte[] bytes) => _peer.Send(bytes, DeliveryMethod.ReliableOrdered); + + public T Next() where T : ICultNetSchemaMessage + { + if (!_received.TryTake(out var message, Cap)) Assert.Fail($"no {typeof(T).Name} arrived within {Cap}"); + Assert.That(message, Is.InstanceOf()); + return (T)message!; + } + + public void ExpectNothingMore(string because) + { + // A reliable ordered channel: anything the server sent before the probe's answer has already arrived. + Assert.That(_received.Count, Is.Zero, because); + } + + public void Dispose() + { + _manager.Stop(); + _received.Dispose(); + } + } + + private sealed class Authority : ICultNetRemoteWriteAuthority + { + public CultNetRemoteWriteDecision Decide(CultNetRemoteWriteRequest request) => + request.RecordKey.Equals(KeyB) ? CultNetRemoteWriteDecision.Refuse("denied") : CultNetRemoteWriteDecision.Grant(); + } + + private sealed class Running : IDisposable + { + public Server Server = null!; + public CultCache Cache = null!; + public CultNetDatabase Database = null!; + public string SchemaId = string.Empty; + private CultNetDatabaseServer _databaseServer = null!; + + public static Running Start() + { + var cache = new CultCache(); + var schemaId = cache.Registry.GetRequired().SchemaId; + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions + { + Shards = [new CultNetShardDescriptor(ShardId, "primary", epoch: 1, isPrimary: true, schemaIds: [schemaId])] + }); + var server = new Server(cache, ServerSecurityOptions.Development()) { Port = 0 }; + var databaseServer = new CultNetDatabaseServer(server, database, new CultNetDatabaseServerOptions + { + RemoteWriteAuthority = new Authority() + }); + server.Start(); + return new Running { Server = server, Cache = cache, Database = database, SchemaId = schemaId, _databaseServer = databaseServer }; + } + + public Client Connect() => new(Server.Port, ServerSecurityOptions.Development().ConnectionKey); + + public CultNetDocumentPutRawMessage PutOf(string id, CultRecordKey key, string text) + { + var message = Database.Documents.CreateRawDocumentPutMessage(id, new CultRecordHandle(key), + new NetworkSchemaNote { Schema = "tests.networking_note.v1", Text = text }); + message.ShardId = ShardId; + message.ShardEpoch = 1; + return message; + } + + public void Dispose() + { + _databaseServer.Dispose(); + Server.Dispose(); + } + } + + private static CultNetHelloMessage HelloOf(params string[] versions) => + new() { RuntimeId = "loopback-client", RuntimeKind = "test", SupportedMessageVersions = versions }; + + private static readonly string[] BothFrames = [CultNetSchemaVersions.WriteAdmitted, CultNetSchemaVersions.ErrorV1]; + + [Test] + public void StartBindsTheRequestedPortAndReportsTheOneBound() + { + using var running = Running.Start(); + Assert.That(running.Server.Port, Is.Not.Zero.And.Not.EqualTo(3075)); + } + + // contracts/cultnet/interop/write-receipt-vectors.json, error_v1_unreadable_frame_has_null_message_id: code + // message_invalid, details.field "message", messageId null. + [TestCase(new byte[] { 0xC1 }, TestName = "AnUnreadableFrameFromAReceiptPeerIsAnsweredWithMessageInvalidAndNoId_NeverUsedByte")] + [TestCase(new byte[] { 0x92, 0x01, 0x02 }, TestName = "AnUnreadableFrameFromAReceiptPeerIsAnsweredWithMessageInvalidAndNoId_NotAMap")] + public void AnUnreadableFrameFromAReceiptPeerIsAnsweredWithMessageInvalidAndNoId(byte[] garbage) + { + using var running = Running.Start(); + using var client = running.Connect(); + client.Send(HelloOf(BothFrames)); + client.Next(); + + client.SendRaw(garbage); + + var error = client.Next(); + Assert.That(error.Code, Is.EqualTo("message_invalid")); + Assert.That(error.Details!.Field, Is.EqualTo("message")); + Assert.That(error.MessageId, Is.Null); + } + + [Test] + public async Task AReceiptPeerIsStillServedAfterAnUnreadableFrameAndALegacyPeerIsAnsweredAsBefore() + { + using var running = Running.Start(); + using var receipt = running.Connect(); + receipt.Send(HelloOf(BothFrames)); + receipt.Next(); + receipt.SendRaw(new byte[] { 0xC1 }); + receipt.Next(); + + receipt.Send(running.PutOf("r1", KeyA, "one")); + Assert.That(receipt.Next().MessageId, Is.EqualTo("r1")); + + using var legacy = running.Connect(); + legacy.Send(HelloOf()); // a hello that lists neither frame is answered with nothing + legacy.SendRaw(new byte[] { 0xC1 }); // unanswered: were it answered, error.v1 would arrive ahead of the refusal + legacy.Send(running.PutOf("l1", KeyB, "two")); + var refusal = legacy.Next(); + Assert.That(refusal, Is.TypeOf()); + Assert.That(refusal.Code, Is.EqualTo("write_not_authorized")); + legacy.Send(running.PutOf("l2", KeyA, "three")); + await WaitFor(() => running.Cache.Get(KeyA)?.Text == "three"); + legacy.ExpectNothingMore("a legacy peer is never sent a receipt or error.v1"); + Assert.That(running.Cache.Get(KeyB), Is.Null); + } + + // write-receipt.md, Reliable channel only: a write on an unreliable channel of a receipt session is refused + // message_invalid, details.field "channel", fixed text, carrying the write's id; it is not applied. + [Test] + public async Task AWriteOnAnUnreliableChannelOfAReceiptPeerIsRefusedAndNotApplied() + { + using var running = Running.Start(); + using var client = running.Connect(); + client.Send(HelloOf(BothFrames)); + client.Next(); + + client.SendUnreliable(running.PutOf("u1", KeyA, "lost")); + + var error = client.Next(); + Assert.That(error.Code, Is.EqualTo("message_invalid")); + Assert.That(error.Details!.Field, Is.EqualTo("channel")); + Assert.That(error.Error, Is.EqualTo("message_invalid: receipt sessions require the reliable channel")); + Assert.That(error.MessageId, Is.EqualTo("u1")); + + // The session goes on, and the same id on the reliable channel is a new write, not a replayed refusal. + client.Send(running.PutOf("u1", KeyA, "kept")); + Assert.That(client.Next().MessageId, Is.EqualTo("u1")); + await WaitFor(() => running.Cache.Get(KeyA)?.Text == "kept"); + } + + // write-receipt.md, Reliable channel only: reliable and not sequenced. Reliable ordered and unordered qualify; reliable + // sequenced does not, and nor does any unreliable method. + [TestCase(DeliveryMethod.ReliableSequenced, true)] + [TestCase(DeliveryMethod.Sequenced, true)] + [TestCase(DeliveryMethod.Unreliable, true)] + [TestCase(DeliveryMethod.ReliableUnordered, false)] + [TestCase(DeliveryMethod.ReliableOrdered, false)] + public async Task OnlyAReliableNonSequencedChannelCarriesAWriteOfAReceiptPeer(DeliveryMethod method, bool refused) + { + using var running = Running.Start(); + using var client = running.Connect(); + client.Send(HelloOf(BothFrames)); + client.Next(); + + client.Send(running.PutOf("c1", KeyA, "text"), method); + + if (refused) + { + var error = client.Next(); + Assert.That(error.Details!.Field, Is.EqualTo("channel")); + Assert.That(error.MessageId, Is.EqualTo("c1")); + Assert.That(running.Cache.Get(KeyA), Is.Null); + } + else + { + Assert.That(client.Next().MessageId, Is.EqualTo("c1")); + await WaitFor(() => running.Cache.Get(KeyA)?.Text == "text"); + } + } + + [Test] + public void ADeleteOnAnUnreliableChannelOfAReceiptPeerIsRefusedWithItsId() + { + using var running = Running.Start(); + using var client = running.Connect(); + client.Send(HelloOf(BothFrames)); + client.Next(); + + client.SendUnreliable(new CultNetDocumentDeleteMessage + { + MessageId = "ud1", SchemaId = running.SchemaId, RecordKey = KeyA.Value, ShardId = ShardId, ShardEpoch = 1 + }); + + var error = client.Next(); + Assert.That(error.Code, Is.EqualTo("message_invalid")); + Assert.That(error.Details!.Field, Is.EqualTo("channel")); + Assert.That(error.MessageId, Is.EqualTo("ud1")); + } + + [Test] + public async Task OnlyWritesAreRefusedOnTheUnreliableChannelAndALegacyPeerIsLeftAsBefore() + { + using var running = Running.Start(); + using var receipt = running.Connect(); + receipt.Send(HelloOf(BothFrames)); + receipt.Next(); + receipt.SendUnreliable(HelloOf(BothFrames)); // not a write: answered with nothing on the unreliable channel + receipt.Send(running.PutOf("r1", KeyA, "one")); + Assert.That(receipt.Next().MessageId, Is.EqualTo("r1"), "nothing else was sent ahead of the receipt"); + receipt.Send(running.PutOf("r2", KeyA, "two")); + Assert.That(receipt.Next().MessageId, Is.EqualTo("r2")); + receipt.ExpectNothingMore("the unreliable hello was answered with nothing"); + + using var legacy = running.Connect(); + legacy.Send(HelloOf()); + legacy.SendUnreliable(running.PutOf("l1", KeyB, "two")); // refused by the authority, answered as v0 as before + Assert.That(legacy.Next().Code, Is.EqualTo("write_not_authorized")); + legacy.SendUnreliable(running.PutOf("l2", KeyA, "three")); + await WaitFor(() => running.Cache.Get(KeyA)?.Text == "three"); + legacy.ExpectNothingMore("a legacy peer is never sent a receipt, error.v1 or a channel refusal"); + } + + private static async Task WaitFor(Func condition) + { + var deadline = DateTime.UtcNow + Cap; + while (!condition()) + { + if (DateTime.UtcNow > deadline) Assert.Fail("the condition did not hold within the cap"); + await Task.Delay(5); + } + } + } +} diff --git a/tests/GameCult.Networking.Tests/CultNetWriteReceiptServerTests.cs b/tests/GameCult.Networking.Tests/CultNetWriteReceiptServerTests.cs new file mode 100644 index 00000000..e42961a2 --- /dev/null +++ b/tests/GameCult.Networking.Tests/CultNetWriteReceiptServerTests.cs @@ -0,0 +1,1431 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using GameCult.Caching; +using NUnit.Framework; +using static GameCult.Networking.Tests.NetworkingTests; + +namespace GameCult.Networking.Tests +{ + // The database server's half of contracts/cultnet/interop/write-receipt.md. A peer whose hello lists both new frames is + // answered with write_admitted or error.v1, each naming the write's id; any other peer is answered as before. The handlers + // are reached through their private delegates; a peer's transport is a capture of what leaves it. + public sealed class CultNetWriteReceiptServerTests + { + private const string ShardId = "receipt-shard"; + private static readonly CultRecordKey KeyA = new("tests:receipt:a"); + private static readonly CultRecordKey KeyB = new("tests:receipt:b"); + + private sealed class Authority : ICultNetRemoteWriteAuthority + { + public HashSet Denied { get; } = new(); + public int Asked { get; private set; } + public CultNetRemoteWriteDecision Decide(CultNetRemoteWriteRequest request) + { + Asked++; + return Denied.Contains(request.RecordKey.Value) ? CultNetRemoteWriteDecision.Refuse("denied") : CultNetRemoteWriteDecision.Grant(); + } + } + + private sealed class Wire + { + public List Sent { get; } = new(); + /// When set, the connection cannot queue what it is sent. + public bool Unsendable { get; set; } + public int Ended { get; private set; } + public LiteNetLibTransportConnection Transport { get; } + public CultNetServerPeer Peer { get; } + + public Wire() + { + Transport = new LiteNetLibTransportConnection( + bytes => + { + if (Unsendable) throw new InvalidOperationException("the send queue is full"); + Sent.Add(LiteNetLibTransportConnection.DecodeSchema(LiteNetLibTransportConnection.Decode(bytes))); + }, + () => Ended++); + Peer = (CultNetServerPeer)RuntimeHelpers.GetUninitializedObject(typeof(CultNetServerPeer)); + typeof(CultNetServerPeer).GetField("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance)! + .SetValue(Peer, Transport); + } + } + + private sealed class Rig + { + public CultCache Cache = null!; + public CultNetDatabase Database = null!; + public CultNetDatabaseServer DatabaseServer = null!; + public Authority Authority = null!; + public string SchemaId = string.Empty; + public Func PutHandler = null!; + public Func DeleteHandler = null!; + public Func HelloHandler = null!; + + public int LogLength => Database.GetMutationLog(ShardId).Count; + public string? TextOf(CultRecordKey key) => Cache.Get(key)?.Text; + + public CultNetDocumentPutRawMessage PutOf(string id, CultRecordKey key, string text) + { + var message = Database.Documents.CreateRawDocumentPutMessage(id, new CultRecordHandle(key), + new NetworkSchemaNote { Schema = "tests.networking_note.v1", Text = text }); + message.ShardId = ShardId; + message.ShardEpoch = 1; + return message; + } + + public CultNetDocumentDeleteMessage DeleteOf(string id, CultRecordKey key) => + new() { MessageId = id, SchemaId = SchemaId, RecordKey = key.Value, ShardId = ShardId, ShardEpoch = 1 }; + + public Task Put(Wire wire, string id, CultRecordKey key, string text) => PutHandler(PutOf(id, key, text), wire.Peer); + public Task Delete(Wire wire, string id, CultRecordKey key) => DeleteHandler(DeleteOf(id, key), wire.Peer); + public Task Hello(Wire wire, params string[] versions) => HelloHandler(HelloOf(versions), wire.Peer); + } + + private static CultNetHelloMessage HelloOf(params string[] versions) => + new() { RuntimeId = "test-client", RuntimeKind = "test", SupportedMessageVersions = versions }; + + private static readonly string[] BothFrames = [CultNetSchemaVersions.WriteAdmitted, CultNetSchemaVersions.ErrorV1]; + + private static Rig Build(Authority? authority = null, bool primary = true, ICultNetShardWriteForwarder? forwarder = null) + { + var cache = new CultCache(); + var schemaId = cache.Registry.GetRequired().SchemaId; + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions + { + Shards = + [ + new CultNetShardDescriptor(ShardId, "primary", epoch: 1, isPrimary: primary, schemaIds: [schemaId], + primaryEndpoints: primary ? null : ["cultnet://runtime-owner:3075"]) + ] + }); + var host = new Server(cache, ServerSecurityOptions.Development()); + authority ??= new Authority(); + var databaseServer = new CultNetDatabaseServer(host, database, new CultNetDatabaseServerOptions + { + RemoteWriteAuthority = authority, + ForwardNonPrimaryWrites = forwarder != null, + WriteForwarder = forwarder + }); + const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance; + T Handler(string field) => (T)typeof(CultNetDatabaseServer).GetField(field, flags)!.GetValue(databaseServer)!; + return new Rig + { + Cache = cache, + Database = database, + DatabaseServer = databaseServer, + Authority = authority, + SchemaId = schemaId, + PutHandler = Handler>("_putHandler"), + DeleteHandler = Handler>("_deleteHandler"), + HelloHandler = Handler>("_helloHandler") + }; + } + + private static async Task<(Rig Rig, Wire Wire)> Capable() + { + var rig = Build(); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); // the server's own hello is checked on its own + return (rig, wire); + } + + private static CultNetWriteAdmittedMessage AssertAdmitted(ICultNetSchemaMessage message, string id, string operation, string recordKey) + { + var admitted = (CultNetWriteAdmittedMessage)message; + Assert.That(admitted.MessageId, Is.EqualTo(id)); + Assert.That(admitted.Operation, Is.EqualTo(operation)); + Assert.That(admitted.RecordKey, Is.EqualTo(recordKey)); + return admitted; + } + + private static CultNetErrorV1Message AssertRefused(ICultNetSchemaMessage message, string? id, string? code) + { + var error = (CultNetErrorV1Message)message; + Assert.That(error.MessageId, Is.EqualTo(id)); + Assert.That(error.Code, Is.EqualTo(code)); + return error; + } + + [Test] + public async Task AnAdmittedPutOnAReceiptConnectionIsAnsweredAfterItsCommit() + { + var (rig, wire) = await Capable(); + rig.Authority.Denied.Clear(); + + await rig.Put(wire, "m1", KeyA, "one"); + + Assert.That(rig.TextOf(KeyA), Is.EqualTo("one")); + var admitted = AssertAdmitted(wire.Sent.Single(), "m1", "put", KeyA.Value); + Assert.That(admitted.SchemaId, Is.EqualTo(rig.SchemaId)); + } + + [Test] + public async Task AnAdmittedDeleteIsAnsweredWithAReceiptNamingTheDelete() + { + var (rig, wire) = await Capable(); + await rig.Put(wire, "m1", KeyA, "one"); + wire.Sent.Clear(); + + await rig.Delete(wire, "d1", KeyA); + + Assert.That(rig.TextOf(KeyA), Is.Null); + AssertAdmitted(wire.Sent.Single(), "d1", "delete", KeyA.Value); + } + + [Test] + public async Task TheServerAnswersAReceiptHelloWithItsOwnListingBothFrames() + { + var rig = Build(); + var wire = new Wire(); + + await rig.Hello(wire, BothFrames); + + var hello = (CultNetHelloMessage)wire.Sent.Single(); + Assert.That(hello.SupportedMessageVersions, Is.EquivalentTo(BothFrames)); + } + + [TestCase("")] + [TestCase("cultnet.write_admitted.v0")] + [TestCase("cultnet.error.v1")] + public async Task APeerThatDoesNotListBothFramesIsAnsweredAsBeforeAndTheServerSaysNothingOfReceipts(string listed) + { + var rig = Build(); + var wire = new Wire(); + await rig.Hello(wire, listed.Length == 0 ? [] : [listed]); + await rig.Put(wire, "m1", KeyA, "one"); + + Assert.That(rig.TextOf(KeyA), Is.EqualTo("one"), "admitted all the same"); + Assert.That(wire.Sent, Is.Empty, "no receipt, no hello"); + + rig.Authority.Denied.Add(KeyB.Value); + await rig.Put(wire, "m2", KeyB, "two"); + Assert.That(wire.Sent.Single(), Is.TypeOf(), "a refusal is the v0 error, without an id"); + } + + [Test] + public async Task APeerThatNeverSaidHelloGetsNoReceipt() + { + var rig = Build(); + var wire = new Wire(); + + await rig.Put(wire, "m1", KeyA, "one"); + + Assert.That(wire.Sent, Is.Empty); + } + + [Test] + public async Task ASecondHelloDoesNotChangeTheCapability() + { + var (rig, wire) = await Capable(); + await rig.Hello(wire); + await rig.Put(wire, "m1", KeyA, "one"); + AssertAdmitted(wire.Sent.Single(), "m1", "put", KeyA.Value); + + var late = Build(); + var legacy = new Wire(); + await late.Put(legacy, "m1", KeyA, "one"); + await late.Hello(legacy, BothFrames); + await late.Put(legacy, "m2", KeyB, "two"); + Assert.That(legacy.Sent, Is.Empty, "a hello after the first write does not opt the connection in"); + } + + [Test] + public async Task ACapabilityNeverAuthorizes() + { + var (rig, wire) = await Capable(); + rig.Authority.Denied.Add(KeyA.Value); + + await rig.Put(wire, "m1", KeyA, "one"); + await rig.Delete(wire, "d1", KeyA); + + Assert.That(rig.TextOf(KeyA), Is.Null); + AssertRefused(wire.Sent[0], "m1", "write_not_authorized"); + AssertRefused(wire.Sent[1], "d1", "write_not_authorized"); + Assert.That(wire.Sent, Has.Count.EqualTo(2), "one answer per write"); + } + + [Test] + public async Task AResendOfAnAdmittedWriteIsReceiptedAgainWithoutBeingAppliedAgain() + { + var (rig, wire) = await Capable(); + await rig.Put(wire, "m1", KeyA, "one"); + var logAfterFirst = rig.LogLength; + + await rig.Put(wire, "m1", KeyA, "one"); + + Assert.That(wire.Sent, Has.Count.EqualTo(2)); + AssertAdmitted(wire.Sent[1], "m1", "put", KeyA.Value); + Assert.That(rig.LogLength, Is.EqualTo(logAfterFirst), "the resend was not committed again"); + } + + [Test] + public async Task TheSameIdWithOtherContentIsRefusedAndNeverReReceipted() + { + var (rig, wire) = await Capable(); + await rig.Put(wire, "m1", KeyA, "one"); + + await rig.Put(wire, "m1", KeyA, "other"); + await rig.Put(wire, "m1", KeyB, "one"); + await rig.Delete(wire, "m1", KeyA); + + Assert.That(rig.TextOf(KeyA), Is.EqualTo("one")); + Assert.That(rig.TextOf(KeyB), Is.Null); + Assert.That(wire.Sent, Has.Count.EqualTo(4)); + for (var index = 1; index < 4; index++) + { + var error = AssertRefused(wire.Sent[index], "m1", "message_invalid"); + Assert.That(error.Details!.Field, Is.EqualTo("messageId")); + } + } + + [Test] + public async Task AReusedIdIsJudgedBeforeAuthorityIsAskedAgain() + { + var (rig, wire) = await Capable(); + await rig.Put(wire, "m1", KeyA, "one"); + rig.Authority.Denied.Add(KeyB.Value); + + await rig.Put(wire, "m1", KeyB, "other"); + + AssertRefused(wire.Sent[1], "m1", "message_invalid"); + Assert.That(rig.Authority.Asked, Is.EqualTo(1), "authority is asked on an id's first sighting only"); + } + + [Test] + public async Task AResendIsAnsweredFromMemoryWithoutAskingAuthorityAgain() + { + var (rig, wire) = await Capable(); + await rig.Put(wire, "m1", KeyA, "one"); + rig.Authority.Denied.Add(KeyA.Value); + + await rig.Put(wire, "m1", KeyA, "one"); + + AssertAdmitted(wire.Sent[1], "m1", "put", KeyA.Value); + Assert.That(rig.Authority.Asked, Is.EqualTo(1)); + } + + [Test] + public async Task ARefusedWriteIsRememberedSoItsResendReplaysTheRefusal() + { + var (rig, wire) = await Capable(); + rig.Authority.Denied.Add(KeyA.Value); + await rig.Put(wire, "m1", KeyA, "one"); + rig.Authority.Denied.Clear(); + + await rig.Put(wire, "m1", KeyA, "one"); + + var first = AssertRefused(wire.Sent[0], "m1", "write_not_authorized"); + var again = AssertRefused(wire.Sent[1], "m1", "write_not_authorized"); + Assert.That(again.Error, Is.EqualTo(first.Error)); + Assert.That(rig.TextOf(KeyA), Is.Null, "the resend was not decided afresh"); + Assert.That(rig.Authority.Asked, Is.EqualTo(1)); + } + + [Test] + public async Task ARefusedIdReusedForOtherContentIsMessageInvalid() + { + var (rig, wire) = await Capable(); + rig.Authority.Denied.Add(KeyA.Value); + await rig.Put(wire, "m1", KeyA, "one"); + + await rig.Put(wire, "m1", KeyB, "other"); + + AssertRefused(wire.Sent[1], "m1", "message_invalid"); + Assert.That(rig.TextOf(KeyB), Is.Null); + } + + [Test] + public async Task RefusedWritesCountAgainstTheRememberedWriteLimit() + { + var (rig, wire) = await Capable(); + rig.Authority.Denied.Add(KeyA.Value); + for (var index = 0; index < CultNetWriteReceiptSession.MaxRememberedWrites; index++) + { + await rig.Put(wire, $"r{index}", KeyA, $"v{index}"); + } + + wire.Sent.Clear(); + await rig.Put(wire, "over", KeyB, "x"); + await rig.Put(wire, "r0", KeyA, "v0"); + + AssertRefused(wire.Sent[0], "over", "limit_reached"); + AssertRefused(wire.Sent[1], "r0", "write_not_authorized"); + Assert.That(rig.TextOf(KeyB), Is.Null); + } + + [Test] + public async Task APutAndADeleteNeverShareAnId() + { + var (rig, wire) = await Capable(); + await rig.Put(wire, "p1", KeyA, "one"); + await rig.Delete(wire, "d1", KeyA); + wire.Sent.Clear(); + + await rig.Delete(wire, "p1", KeyA); + await rig.Put(wire, "d1", KeyA, "one"); + + AssertRefused(wire.Sent[0], "p1", "message_invalid"); + AssertRefused(wire.Sent[1], "d1", "message_invalid"); + Assert.That(rig.TextOf(KeyA), Is.Null, "neither reuse was applied"); + } + + [Test] + public async Task ADeleteAsTheFirstFrameSettlesTheConnectionAsLegacy() + { + var rig = Build(); + var wire = new Wire(); + await rig.Delete(wire, "d1", KeyA); + await rig.Hello(wire, BothFrames); + await rig.Put(wire, "m1", KeyA, "one"); + + Assert.That(wire.Sent, Is.Empty, "a hello after the first delete does not opt the connection in"); + } + + [Test] + public async Task AnAnswerThatCannotBeSentEndsTheConnectionInsteadOfLeavingTheWriteSilent() + { + var (rig, wire) = await Capable(); + wire.Unsendable = true; + await rig.Put(wire, "m1", KeyA, "one"); + Assert.That(wire.Ended, Is.EqualTo(1), "a receipt that cannot be queued"); + + rig.Authority.Denied.Add(KeyB.Value); + await rig.Put(wire, "m2", KeyB, "two"); + Assert.That(wire.Ended, Is.EqualTo(2), "a refusal that cannot be queued"); + + wire.Transport.AnswerUnreadableSchemaFrame(new byte[] { 0xC1 }); + Assert.That(wire.Ended, Is.EqualTo(3), "an unreadable-frame answer that cannot be queued"); + } + + [Test] + public async Task AnUnexpectedFailureIsRefusedWithFixedTextNotTheExceptionsOwn() + { + var (rig, wire) = await Capable(); + var message = rig.PutOf("m1", KeyA, "one"); + message.Document!.Payload = [0xC1]; + var legacy = new Wire(); + + await rig.PutHandler(message, wire.Peer); + await rig.PutHandler(message, legacy.Peer); + await rig.DeleteHandler(new CultNetDocumentDeleteMessage { MessageId = "d1", SchemaId = "no.such.schema", RecordKey = "k" }, legacy.Peer); + + Assert.That(((CultNetErrorV1Message)wire.Sent.Single()).Error, Is.EqualTo(CultNetWriteReceiptSession.WriteFailedText)); + Assert.That(((CultNetErrorMessage)legacy.Sent[0]).Error, Is.EqualTo(CultNetWriteReceiptSession.WriteFailedText)); + } + + [Test] + public void TheLimitReachedRefusalIsTheSpecVectorByteForByte() + { + const string vector = "86AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7631A56572726F72D93B6C696D69745F726561636865643A207468652073657373696F6E27732072656D656D62657265642D7772697465206C696D69742069732066756C6CAB726F7574696E6748696E74C0A4636F6465AD6C696D69745F72656163686564A764657461696C7384A56669656C64C0A576616C7565C0A461734F66C0A763757272656E74C0A96D6573736167654964A87075742D31303235"; + + var bytes = CultNetSchemaMessageSerialization.Serialize(CultNetErrorV1Message.LimitReached("put-1025")); + + Assert.That(Convert.ToHexString(bytes), Is.EqualTo(vector)); + } + + [Test] + public void TheSpecWireVectorsDecodeToTheirExpectedFields() + { + var admitted = (CultNetWriteAdmittedMessage)CultNetSchemaMessageSerialization.Deserialize(Convert.FromHexString( + "85AD736368656D6156657273696F6EB963756C746E65742E77726974655F61646D69747465642E7630A96D6573736167654964A57075742D31A96F7065726174696F6EA3707574A8736368656D614964A76E6F74652E7630A97265636F72644B6579A66E6F74653A31")); + Assert.That((admitted.MessageId, admitted.Operation, admitted.SchemaId, admitted.RecordKey), + Is.EqualTo(("put-1", "put", "note.v0", "note:1"))); + + var refused = (CultNetErrorV1Message)CultNetSchemaMessageSerialization.Deserialize(Convert.FromHexString( + "86AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7631A56572726F72D93677726974655F6E6F745F617574686F72697A65643A2074686520636174616C6F6720726566757365642074686520646F63756D656E74AB726F7574696E6748696E74C0A4636F6465B477726974655F6E6F745F617574686F72697A6564A764657461696C7384A56669656C64A97265636F72644B6579A576616C7565A66E6F74653A32A461734F66C0A763757272656E74C0A96D6573736167654964A57075742D32")); + Assert.That(refused.Error, Is.EqualTo("write_not_authorized: the catalog refused the document")); + Assert.That(refused.Code, Is.EqualTo("write_not_authorized")); + Assert.That(refused.MessageId, Is.EqualTo("put-2")); + Assert.That((refused.Details!.Field, refused.Details.Value), Is.EqualTo(("recordKey", "note:2"))); + Assert.That(refused.Details.AsOf, Is.Null); + Assert.That(refused.Details.Current, Is.Null); + } + + [Test] + public async Task AFullDedupeTableRefusesNewWritesAndStillAnswersRememberedOnes() + { + var (rig, wire) = await Capable(); + for (var index = 0; index < CultNetWriteReceiptSession.MaxRememberedWrites; index++) + { + await rig.Put(wire, $"w{index}", new CultRecordKey($"tests:receipt:{index}"), "x"); + } + + wire.Sent.Clear(); + await rig.Put(wire, "over", KeyA, "x"); + await rig.Put(wire, "w0", new CultRecordKey("tests:receipt:0"), "x"); + + var limit = AssertRefused(wire.Sent[0], "over", "limit_reached"); + Assert.That(limit.Error, Is.EqualTo("limit_reached: the session's remembered-write limit is full")); + AssertAdmitted(wire.Sent[1], "w0", "put", "tests:receipt:0"); + Assert.That(rig.TextOf(KeyA), Is.Null); + } + + [Test] + public async Task AWriteWithNoIdIsRefusedWithNoId() + { + var (rig, wire) = await Capable(); + + var message = rig.PutOf("placeholder", KeyA, "one"); + message.MessageId = string.Empty; + await rig.PutHandler(message, wire.Peer); + + var error = AssertRefused(wire.Sent.Single(), null, "message_invalid"); + Assert.That(error.Details!.Field, Is.EqualTo("messageId")); + Assert.That(rig.TextOf(KeyA), Is.Null); + } + + [Test] + public async Task AFrameThatDoesNotDecodeIsRefusedWithItsIdWhenItHoldsOne() + { + var (_, wire) = await Capable(); + var withId = MessagePack.MessagePackSerializer.Serialize(new Dictionary + { + ["schemaVersion"] = "cultnet.document_put_raw.v9", + ["messageId"] = "bad-1" + }); + + wire.Transport.AnswerUnreadableSchemaFrame(withId); + wire.Transport.AnswerUnreadableSchemaFrame(new byte[] { 0xC1 }); + + var error = AssertRefused(wire.Sent[0], "bad-1", "message_invalid"); + Assert.That(error.Details!.Field, Is.EqualTo("message")); + AssertRefused(wire.Sent[1], null, "message_invalid"); + } + + [Test] + public void ReadableMessageIdFindsOnlyANonEmptyStringIdInATopLevelMap() + { + string? IdOf(object value) => CultNetReadableMessageId.From(MessagePack.MessagePackSerializer.Serialize(value)); + + Assert.That(IdOf(new Dictionary { ["a"] = new[] { 1, 2 }, ["messageId"] = "x" }), Is.EqualTo("x")); + Assert.That(IdOf(new Dictionary { ["messageId"] = 5 }), Is.Null); + Assert.That(IdOf(new Dictionary { ["messageId"] = "" }), Is.Null); + Assert.That(IdOf(new Dictionary { ["nested"] = new Dictionary { ["messageId"] = "deep" } }), Is.Null); + Assert.That(IdOf("messageId"), Is.Null); + } + + [Test] + public void TheContentHashMatchesTheSpecVectors() + { + byte[] a = [0x81, 0xA2, 0x69, 0x64, 0xA1, 0x31]; + byte[] b = [0x81, 0xA2, 0x69, 0x64, 0xA1, 0x32]; + string Hex(byte[] hash) => Convert.ToHexString(hash).ToLowerInvariant(); + + Assert.That(Hex(CultNetWriteContentHash.Compute("put", "note.v0", "note:1", a)), Is.EqualTo("7051c10071123b6ade50fbd5075e3859cae4ea70ce358a24a0b0c6980090e95d")); + Assert.That(Hex(CultNetWriteContentHash.Compute("put", "note.v0", "note:1", b)), Is.EqualTo("58d3fc6b858d2605a68550c9d4811ccdca6b9db7a0c3bfebf304d279257f6f9f")); + Assert.That(Hex(CultNetWriteContentHash.Compute("put", "note.v0", "note:2", a)), Is.EqualTo("a248cd920e58d41bc6ccca9e108030b1d491239000047fef088122364a32b6f8")); + Assert.That(Hex(CultNetWriteContentHash.Compute("delete", "note.v0", "note:1", null)), Is.EqualTo("232b0f96651b28aa8ab7673a6106944a9f6a8d66852b6e21291a23ed084b8b37")); + } + + [Test] + public void TheNewFramesRoundTripOnTheWire() + { + var admitted = new CultNetWriteAdmittedMessage { MessageId = "m", Operation = "put", SchemaId = "s", RecordKey = "k" }; + var error = new CultNetErrorV1Message { Error = "e", Code = "message_invalid", MessageId = null }; + + var admittedBack = (CultNetWriteAdmittedMessage)CultNetSchemaMessageSerialization.Deserialize(CultNetSchemaMessageSerialization.Serialize(admitted)); + var errorBack = (CultNetErrorV1Message)CultNetSchemaMessageSerialization.Deserialize(CultNetSchemaMessageSerialization.Serialize(error)); + + Assert.That(admittedBack.MessageId, Is.EqualTo("m")); + Assert.That(admittedBack.RecordKey, Is.EqualTo("k")); + Assert.That(errorBack.MessageId, Is.Null); + Assert.That(errorBack.Code, Is.EqualTo("message_invalid")); + } + + private sealed class ScriptedForwarder : ICultNetShardWriteForwarder + { + public Func OnPut { get; set; } = _ => Task.CompletedTask; + public Func OnDelete { get; set; } = _ => Task.CompletedTask; + public int Forwarded { get; private set; } + + public Task ForwardPutAsync(CultNetShardDescriptor shard, CultNetDocumentPutRawMessage message) + { + Forwarded++; + return OnPut(message); + } + + public Task ForwardDeleteAsync(CultNetShardDescriptor shard, CultNetDocumentDeleteMessage message) + { + Forwarded++; + return OnDelete(message); + } + } + + [Test] + public async Task AForwardedWriteIsReceiptedUnderItsOriginalIdOnlyWhenThePrimaryAnswered() + { + var forwarder = new ScriptedForwarder(); + var rig = Build(primary: false, forwarder: forwarder); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + + await rig.Put(wire, "fwd-1", KeyA, "one"); + await rig.Delete(wire, "fwd-2", KeyA); + + AssertAdmitted(wire.Sent[0], "fwd-1", "put", KeyA.Value); + AssertAdmitted(wire.Sent[1], "fwd-2", "delete", KeyA.Value); + Assert.That(forwarder.Forwarded, Is.EqualTo(2)); + } + + [Test] + public async Task AForwardedWritesRefusalIsRelayedAsErrorV1UnderTheOriginalId() + { + var forwarder = new ScriptedForwarder + { + OnPut = _ => Task.FromException(new CultNetWriteRefusedException(new CultNetErrorMessage { Error = "primary says no", Code = "write_not_authorized" })), + OnDelete = _ => Task.FromException(new CultNetWriteRefusedException(CultNetErrorMessage.ForMessageInvalid("recordKey", "bad"))) + }; + var rig = Build(primary: false, forwarder: forwarder); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + + await rig.Put(wire, "fwd-1", KeyA, "one"); + await rig.Delete(wire, "fwd-2", KeyA); + + AssertRefused(wire.Sent[0], "fwd-1", "write_not_authorized"); + Assert.That(((CultNetErrorV1Message)wire.Sent[0]).Error, Is.EqualTo("write_not_authorized"), "a relayed refusal is in fixed text, the same one a resend replays"); + AssertRefused(wire.Sent[1], "fwd-2", "message_invalid"); + } + + [Test] + public async Task AForwardThePrimaryLeftSilentIsNeverForwardedAgainOnTheSession() + { + var forwarder = new ScriptedForwarder { OnPut = _ => Task.FromException(new CultNetWriteUnconfirmedException("fwd-1")) }; + var rig = Build(primary: false, forwarder: forwarder); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + + await rig.Put(wire, "fwd-1", KeyA, "one"); + forwarder.OnPut = _ => Task.CompletedTask; + await rig.Put(wire, "fwd-1", KeyA, "one"); + + Assert.That(wire.Sent, Is.Empty, "no receipt, no error: the write stays unconfirmed"); + Assert.That(forwarder.Forwarded, Is.EqualTo(1), "the primary may have applied it, so it is not sent again"); + + await rig.Put(wire, "fwd-1", KeyB, "other"); + AssertRefused(wire.Sent.Single(), "fwd-1", "message_invalid"); + } + + [Test] + public async Task AForwardRefusedByThePrimaryReplaysItsRefusalOnResend() + { + var forwarder = new ScriptedForwarder + { + OnPut = _ => Task.FromException(new CultNetWriteRefusedException(new CultNetErrorMessage { Error = "primary says no", Code = "write_not_authorized" })) + }; + var rig = Build(primary: false, forwarder: forwarder); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + + await rig.Put(wire, "fwd-1", KeyA, "one"); + await rig.Put(wire, "fwd-1", KeyA, "one"); + + Assert.That(wire.Sent, Has.Count.EqualTo(2)); + Assert.That(((CultNetErrorV1Message)wire.Sent[1]).Error, Is.EqualTo("write_not_authorized"), "a remembered refusal is replayed in fixed text, not the primary's own"); + Assert.That(forwarder.Forwarded, Is.EqualTo(1)); + } + + [Test] + public async Task AForwardThatWasNotSentMayBeRetriedUnderTheSameId() + { + var forwarder = new ScriptedForwarder { OnPut = _ => Task.FromException(new CultNetWriteNotSentException("fwd-1", new TimeoutException("primary unreachable"))) }; + var rig = Build(primary: false, forwarder: forwarder); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + + await rig.Put(wire, "fwd-1", KeyA, "one"); + Assert.That(wire.Sent, Is.Empty, "no receipt, no error, no synthesized refusal"); + + forwarder.OnPut = _ => Task.CompletedTask; + await rig.Put(wire, "fwd-1", KeyA, "one"); + AssertAdmitted(wire.Sent.Single(), "fwd-1", "put", KeyA.Value); + Assert.That(forwarder.Forwarded, Is.EqualTo(2), "the unsent attempt left no claim behind"); + } + + // Once the frame may have gone out, whatever failed, the id is never forwarded again on the session. + private static IEnumerable PostSendFailures() + { + yield return new TestCaseData(new TimeoutException("no answer")).SetName("timeout"); + yield return new TestCaseData(new System.IO.IOException("connection reset")).SetName("reset"); + yield return new TestCaseData(new InvalidOperationException("client disconnected")).SetName("disconnected"); + yield return new TestCaseData(new CultNetWriteUnconfirmedException("fwd-1")).SetName("no answer in the window"); + yield return new TestCaseData(new Exception("anything else, ambiguous")).SetName("ambiguous"); + } + + [TestCaseSource(nameof(PostSendFailures))] + public async Task AForwardThatMayHaveBeenSentIsNeverForwardedAgainOnTheSession(Exception failure) + { + var forwarder = new ScriptedForwarder { OnPut = _ => Task.FromException(failure) }; + var rig = Build(primary: false, forwarder: forwarder); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + + await rig.Put(wire, "fwd-1", KeyA, "one"); + forwarder.OnPut = _ => Task.CompletedTask; + await rig.Put(wire, "fwd-1", KeyA, "one"); + + Assert.That(wire.Sent, Is.Empty, "unconfirmed: nothing answered, nothing synthesized"); + Assert.That(forwarder.Forwarded, Is.EqualTo(1), "the claim stays"); + } + + [Test] + public async Task TheRealForwarderRetriesAConnectFailureButNotAFailureAfterTheWriteWasSent() + { + var clients = new Queue(); + var forwarder = new CultNetSchemaWriteForwarder(new CultNetSchemaWriteForwarderOptions + { + CreateClient = () => clients.Dequeue(), + ConnectTimeout = TimeSpan.FromMilliseconds(100), + ResultWindow = TimeSpan.FromMilliseconds(100) + }); + var rig = Build(primary: false, forwarder: forwarder); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + + clients.Enqueue(new ForwardingClient { ConnectFails = true }); + await rig.Put(wire, "fwd-1", KeyA, "one"); + var sent = new ForwardingClient { AdmitWrites = true }; + clients.Enqueue(sent); + await rig.Put(wire, "fwd-1", KeyA, "one"); + AssertAdmitted(wire.Sent.Single(), "fwd-1", "put", KeyA.Value); + + wire.Sent.Clear(); + var reset = new ForwardingClient { WriteSendFails = true }; + clients.Enqueue(reset); + await rig.Put(wire, "fwd-2", KeyA, "two"); + clients.Enqueue(new ForwardingClient { AdmitWrites = true }); + await rig.Put(wire, "fwd-2", KeyA, "two"); + Assert.That(wire.Sent, Is.Empty, "the write send threw: it may have gone out"); + Assert.That(clients, Has.Count.EqualTo(1), "and the id was not forwarded again"); + } + + private sealed class ForwardingClient : ICultNetSchemaClient + { + private Action? _admitted; + public bool ConnectFails { get; set; } + public bool NeverConnects { get; set; } + public bool HelloSendFails { get; set; } + public bool WriteSendFails { get; set; } + public bool WriteNotSentFails { get; set; } + public bool AdmitWrites { get; set; } + public bool Connected { get; private set; } + public List Sent { get; } = new(); + + public void Connect(string host, int port) + { + if (ConnectFails) throw new System.Net.Sockets.SocketException(); + Connected = !NeverConnects; + } + + public void SendCultNet(T message) where T : ICultNetSchemaMessage + { + if (message is CultNetHelloMessage) + { + if (HelloSendFails) throw new System.IO.IOException("hello failed"); + return; + } + + if (WriteNotSentFails) throw new CultNetWriteNotSentException("x"); + if (WriteSendFails) throw new System.IO.IOException("send failed after an unknown number of bytes"); + Sent.Add(message); + if (AdmitWrites && message is CultNetDocumentPutRawMessage put) + _admitted?.Invoke(new CultNetWriteAdmittedMessage { MessageId = put.MessageId, Operation = "put", SchemaId = put.Document?.SchemaId, RecordKey = put.Document?.RecordKey }); + } + + public void OnCultNet(Action callback) where T : ICultNetSchemaMessage + { + if (callback is Action admitted) _admitted = admitted; + } + + public void Dispose() { } + } + + private static CultNetSchemaWriteForwarder RealForwarder(ForwardingClient client) => new(new CultNetSchemaWriteForwarderOptions + { + CreateClient = () => client, + ConnectTimeout = TimeSpan.FromMilliseconds(100), + ResultWindow = TimeSpan.FromMilliseconds(100) + }); + + private static readonly CultNetShardDescriptor ForwardShard = new("notes", "primary", 1, isPrimary: false, primaryEndpoints: ["cultnet://primary.example.test:4075"]); + + private static CultNetDocumentPutRawMessage ForwardPut() => new() { MessageId = "fwd-1", Document = new CultNetRawDocumentRecord { SchemaId = "s", RecordKey = "k", Payload = [1] } }; + + [TestCase("connect")] + [TestCase("never connects")] + [TestCase("hello")] + [TestCase("write not sent")] + public void TheForwarderNamesEveryFailureBeforeTheWriteWasSentAsNotSent(string stage) + { + var client = new ForwardingClient + { + ConnectFails = stage == "connect", + NeverConnects = stage == "never connects", + HelloSendFails = stage == "hello", + WriteNotSentFails = stage == "write not sent" + }; + + Assert.ThrowsAsync(() => RealForwarder(client).ForwardPutAsync(ForwardShard, ForwardPut())); + Assert.That(client.Sent, Is.Empty); + } + + [Test] + public void TheForwarderNamesNoPrimaryEndpointAsNotSent() + { + var shard = new CultNetShardDescriptor("notes", "primary", 1, isPrimary: false, primaryEndpoints: []); + Assert.ThrowsAsync(() => RealForwarder(new ForwardingClient()).ForwardPutAsync(shard, ForwardPut())); + } + + [Test] + public void ASendThatThrewWithoutProvingNothingWasWrittenIsNotNotSent() + { + var client = new ForwardingClient { WriteSendFails = true }; + var failure = Assert.CatchAsync(() => RealForwarder(client).ForwardPutAsync(ForwardShard, ForwardPut())); + Assert.That(failure, Is.Not.InstanceOf(), "ambiguous: unconfirmed"); + } + + [Test] + public void ASentWriteNobodyAnswersIsUnconfirmedNotNotSent() + { + var client = new ForwardingClient(); + Assert.ThrowsAsync(() => RealForwarder(client).ForwardPutAsync(ForwardShard, ForwardPut())); + Assert.That(client.Sent, Has.Count.EqualTo(1)); + } + + [Test] + public async Task TheRoutingRefusalAndTheUnownedSchemaRefusalCarryNoExceptionText() + { + var rig = Build(primary: false); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + await rig.Put(wire, "fwd-1", KeyA, "one"); + var routing = AssertRefused(wire.Sent.Single(), "fwd-1", null); + Assert.That(routing.Error, Is.EqualTo(CultNetDatabaseServer.RoutingRefusalText)); + + var secret = new CultNetUnownedSchemaException("secret.schema.v1", new CultRecordKey("secret:key")); + var unowned = CultNetErrorMessage.ForUnownedSchema(secret); + Assert.That(unowned.Error, Does.Not.Contain(secret.Message).And.Not.Contain("secret")); + Assert.That(unowned.Details!.Value, Is.EqualTo("secret.schema.v1"), "the structured detail still names the schema"); + } + + [Test] + public async Task APeerThatDidNotOptInIsToldNothingOfAnUnansweredForward() + { + var forwarder = new ScriptedForwarder { OnPut = _ => Task.FromException(new CultNetWriteUnconfirmedException("fwd-1")) }; + var rig = Build(primary: false, forwarder: forwarder); + var wire = new Wire(); + + await rig.Put(wire, "fwd-1", KeyA, "one"); + + Assert.That(wire.Sent, Is.Empty); + } + + [Test] + public async Task AReceiptConnectionNotForwardableIsRefusedWithTheRoutingErrorAndItsId() + { + var rig = Build(primary: false); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + + await rig.Put(wire, "fwd-1", KeyA, "one"); + + var error = AssertRefused(wire.Sent.Single(), "fwd-1", null); + Assert.That(error.RoutingHint, Is.Not.Null); + } + + [Test] + public async Task AResendWhileTheFirstAttemptIsStillBeingAppliedIsNotAnsweredTwice() + { + var release = new TaskCompletionSource(); + var forwarder = new ScriptedForwarder { OnPut = _ => release.Task }; + var rig = Build(primary: false, forwarder: forwarder); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + + var first = rig.Put(wire, "fwd-1", KeyA, "one"); + await rig.Put(wire, "fwd-1", KeyA, "one"); + Assert.That(wire.Sent, Is.Empty, "the resend waits for the first attempt's answer"); + release.SetResult(); + await first; + + AssertAdmitted(wire.Sent.Single(), "fwd-1", "put", KeyA.Value); + Assert.That(forwarder.Forwarded, Is.EqualTo(1), "and is not forwarded again"); + } + + [Test] + public void TheForwarderWaitsTheReceiptWindowByDefault() + { + Assert.That(new CultNetSchemaWriteForwarderOptions().ResultWindow, Is.EqualTo(CultNetWriteCompletion.ReceiptResultWindow)); + } + + // ---- Heimdall round two ---- + + private static string IdOfBytes(int bytes) => new string('i', bytes); + + [Test] + public async Task AnIdOver256BytesIsRefusedBeforeAnythingIsRemembered() + { + var (rig, wire) = await Capable(); + var tooLong = IdOfBytes(257); + + await rig.Put(wire, tooLong, KeyA, "one"); + await rig.Put(wire, tooLong, KeyA, "one"); + + Assert.That(wire.Sent, Has.Count.EqualTo(2)); + foreach (var sent in wire.Sent) + { + var error = AssertRefused(sent, tooLong, "message_invalid"); + Assert.That(error.Details!.Field, Is.EqualTo("messageId")); + Assert.That(error.Error, Is.EqualTo("message_invalid: messageId exceeds 256 bytes")); + } + + Assert.That(rig.TextOf(KeyA), Is.Null); + // Nothing was remembered: the whole table is still free for admitted writes. + wire.Sent.Clear(); + for (var index = 0; index < CultNetWriteReceiptSession.MaxRememberedWrites; index++) + await rig.Put(wire, $"w{index}", new CultRecordKey($"tests:receipt:{index}"), "x"); + Assert.That(wire.Sent.OfType().Count(), Is.EqualTo(CultNetWriteReceiptSession.MaxRememberedWrites)); + } + + [Test] + public async Task TheIdLimitCountsUtf8BytesNotCharacters() + { + var (rig, wire) = await Capable(); + var atLimit = IdOfBytes(256); + var multibyte = new string('\u00e9', 129); // 129 chars, 258 bytes + + await rig.Put(wire, atLimit, KeyA, "one"); + await rig.Put(wire, multibyte, KeyB, "two"); + + AssertAdmitted(wire.Sent[0], atLimit, "put", KeyA.Value); + AssertRefused(wire.Sent[1], multibyte, "message_invalid"); + } + + [Test] + public void ARememberedEntryHoldsOnlyFixedSizeDigestsNotTheStrings() + { + var flags = BindingFlags.NonPublic | BindingFlags.Instance; + var table = typeof(CultNetWriteReceiptSession).GetFields(flags) + .Where(f => f.FieldType.IsGenericType && f.FieldType.GetGenericTypeDefinition() == typeof(Dictionary<,>)); + Assert.That(table, Is.Not.Empty); + foreach (var field in table) + { + var args = field.FieldType.GetGenericArguments(); + Assert.That(args[0].IsValueType, Is.True, $"{field.Name} is keyed by {args[0]}"); + foreach (var held in args[1].IsValueType || args[1] == typeof(string) ? new[] { args[1] } : args[1].GetFields(flags).Select(f => f.FieldType).Concat(args[1].GetProperties(flags | BindingFlags.Public).Select(p => p.PropertyType))) + { + Assert.That(held == typeof(string) || held == typeof(byte[]), Is.False, $"{field.Name} holds {held}"); + } + } + } + + [Test] + public async Task AnAdmittedResendIsAnsweredFromDigestsWithTheResendsOwnBody() + { + var (rig, wire) = await Capable(); + await rig.Put(wire, "m1", KeyA, "one"); + await rig.Put(wire, "m1", KeyA, "one"); + + AssertAdmitted(wire.Sent[1], "m1", "put", KeyA.Value); + Assert.That(rig.LogLength, Is.EqualTo(1)); + } + + [Test] + public async Task ARefusalIsReplayedForAResendAfterTheDigestChange() + { + var (rig, wire) = await Capable(); + rig.Authority.Denied.Add(KeyA.Value); + await rig.Put(wire, "m1", KeyA, "one"); + await rig.Put(wire, "m1", KeyA, "one"); + + AssertRefused(wire.Sent[0], "m1", "write_not_authorized"); + AssertRefused(wire.Sent[1], "m1", "write_not_authorized"); + Assert.That(rig.Authority.Asked, Is.EqualTo(1)); + } + + [Test] + public async Task APutWithNoDocumentIsRefusedNamingTheDocumentWithFixedText([Values] bool capable) + { + var rig = Build(); + var wire = new Wire(); + if (capable) await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + var message = rig.PutOf("m1", KeyA, "one"); + message.Document = null!; + + await rig.PutHandler(message, wire.Peer); + + var sent = wire.Sent.Single(); + var error = capable ? AssertRefused(sent, "m1", "message_invalid").ToV0() : (CultNetErrorMessage)sent; + Assert.That(error.Code, Is.EqualTo("message_invalid")); + Assert.That(error.Details!.Field, Is.EqualTo("document")); + Assert.That(error.Error, Is.EqualTo("message_invalid: document is required")); + } + + [Test] + public async Task APutWithNoSchemaIdIsRefusedNamingTheSchemaIdWithFixedText() + { + var (rig, wire) = await Capable(); + var message = rig.PutOf("m1", KeyA, "one"); + message.Document.SchemaId = null!; + + await rig.PutHandler(message, wire.Peer); + + var error = AssertRefused(wire.Sent.Single(), "m1", "message_invalid"); + Assert.That(error.Details!.Field, Is.EqualTo("schemaId")); + Assert.That(error.Error, Is.EqualTo("message_invalid: schemaId is required")); + } + + [Test] + public async Task ADeleteWithNoSchemaIdIsRefusedNamingTheSchemaIdWithFixedText([Values] bool capable) + { + var rig = Build(); + var wire = new Wire(); + if (capable) await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + var message = rig.DeleteOf("d1", KeyA); + message.SchemaId = null!; + + await rig.DeleteHandler(message, wire.Peer); + + var sent = wire.Sent.Single(); + var error = capable ? AssertRefused(sent, "d1", "message_invalid").ToV0() : (CultNetErrorMessage)sent; + Assert.That(error.Details!.Field, Is.EqualTo("schemaId")); + Assert.That(error.Error, Is.EqualTo("message_invalid: schemaId is required")); + } + + // An empty or blank schemaId or recordKey is refused like a frame that does not read (the Rust server's rule): message_invalid, + // details.field "message", the write's id, nothing applied. A null schemaId stays "schemaId is required". + [TestCase("", null)] + [TestCase(" ", null)] + [TestCase(null, "")] + [TestCase(null, " ")] + public async Task APutWithAnEmptyOrBlankSchemaIdOrRecordKeyIsRefusedAsUnreadableAndNotApplied(string? schemaId, string? recordKey) + { + var (rig, wire) = await Capable(); + var message = rig.PutOf("m1", KeyA, "one"); + if (schemaId != null) message.Document.SchemaId = schemaId; + if (recordKey != null) message.Document.RecordKey = recordKey; + wire.Sent.Clear(); + + await rig.PutHandler(message, wire.Peer); + + var error = AssertRefused(wire.Sent.Single(), "m1", "message_invalid"); + Assert.That(error.Details!.Field, Is.EqualTo("message")); + Assert.That(rig.TextOf(KeyA), Is.Null); + } + + private static JsonElement Vectors() + { + var directory = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); + while (directory != null && !File.Exists(Path.Combine(directory.FullName, "CultLib.sln"))) + directory = directory.Parent; + var path = Path.Combine(directory!.FullName, "contracts", "cultnet", "interop", "write-receipt-vectors.json"); + return JsonDocument.Parse(File.ReadAllText(path)).RootElement.Clone(); + } + + public static IEnumerable BlankFieldCases() => + Vectors().GetProperty("blankFields").GetProperty("cases").EnumerateArray().Select(c => c.GetProperty("name").GetString()!); + + // The one fixed text of a frame that does not read or a write that names nothing, read from the vector that carries it. + private static string UnreadableVectorText() => + Vectors().GetProperty("wire").EnumerateArray() + .Single(v => v.GetProperty("name").GetString() == "error_v1_empty_schema_id_is_unreadable_and_names_the_write") + .GetProperty("message").GetProperty("error").GetString()!; + + // write-receipt-vectors.json `blankFields`: every case, on a receipt-capable and on a legacy connection. The rig's put is + // the valid document; the case's `set` replaces the named fields (the vectors' payload bytes stand for any non-empty payload). + [Test] + public async Task APutThatNamesNothingIsRefusedAsUnreadableAndANamedOneIsAdmitted( + [ValueSource(nameof(BlankFieldCases))] string name, [Values] bool capable) + { + var vectors = Vectors().GetProperty("blankFields").GetProperty("cases").EnumerateArray() + .Single(c => c.GetProperty("name").GetString() == name); + var rig = Build(); + var wire = new Wire(); + if (capable) await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + var message = rig.PutOf("m1", KeyA, "one"); + var document = message.Document!; + foreach (var field in vectors.GetProperty("set").EnumerateObject()) + { + var value = field.Value; + var text = value.ValueKind == JsonValueKind.String ? value.GetString() : null; + switch (field.Name) + { + case "schemaId": document.SchemaId = text!; break; + case "recordKey": document.RecordKey = text!; break; + case "storedAt": document.StoredAt = text!; break; + case "payloadHex": document.Payload = Convert.FromHexString(text!); break; + case "sourceRuntimeId": document.SourceRuntimeId = text; break; + case "sourceAgentId": document.SourceAgentId = text; break; + case "sourceRole": document.SourceRole = text; break; + case "tags": document.Tags = value.ValueKind == JsonValueKind.Null ? null : value.EnumerateArray().Select(t => t.GetString()!).ToArray(); break; + default: Assert.Fail($"unknown field {field.Name}"); break; + } + } + + await rig.PutHandler(message, wire.Peer); + + if (vectors.GetProperty("outcome").GetString() == "admitted") + { + if (capable) AssertAdmitted(wire.Sent.Single(), "m1", "put", document.RecordKey); + else Assert.That(wire.Sent, Is.Empty, "a legacy connection is sent no receipt"); + if (!vectors.GetProperty("set").EnumerateObject().Any(f => f.Name is "schemaId" or "recordKey")) + Assert.That(rig.TextOf(KeyA), Is.EqualTo("one")); + return; + } + + var refused = wire.Sent.Single(); + var error = capable ? AssertRefused(refused, "m1", "message_invalid").ToV0() : (CultNetErrorMessage)refused; + Assert.That(error.Code, Is.EqualTo("message_invalid")); + Assert.That(error.Details!.Field, Is.EqualTo("message")); + Assert.That(error.Error, Is.EqualTo(UnreadableVectorText())); + Assert.That(rig.TextOf(KeyA), Is.Null, "a write that names nothing is never applied"); + } + + public static IEnumerable WhiteSpaceCodePoints() => + Vectors().GetProperty("blankFields").GetProperty("whiteSpaceCodePoints").EnumerateArray().Select(c => c.GetString()!); + + public static IEnumerable NonWhiteSpaceCodePoints() => + Vectors().GetProperty("blankFields").GetProperty("notWhiteSpaceCodePoints").EnumerateArray().Select(c => c.GetString()!); + + private static readonly string[] BlankRuleFields = + { "schemaId", "recordKey", "storedAt", "sourceRuntimeId", "sourceAgentId", "sourceRole", "tags" }; + + // Blank is the Unicode White_Space property in every runtime (write-receipt.md, Required fields), not whatever the + // platform's char.IsWhiteSpace says: each listed code point, alone or repeated, in each covered field is refused as + // unreadable and never applied; each listed non-White_Space code point (U+200B, U+FEFF, U+180E, ...) is a name. + private async Task AssertBlankRule(string hex, bool blank) + { + foreach (var field in BlankRuleFields) + foreach (var times in new[] { 1, 3 }) + { + var text = string.Concat(Enumerable.Repeat(char.ConvertFromUtf32(Convert.ToInt32(hex, 16)), times)); + var rig = Build(); + var wire = new Wire(); + await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + var message = rig.PutOf("m1", KeyA, "one"); + var document = message.Document!; + switch (field) + { + case "schemaId": document.SchemaId = text; break; + case "recordKey": document.RecordKey = text; break; + case "storedAt": document.StoredAt = text; break; + case "sourceRuntimeId": document.SourceRuntimeId = text; break; + case "sourceAgentId": document.SourceAgentId = text; break; + case "sourceRole": document.SourceRole = text; break; + default: document.Tags = new[] { "a", text }; break; + } + var what = $"U+{hex} in {field} x{times}"; + + await rig.PutHandler(message, wire.Peer); + + if (blank) + { + var error = AssertRefused(wire.Sent.Single(), "m1", "message_invalid").ToV0(); + Assert.That(error.Details!.Field, Is.EqualTo("message"), what); + Assert.That(error.Error, Is.EqualTo(UnreadableVectorText()), what); + Assert.That(rig.TextOf(KeyA), Is.Null, $"{what}: never applied"); + } + else + { + AssertAdmitted(wire.Sent.Single(), "m1", "put", document.RecordKey); + } + } + } + + [Test] + public async Task EveryUnicodeWhiteSpaceCodePointIsBlank([ValueSource(nameof(WhiteSpaceCodePoints))] string hex) => + await AssertBlankRule(hex, blank: true); + + [Test] + public async Task CodePointsOutsideWhiteSpaceNameSomething([ValueSource(nameof(NonWhiteSpaceCodePoints))] string hex) => + await AssertBlankRule(hex, blank: false); + + // A nil payload names no document either; it is refused like an empty one, never handed to the store. + [Test] + public async Task APutWithANilPayloadIsRefusedAsUnreadable([Values] bool capable) + { + var rig = Build(); + var wire = new Wire(); + if (capable) await rig.Hello(wire, BothFrames); + wire.Sent.Clear(); + var message = rig.PutOf("m1", KeyA, "one"); + message.Document!.Payload = null!; + + await rig.PutHandler(message, wire.Peer); + + var refused = wire.Sent.Single(); + var error = capable ? AssertRefused(refused, "m1", "message_invalid").ToV0() : (CultNetErrorMessage)refused; + Assert.That(error.Error, Is.EqualTo(UnreadableVectorText())); + Assert.That(rig.TextOf(KeyA), Is.Null); + } + + // The fixed text is also what an undecodable frame is answered with, from the transport, not a decoder's wording. + [Test] + public async Task AnUnreadableSchemaFrameIsAnsweredWithTheFixedText() + { + var (_, wire) = await Capable(); + wire.Transport.AnswerUnreadableSchemaFrame(new byte[] { 0xC1 }); + Assert.That(AssertRefused(wire.Sent.Single(), null, "message_invalid").Error, Is.EqualTo(UnreadableVectorText())); + } + + [TestCase("", "k")] + [TestCase(" ", "k")] + [TestCase("note.v0", "")] + public async Task ADeleteWithAnEmptyOrBlankSchemaIdOrRecordKeyIsRefusedAsUnreadable(string schemaId, string recordKey) + { + var (rig, wire) = await Capable(); + var message = rig.DeleteOf("d1", new CultRecordKey(recordKey)); + message.SchemaId = schemaId; + wire.Sent.Clear(); + + await rig.DeleteHandler(message, wire.Peer); + + var error = AssertRefused(wire.Sent.Single(), "d1", "message_invalid"); + Assert.That(error.Details!.Field, Is.EqualTo("message")); + } + + [Test] + public async Task ARefusalAtTheCapIsRememberedSoAResendReplaysItAndADifferentContentResendIsRefused() + { + var (rig, wire) = await Capable(); + for (var index = 0; index < CultNetWriteReceiptSession.MaxRememberedWrites; index++) + await rig.Put(wire, $"w{index}", new CultRecordKey($"tests:receipt:{index}"), "x"); + wire.Sent.Clear(); + + await rig.Put(wire, "over", KeyA, "x"); + await rig.Put(wire, "over", KeyA, "x"); + await rig.Put(wire, "over", KeyB, "other"); + + AssertRefused(wire.Sent[0], "over", "limit_reached"); + AssertRefused(wire.Sent[1], "over", "limit_reached"); + var changed = AssertRefused(wire.Sent[2], "over", "message_invalid"); + Assert.That(changed.Details!.Field, Is.EqualTo("messageId")); + Assert.That(rig.TextOf(KeyA), Is.Null); + } + + private static byte[] HashOf(string text) => CultNetWriteContentHash.Compute("put", "s", text, new byte[] { 1 }); + + [Test] + public void AnAbandonedClaimFreesNoSlotSoARefusedIdNeverBecomesAdmissible() + { + var session = new CultNetWriteReceiptSession(); + for (var index = 0; index < CultNetWriteReceiptSession.MaxRememberedWrites; index++) + Assert.That(session.TryBegin($"w{index}", HashOf($"k{index}"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.New)); + Assert.That(session.TryBegin("over", HashOf("o"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.Full)); + + session.Abandoned("w0"); + + Assert.That(session.TryBegin("over", HashOf("o"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.Full)); + Assert.That(session.TryBegin("another", HashOf("a"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.Full)); + // The abandoned id itself is judged afresh, in its own slot. + Assert.That(session.TryBegin("w0", HashOf("k0"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.New)); + } + + [Test] + public void TheRefusalSetIsBoundedAndNeverAdmitsAnId() + { + var session = new CultNetWriteReceiptSession(); + for (var index = 0; index < CultNetWriteReceiptSession.MaxRememberedWrites; index++) + session.TryBegin($"w{index}", HashOf($"k{index}"), out _); + for (var index = 0; index < CultNetWriteReceiptSession.MaxRememberedWrites + 5; index++) + Assert.That(session.TryBegin($"o{index}", HashOf("o"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.Full)); + + session.Abandoned("w1"); + + Assert.That(session.TryBegin("o1030", HashOf("o"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.Full)); + } + + [Test] + public void TheRefusalSetStopsRememberingAtItsBound() + { + var session = new CultNetWriteReceiptSession(); + for (var index = 0; index < CultNetWriteReceiptSession.MaxRememberedWrites; index++) + session.TryBegin($"w{index}", HashOf($"k{index}"), out _); + for (var index = 0; index < CultNetWriteReceiptSession.MaxRememberedLimitRefusals; index++) + session.TryBegin($"o{index}", HashOf("o"), out _); + + // Past the bound a refusal is not remembered: its changed-content resend is simply refused at the limit again. + Assert.That(session.TryBegin("late", HashOf("a"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.Full)); + Assert.That(session.TryBegin("late", HashOf("b"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.Full)); + // Inside the bound it is remembered. + Assert.That(session.TryBegin("o0", HashOf("changed"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.DifferentContent)); + } + + [Test] + public void AnAbandonedIdMayBeResentWithOtherContentBecauseItWasNeverSent() + { + var session = new CultNetWriteReceiptSession(); + session.TryBegin("m1", HashOf("a"), out _); + session.Abandoned("m1"); + + Assert.That(session.TryBegin("m1", HashOf("b"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.New)); + Assert.That(session.TryBegin("m1", HashOf("b"), out _), Is.EqualTo(CultNetWriteReceiptSession.Begin.Unanswered)); + } + + // ---- Fixed text in v0 errors: an exception's own words never reach the wire ---- + + private static Func HandlerOf(Rig rig, string field) => + (Func)typeof(CultNetDatabaseServer) + .GetField(field, BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(rig.DatabaseServer)!; + + [Test] + public async Task ASnapshotFaultIsAnsweredWithFixedTextNotTheExceptionMessage() + { + var rig = Build(); + var wire = new Wire(); + + await HandlerOf(rig, "_snapshotHandlerV1")( + new CultNetSnapshotRequestV1Message { MessageId = "s1", Selection = null! }, wire.Peer); + + var error = (CultNetErrorMessage)wire.Sent.Single(); + Assert.That(error.Error, Is.EqualTo("the snapshot request could not be answered")); + } + + [Test] + public async Task AShardLogFaultIsAnsweredWithFixedTextNotTheExceptionMessage() + { + var rig = Build(); + var wire = new Wire(); + + await HandlerOf(rig, "_shardLogHandler")( + new CultNetShardLogRequestMessage { MessageId = "l1", ShardId = string.Empty }, wire.Peer); + + var error = (CultNetErrorMessage)wire.Sent.Single(); + Assert.That(error.Error, Is.EqualTo("the shard log request could not be answered")); + } + + private static CultNetErrorMessage DeniedWith(string recordKey, string reason) => new() + { + Error = $"write_not_authorized: {reason}", + Code = "write_not_authorized", + Details = new CultNetErrorDetails { Field = "recordKey", Value = recordKey } + }; + + // write-receipt.md, What is remembered: a refusal is remembered as its code (and the field it names), never the strings of + // the write or of the authority's reason; the replay is built from fixed text and the resend's own fields. + [Test] + public void ARefusalIsReplayedFromFixedTextAndTheResendsOwnFieldsNotFromRememberedStrings() + { + var session = new CultNetWriteReceiptSession(); + var sent = new List(); + var longKey = new string('k', 50_000); + CultNetReceiptedWrite Write() => new(session, sent.Add, "put", "m1", "schema.v1", longKey, [1]); + + var first = Write(); + Assert.That(first.Begin(), Is.True); + first.Refused(DeniedWith(longKey, new string('r', 50_000))); + Assert.That(Write().Begin(), Is.False); + + var again = (CultNetErrorV1Message)sent[1]; + Assert.That(again.MessageId, Is.EqualTo("m1")); + Assert.That(again.Code, Is.EqualTo("write_not_authorized")); + Assert.That(again.Error, Is.EqualTo("write_not_authorized")); + Assert.That(again.Details!.Field, Is.EqualTo("recordKey")); + Assert.That(again.Details.Value, Is.EqualTo(longKey)); + var firstAnswer = (CultNetErrorV1Message)sent[0]; + Assert.That(firstAnswer.Error, Is.EqualTo(again.Error), "the replay is the refusal again"); + Assert.That(firstAnswer.Details!.Value, Is.EqualTo(again.Details.Value)); + } + + [Test] + public void ThousandsOfRefusalsOf50kCharacterKeysAreRememberedInBoundedMemory() + { + var session = new CultNetWriteReceiptSession(); + var before = GC.GetTotalMemory(true); + for (var i = 0; i < CultNetWriteReceiptSession.MaxRememberedWrites; i++) + { + var key = new string('k', 50_000) + i; + var write = new CultNetReceiptedWrite(session, _ => { }, "put", $"m{i}", "schema.v1", key, [1]); + Assert.That(write.Begin(), Is.True); + write.Refused(DeniedWith(key, key)); + } + + // Held as strings, the 1024 keys and reasons alone would be over 200 MB. + var growth = GC.GetTotalMemory(true) - before; + GC.KeepAlive(session); + Assert.That(growth, Is.LessThan(8L * 1024 * 1024)); + } + + // A remembered refusal is replayed with the details its code carries: the schema id of an unowned write, no details + // at all for the routing refusal. + [Test] + public void AReplayedRefusalCarriesTheDetailsOfItsCodeAndNoOthers() + { + var session = new CultNetWriteReceiptSession(); + var sent = new List(); + CultNetReceiptedWrite Write(string id) => new(session, sent.Add, "put", id, "schema.v1", "note:1", [1]); + + var unowned = Write("u1"); + Assert.That(unowned.Begin(), Is.True); + unowned.Refused(CultNetErrorMessage.ForUnownedSchema(new CultNetUnownedSchemaException("schema.v1", new CultRecordKey("note:1")))); + Assert.That(Write("u1").Begin(), Is.False); + + var routed = Write("g1"); + Assert.That(routed.Begin(), Is.True); + routed.Refused(new CultNetErrorMessage + { + Error = CultNetDatabaseServer.RoutingRefusalText, + RoutingHint = new CultNetShardRoutingHint { Reason = "not_primary" } + }); + Assert.That(Write("g1").Begin(), Is.False); + + var unownedAgain = (CultNetErrorV1Message)sent[1]; + Assert.That(unownedAgain.Code, Is.EqualTo("unowned_schema")); + Assert.That(unownedAgain.Details!.Field, Is.EqualTo("schemaId")); + Assert.That(unownedAgain.Details.Value, Is.EqualTo("schema.v1")); + Assert.That(unownedAgain.Error, Is.EqualTo(((CultNetErrorV1Message)sent[0]).Error)); + var routedAgain = (CultNetErrorV1Message)sent[3]; + Assert.That(routedAgain.Details, Is.Null); + Assert.That(routedAgain.RoutingHint!.Reason, Is.EqualTo("not_primary")); + Assert.That(routedAgain.Error, Is.EqualTo(CultNetDatabaseServer.RoutingRefusalText)); + } + + // A write that carries no record key or schema id has none to echo: the detail value is null, not an empty string. + [Test] + public void AReplayedRefusalOfAWriteWithoutTheNamedFieldCarriesANullValue() + { + var session = new CultNetWriteReceiptSession(); + var sent = new List(); + CultNetReceiptedWrite Write() => new(session, sent.Add, "delete", "m1", null, null, null); + var first = Write(); + Assert.That(first.Begin(), Is.True); + first.Refused(DeniedWith("ignored", "reason")); + Assert.That(Write().Begin(), Is.False); + + foreach (var message in sent) + { + var error = (CultNetErrorV1Message)message; + Assert.That(error.Details!.Field, Is.EqualTo("recordKey")); + Assert.That(error.Details.Value, Is.Null); + } + + var unowned = new CultNetReceiptedWrite(session, sent.Add, "delete", "m2", null, null, null); + Assert.That(unowned.Begin(), Is.True); + unowned.Refused(CultNetErrorMessage.ForUnownedSchema(new CultNetUnownedSchemaException("x", new CultRecordKey("k")))); + Assert.That(((CultNetErrorV1Message)sent[^1]).Details!.Field, Is.EqualTo("schemaId")); + Assert.That(((CultNetErrorV1Message)sent[^1]).Details!.Value, Is.Null); + } + } +} diff --git a/tests/GameCult.Networking.Tests/NetworkingTests.cs b/tests/GameCult.Networking.Tests/NetworkingTests.cs index 2a75b5c2..606d5625 100644 --- a/tests/GameCult.Networking.Tests/NetworkingTests.cs +++ b/tests/GameCult.Networking.Tests/NetworkingTests.cs @@ -5189,7 +5189,9 @@ namespace GameCult.Networking.Tests [Test] public async Task CultNetSchemaWriteForwarder_Uses_SchemaClientPort() { - var fake = new CapturingSchemaClient(_ => null); + var fake = new CapturingSchemaClient(message => message is CultNetDocumentDeleteMessage delete + ? new CultNetWriteAdmittedMessage { MessageId = delete.MessageId, Operation = "delete", SchemaId = delete.SchemaId, RecordKey = delete.RecordKey } + : null); var forwarder = new CultNetSchemaWriteForwarder(new CultNetSchemaWriteForwarderOptions { CreateClient = () => fake @@ -5203,11 +5205,16 @@ namespace GameCult.Networking.Tests await forwarder.ForwardDeleteAsync(shard, new CultNetDocumentDeleteMessage { + MessageId = "fwd-del", SchemaId = "note.v0", RecordKey = "note:1" }); - var sent = (CultNetDocumentDeleteMessage)fake.SentMessages.Single(); + var hello = (CultNetHelloMessage)fake.SentMessages[0]; + Assert.That(hello.SupportedMessageVersions, Is.EquivalentTo(new[] { CultNetSchemaVersions.WriteAdmitted, CultNetSchemaVersions.ErrorV1 }), + "the hello opts the forwarding connection in before the write"); + var sent = (CultNetDocumentDeleteMessage)fake.SentMessages[1]; + Assert.That(sent.MessageId, Is.EqualTo("fwd-del"), "the write goes under its original id"); Assert.That(fake.ConnectedHost, Is.EqualTo("primary.example.test")); Assert.That(sent.ShardId, Is.EqualTo("notes")); Assert.That(sent.ShardEpoch, Is.EqualTo(3)); @@ -5241,7 +5248,7 @@ namespace GameCult.Networking.Tests } [Test] - public async Task CultNetSchemaWriteForwarder_DoesNotCompleteOnTheSendReturning() + public void CultNetSchemaWriteForwarder_SilenceIsUnconfirmedNotSuccess() { var fake = new CapturingSchemaClient(_ => null); var forwarder = new CultNetSchemaWriteForwarder(new CultNetSchemaWriteForwarderOptions @@ -5254,11 +5261,51 @@ namespace GameCult.Networking.Tests primaryEndpoints: ["cultnet://primary.example.test:4075"]); var started = DateTime.UtcNow; - await forwarder.ForwardDeleteAsync(shard, new CultNetDocumentDeleteMessage { SchemaId = "note.v0", RecordKey = "note:1" }); + var unconfirmed = Assert.ThrowsAsync(() => + forwarder.ForwardDeleteAsync(shard, new CultNetDocumentDeleteMessage { MessageId = "fwd-del", SchemaId = "note.v0", RecordKey = "note:1" })); + Assert.That(unconfirmed!.MessageId, Is.EqualTo("fwd-del")); Assert.That(DateTime.UtcNow - started, Is.GreaterThanOrEqualTo(TimeSpan.FromMilliseconds(380))); } + [Test] + public void CultNetSchemaWriteForwarder_AnswersNamingAnotherWriteSettleNothing() + { + var fake = new CapturingSchemaClient(_ => null); + var forwarder = new CultNetSchemaWriteForwarder(new CultNetSchemaWriteForwarderOptions + { + CreateClient = () => fake, + ResultWindow = TimeSpan.FromMilliseconds(300) + }); + var shard = new CultNetShardDescriptor( + "notes", "primary", 3, isPrimary: false, + primaryEndpoints: ["cultnet://primary.example.test:4075"]); + fake.OnSend = () => + { + fake.Deliver(new CultNetWriteAdmittedMessage { MessageId = "someone-else", Operation = "delete", SchemaId = "note.v0", RecordKey = "note:1" }); + fake.Deliver(new CultNetErrorV1Message { Error = "refused", Code = "write_not_authorized", MessageId = "someone-else" }); + }; + + Assert.ThrowsAsync(() => + forwarder.ForwardDeleteAsync(shard, new CultNetDocumentDeleteMessage { MessageId = "fwd-del", SchemaId = "note.v0", RecordKey = "note:1" })); + } + + [Test] + public void CultNetSchemaWriteForwarder_RejectsWithTheErrorV1NamingItsWrite() + { + var fake = new CapturingSchemaClient(_ => null); + var forwarder = new CultNetSchemaWriteForwarder(new CultNetSchemaWriteForwarderOptions { CreateClient = () => fake }); + var shard = new CultNetShardDescriptor( + "notes", "primary", 3, isPrimary: false, + primaryEndpoints: ["cultnet://primary.example.test:4075"]); + fake.OnSend = () => fake.Deliver(new CultNetErrorV1Message { Error = "refused", Code = "write_not_authorized", MessageId = "fwd-del" }); + + var refused = Assert.ThrowsAsync(() => + forwarder.ForwardDeleteAsync(shard, new CultNetDocumentDeleteMessage { MessageId = "fwd-del", SchemaId = "note.v0", RecordKey = "note:1" })); + + Assert.That(refused!.Code, Is.EqualTo("write_not_authorized")); + } + [Test] public void CultMeshVerseCatalog_Finds_CompatibleTransferTargets() {