diff --git a/CultLib.sln b/CultLib.sln index 0319071d..65f940c8 100644 --- a/CultLib.sln +++ b/CultLib.sln @@ -33,6 +33,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Geometry.Planetary EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Mesh.Tests", "tests\GameCult.Mesh.Tests\GameCult.Mesh.Tests.csproj", "{F8A5060A-FB0B-4B8B-AE06-5147BB4CA127}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Mesh.Quic", "src\GameCult.Mesh.Quic\GameCult.Mesh.Quic.csproj", "{B67042B8-1135-4E54-B1EB-D45342C720D7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Mesh.Quic.Tests", "tests\GameCult.Mesh.Quic.Tests\GameCult.Mesh.Quic.Tests.csproj", "{21F26329-2119-4037-93CC-DD1801A1AB78}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -199,6 +203,30 @@ Global {F8A5060A-FB0B-4B8B-AE06-5147BB4CA127}.Release|x64.Build.0 = Release|Any CPU {F8A5060A-FB0B-4B8B-AE06-5147BB4CA127}.Release|x86.ActiveCfg = Release|Any CPU {F8A5060A-FB0B-4B8B-AE06-5147BB4CA127}.Release|x86.Build.0 = Release|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Debug|x64.ActiveCfg = Debug|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Debug|x64.Build.0 = Debug|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Debug|x86.ActiveCfg = Debug|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Debug|x86.Build.0 = Debug|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Release|Any CPU.Build.0 = Release|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Release|x64.ActiveCfg = Release|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Release|x64.Build.0 = Release|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Release|x86.ActiveCfg = Release|Any CPU + {B67042B8-1135-4E54-B1EB-D45342C720D7}.Release|x86.Build.0 = Release|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Debug|Any CPU.Build.0 = Debug|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Debug|x64.ActiveCfg = Debug|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Debug|x64.Build.0 = Debug|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Debug|x86.ActiveCfg = Debug|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Debug|x86.Build.0 = Debug|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Release|Any CPU.ActiveCfg = Release|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Release|Any CPU.Build.0 = Release|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Release|x64.ActiveCfg = Release|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Release|x64.Build.0 = Release|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Release|x86.ActiveCfg = Release|Any CPU + {21F26329-2119-4037-93CC-DD1801A1AB78}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -217,5 +245,7 @@ Global {C95A9A21-34FA-4D82-BE5B-88FBDA836D31} = {39D316AB-ABB5-49A2-8E83-CAF4C75B48F4} {CE447820-B407-48DE-8957-F373E032C4AE} = {39D316AB-ABB5-49A2-8E83-CAF4C75B48F4} {F8A5060A-FB0B-4B8B-AE06-5147BB4CA127} = {39D316AB-ABB5-49A2-8E83-CAF4C75B48F4} + {B67042B8-1135-4E54-B1EB-D45342C720D7} = {E733CBFF-42AE-4B6A-B5B9-0071ECFB45F1} + {21F26329-2119-4037-93CC-DD1801A1AB78} = {39D316AB-ABB5-49A2-8E83-CAF4C75B48F4} EndGlobalSection EndGlobal diff --git a/Directory.Build.props b/Directory.Build.props index e38b66bc..a9390c76 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -14,7 +14,7 @@ MIT © Meta Vens and contributors true - 1.0.3 + 1.0.33 $(MSBuildThisFileDirectory)..\CultMath\.tools\local-feed $(RestoreAdditionalProjectSources);$(CultMathCandidateFeed) diff --git a/docs/cultmesh-provider-session.md b/docs/cultmesh-provider-session.md new file mode 100644 index 00000000..3e45c799 --- /dev/null +++ b/docs/cultmesh-provider-session.md @@ -0,0 +1,61 @@ +# CultMesh Provider Session + +## Authority map + +- Owner: the provider-session broker owns registration, active lease fencing, + accepted publication membership, command retention, receipt acceptance, and + withdrawal. +- Inputs: a physical CultNet session, an explicit registration-authorization + decision, correlated typed operations, the broker clock, provider commands, + and persistence callbacks. The current RUDP adapter does not itself provide + an authenticated claim. +- Outputs: leases, application acceptances, accepted raw documents, pushed + typed commands, persisted receipts, and deterministic removals. +- Derived state: socket sessions, retry schedules, connection health, and + provider projections are observations. They do not authorize publications. +- Forbidden writers: RUDP packet acknowledgements, source addresses, direct raw + document callbacks, renderer-owned catalogs, and arrival-time freshness maps + cannot create accepted provider truth. +- Shared paths: initial connect and reconnect use `provider.register`; initial, + replayed, and live documents use `provider.publication.put`; explicit + withdrawal and lease expiry remove the broker-owned publication set; command + retry ends only when `provider.receipt.put` is accepted. +- Cut line: a receiver must stop accepting unleased provider raw puts before it + claims this protocol as its ingress authority. + +## Wire contract + +Provider lifecycle operations use the reliable ordered CultNet schema channel +and the existing `cultnet.operation_request.v0` / `cultnet.operation_response.v0` +envelopes with service id `gamecult.mesh.provider_session`. Inner payloads are +camel-case MessagePack maps encoded as `messagepack-base64`. + +The v1 operations are: + +| Operation | Request payload | Successful payload | +| --- | --- | --- | +| `provider.register` | `gamecult.mesh.provider_registration.v1` | `gamecult.mesh.provider_lease.v1` | +| `provider.renew` | `gamecult.mesh.provider_lease_renewal.v1` | `gamecult.mesh.provider_lease.v1` | +| `provider.publication.put` | `gamecult.mesh.provider_publication_put.v1` | `gamecult.mesh.provider_mutation_acceptance.v1` | +| `provider.publication.delete` | `gamecult.mesh.provider_publication_delete.v1` | `gamecult.mesh.provider_mutation_acceptance.v1` | +| `provider.receipt.put` | `gamecult.mesh.provider_receipt_put.v1` | `gamecult.mesh.provider_mutation_acceptance.v1` | +| `provider.withdraw` | `gamecult.mesh.provider_withdrawal.v1` | `gamecult.mesh.provider_mutation_acceptance.v1` | + +Broker-to-provider commands are raw typed documents using +`gamecult.mesh.provider_command.v1`. Asset bodies do not travel inside these +operation payloads. + +Responses use `ok`, `conflict`, `expired`, `denied`, or `invalid`. A transport +ACK is never an application acceptance. Renewal issues a new lease id and +immediately fences the previous id. The broker derives the set removed by full +withdrawal; a provider cannot use a supplied list to hide owned publications. + +Public deployment additionally requires a CultNet authentication claim that +authorizes the provider identity. Until that claim is wired and checked, the +TypeScript RUDP adapter is a private-development transport. + +`CultMeshProviderSessionBroker` is an in-memory reference broker and socket +proof. Its command and receipt retention does not survive process restart. +Production receivers must persist that control-plane state atomically with +accepted publication ownership; Odin must not substitute these volatile maps +for its durable broker authority. diff --git a/docs/nuget-packaging.md b/docs/nuget-packaging.md index 88eb4a2d..a269090a 100644 --- a/docs/nuget-packaging.md +++ b/docs/nuget-packaging.md @@ -15,3 +15,9 @@ a clean .NET consumer using only `PackageReference Include="GameCult.Mesh"`. The Unity distribution remains `org.gamecult.cultlib`, built by `scripts/build-unity-package.ps1`, because Unity consumes the managed assembly closure through UPM rather than NuGet restore. + +Install the Unity package from the immutable release tag: + +```text +https://github.com/GameCult/CultLib.git?path=/unity/org.gamecult.cultlib#cultlib-unity-v1.0.8 +``` diff --git a/native/GameCult.Mesh.Quic.Native/CMakeLists.txt b/native/GameCult.Mesh.Quic.Native/CMakeLists.txt new file mode 100644 index 00000000..2850951d --- /dev/null +++ b/native/GameCult.Mesh.Quic.Native/CMakeLists.txt @@ -0,0 +1,20 @@ +cmake_minimum_required(VERSION 3.24) +project(gamecult_mesh_quic_native LANGUAGES CXX) + +if(NOT WIN32) + message(FATAL_ERROR "The current CultMesh native QUIC connector supports Windows desktop only") +endif() +if(NOT DEFINED MSQUIC_ROOT) + message(FATAL_ERROR "MSQUIC_ROOT must point at the extracted Microsoft.Native.Quic.MsQuic.Schannel package build/native directory") +endif() + +add_library(gamecult_mesh_quic_native SHARED cultmesh_quic_native.cpp) +target_compile_features(gamecult_mesh_quic_native PRIVATE cxx_std_20) +target_compile_definitions(gamecult_mesh_quic_native PRIVATE GAMECULT_MESH_QUIC_NATIVE_EXPORTS WIN32_LEAN_AND_MEAN NOMINMAX) +target_include_directories(gamecult_mesh_quic_native PRIVATE "${MSQUIC_ROOT}/include") +target_link_directories(gamecult_mesh_quic_native PRIVATE "${MSQUIC_ROOT}/lib/x64") +target_link_libraries(gamecult_mesh_quic_native PRIVATE msquic crypt32 bcrypt) + +set_target_properties(gamecult_mesh_quic_native PROPERTIES + OUTPUT_NAME "gamecult_mesh_quic_native" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") diff --git a/native/GameCult.Mesh.Quic.Native/README.md b/native/GameCult.Mesh.Quic.Native/README.md new file mode 100644 index 00000000..875ebb3b --- /dev/null +++ b/native/GameCult.Mesh.Quic.Native/README.md @@ -0,0 +1,10 @@ +# GameCult.Mesh.Quic.Native + +This Windows desktop bridge keeps MsQuic's callback-heavy C API below the +managed runtime boundary. It accepts a discovery-authorized SHA-256 certificate +pin, negotiates `cultmesh-state-v1`, and emits complete CultMesh realtime frame +payloads. It owns transport only; frame meaning remains in `GameCult.Mesh`. + +The build consumes Microsoft's pinned +`Microsoft.Native.Quic.MsQuic.Schannel` package. It does not contain +Aetheria-specific code. diff --git a/native/GameCult.Mesh.Quic.Native/cultmesh_quic_native.cpp b/native/GameCult.Mesh.Quic.Native/cultmesh_quic_native.cpp new file mode 100644 index 00000000..bbb6e193 --- /dev/null +++ b/native/GameCult.Mesh.Quic.Native/cultmesh_quic_native.cpp @@ -0,0 +1,440 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(GAMECULT_MESH_QUIC_NATIVE_EXPORTS) +#define CULTMESH_API extern "C" __declspec(dllexport) +#else +#define CULTMESH_API extern "C" __declspec(dllimport) +#endif + +namespace { + +constexpr uint32_t kApiVersion = 2; +constexpr uint64_t kConnectionCloseCode = 0x43554c54; +constexpr uint64_t kStreamAbortCode = 0x53544154; +constexpr uint8_t kReliableStream = 1; +constexpr uint8_t kLatestOnlyStream = 2; +constexpr uint32_t kMaximumEncodedFrameBytes = (64u * 1024u * 1024u) + 37u + (3u * 65535u); +constexpr char kAlpn[] = "cultmesh-state-v1"; + +enum class ClientState : int32_t { + Connecting = 0, + Connected = 1, + Failed = 2, + Closed = 3, +}; + +struct Client; + +struct StreamContext { + explicit StreamContext(Client* client) : owner(client) {} + Client* owner; + std::vector buffered; + uint8_t kind = 0; + bool has_kind = false; +}; + +struct Client { + const QUIC_API_TABLE* api = nullptr; + HQUIC registration = nullptr; + HQUIC configuration = nullptr; + HQUIC connection = nullptr; + std::array certificate_pin{}; + std::atomic state{ClientState::Connecting}; + std::atomic closing{false}; + std::mutex gate; + std::deque> received; + std::string error; + std::string trace; +}; + +void AppendTrace(Client* client, const std::string& event) { + if (client == nullptr || client->state.load() == ClientState::Connected) return; + std::lock_guard lock(client->gate); + if (!client->trace.empty()) client->trace += ","; + client->trace += event; +} + +std::string TraceSnapshot(Client* client) { + if (client == nullptr) return "none"; + std::lock_guard lock(client->gate); + return client->trace.empty() ? "none" : client->trace; +} + +void SetFailure(Client* client, const std::string& message) { + if (client == nullptr || client->closing.load()) return; + { + std::lock_guard lock(client->gate); + if (client->error.empty()) client->error = message; + } + client->state.store(ClientState::Failed); +} + +bool ParseHexNibble(char value, uint8_t& nibble) { + if (value >= '0' && value <= '9') nibble = static_cast(value - '0'); + else if (value >= 'a' && value <= 'f') nibble = static_cast(value - 'a' + 10); + else if (value >= 'A' && value <= 'F') nibble = static_cast(value - 'A' + 10); + else return false; + return true; +} + +bool ParsePin(const char* value, std::array& pin) { + if (value == nullptr || std::strlen(value) != 64) return false; + for (size_t index = 0; index < pin.size(); ++index) { + uint8_t high = 0; + uint8_t low = 0; + if (!ParseHexNibble(value[index * 2], high) || !ParseHexNibble(value[(index * 2) + 1], low)) + return false; + pin[index] = static_cast((high << 4) | low); + } + return true; +} + +uint32_t ReadUInt32LittleEndian(const uint8_t* value) { + return static_cast(value[0]) | + (static_cast(value[1]) << 8) | + (static_cast(value[2]) << 16) | + (static_cast(value[3]) << 24); +} + +void FailStream(StreamContext* stream, const char* message) { + SetFailure(stream->owner, message); + if (stream->owner != nullptr && stream->owner->api != nullptr && stream->owner->connection != nullptr) + stream->owner->api->ConnectionShutdown( + stream->owner->connection, + QUIC_CONNECTION_SHUTDOWN_FLAG_SILENT, + kStreamAbortCode); +} + +bool ConsumeFrames(StreamContext* stream) { + auto& bytes = stream->buffered; + if (!stream->has_kind) { + if (bytes.empty()) return true; + stream->kind = bytes.front(); + bytes.erase(bytes.begin()); + stream->has_kind = true; + if (stream->kind != kReliableStream && stream->kind != kLatestOnlyStream) { + FailStream(stream, "CultMesh QUIC stream kind is invalid."); + return false; + } + } + + while (bytes.size() >= sizeof(uint32_t)) { + const uint32_t length = ReadUInt32LittleEndian(bytes.data()); + if (length == 0 || length > kMaximumEncodedFrameBytes) { + FailStream(stream, "CultMesh QUIC frame length is invalid."); + return false; + } + const size_t framed_length = sizeof(uint32_t) + static_cast(length); + if (bytes.size() < framed_length) return true; + std::vector frame(length); + std::memcpy(frame.data(), bytes.data() + sizeof(uint32_t), length); + { + std::lock_guard lock(stream->owner->gate); + stream->owner->received.emplace_back(std::move(frame)); + } + bytes.erase(bytes.begin(), bytes.begin() + static_cast(framed_length)); + if (stream->kind == kLatestOnlyStream && !bytes.empty()) { + FailStream(stream, "CultMesh latest-only QUIC stream carried multiple frames."); + return false; + } + } + return true; +} + +QUIC_STATUS QUIC_API StreamCallback(HQUIC stream_handle, void* context, QUIC_STREAM_EVENT* event) { + auto* stream = static_cast(context); + switch (event->Type) { + case QUIC_STREAM_EVENT_RECEIVE: + for (uint32_t index = 0; index < event->RECEIVE.BufferCount; ++index) { + const auto& buffer = event->RECEIVE.Buffers[index]; + stream->buffered.insert(stream->buffered.end(), buffer.Buffer, buffer.Buffer + buffer.Length); + } + ConsumeFrames(stream); + break; + case QUIC_STREAM_EVENT_PEER_SEND_SHUTDOWN: + if (!stream->buffered.empty()) + FailStream(stream, "CultMesh QUIC stream ended with a truncated frame."); + break; + case QUIC_STREAM_EVENT_SHUTDOWN_COMPLETE: + if (!event->SHUTDOWN_COMPLETE.AppCloseInProgress) + stream->owner->api->StreamClose(stream_handle); + delete stream; + break; + default: + break; + } + return QUIC_STATUS_SUCCESS; +} + +bool CertificateMatchesPin(Client* client, QUIC_CERTIFICATE* certificate) { + if (certificate == nullptr) return false; + const auto* encoded = reinterpret_cast(certificate); + if (encoded->Buffer == nullptr || encoded->Length == 0) return false; + BYTE digest[32]{}; + DWORD digest_length = sizeof(digest); + if (!CryptHashCertificate2( + BCRYPT_SHA256_ALGORITHM, + 0, + nullptr, + encoded->Buffer, + encoded->Length, + digest, + &digest_length) || digest_length != sizeof(digest)) + return false; + return std::memcmp(digest, client->certificate_pin.data(), sizeof(digest)) == 0; +} + +std::string Hex(uint64_t value) { + std::ostringstream text; + text << "0x" << std::hex << std::uppercase << value; + return text.str(); +} + +std::string LoadedMsQuicPath() { + const auto module = GetModuleHandleW(L"msquic.dll"); + if (module == nullptr) return "unresolved"; + std::array path{}; + const auto length = GetModuleFileNameW(module, path.data(), static_cast(path.size())); + if (length == 0 || length >= path.size()) return "unresolved"; + const auto required = WideCharToMultiByte( + CP_UTF8, 0, path.data(), static_cast(length), nullptr, 0, nullptr, nullptr); + if (required <= 0) return "unresolved"; + std::string utf8(static_cast(required), '\0'); + WideCharToMultiByte( + CP_UTF8, 0, path.data(), static_cast(length), utf8.data(), required, nullptr, nullptr); + return utf8; +} + +QUIC_STATUS QUIC_API ConnectionCallback(HQUIC connection, void* context, QUIC_CONNECTION_EVENT* event) { + auto* client = static_cast(context); + AppendTrace(client, "event=" + std::to_string(static_cast(event->Type))); + switch (event->Type) { + case QUIC_CONNECTION_EVENT_CONNECTED: + client->state.store(ClientState::Connected); + break; + case QUIC_CONNECTION_EVENT_PEER_STREAM_STARTED: { + auto* stream = new (std::nothrow) StreamContext(client); + if (stream == nullptr) return QUIC_STATUS_OUT_OF_MEMORY; + client->api->SetCallbackHandler( + event->PEER_STREAM_STARTED.Stream, + reinterpret_cast(StreamCallback), + stream); + break; + } + case QUIC_CONNECTION_EVENT_PEER_CERTIFICATE_RECEIVED: + { + AppendTrace( + client, + "certificate-status=" + + Hex(static_cast(event->PEER_CERTIFICATE_RECEIVED.DeferredStatus))); + const auto matches = CertificateMatchesPin( + client, + event->PEER_CERTIFICATE_RECEIVED.Certificate); + if (!matches) { + SetFailure(client, "CultMesh QUIC provider certificate does not match the advertised SHA-256 pin."); + } + const auto completion = client->api->ConnectionCertificateValidationComplete( + connection, + matches ? TRUE : FALSE, + matches ? QUIC_TLS_ALERT_CODE_SUCCESS : QUIC_TLS_ALERT_CODE_BAD_CERTIFICATE); + if (QUIC_FAILED(completion)) { + SetFailure( + client, + "CultMesh QUIC certificate validation completion failed (status=" + + Hex(static_cast(completion)) + ")."); + return completion; + } + return QUIC_STATUS_PENDING; + } + case QUIC_CONNECTION_EVENT_SHUTDOWN_INITIATED_BY_TRANSPORT: + if (!client->closing.load()) { + SetFailure( + client, + "CultMesh QUIC connection was shut down by the transport " + "(status=" + Hex(static_cast(event->SHUTDOWN_INITIATED_BY_TRANSPORT.Status)) + + ", error=" + Hex(event->SHUTDOWN_INITIATED_BY_TRANSPORT.ErrorCode) + + ", msquic=" + LoadedMsQuicPath() + + ", events=" + TraceSnapshot(client) + ")."); + } + break; + case QUIC_CONNECTION_EVENT_SHUTDOWN_INITIATED_BY_PEER: + if (!client->closing.load()) + SetFailure(client, "CultMesh QUIC connection was shut down by the provider."); + break; + case QUIC_CONNECTION_EVENT_SHUTDOWN_COMPLETE: + if (client->closing.load()) client->state.store(ClientState::Closed); + break; + default: + break; + } + return QUIC_STATUS_SUCCESS; +} + +void CloseHandles(Client* client) { + if (client->connection != nullptr) { + client->api->ConnectionClose(client->connection); + client->connection = nullptr; + } + if (client->configuration != nullptr) { + client->api->ConfigurationClose(client->configuration); + client->configuration = nullptr; + } + if (client->registration != nullptr) { + client->api->RegistrationClose(client->registration); + client->registration = nullptr; + } + if (client->api != nullptr) { + MsQuicClose(client->api); + client->api = nullptr; + } +} + +} // namespace + +CULTMESH_API int32_t cultmesh_quic_open( + const char* host, + uint16_t port, + const char* certificate_sha256, + Client** result) { + if (host == nullptr || *host == '\0' || port == 0 || result == nullptr) return -1; + *result = nullptr; + auto client = std::make_unique(); + if (!ParsePin(certificate_sha256, client->certificate_pin)) return -2; + + QUIC_STATUS status = MsQuicOpenVersion( + kApiVersion, + reinterpret_cast(&client->api)); + if (QUIC_FAILED(status)) return status; + + const QUIC_REGISTRATION_CONFIG registration_config = { + "GameCult.Mesh.Quic.Native", + QUIC_EXECUTION_PROFILE_TYPE_REAL_TIME + }; + status = client->api->RegistrationOpen(®istration_config, &client->registration); + if (QUIC_FAILED(status)) { + CloseHandles(client.get()); + return status; + } + + QUIC_SETTINGS settings{}; + settings.IdleTimeoutMs = 30000; + settings.IsSet.IdleTimeoutMs = TRUE; + settings.KeepAliveIntervalMs = 5000; + settings.IsSet.KeepAliveIntervalMs = TRUE; + settings.PeerUnidiStreamCount = 1024; + settings.IsSet.PeerUnidiStreamCount = TRUE; + const QUIC_BUFFER alpn = { + static_cast(sizeof(kAlpn) - 1), + reinterpret_cast(const_cast(kAlpn)) + }; + status = client->api->ConfigurationOpen( + client->registration, + &alpn, + 1, + &settings, + sizeof(settings), + nullptr, + &client->configuration); + if (QUIC_FAILED(status)) { + CloseHandles(client.get()); + return status; + } + + QUIC_CREDENTIAL_CONFIG credentials{}; + credentials.Type = QUIC_CREDENTIAL_TYPE_NONE; + credentials.Flags = static_cast( + QUIC_CREDENTIAL_FLAG_CLIENT | + QUIC_CREDENTIAL_FLAG_INDICATE_CERTIFICATE_RECEIVED | + QUIC_CREDENTIAL_FLAG_DEFER_CERTIFICATE_VALIDATION | + QUIC_CREDENTIAL_FLAG_USE_PORTABLE_CERTIFICATES); + status = client->api->ConfigurationLoadCredential(client->configuration, &credentials); + if (QUIC_FAILED(status)) { + CloseHandles(client.get()); + return status; + } + + status = client->api->ConnectionOpen( + client->registration, + ConnectionCallback, + client.get(), + &client->connection); + if (QUIC_FAILED(status)) { + CloseHandles(client.get()); + return status; + } + status = client->api->ConnectionStart( + client->connection, + client->configuration, + QUIC_ADDRESS_FAMILY_UNSPEC, + host, + port); + if (QUIC_FAILED(status)) { + CloseHandles(client.get()); + return status; + } + + *result = client.release(); + return 0; +} + +CULTMESH_API int32_t cultmesh_quic_state(Client* client) { + if (client == nullptr) return static_cast(ClientState::Failed); + return static_cast(client->state.load()); +} + +CULTMESH_API int32_t cultmesh_quic_poll( + Client* client, + uint8_t* destination, + int32_t destination_length, + int32_t* required_length) { + if (client == nullptr || required_length == nullptr || destination_length < 0) return -1; + std::lock_guard lock(client->gate); + if (client->received.empty()) { + *required_length = 0; + return client->state.load() == ClientState::Failed ? -2 : 0; + } + const auto& frame = client->received.front(); + if (frame.size() > static_cast(INT32_MAX)) return -3; + *required_length = static_cast(frame.size()); + if (destination == nullptr || destination_length < *required_length) return 2; + std::memcpy(destination, frame.data(), frame.size()); + client->received.pop_front(); + return 1; +} + +CULTMESH_API int32_t cultmesh_quic_error( + Client* client, + char* destination, + int32_t destination_length) { + if (client == nullptr || destination == nullptr || destination_length <= 0) return -1; + std::lock_guard lock(client->gate); + const size_t count = (std::min)(client->error.size(), static_cast(destination_length - 1)); + std::memcpy(destination, client->error.data(), count); + destination[count] = '\0'; + return static_cast(count); +} + +CULTMESH_API void cultmesh_quic_close(Client* client) { + if (client == nullptr) return; + client->closing.store(true); + if (client->connection != nullptr && client->api != nullptr) + client->api->ConnectionShutdown(client->connection, QUIC_CONNECTION_SHUTDOWN_FLAG_SILENT, kConnectionCloseCode); + CloseHandles(client); + client->state.store(ClientState::Closed); + delete client; +} diff --git a/packages/cultnet-ts/package-lock.json b/package-lock.json similarity index 79% rename from packages/cultnet-ts/package-lock.json rename to package-lock.json index 349dfe87..bc42f617 100644 --- a/packages/cultnet-ts/package-lock.json +++ b/package-lock.json @@ -1,24 +1,15 @@ { - "name": "cultnet-ts", - "version": "0.1.0", + "name": "cultlib", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "cultnet-ts", - "version": "0.1.0", - "license": "MIT", - "dependencies": { - "@msgpack/msgpack": "^3.1.3", - "ajv": "^8.17.1", - "cultcache-ts": "github:GameCult/cultcache-ts" - }, - "devDependencies": { - "@types/node": "^24.0.0", - "json-schema-to-typescript": "^15.0.4", - "typescript": "^5.9.0", - "zod": "^3.25.76" - } + "name": "cultlib", + "workspaces": [ + "packages/cultcache-ts", + "packages/cultnet-ts", + "packages/cultmesh-ts" + ] }, "node_modules/@apidevtools/json-schema-ref-parser": { "version": "11.9.3", @@ -69,13 +60,13 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "24.12.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz", - "integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==", + "version": "24.13.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz", + "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~7.16.0" + "undici-types": "~7.18.0" } }, "node_modules/ajv": { @@ -102,13 +93,16 @@ "license": "Python-2.0" }, "node_modules/cultcache-ts": { - "version": "0.1.0", - "resolved": "git+ssh://git@github.com/GameCult/cultcache-ts.git#6c2e1e3691146f99c44c098371cc8c787b4a8d0c", - "license": "MIT", - "dependencies": { - "@msgpack/msgpack": "^3.1.3", - "zod": "^3.25.76" - } + "resolved": "packages/cultcache-ts", + "link": true + }, + "node_modules/cultmesh-ts": { + "resolved": "packages/cultmesh-ts", + "link": true + }, + "node_modules/cultnet-ts": { + "resolved": "packages/cultnet-ts", + "link": true }, "node_modules/fast-deep-equal": { "version": "3.1.3", @@ -117,9 +111,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz", - "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==", + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.3.tgz", + "integrity": "sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==", "funding": [ { "type": "github", @@ -174,10 +168,20 @@ } }, "node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", + "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "license": "MIT", "dependencies": { "argparse": "^2.0.1" @@ -234,9 +238,9 @@ } }, "node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", "dev": true, "license": "MIT", "engines": { @@ -247,9 +251,9 @@ } }, "node_modules/prettier": { - "version": "3.8.3", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.3.tgz", - "integrity": "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==", + "version": "3.9.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.5.tgz", + "integrity": "sha512-/FVl766LpUfB5vXgCYOYa0MeV/441Ia99AeICQIQFTY/Nw0roZwULcXpku5i1/m5kt/baz+s4Zogspd839HSMg==", "dev": true, "license": "MIT", "bin": { @@ -272,9 +276,9 @@ } }, "node_modules/tinyglobby": { - "version": "0.2.16", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", - "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", "dev": true, "license": "MIT", "dependencies": { @@ -303,9 +307,9 @@ } }, "node_modules/undici-types": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", - "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", "dev": true, "license": "MIT" }, @@ -317,6 +321,56 @@ "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "packages/cultcache-ts": { + "version": "0.13.5", + "license": "MIT", + "dependencies": { + "@msgpack/msgpack": "^3.1.3", + "zod": "^3.25.76" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "typescript": "^5.9.0" + }, + "engines": { + "node": ">=18" + } + }, + "packages/cultmesh-ts": { + "version": "0.1.1", + "license": "MIT", + "dependencies": { + "@msgpack/msgpack": "^3.1.2", + "cultcache-ts": "^0.13.5", + "cultnet-ts": "^0.1.1" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "typescript": "^5.9.0", + "zod": "^3.25.76" + }, + "engines": { + "node": ">=18" + } + }, + "packages/cultnet-ts": { + "version": "0.1.1", + "license": "MIT", + "dependencies": { + "@msgpack/msgpack": "^3.1.3", + "ajv": "^8.17.1", + "cultcache-ts": "^0.13.5" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "json-schema-to-typescript": "^15.0.4", + "typescript": "^5.9.0", + "zod": "^3.25.76" + }, + "engines": { + "node": ">=18" + } } } } diff --git a/package.json b/package.json index a6803b6b..09a80f89 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ "packages/gamecult-geometry-ts" ], "scripts": { - "build:ts": "npm --workspaces run build", - "test:ts": "npm --workspaces run test" + "build:ts": "node scripts/run-typescript-workspaces.mjs build", + "test:ts": "node scripts/run-typescript-workspaces.mjs test", + "test:pack:ts": "node scripts/test-typescript-package-closure.mjs" } } diff --git a/packages/cultcache-rs/Cargo.toml b/packages/cultcache-rs/Cargo.toml index b11a909e..ef06727d 100644 --- a/packages/cultcache-rs/Cargo.toml +++ b/packages/cultcache-rs/Cargo.toml @@ -22,6 +22,9 @@ serde_bytes = "0.11" serde_json = "1" uuid = { version = "1", features = ["v4"] } +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.59", features = ["Win32_Storage_FileSystem"] } + [dev-dependencies] pretty_assertions = "1.4" tempfile = "3" diff --git a/packages/cultcache-rs/README.md b/packages/cultcache-rs/README.md index 2d75d94e..74b20dd3 100644 --- a/packages/cultcache-rs/README.md +++ b/packages/cultcache-rs/README.md @@ -250,8 +250,38 @@ marked `default` use `Default::default()` when older payloads are read. Deleted field slots should stay reserved until an explicit store migration rewrites the data. -The single-file MessagePack store rewrites an atomic snapshot. That is a sane -starting point for small typed state surfaces, settings, Epiphany agent memory, +The single-file MessagePack store rewrites one complete snapshot. Under the +exclusive sidecar lock it removes abandoned candidates without following them, +creates a unique same-directory candidate with create-new semantics, writes and +flushes it, and then replaces the committed pathname without deleting that +pathname first. A process interruption before replacement leaves the previous +snapshot authoritative. Once replacement succeeds, readers observe the complete +new snapshot rather than a partial file. + +Unix requests a parent-directory flush after replacement. Windows uses +`MoveFileExW` with replace-existing and write-through flags. If the final Unix +directory flush fails, the method returns a downcastable +`CommittedSnapshotDurabilityUncertain`: the complete new snapshot may already be +visible, so the caller must fail-stop or reopen and reconcile before issuing +higher-level work again. Treating that error as "not committed" and blindly +retrying can duplicate commands or receipts. + +Abandoned `..tmp` candidates are never read as committed state and are +removed by the next exclusive writer. Cleanup recognizes only the exact +canonical UUID form emitted for that target, including targets whose native +filename is not UTF-8; similar `.tmp` names remain untouched. Candidate creation +uses create-new semantics, so an unexpected file or symlink collision fails +instead of being opened or truncated. The canonical candidate filename namespace +is reserved to the store. + +These guarantees assume a local filesystem that honors the platform rename and +flush primitives, and writers that honor the sidecar lock. Network filesystems, +faulty storage hardware, and unrelated writers may provide weaker behavior. +Fault-injection tests prove the process-visible old-or-new outcomes around the +replacement boundary; they do not simulate sudden power loss or prove that a +device honored a successful flush. + +This is a sane starting point for small typed state surfaces, settings, Epiphany agent memory, heartbeat state, and other compact control-plane data. Large corpora should use a sharded store or a real database instead of asking one file to become a warehouse and then acting wounded when physics invoices us. @@ -260,6 +290,9 @@ The single-file store uses a sidecar lock file for shared reads and exclusive writes. That protects ordinary multi-process access to the same file. It is still not a multi-master replication protocol, and it is not a substitute for a coordinator when higher-level write ordering matters. +An explicit unlock error cannot replace the write outcome: dropping the lock-file +handle is the final OS lock-release path, so a committed-durability-uncertain +result remains inspectable rather than being masked by cleanup noise. ## Near-Term Ergonomic Improvements diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index 67e88cdf..b85b763a 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -5,9 +5,12 @@ use serde::Serialize; use serde::de::DeserializeOwned; use std::collections::BTreeMap; use std::collections::BTreeSet; +use std::ffi::OsStr; +use std::fmt; use std::fs; use std::fs::File; use std::fs::OpenOptions; +use std::io::Write; use std::path::Path; use std::path::PathBuf; @@ -97,6 +100,45 @@ pub struct PushAllOptions { pub soft: bool, } +/// A complete new snapshot replaced the committed pathname, but its final +/// durability barrier failed. Callers must fail-stop or reopen and reconcile; +/// retrying as though the write never committed can duplicate higher-level work. +#[derive(Debug)] +pub struct CommittedSnapshotDurabilityUncertain { + path: PathBuf, + detail: String, +} + +impl CommittedSnapshotDurabilityUncertain { + fn new(path: PathBuf, error: impl fmt::Display) -> Self { + Self { + path, + detail: error.to_string(), + } + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn detail(&self) -> &str { + &self.detail + } +} + +impl fmt::Display for CommittedSnapshotDurabilityUncertain { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "snapshot {} was committed but its durability is uncertain: {}", + self.path.display(), + self.detail + ) + } +} + +impl std::error::Error for CommittedSnapshotDurabilityUncertain {} + pub trait CacheBackingStore: Send { fn pull_all(&self) -> Result>; fn push(&mut self, entry: &CultCacheEnvelope) -> Result<()>; @@ -144,26 +186,50 @@ impl SingleFileMessagePackBackingStore { } fn write_all_unlocked(&self, entries: &[CultCacheEnvelope]) -> Result<()> { + self.write_all_unlocked_with_observer(entries, |_| Ok(())) + } + + fn write_all_unlocked_with_observer( + &self, + entries: &[CultCacheEnvelope], + mut observe: impl FnMut(SnapshotReplacementStage) -> Result<()>, + ) -> Result<()> { if let Some(parent) = self.path.parent() { fs::create_dir_all(parent) .with_context(|| format!("failed to create {}", parent.display()))?; } + remove_stale_candidates(&self.path)?; let bytes = rmp_serde::to_vec(&encode_store_snapshot(entries)) .context("failed to encode MessagePack")?; let tmp_path = temporary_path_for(&self.path); - fs::write(&tmp_path, bytes) + let mut candidate = OpenOptions::new() + .create_new(true) + .write(true) + .open(&tmp_path) + .with_context(|| format!("failed to open {}", tmp_path.display()))?; + candidate + .write_all(&bytes) .with_context(|| format!("failed to write {}", tmp_path.display()))?; - if self.path.exists() { - fs::remove_file(&self.path) - .with_context(|| format!("failed to replace {}", self.path.display()))?; + candidate + .sync_all() + .with_context(|| format!("failed to flush {}", tmp_path.display()))?; + drop(candidate); + + observe(SnapshotReplacementStage::CandidateSynced)?; + replace_file(&tmp_path, &self.path)?; + if let Err(error) = observe(SnapshotReplacementStage::TargetReplaced) { + return Err(anyhow::Error::new( + CommittedSnapshotDurabilityUncertain::new(self.path.clone(), error), + )); + } + + if let Some(parent) = self.path.parent() { + if let Err(error) = sync_parent_directory(parent) { + return Err(anyhow::Error::new( + CommittedSnapshotDurabilityUncertain::new(self.path.clone(), error), + )); + } } - fs::rename(&tmp_path, &self.path).with_context(|| { - format!( - "failed to move {} to {}", - tmp_path.display(), - self.path.display() - ) - })?; Ok(()) } @@ -178,13 +244,26 @@ impl SingleFileMessagePackBackingStore { } fn with_exclusive_lock(&self, action: impl FnOnce() -> Result) -> Result { + self.with_exclusive_lock_using_unlock(action, |lock| fs2::FileExt::unlock(lock)) + } + + fn with_exclusive_lock_using_unlock( + &self, + action: impl FnOnce() -> Result, + unlock: impl FnOnce(&File) -> std::io::Result<()>, + ) -> Result { let lock = self.open_lock_file()?; fs2::FileExt::lock_exclusive(&lock) .with_context(|| format!("failed to lock {}", self.lock_path().display()))?; - let result = action(); - fs2::FileExt::unlock(&lock) - .with_context(|| format!("failed to unlock {}", self.lock_path().display()))?; - result + let action_result = action(); + + // Closing the file handle releases the OS lock even when an explicit + // unlock reports an error. The action outcome remains authoritative: + // in particular, never replace a committed-durability-uncertain error + // with secondary lock-cleanup noise. + let _unlock_result = unlock(&lock); + drop(lock); + action_result } fn open_lock_file(&self) -> Result { @@ -742,6 +821,186 @@ fn temporary_path_for(path: &Path) -> PathBuf { path.with_file_name(file_name) } +fn is_canonical_candidate_uuid(value: &[u8]) -> bool { + if value.len() != 36 || !value.is_ascii() { + return false; + } + let Ok(value) = std::str::from_utf8(value) else { + return false; + }; + let Ok(uuid) = uuid::Uuid::parse_str(value) else { + return false; + }; + uuid.hyphenated().to_string() == value +} + +#[cfg(unix)] +fn is_owned_candidate_name(target_name: &OsStr, candidate_name: &OsStr) -> bool { + use std::os::unix::ffi::OsStrExt; + + let target = target_name.as_bytes(); + let candidate = candidate_name.as_bytes(); + let Some(remainder) = candidate.strip_prefix(target) else { + return false; + }; + let Some(remainder) = remainder.strip_prefix(b".") else { + return false; + }; + let Some(uuid) = remainder.strip_suffix(b".tmp") else { + return false; + }; + is_canonical_candidate_uuid(uuid) +} + +#[cfg(windows)] +fn is_owned_candidate_name(target_name: &OsStr, candidate_name: &OsStr) -> bool { + use std::os::windows::ffi::OsStrExt; + + let target = target_name.encode_wide().collect::>(); + let candidate = candidate_name.encode_wide().collect::>(); + let Some(remainder) = candidate.strip_prefix(target.as_slice()) else { + return false; + }; + let Some(remainder) = remainder.strip_prefix(&[b'.' as u16]) else { + return false; + }; + let suffix = [b'.' as u16, b't' as u16, b'm' as u16, b'p' as u16]; + let Some(uuid_wide) = remainder.strip_suffix(&suffix) else { + return false; + }; + let Ok(uuid) = uuid_wide + .iter() + .map(|value| u8::try_from(*value)) + .collect::, _>>() + else { + return false; + }; + is_canonical_candidate_uuid(&uuid) +} + +#[cfg(not(any(unix, windows)))] +fn is_owned_candidate_name(target_name: &OsStr, candidate_name: &OsStr) -> bool { + let (Some(target), Some(candidate)) = (target_name.to_str(), candidate_name.to_str()) else { + return false; + }; + let Some(remainder) = candidate.strip_prefix(target) else { + return false; + }; + let Some(remainder) = remainder.strip_prefix('.') else { + return false; + }; + let Some(uuid) = remainder.strip_suffix(".tmp") else { + return false; + }; + is_canonical_candidate_uuid(uuid.as_bytes()) +} + +fn stale_candidate_paths(path: &Path) -> Result> { + let parent = path.parent().unwrap_or_else(|| Path::new(".")); + if !parent.exists() { + return Ok(Vec::new()); + } + let target_name = path + .file_name() + .unwrap_or_else(|| OsStr::new("cultcache.msgpack")); + let mut candidates = Vec::new(); + for entry in + fs::read_dir(parent).with_context(|| format!("failed to inspect {}", parent.display()))? + { + let entry = entry.with_context(|| format!("failed to inspect {}", parent.display()))?; + let name = entry.file_name(); + if is_owned_candidate_name(target_name, &name) { + candidates.push(entry.path()); + } + } + Ok(candidates) +} + +fn remove_stale_candidates(path: &Path) -> Result<()> { + for candidate in stale_candidate_paths(path)? { + fs::remove_file(&candidate) + .with_context(|| format!("failed to remove stale candidate {}", candidate.display()))?; + } + Ok(()) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SnapshotReplacementStage { + CandidateSynced, + TargetReplaced, +} + +#[cfg(unix)] +fn replace_file(candidate: &Path, target: &Path) -> Result<()> { + fs::rename(candidate, target).with_context(|| { + format!( + "failed to atomically replace {} with {}", + target.display(), + candidate.display() + ) + }) +} + +#[cfg(windows)] +fn replace_file(candidate: &Path, target: &Path) -> Result<()> { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Storage::FileSystem::{ + MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW, + }; + + let candidate_wide = candidate + .as_os_str() + .encode_wide() + .chain(std::iter::once(0)) + .collect::>(); + let target_wide = target + .as_os_str() + .encode_wide() + .chain(std::iter::once(0)) + .collect::>(); + let replaced = unsafe { + MoveFileExW( + candidate_wide.as_ptr(), + target_wide.as_ptr(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, + ) + }; + if replaced == 0 { + return Err(std::io::Error::last_os_error()).with_context(|| { + format!( + "failed to atomically replace {} with {}", + target.display(), + candidate.display() + ) + }); + } + Ok(()) +} + +#[cfg(not(any(unix, windows)))] +fn replace_file(candidate: &Path, target: &Path) -> Result<()> { + fs::rename(candidate, target).with_context(|| { + format!( + "failed to replace {} with {}", + target.display(), + candidate.display() + ) + }) +} + +#[cfg(unix)] +fn sync_parent_directory(parent: &Path) -> Result<()> { + File::open(parent) + .with_context(|| format!("failed to open directory {}", parent.display()))? + .sync_all() + .with_context(|| format!("failed to flush directory {}", parent.display())) +} + +#[cfg(not(unix))] +fn sync_parent_directory(_parent: &Path) -> Result<()> { + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -778,6 +1037,263 @@ mod tests { cultcache_registry!(TestEntries { Settings, Note }); + fn test_envelope(value: &str) -> CultCacheEnvelope { + CultCacheEnvelope { + key: "state".to_string(), + r#type: "test-state".to_string(), + payload: value.as_bytes().to_vec(), + stored_at: "2026-07-15T00:00:00Z".to_string(), + schema_id: Some("tests.test_state.v1".to_string()), + } + } + + #[test] + fn interruption_before_replacement_preserves_committed_snapshot() -> Result<()> { + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("cache.msgpack"); + let mut store = SingleFileMessagePackBackingStore::new(&store_path); + let old = test_envelope("old"); + let new = test_envelope("new"); + store.push_all(std::slice::from_ref(&old), PushAllOptions::default())?; + + let result = store.write_all_unlocked_with_observer(std::slice::from_ref(&new), |stage| { + assert_eq!(stage, SnapshotReplacementStage::CandidateSynced); + assert!( + store_path.exists(), + "the committed pathname must never be removed" + ); + Err(anyhow!("simulated interruption before replacement")) + }); + + assert!(result.is_err()); + let recovered = store.pull_all()?; + assert_eq!(recovered.len(), 1); + assert_eq!(recovered[0].payload, old.payload); + assert_eq!(stale_candidate_paths(&store_path)?.len(), 1); + + store.push_all(std::slice::from_ref(&new), PushAllOptions::default())?; + let recovered = store.pull_all()?; + assert_eq!(recovered.len(), 1); + assert_eq!(recovered[0].payload, new.payload); + assert!(stale_candidate_paths(&store_path)?.is_empty()); + Ok(()) + } + + #[test] + fn interruption_after_replacement_recovers_new_snapshot() -> Result<()> { + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("cache.msgpack"); + let mut store = SingleFileMessagePackBackingStore::new(&store_path); + let old = test_envelope("old"); + let new = test_envelope("new"); + store.push_all(std::slice::from_ref(&old), PushAllOptions::default())?; + + let result = store.write_all_unlocked_with_observer(std::slice::from_ref(&new), |stage| { + if stage == SnapshotReplacementStage::TargetReplaced { + return Err(anyhow!("simulated interruption after replacement")); + } + Ok(()) + }); + + let error = result.expect_err("the injected post-replacement failure must surface"); + let uncertain = error + .downcast_ref::() + .expect("post-replacement failures must be typed as committed but uncertain"); + assert_eq!(uncertain.path(), store_path.as_path()); + assert!(uncertain.detail().contains("simulated interruption")); + let recovered = store.pull_all()?; + assert_eq!(recovered.len(), 1); + assert_eq!(recovered[0].payload, new.payload); + assert!(stale_candidate_paths(&store_path)?.is_empty()); + Ok(()) + } + + #[test] + fn first_write_interruption_before_replacement_leaves_store_uncommitted() -> Result<()> { + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("cache.msgpack"); + let store = SingleFileMessagePackBackingStore::new(&store_path); + let new = test_envelope("new"); + + let result = store.write_all_unlocked_with_observer(std::slice::from_ref(&new), |stage| { + assert_eq!(stage, SnapshotReplacementStage::CandidateSynced); + Err(anyhow!("simulated interruption before first replacement")) + }); + + assert!(result.is_err()); + assert!(!store_path.exists()); + assert!(store.pull_all()?.is_empty()); + assert_eq!(stale_candidate_paths(&store_path)?.len(), 1); + Ok(()) + } + + #[test] + fn first_write_interruption_after_replacement_exposes_complete_snapshot() -> Result<()> { + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("cache.msgpack"); + let store = SingleFileMessagePackBackingStore::new(&store_path); + let new = test_envelope("new"); + + let result = store.write_all_unlocked_with_observer(std::slice::from_ref(&new), |stage| { + if stage == SnapshotReplacementStage::TargetReplaced { + return Err(anyhow!("simulated interruption after first replacement")); + } + Ok(()) + }); + + let error = result.expect_err("the injected post-replacement failure must surface"); + assert!( + error + .downcast_ref::() + .is_some() + ); + let recovered = store.pull_all()?; + assert_eq!(recovered.len(), 1); + assert_eq!(recovered[0].payload, new.payload); + assert!(stale_candidate_paths(&store_path)?.is_empty()); + Ok(()) + } + + #[test] + fn unlock_failure_never_masks_the_action_outcome() -> Result<()> { + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("cache.msgpack"); + let store = SingleFileMessagePackBackingStore::new(&store_path); + + let completed = store.with_exclusive_lock_using_unlock( + || Ok(42_u32), + |_| Err(std::io::Error::other("simulated unlock failure")), + )?; + assert_eq!(completed, 42); + + let uncertain: Result<()> = store.with_exclusive_lock_using_unlock( + || { + Err(anyhow::Error::new( + CommittedSnapshotDurabilityUncertain::new( + store_path.clone(), + "primary post-commit failure", + ), + )) + }, + |_| Err(std::io::Error::other("secondary unlock failure")), + ); + let error = uncertain.expect_err("the action error must survive unlock cleanup"); + let error = error + .downcast_ref::() + .expect("the primary typed outcome must not be masked"); + assert!(error.detail().contains("primary post-commit failure")); + assert!(!error.detail().contains("secondary unlock failure")); + + // Both injected unlock failures still close their lock handles. A new + // exclusive operation must therefore acquire the lock normally. + store.with_exclusive_lock(|| Ok(()))?; + Ok(()) + } + + #[test] + fn stale_cleanup_preserves_non_uuid_lookalikes() -> Result<()> { + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("cache.msgpack"); + let lookalike = temp.path().join("cache.msgpack.not-a-uuid.tmp"); + fs::write(&lookalike, b"belongs to somebody else")?; + + let mut store = SingleFileMessagePackBackingStore::new(&store_path); + store.push_all(&[test_envelope("new")], PushAllOptions::default())?; + + assert_eq!(fs::read(&lookalike)?, b"belongs to somebody else"); + assert!(stale_candidate_paths(&store_path)?.is_empty()); + Ok(()) + } + + #[cfg(unix)] + #[test] + fn stale_candidate_symlink_is_removed_without_clobbering_its_target() -> Result<()> { + use std::os::unix::fs::symlink; + + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("cache.msgpack"); + let victim_path = temp.path().join("victim.txt"); + fs::write(&victim_path, b"untouched")?; + let stale_path = temporary_path_for(&store_path); + symlink(&victim_path, &stale_path)?; + + let mut store = SingleFileMessagePackBackingStore::new(&store_path); + store.push_all(&[test_envelope("new")], PushAllOptions::default())?; + + assert_eq!(fs::read(&victim_path)?, b"untouched"); + assert!(!stale_path.exists()); + assert!(stale_candidate_paths(&store_path)?.is_empty()); + Ok(()) + } + + #[cfg(unix)] + #[test] + fn non_utf8_target_names_recover_their_own_candidates() -> Result<()> { + use std::ffi::OsString; + use std::os::unix::ffi::OsStringExt; + + let temp = tempfile::tempdir()?; + let store_name = OsString::from_vec(b"cache-\xff.msgpack".to_vec()); + let store_path = temp.path().join(store_name); + let mut store = SingleFileMessagePackBackingStore::new(&store_path); + let new = test_envelope("new"); + + let interrupted = store + .write_all_unlocked_with_observer(std::slice::from_ref(&new), |_| { + Err(anyhow!("simulated interruption")) + }); + assert!(interrupted.is_err()); + assert_eq!(stale_candidate_paths(&store_path)?.len(), 1); + + store.push_all(std::slice::from_ref(&new), PushAllOptions::default())?; + assert!(stale_candidate_paths(&store_path)?.is_empty()); + assert_eq!(store.pull_all()?[0].payload, new.payload); + Ok(()) + } + + #[test] + fn two_contending_writers_leave_one_complete_snapshot() -> Result<()> { + use std::sync::{Arc, Barrier}; + + let temp = tempfile::tempdir()?; + let store_path = temp.path().join("cache.msgpack"); + let barrier = Arc::new(Barrier::new(3)); + let spawn_writer = |marker: u8| { + let store_path = store_path.clone(); + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || -> Result<()> { + let mut entries = Vec::new(); + for index in 0..128 { + let mut entry = test_envelope(std::str::from_utf8(&[marker]).unwrap()); + entry.key = format!("state-{index:03}"); + entry.payload = vec![marker; 4096]; + entries.push(entry); + } + let mut store = SingleFileMessagePackBackingStore::new(store_path); + barrier.wait(); + store.push_all(&entries, PushAllOptions::default()) + }) + }; + + let writer_a = spawn_writer(b'a'); + let writer_b = spawn_writer(b'b'); + barrier.wait(); + writer_a.join().expect("writer A panicked")?; + writer_b.join().expect("writer B panicked")?; + + let recovered = SingleFileMessagePackBackingStore::new(&store_path).pull_all()?; + assert_eq!(recovered.len(), 128); + let winner = recovered[0].payload[0]; + assert!(winner == b'a' || winner == b'b'); + assert!( + recovered + .iter() + .all(|entry| entry.payload == vec![winner; 4096]) + ); + assert!(stale_candidate_paths(&store_path)?.is_empty()); + Ok(()) + } + #[test] fn familiar_cultcache_flow_persists_and_reloads_typed_documents() -> Result<()> { let temp = tempfile::tempdir()?; diff --git a/packages/cultcache-ts/package-lock.json b/packages/cultcache-ts/package-lock.json deleted file mode 100644 index 4b3cf3f6..00000000 --- a/packages/cultcache-ts/package-lock.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "cultcache-ts", - "version": "0.13.5", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "cultcache-ts", - "version": "0.13.5", - "license": "MIT", - "dependencies": { - "@msgpack/msgpack": "^3.1.3", - "zod": "^3.25.76" - }, - "devDependencies": { - "@types/node": "^24.0.0", - "typescript": "^5.9.0" - } - }, - "node_modules/@msgpack/msgpack": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz", - "integrity": "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==", - "license": "ISC", - "engines": { - "node": ">= 18" - } - }, - "node_modules/@types/node": { - "version": "24.12.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz", - "integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~7.16.0" - } - }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", - "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", - "dev": true, - "license": "MIT" - }, - "node_modules/zod": { - "version": "3.25.76", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", - "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - } - } -} diff --git a/packages/cultcache-ts/package.json b/packages/cultcache-ts/package.json index 60731b8f..b9df4300 100644 --- a/packages/cultcache-ts/package.json +++ b/packages/cultcache-ts/package.json @@ -20,9 +20,10 @@ "dist" ], "scripts": { - "build": "tsc -p tsconfig.json", - "typecheck": "tsc -p tsconfig.json --pretty false", - "test": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/test/cult-cache.test.js" + "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 --test dist-test/test/cult-cache.test.js" }, "keywords": [ "messagepack", @@ -34,6 +35,18 @@ ], "author": "metacratic", "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/GameCult/CultLib.git", + "directory": "packages/cultcache-ts" + }, + "bugs": { + "url": "https://github.com/GameCult/CultLib/issues" + }, + "homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultcache-ts#readme", + "engines": { + "node": ">=18" + }, "dependencies": { "@msgpack/msgpack": "^3.1.3", "zod": "^3.25.76" diff --git a/packages/cultmesh-ts/README.md b/packages/cultmesh-ts/README.md index 279e271e..9c4dfb01 100644 --- a/packages/cultmesh-ts/README.md +++ b/packages/cultmesh-ts/README.md @@ -262,6 +262,71 @@ Schema and shard catalog factories delegate to `cultnet-ts`; the branded `CultMesh` entrypoint does not create a second owner for schema discovery or topology truth. +## Long-Lived Providers + +TypeScript provider daemons use `CultMeshProviderSession` to retain one logical +provider lifecycle across physical reconnects. The session owns registration, +lease renewal, desired typed publication replay, command dispatch, receipt +publication, and withdrawal. Provider code owns domain state and idempotent +command transactions; the injected transport owns CultNet wire details. + +```ts +import { + CultMeshProviderRudpTransport, + CultMeshProviderSession, +} from "cultmesh-ts"; + +const odinTransport = new CultMeshProviderRudpTransport({ + endpoint: "rudp://127.0.0.1:17871", + runtimeId: "voidbot-worker-7", + connectionId: 0x43554c54, + sessionToken: process.env.ODIN_PROVIDER_SESSION_TOKEN, +}); + +const session = new CultMeshProviderSession({ + identity: { + providerId: "voidbot.swarm", + serviceInstanceId: "voidbot-worker-7", + endpointId: "odin:voidbot-worker-7", + verseId: "voidbot.local", + }, + transport: odinTransport, + receiptStore: durableReceiptStore, + publications: [advertisementPublication, surfacePublication], + commandHandlers: { + "swarm.set_heat": applyHeatCommandTransaction, + }, +}); + +await session.start(); +await session.upsertPublication(nextSurfacePublication); +``` + +Provider, service-instance, endpoint, and body-producer identities are separate +contracts. The provider session never infers one from another. A durable +receipt store is required; `CultMeshMemoryProviderReceiptStore` is intended +only for tests and disposable tools. The store is a durable outbox: a receipt +is persisted before transport publication, remains pending across reconnects, +and is marked published only after the current connection accepts it. Receipt +store failure degrades command intake without inventing a network outage. + +The RUDP provider transport carries lifecycle payloads inside the existing +`cultnet.operation_request.v0` and `cultnet.operation_response.v0` envelopes. +RUDP acknowledgements prove byte delivery only. Registration, renewal, +publication changes, receipts, and withdrawal complete only after the +provider-session broker returns a correlated application response. The broker +owns lease fencing and accepted publication membership; the provider owns its +desired documents and durable receipt outbox. + +`CultMeshProviderRudpTransport` is currently a private-development transport. +Do not advertise it as a public provider boundary until the surrounding +CultNet session authenticates a claim authorizing the four-part provider +identity. Source address and successful contact are not authority. +The adapter carries `sessionToken` in a typed RUDP Connect-evidence map beside +a fresh `clientSessionId`. Packet retransmits reuse that id; an actual reconnect +mints another. The receiver must decode and validate the token as authorization +evidence for the requested provider identity. + ## RUDP Helpers Node runtimes can build the shared CultNet reliable-UDP transport from the diff --git a/packages/cultmesh-ts/package.json b/packages/cultmesh-ts/package.json index b233d448..a1cc77c4 100644 --- a/packages/cultmesh-ts/package.json +++ b/packages/cultmesh-ts/package.json @@ -1,16 +1,24 @@ { "name": "cultmesh-ts", - "version": "0.1.0", + "version": "0.1.1", "description": "CultMesh local typed state and mesh catalog primitives for TypeScript runtimes.", "main": "dist/index.js", "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.js", + "default": "./dist/index.js" + } + }, "files": [ "dist" ], "scripts": { - "build": "tsc -p tsconfig.json", - "typecheck": "tsc -p tsconfig.json --pretty false", - "test": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js" + "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 --test dist-test/test/*.test.js" }, "keywords": [ "cultmesh", @@ -21,10 +29,22 @@ ], "author": "metacratic", "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/GameCult/CultLib.git", + "directory": "packages/cultmesh-ts" + }, + "bugs": { + "url": "https://github.com/GameCult/CultLib/issues" + }, + "homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultmesh-ts#readme", + "engines": { + "node": ">=18" + }, "dependencies": { "@msgpack/msgpack": "^3.1.2", - "cultcache-ts": "file:../cultcache-ts", - "cultnet-ts": "file:../cultnet-ts" + "cultcache-ts": "^0.13.5", + "cultnet-ts": "^0.1.1" }, "devDependencies": { "@types/node": "^24.0.0", diff --git a/packages/cultmesh-ts/src/index.ts b/packages/cultmesh-ts/src/index.ts index 687f9b8a..aa84f5f9 100644 --- a/packages/cultmesh-ts/src/index.ts +++ b/packages/cultmesh-ts/src/index.ts @@ -25,6 +25,8 @@ import { type CultNetErrorMessage, type CultNetDocumentBinding, type CultNetMessage, + type CultNetOperationRequestMessage, + type CultNetOperationResponseMessage, type CultNetRawDocumentRecord, type CultNetReconnectPolicy, type CultNetSchemaCatalogOptions, @@ -32,6 +34,11 @@ import { type CultNetWireContract, } from "cultnet-ts"; +export * from "./provider-session"; +export * from "./provider-session-wire"; +export * from "./provider-rudp-transport"; +export * from "./provider-session-broker"; + export interface CultMeshVec2 { readonly x: number; readonly y: number; @@ -68,6 +75,20 @@ export interface CultMeshRouteRecord { readonly description: string; } +/** + * Consumer view of provider-session publications. The provider-session client + * owns ordering, replay, and reconnect; document handles only project that + * live publication state into typed latest/watch semantics. + */ +export interface CultMeshLivePublicationSource { + latest(schemaId: string, recordKey: string): Promise; + watch( + schemaId: string, + recordKey: string, + callback: (value: unknown) => void, + ): CultMeshUnsubscribe; +} + export type CultMeshDocumentPublicationSource = | { readonly kind: "single-file"; @@ -81,6 +102,11 @@ export type CultMeshDocumentPublicationSource = readonly kind: "peer-snapshot"; readonly peer: CultNetPeer | (() => CultNetPeer | Promise); readonly endpoint?: string; + } + | { + readonly kind: "live-publication"; + readonly source: CultMeshLivePublicationSource; + readonly endpoint?: string; }; export interface CultMeshPublicationDocumentBinding { @@ -2705,6 +2731,33 @@ export function cultMeshDocumentFromPublication( requireNonEmpty(recordKey, "recordKey"); switch (source.kind) { + case "live-publication": { + const schema = typeof schemaOrDefinition === "string" + ? { schemaId: schemaOrDefinition } + : cultMeshSchemaFromDefinition(schemaOrDefinition); + const schemaId = schema.schemaId ?? schema.type; + if (!schemaId) { + throw new Error("CultMesh live publication document requires a schema id or document type."); + } + const parse = (value: unknown) => parseCultMeshDocumentValue(schemaOrDefinition, value); + return cultMeshDocument( + options.documentId ?? recordKey, + schema, + async () => parse(await source.source.latest(schemaId, recordKey)), + { + routeHint: options.routeHint ?? cultMeshRouteHint( + "network", + source.endpoint ?? "CultMesh provider-session publication", + ), + sources: [cultMeshProjectionSource(options.sourceId ?? recordKey, { schemaId })], + watchDocument: (_context, callback) => source.source.watch( + schemaId, + recordKey, + value => callback(parse(value)), + ), + }, + ); + } case "single-file": return typeof schemaOrDefinition === "string" ? cultMeshDocumentFromSingleFile(source.path, schemaOrDefinition, { @@ -4107,10 +4160,22 @@ export interface CultMeshRudpDocumentServerOptions extends CultMeshRudpSocketOpt | CultMeshRudpDocumentReceipt | void | Promise; + onOperationRequest?: ( + request: CultNetOperationRequestMessage, + session: CultMeshRudpServerSession, + ) => CultNetOperationResponseMessage | Promise; + onSessionClosed?: (session: CultMeshRudpServerSession) => void | Promise; wireContract?: CultNetWireContract; sessionTimeoutMs?: number; } +export interface CultMeshRudpServerSession { + readonly sessionId: string; + readonly remote: { address: string; family: string; port: number }; + readonly connectPayload?: Uint8Array; + send(message: CultNetMessage): void; +} + export interface CultMeshRudpDocumentServer { readonly bind: { host: string; port: number }; start(): Promise; @@ -5558,9 +5623,14 @@ export class CultMesh { const bind = { host, port }; const socket = options.socket ?? createSocket(host.includes(":") ? "udp6" : "udp4"); const sessions = new Map; }>(); + let sessionSequence = 0; const resendPollMs = Math.max(10, options.resendPollMs ?? 25); const sessionTimeoutMs = Math.max(1_000, options.sessionTimeoutMs ?? 30_000); const wireContract = options.wireContract ?? "cultnet.schema.v0"; @@ -5583,14 +5653,28 @@ export class CultMesh { let record = sessions.get(key); if (packet.packetType === "connect") { + const connectPayload = Uint8Array.from(packet.payload ?? []); + if (record && byteArraysEqual(record.connectPayload, connectPayload)) { + socket.send( + encodeRudpPacket(record.session.acceptConnect(packet, nowMs)), + remote.port, + remote.address, + ); + return; + } + if (record) closeSession(record); record = { + sessionId: `${runtimeId}:${++sessionSequence}`, remote: { address: remote.address, family: remote.family, port: remote.port }, + connectPayload, + closed: false, session: new CultNetRudpSession({ connectionId, initialSequence: options.initialSequence, resendDelayMs: options.resendDelayMs, maxPendingReliablePackets: options.maxPendingReliablePackets, }), + work: Promise.resolve(), }; sessions.set(key, record); socket.send(encodeRudpPacket(record.session.acceptConnect(packet, nowMs)), remote.port, remote.address); @@ -5609,16 +5693,21 @@ export class CultMesh { if (frame.channelId !== "schema") { continue; } - handleDocumentServerFrame(record, frame.payload).catch((error) => { - reportError(error); - }); + record.work = record.work + .then(() => handleDocumentServerFrame(record, frame.payload)) + .catch(reportError); } if (result.disconnected) { sessions.delete(key); + closeSession(record); return; } - if (packet.packetType === "accept" || result.delivered.length > 0) { - socket.send(encodeRudpPacket(record.session.createAck()), record.remote.port, record.remote.address); + if (packet.reliable) { + socket.send( + encodeRudpPacket(record.session.createAckFor(packet.sequence)), + record.remote.port, + record.remote.address, + ); } } catch (error) { reportError(error); @@ -5627,9 +5716,10 @@ export class CultMesh { socket.on("error", reportError); async function handleDocumentServerFrame( - record: { remote: { address: string; family: string; port: number }; session: CultNetRudpSession }, + record: { sessionId: string; remote: { address: string; family: string; port: number }; session: CultNetRudpSession; connectPayload: Uint8Array; closed: boolean }, payload: Uint8Array, ): Promise { + if (record.closed) return; const message = parseCultNetMessage(decode(payload), wireContract); switch (message.schemaVersion) { case "cultnet.snapshot_request.v0": { @@ -5670,6 +5760,16 @@ export class CultMesh { } } return; + case "cultnet.operation_request.v0": + if (!options.onOperationRequest) { + sendSchemaMessage(record, { + schemaVersion: "cultnet.error.v0", + error: "CultMesh RUDP document server has no operation handler.", + }); + return; + } + sendSchemaMessage(record, await options.onOperationRequest(message, publicSession(record))); + return; default: sendSchemaMessage(record, { schemaVersion: "cultnet.error.v0", @@ -5678,10 +5778,52 @@ export class CultMesh { } } + function publicSession(record: { + sessionId: string; + remote: { address: string; family: string; port: number }; + session: CultNetRudpSession; + connectPayload: Uint8Array; + closed: boolean; + }): CultMeshRudpServerSession { + return { + sessionId: record.sessionId, + remote: { ...record.remote }, + connectPayload: Uint8Array.from(record.connectPayload), + send: message => { + if (record.closed) throw new Error(`CultMesh RUDP session ${record.sessionId} is closed.`); + sendSchemaMessage(record, message); + }, + }; + } + + function notifySessionClosed(record: { + sessionId: string; + remote: { address: string; family: string; port: number }; + session: CultNetRudpSession; + connectPayload: Uint8Array; + closed: boolean; + }): void { + if (!options.onSessionClosed) return; + void Promise.resolve(options.onSessionClosed(publicSession(record))).catch(reportError); + } + + function closeSession(record: { + sessionId: string; + remote: { address: string; family: string; port: number }; + session: CultNetRudpSession; + connectPayload: Uint8Array; + closed: boolean; + }): void { + if (record.closed) return; + record.closed = true; + notifySessionClosed(record); + } + function sendSchemaMessage( - record: { remote: { address: string; port: number }; session: CultNetRudpSession }, + record: { sessionId: string; remote: { address: string; port: number }; session: CultNetRudpSession; closed: boolean }, message: CultNetMessage, ): void { + if (record.closed) throw new Error(`CultMesh RUDP session ${record.sessionId} is closed.`); const payload = encode(encodeCultNetMessageForWire(message, wireContract)); for (const packet of record.session.sendMany("schema", payload, { reliable: true, @@ -5711,6 +5853,7 @@ export class CultMesh { for (const [key, record] of sessions) { if (record.session.checkTimeout(nowMs, sessionTimeoutMs)) { sessions.delete(key); + closeSession(record); continue; } for (const packet of record.session.dueResends(nowMs)) { @@ -5725,6 +5868,7 @@ export class CultMesh { clearInterval(resendTimer); resendTimer = undefined; } + for (const record of sessions.values()) closeSession(record); sessions.clear(); socket.close(); }, @@ -6332,6 +6476,14 @@ function nonBlankOr(value?: string, fallback = ""): string { return value && value.trim() ? value : fallback; } +function byteArraysEqual(left: Uint8Array, right: Uint8Array): boolean { + if (left.byteLength !== right.byteLength) return false; + for (let index = 0; index < left.byteLength; index += 1) { + if (left[index] !== right[index]) return false; + } + return true; +} + function parseCultMeshLocalityKind( value: string | undefined, fallback: CultMeshLocalityKind, diff --git a/packages/cultmesh-ts/src/provider-rudp-transport.ts b/packages/cultmesh-ts/src/provider-rudp-transport.ts new file mode 100644 index 00000000..0557bf48 --- /dev/null +++ b/packages/cultmesh-ts/src/provider-rudp-transport.ts @@ -0,0 +1,395 @@ +import { randomUUID } from "node:crypto"; +import { createSocket, type Socket } from "node:dgram"; +import { encode } from "@msgpack/msgpack"; +import { + CultNetPeer, + CultNetRudpSocketTransportConnection, + type CultNetMessage, + type CultNetOperationRequestMessage, + type CultNetOperationResponseMessage, + type CultNetRawDocumentRecord, +} from "cultnet-ts"; + +import type { + CultMeshProviderCommand, + CultMeshProviderCommandListener, + CultMeshProviderCommandReceipt, + CultMeshProviderConnection, + CultMeshProviderIdentity, + CultMeshProviderLease, + CultMeshProviderPublication, + CultMeshProviderRegistration, + CultMeshProviderTransport, + CultMeshProviderUnsubscribe, + CultMeshProviderWithdrawal, +} from "./provider-session"; +import { + CULTMESH_PROVIDER_SESSION_SERVICE_ID, + assertMutationAcceptance, + assertProviderLease, + cultMeshProviderSessionOperations, + cultMeshProviderSessionSchemas, + decodeProviderCommandDocument, + encodeProviderConnectEvidence, + decodeProviderSessionPayload, + encodeProviderSessionPayload, + type CultMeshProviderCommandReceiptWire, + type CultMeshProviderLeaseWire, + type CultMeshProviderMutationAcceptanceWire, +} from "./provider-session-wire"; + +export interface CultMeshProviderRudpTransportOptions { + readonly endpoint: string; + readonly runtimeId: string; + readonly connectionId: number; + readonly bindHost?: string; + readonly connectTimeoutMs?: number; + readonly operationTimeoutMs?: number; + readonly maxFragmentBytes?: number; + readonly sessionToken?: string; + readonly socketFactory?: () => Socket; +} + +/** + * Private-development provider transport. Public deployment additionally needs + * an authenticated CultNet session whose claims authorize the provider identity. + */ +export class CultMeshProviderRudpTransport implements CultMeshProviderTransport { + readonly #options: CultMeshProviderRudpTransportOptions; + + public constructor(options: CultMeshProviderRudpTransportOptions) { + if (!options.endpoint) throw new Error("CultMesh provider RUDP transport requires endpoint."); + if (!options.runtimeId) throw new Error("CultMesh provider RUDP transport requires runtimeId."); + if (!Number.isInteger(options.connectionId)) throw new Error("CultMesh provider RUDP transport requires integer connectionId."); + this.#options = options; + } + + public async connect( + identity: CultMeshProviderIdentity, + signal: AbortSignal, + ): Promise { + if (signal.aborted) throw abortError(); + const endpoint = parseEndpoint(this.#options.endpoint); + const socket = this.#options.socketFactory?.() ?? createSocket(endpoint.host.includes(":") ? "udp6" : "udp4"); + await bindSocket(socket, this.#options.bindHost ?? (endpoint.host.includes(":") ? "::" : "0.0.0.0"), signal); + const transport = new CultNetRudpSocketTransportConnection({ + mode: "client", + runtimeId: this.#options.runtimeId, + transportId: `${this.#options.runtimeId}.cultmesh-provider-session`, + socket, + remoteHost: endpoint.host, + remotePort: endpoint.port, + connectionId: this.#options.connectionId, + maxFragmentBytes: this.#options.maxFragmentBytes ?? 2_048, + }); + const peer = new CultNetPeer(transport, { wireContract: "cultnet.schema.v0" }); + transport.connect(Buffer.from(encodeProviderConnectEvidence({ + clientSessionId: randomUUID(), + sessionToken: this.#options.sessionToken ?? null, + }))); + try { + await waitUntilConnected(transport, signal, this.#options.connectTimeoutMs ?? 2_000); + return new RudpProviderConnection(identity, peer, transport, this.#options.operationTimeoutMs ?? 5_000); + } catch (error) { + transport.close(); + throw error; + } + } +} + +class RudpProviderConnection implements CultMeshProviderConnection { + readonly #identity: CultMeshProviderIdentity; + readonly #peer: CultNetPeer; + readonly #transport: CultNetRudpSocketTransportConnection; + readonly #timeoutMs: number; + readonly #listeners = new Set(); + readonly #pending = new Map void; + reject: (error: Error) => void; + timer: NodeJS.Timeout; + }>(); + readonly #publications = new Map(); + readonly #bufferedCommands = new Map(); + #closed = false; + #requestedLeaseDurationMs = 30_000; + + public constructor( + identity: CultMeshProviderIdentity, + peer: CultNetPeer, + transport: CultNetRudpSocketTransportConnection, + timeoutMs: number, + ) { + this.#identity = identity; + this.#peer = peer; + this.#transport = transport; + this.#timeoutMs = timeoutMs; + peer.on("message", message => this.#onMessage(message)); + peer.on("invalidMessage", error => this.#failPending(error)); + peer.on("close", () => this.#failPending(new Error("CultMesh provider RUDP connection closed."))); + peer.on("error", error => this.#failPending(error)); + } + + public async register( + registration: CultMeshProviderRegistration, + signal: AbortSignal, + ): Promise { + this.#requestedLeaseDurationMs = registration.requestedLeaseDurationMs; + const response = await this.#operation( + cultMeshProviderSessionOperations.register, + cultMeshProviderSessionSchemas.registration, + cultMeshProviderSessionSchemas.lease, + { ...registration.identity, requestedLeaseDurationMs: registration.requestedLeaseDurationMs }, + signal, + ); + const wire = decodeProviderSessionPayload(response.payload); + assertProviderLease(wire); + assertIdentity(this.#identity, wire); + return { leaseId: wire.leaseId, expiresAt: new Date(wire.expiresAtUtc) }; + } + + public async renew(lease: CultMeshProviderLease): Promise { + const response = await this.#operation( + cultMeshProviderSessionOperations.renew, + cultMeshProviderSessionSchemas.leaseRenewal, + cultMeshProviderSessionSchemas.lease, + { leaseId: lease.leaseId, requestedLeaseDurationMs: this.#requestedLeaseDurationMs }, + ); + const wire = decodeProviderSessionPayload(response.payload); + assertProviderLease(wire); + assertIdentity(this.#identity, wire); + return { leaseId: wire.leaseId, expiresAt: new Date(wire.expiresAtUtc) }; + } + + public async publish( + publication: CultMeshProviderPublication, + lease: CultMeshProviderLease, + ): Promise { + const document: CultNetRawDocumentRecord = { + schemaId: publication.schemaId, + recordKey: publication.recordKey, + storedAt: new Date().toISOString(), + payloadEncoding: "messagepack", + payload: encode(publication.value), + sourceRuntimeId: this.#identity.serviceInstanceId, + sourceAgentId: this.#identity.providerId, + sourceRole: "provider", + }; + await this.#accepted(cultMeshProviderSessionOperations.publicationPut, cultMeshProviderSessionSchemas.publicationPut, { + leaseId: lease.leaseId, + publicationId: publication.publicationId, + document, + }); + this.#publications.set(publication.publicationId, publication); + } + + public async withdrawPublication(publicationId: string, lease: CultMeshProviderLease): Promise { + const publication = this.#publications.get(publicationId); + if (!publication) throw new Error(`CultMesh provider publication ${publicationId} is not owned by this connection.`); + await this.#accepted(cultMeshProviderSessionOperations.publicationDelete, cultMeshProviderSessionSchemas.publicationDelete, { + leaseId: lease.leaseId, + publicationId, + schemaId: publication.schemaId, + recordKey: publication.recordKey, + }); + this.#publications.delete(publicationId); + } + + public watchCommands(listener: CultMeshProviderCommandListener): CultMeshProviderUnsubscribe { + this.#listeners.add(listener); + for (const [commandId, command] of this.#bufferedCommands) { + this.#bufferedCommands.delete(commandId); + void Promise.resolve(listener(command)).catch(() => undefined); + } + return () => { + this.#listeners.delete(listener); + }; + } + + public async publishReceipt( + receipt: CultMeshProviderCommandReceipt, + lease: CultMeshProviderLease, + ): Promise { + const wire: CultMeshProviderCommandReceiptWire = { + receiptId: receipt.receiptId, + commandId: receipt.commandId, + commandKind: receipt.commandKind, + providerId: receipt.providerId, + serviceInstanceId: receipt.serviceInstanceId, + state: receipt.state, + completedAtUtc: receipt.completedAt.toISOString(), + result: receipt.result, + error: receipt.error, + }; + await this.#accepted(cultMeshProviderSessionOperations.receiptPut, cultMeshProviderSessionSchemas.receiptPut, { + leaseId: lease.leaseId, + receipt: wire, + }); + } + + public async withdraw(withdrawal: CultMeshProviderWithdrawal): Promise { + await this.#accepted(cultMeshProviderSessionOperations.withdraw, cultMeshProviderSessionSchemas.withdrawal, { + leaseId: withdrawal.leaseId, + }); + this.#publications.clear(); + } + + public close(): void { + if (this.#closed) return; + this.#closed = true; + this.#failPending(new Error("CultMesh provider RUDP connection closed.")); + this.#listeners.clear(); + this.#transport.close(); + } + + async #accepted(operation: string, payloadSchema: string, payload: unknown): Promise { + const response = await this.#operation(operation, payloadSchema, cultMeshProviderSessionSchemas.mutationAcceptance, payload); + const acceptance = decodeProviderSessionPayload(response.payload); + assertMutationAcceptance(acceptance); + return acceptance; + } + + async #operation( + operation: string, + payloadSchema: string, + responsePayloadSchema: string, + payload: unknown, + signal?: AbortSignal, + ): Promise { + if (this.#closed) throw new Error("CultMesh provider RUDP connection is closed."); + if (signal?.aborted) throw abortError(); + const messageId = randomUUID(); + const request: CultNetOperationRequestMessage = { + schemaVersion: "cultnet.operation_request.v0", + messageId, + serviceId: CULTMESH_PROVIDER_SESSION_SERVICE_ID, + operation, + payloadSchema, + payloadEncoding: "messagepack-base64", + payload: encodeProviderSessionPayload(payload), + sourceRuntimeId: this.#identity.serviceInstanceId, + }; + return await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.#pending.delete(messageId); + reject(new Error(`CultMesh provider operation ${operation} timed out.`)); + }, this.#timeoutMs); + const abort = (): void => { + clearTimeout(timer); + this.#pending.delete(messageId); + reject(abortError()); + }; + signal?.addEventListener("abort", abort, { once: true }); + this.#pending.set(messageId, { + operation, + payloadSchema: responsePayloadSchema, + timer, + resolve: response => { + signal?.removeEventListener("abort", abort); + if (response.serviceId !== CULTMESH_PROVIDER_SESSION_SERVICE_ID || response.operation !== operation) { + reject(new Error(`CultMesh provider response correlation does not match ${operation}.`)); + return; + } + if (response.payloadEncoding !== "messagepack-base64") { + reject(new Error(`CultMesh provider response for ${operation} has incompatible payload encoding.`)); + return; + } + if (response.status !== "ok") { + reject(new Error(`CultMesh provider operation ${operation} was ${response.status}: ${(response.diagnostics ?? []).join("; ")}`)); + return; + } + if (response.payloadSchema !== responsePayloadSchema) { + reject(new Error(`CultMesh provider response for ${operation} has incompatible payload schema.`)); + return; + } + resolve(response); + }, + reject: error => { + signal?.removeEventListener("abort", abort); + reject(error); + }, + }); + this.#peer.send(request); + }); + } + + #onMessage(message: CultNetMessage): void { + if (message.schemaVersion === "cultnet.operation_response.v0") { + const pending = this.#pending.get(message.messageId); + if (!pending) return; + this.#pending.delete(message.messageId); + clearTimeout(pending.timer); + pending.resolve(message); + return; + } + if (message.schemaVersion !== "cultnet.document_put_raw.v0") return; + if (message.document.schemaId !== cultMeshProviderSessionSchemas.command) return; + const wire = decodeProviderCommandDocument(message.document); + if (wire.providerId !== this.#identity.providerId || wire.serviceInstanceId !== this.#identity.serviceInstanceId) return; + const command: CultMeshProviderCommand = { ...wire }; + if (this.#listeners.size === 0) { + this.#bufferedCommands.set(command.commandId, command); + return; + } + for (const listener of [...this.#listeners]) void Promise.resolve(listener(command)).catch(() => undefined); + } + + #failPending(error: Error): void { + for (const [messageId, pending] of this.#pending) { + this.#pending.delete(messageId); + clearTimeout(pending.timer); + pending.reject(error); + } + } +} + +function assertIdentity(identity: CultMeshProviderIdentity, lease: CultMeshProviderLeaseWire): void { + for (const key of ["providerId", "serviceInstanceId", "endpointId", "verseId"] as const) { + if (identity[key] !== lease[key]) throw new Error(`CultMesh provider lease ${key} does not match the registered identity.`); + } +} + +function parseEndpoint(endpoint: string): { host: string; port: number } { + const url = new URL(endpoint); + const port = Number(url.port); + if (url.protocol !== "rudp:" || !url.hostname || !Number.isInteger(port) || port <= 0 || port > 65_535) { + throw new Error(`Invalid CultMesh provider RUDP endpoint ${endpoint}.`); + } + return { host: url.hostname, port }; +} + +function bindSocket(socket: Socket, host: string, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const abort = (): void => { + socket.close(); + reject(abortError()); + }; + signal.addEventListener("abort", abort, { once: true }); + socket.once("error", reject); + socket.bind(0, host, () => { + signal.removeEventListener("abort", abort); + socket.removeListener("error", reject); + resolve(); + }); + }); +} + +async function waitUntilConnected( + transport: CultNetRudpSocketTransportConnection, + signal: AbortSignal, + timeoutMs: number, +): Promise { + const deadline = Date.now() + timeoutMs; + while (!transport.connected) { + if (signal.aborted) throw abortError(); + if (Date.now() >= deadline) throw new Error("CultMesh provider RUDP connection timed out."); + await new Promise(resolve => setTimeout(resolve, 5)); + } +} + +function abortError(): Error { + const error = new Error("CultMesh provider RUDP operation aborted."); + error.name = "AbortError"; + return error; +} diff --git a/packages/cultmesh-ts/src/provider-session-broker.ts b/packages/cultmesh-ts/src/provider-session-broker.ts new file mode 100644 index 00000000..eb9e18b5 --- /dev/null +++ b/packages/cultmesh-ts/src/provider-session-broker.ts @@ -0,0 +1,528 @@ +import { encode } from "@msgpack/msgpack"; +import type { + CultNetDocumentPutRawMessage, + CultNetOperationRequestMessage, + CultNetOperationResponseMessage, + CultNetRawDocumentRecord, +} from "cultnet-ts"; + +import type { CultMeshRudpServerSession } from "./index"; +import { + CULTMESH_PROVIDER_SESSION_SERVICE_ID, + cultMeshProviderSessionOperations, + cultMeshProviderSessionSchemas, + decodeProviderSessionPayload, + encodeProviderSessionPayload, + type CultMeshProviderCommandReceiptWire, + type CultMeshProviderCommandWire, + type CultMeshProviderLeaseRenewalWire, + type CultMeshProviderLeaseWire, + type CultMeshProviderOperationStatus, + type CultMeshProviderPublicationDeleteWire, + type CultMeshProviderPublicationPutWire, + type CultMeshProviderReceiptPutWire, + type CultMeshProviderRegistrationWire, + type CultMeshProviderWithdrawalWire, +} from "./provider-session-wire"; + +export interface CultMeshProviderBrokerClock { + now(): Date; +} + +export interface CultMeshProviderSessionBrokerOptions { + readonly runtimeId: string; + readonly clock?: CultMeshProviderBrokerClock; + readonly createLeaseId?: () => string; + readonly maximumLeaseDurationMs?: number; + readonly expiryPollMs?: number; + readonly onError?: (error: Error) => void; + readonly authorizeRegistration: ( + identity: CultMeshProviderRegistrationWire, + session: CultMeshRudpServerSession, + ) => boolean | Promise; + readonly acceptPublication: ( + identity: CultMeshProviderRegistrationWire, + publicationId: string, + document: CultNetRawDocumentRecord, + ) => void | Promise; + readonly deletePublications: ( + identity: CultMeshProviderRegistrationWire, + publications: readonly { + publicationId: string; + document: Pick; + }[], + ) => void | Promise; + readonly acceptReceipt: ( + identity: CultMeshProviderRegistrationWire, + receipt: CultMeshProviderCommandReceiptWire, + ) => void | Promise; +} + +interface LeaseRecord { + identity: CultMeshProviderRegistrationWire; + lease: CultMeshProviderLeaseWire; + session?: CultMeshRudpServerSession; + publications: Map; +} + +export class CultMeshProviderSessionBroker { + readonly #options: CultMeshProviderSessionBrokerOptions; + readonly #clock: CultMeshProviderBrokerClock; + readonly #leases = new Map(); + readonly #identityLeases = new Map(); + readonly #sessionLeases = new Map>(); + readonly #commands = new Map(); + readonly #receipts = new Map(); + readonly #publicationOwners = new Map(); + readonly #closedSessions = new Set(); + readonly #inFlightBySession = new Map(); + readonly #expiryTimer: NodeJS.Timeout; + #work: Promise = Promise.resolve(); + #leaseSequence = 0; + + public constructor(options: CultMeshProviderSessionBrokerOptions) { + if (!options.runtimeId) throw new Error("CultMesh provider-session broker requires runtimeId."); + if (!options.authorizeRegistration) throw new Error("CultMesh provider-session broker requires an explicit registration authority."); + this.#options = options; + this.#clock = options.clock ?? { now: () => new Date() }; + this.#expiryTimer = setInterval(() => { + void this.expireLeases().catch(error => { + const normalized = error instanceof Error ? error : new Error(String(error)); + if (this.#options.onError) this.#options.onError(normalized); + else console.error(`CultMesh provider-session expiry failed: ${normalized.message}`); + }); + }, Math.max(10, options.expiryPollMs ?? 1_000)); + this.#expiryTimer.unref?.(); + } + + public close(): void { + clearInterval(this.#expiryTimer); + } + + public async handle( + request: CultNetOperationRequestMessage, + session: CultMeshRudpServerSession, + ): Promise { + this.#inFlightBySession.set( + session.sessionId, + (this.#inFlightBySession.get(session.sessionId) ?? 0) + 1, + ); + const work = this.#work.then(() => this.#handle(request, session)); + this.#work = work.then(() => undefined, () => undefined); + try { + return await work; + } finally { + const remaining = (this.#inFlightBySession.get(session.sessionId) ?? 1) - 1; + if (remaining > 0) { + this.#inFlightBySession.set(session.sessionId, remaining); + } else { + this.#inFlightBySession.delete(session.sessionId); + this.#closedSessions.delete(session.sessionId); + } + } + } + + async #handle( + request: CultNetOperationRequestMessage, + session: CultMeshRudpServerSession, + ): Promise { + if (this.#closedSessions.has(session.sessionId)) { + return this.#response(request, "denied", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + "The physical provider session is closed or replaced.", + ]); + } + if (request.serviceId !== CULTMESH_PROVIDER_SESSION_SERVICE_ID) { + return this.#response(request, "denied", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + `Unsupported service ${request.serviceId}.`, + ]); + } + if (request.payloadEncoding !== "messagepack-base64") { + return this.#response(request, "invalid", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + "Provider-session operation payloads must use messagepack-base64.", + ]); + } + try { + switch (request.operation) { + case cultMeshProviderSessionOperations.register: + return await this.#register(request, session); + case cultMeshProviderSessionOperations.renew: + return await this.#renew(request, session); + case cultMeshProviderSessionOperations.publicationPut: + return await this.#publicationPut(request, session); + case cultMeshProviderSessionOperations.publicationDelete: + return await this.#publicationDelete(request, session); + case cultMeshProviderSessionOperations.receiptPut: + return await this.#receiptPut(request, session); + case cultMeshProviderSessionOperations.withdraw: + return await this.#withdraw(request, session); + default: + return this.#response(request, "invalid", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + `Unsupported provider-session operation ${request.operation}.`, + ]); + } + } catch (error) { + if (error instanceof BrokerInfrastructureError) throw error.cause; + return this.#response(request, error instanceof BrokerStatusError ? error.status : "invalid", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + error instanceof Error ? error.message : String(error), + ]); + } + } + + public sessionClosed(session: CultMeshRudpServerSession): void { + if ((this.#inFlightBySession.get(session.sessionId) ?? 0) > 0) { + this.#closedSessions.add(session.sessionId); + } + for (const leaseId of this.#sessionLeases.get(session.sessionId) ?? []) { + const record = this.#leases.get(leaseId); + if (record?.session?.sessionId === session.sessionId) record.session = undefined; + } + this.#sessionLeases.delete(session.sessionId); + } + + public enqueueCommand(command: CultMeshProviderCommandWire): void { + requireText(command.commandId, "commandId"); + requireText(command.providerId, "providerId"); + requireText(command.serviceInstanceId, "serviceInstanceId"); + const completed = this.#receipts.get(command.commandId); + if (completed) { + if (completed.commandKind !== command.commandKind || completed.providerId !== command.providerId || completed.serviceInstanceId !== command.serviceInstanceId) { + throw new Error(`Command id ${command.commandId} is already completed for another command transaction.`); + } + return; + } + const existing = this.#commands.get(command.commandId); + if (existing && !wireEquivalent(existing, command)) { + throw new Error(`Command id ${command.commandId} is already retained for another command transaction.`); + } + this.#commands.set(command.commandId, existing ?? command); + for (const record of this.#leases.values()) { + if (!this.#isActive(record)) continue; + if (record.identity.providerId !== command.providerId || record.identity.serviceInstanceId !== command.serviceInstanceId) continue; + this.#sendCommand(record, command); + } + } + + public get activeLeaseCount(): number { + return [...this.#leases.values()].filter(record => this.#isActive(record)).length; + } + + public async expireLeases(): Promise { + const work = this.#work.then(() => this.#expireLeases()); + this.#work = work.then(() => undefined, () => undefined); + await work; + } + + async #expireLeases(): Promise { + const now = this.#clock.now().getTime(); + for (const [leaseId, record] of [...this.#leases]) { + if (Date.parse(record.lease.expiresAtUtc) > now) continue; + await this.#options.deletePublications(record.identity, publicationEntries(record)); + this.#releasePublicationOwners(record); + this.#removeLease(leaseId, record); + } + } + + async #register(request: CultNetOperationRequestMessage, session: CultMeshRudpServerSession): Promise { + expectSchema(request, cultMeshProviderSessionSchemas.registration); + const identity = decodeProviderSessionPayload(request.payload); + validateRegistration(identity); + if (!await infrastructure(() => this.#options.authorizeRegistration(identity, session))) { + return this.#response(request, "denied", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + "The CultNet session does not authorize this provider identity.", + ]); + } + if (this.#closedSessions.has(session.sessionId)) { + return this.#response(request, "denied", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + "The physical provider session closed while registration authority was being checked.", + ]); + } + const identityKey = identityTuple(identity); + const previousLeaseId = this.#identityLeases.get(identityKey); + let publications = new Map(); + if (previousLeaseId) { + const previous = this.#leases.get(previousLeaseId); + if (previous) { + publications = previous.publications; + this.#removeLease(previousLeaseId, previous); + } + } + const lease = this.#createLease(identity, identity.requestedLeaseDurationMs); + const record: LeaseRecord = { identity, lease, session, publications }; + this.#leases.set(lease.leaseId, record); + this.#identityLeases.set(identityKey, lease.leaseId); + this.#attachSession(session, lease.leaseId); + this.#replayCommands(record); + return this.#response(request, "ok", cultMeshProviderSessionSchemas.lease, lease); + } + + async #renew(request: CultNetOperationRequestMessage, session: CultMeshRudpServerSession): Promise { + expectSchema(request, cultMeshProviderSessionSchemas.leaseRenewal); + const renewal = decodeProviderSessionPayload(request.payload); + const current = this.#requireLease(renewal.leaseId, session); + const lease = this.#createLease(current.identity, renewal.requestedLeaseDurationMs); + const replacement: LeaseRecord = { ...current, lease, session }; + this.#removeLease(renewal.leaseId, current); + this.#leases.set(lease.leaseId, replacement); + this.#identityLeases.set(identityTuple(current.identity), lease.leaseId); + this.#attachSession(session, lease.leaseId); + return this.#response(request, "ok", cultMeshProviderSessionSchemas.lease, lease); + } + + async #publicationPut(request: CultNetOperationRequestMessage, session: CultMeshRudpServerSession): Promise { + expectSchema(request, cultMeshProviderSessionSchemas.publicationPut); + const mutation = decodeProviderSessionPayload(request.payload); + const record = this.#requireLease(mutation.leaseId, session); + requireText(mutation.publicationId, "publicationId"); + validateDocument(mutation.document); + const previous = record.publications.get(mutation.publicationId); + if (previous && (previous.schemaId !== mutation.document.schemaId || previous.recordKey !== mutation.document.recordKey)) { + return this.#response(request, "conflict", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + `Publication ${mutation.publicationId} already owns ${previous.schemaId}:${previous.recordKey}. Delete it before changing its tuple.`, + ]); + } + const tuple = documentTuple(mutation.document); + const owner = this.#publicationOwners.get(tuple); + const ownerIdentity = identityTuple(record.identity); + if (owner && (owner.identityKey !== ownerIdentity || owner.publicationId !== mutation.publicationId)) { + return this.#response(request, "conflict", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + `Publication tuple ${mutation.document.schemaId}:${mutation.document.recordKey} is already owned.`, + ]); + } + const normalizedDocument: CultNetRawDocumentRecord = { + ...mutation.document, + sourceRuntimeId: record.identity.serviceInstanceId, + sourceAgentId: record.identity.providerId, + sourceRole: "provider", + }; + await infrastructure(() => this.#options.acceptPublication(record.identity, mutation.publicationId, normalizedDocument)); + record.publications.set(mutation.publicationId, normalizedDocument); + this.#publicationOwners.set(tuple, { identityKey: ownerIdentity, publicationId: mutation.publicationId }); + return this.#accepted(request, record.lease.leaseId, { publicationId: mutation.publicationId }); + } + + async #publicationDelete(request: CultNetOperationRequestMessage, session: CultMeshRudpServerSession): Promise { + expectSchema(request, cultMeshProviderSessionSchemas.publicationDelete); + const mutation = decodeProviderSessionPayload(request.payload); + const record = this.#requireLease(mutation.leaseId, session); + const owned = record.publications.get(mutation.publicationId); + if (!owned || owned.schemaId !== mutation.schemaId || owned.recordKey !== mutation.recordKey) { + return this.#response(request, "denied", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + `Publication ${mutation.publicationId} is not owned by this lease with the supplied schema and key.`, + ]); + } + await infrastructure(() => this.#options.deletePublications(record.identity, [{ publicationId: mutation.publicationId, document: owned }])); + record.publications.delete(mutation.publicationId); + this.#publicationOwners.delete(documentTuple(owned)); + return this.#accepted(request, record.lease.leaseId, { publicationId: mutation.publicationId }); + } + + async #receiptPut(request: CultNetOperationRequestMessage, session: CultMeshRudpServerSession): Promise { + expectSchema(request, cultMeshProviderSessionSchemas.receiptPut); + const mutation = decodeProviderSessionPayload(request.payload); + const record = this.#requireLease(mutation.leaseId, session); + const receipt = mutation.receipt; + validateReceipt(receipt); + if (receipt.providerId !== record.identity.providerId || receipt.serviceInstanceId !== record.identity.serviceInstanceId) { + return this.#response(request, "denied", cultMeshProviderSessionSchemas.mutationAcceptance, {}, ["Receipt identity does not match its lease."]); + } + const previousReceipt = this.#receipts.get(receipt.commandId); + if (previousReceipt) { + if (!wireEquivalent(previousReceipt, receipt)) { + return this.#response(request, "conflict", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + `Command ${receipt.commandId} already has a different accepted receipt.`, + ]); + } + return this.#accepted(request, record.lease.leaseId, { commandId: receipt.commandId, receiptId: receipt.receiptId }); + } + const command = this.#commands.get(receipt.commandId); + if (!command || command.commandKind !== receipt.commandKind || command.providerId !== receipt.providerId || command.serviceInstanceId !== receipt.serviceInstanceId) { + return this.#response(request, "denied", cultMeshProviderSessionSchemas.mutationAcceptance, {}, [ + `Receipt ${receipt.receiptId} does not match a retained command for this provider generation.`, + ]); + } + await infrastructure(() => this.#options.acceptReceipt(record.identity, receipt)); + this.#receipts.set(receipt.commandId, receipt); + this.#commands.delete(receipt.commandId); + return this.#accepted(request, record.lease.leaseId, { commandId: receipt.commandId, receiptId: receipt.receiptId }); + } + + async #withdraw(request: CultNetOperationRequestMessage, session: CultMeshRudpServerSession): Promise { + expectSchema(request, cultMeshProviderSessionSchemas.withdrawal); + const mutation = decodeProviderSessionPayload(request.payload); + const record = this.#requireLease(mutation.leaseId, session); + await infrastructure(() => this.#options.deletePublications(record.identity, publicationEntries(record))); + this.#releasePublicationOwners(record); + this.#removeLease(mutation.leaseId, record); + return this.#accepted(request, mutation.leaseId); + } + + #requireLease(leaseId: string, session: CultMeshRudpServerSession): LeaseRecord { + requireText(leaseId, "leaseId"); + const record = this.#leases.get(leaseId); + if (!record || !this.#isActive(record)) throw new BrokerStatusError("expired", `Provider lease ${leaseId} is expired or fenced.`); + if (record.session?.sessionId !== session.sessionId) throw new BrokerStatusError("denied", `Provider lease ${leaseId} belongs to another physical session.`); + return record; + } + + #isActive(record: LeaseRecord): boolean { + return Date.parse(record.lease.expiresAtUtc) > this.#clock.now().getTime(); + } + + #createLease(identity: CultMeshProviderRegistrationWire, requestedMs: number): CultMeshProviderLeaseWire { + if (!Number.isFinite(requestedMs) || requestedMs <= 0) throw new Error("requestedLeaseDurationMs must be positive."); + const durationMs = Math.min(requestedMs, this.#options.maximumLeaseDurationMs ?? 120_000); + const now = this.#clock.now(); + return { + providerId: identity.providerId, + serviceInstanceId: identity.serviceInstanceId, + endpointId: identity.endpointId, + verseId: identity.verseId, + leaseId: this.#options.createLeaseId?.() ?? `${this.#options.runtimeId}:lease:${++this.#leaseSequence}`, + validFromUtc: now.toISOString(), + expiresAtUtc: new Date(now.getTime() + durationMs).toISOString(), + }; + } + + #attachSession(session: CultMeshRudpServerSession, leaseId: string): void { + let leases = this.#sessionLeases.get(session.sessionId); + if (!leases) this.#sessionLeases.set(session.sessionId, leases = new Set()); + leases.add(leaseId); + } + + #removeLease(leaseId: string, record: LeaseRecord): void { + this.#leases.delete(leaseId); + if (this.#identityLeases.get(identityTuple(record.identity)) === leaseId) this.#identityLeases.delete(identityTuple(record.identity)); + this.#sessionLeases.get(record.session?.sessionId ?? "")?.delete(leaseId); + } + + #releasePublicationOwners(record: LeaseRecord): void { + const ownerIdentity = identityTuple(record.identity); + for (const [publicationId, document] of record.publications) { + const tuple = documentTuple(document); + const owner = this.#publicationOwners.get(tuple); + if (owner?.identityKey === ownerIdentity && owner.publicationId === publicationId) this.#publicationOwners.delete(tuple); + } + } + + #replayCommands(record: LeaseRecord): void { + for (const command of this.#commands.values()) { + if (command.providerId === record.identity.providerId && command.serviceInstanceId === record.identity.serviceInstanceId) this.#sendCommand(record, command); + } + } + + #sendCommand(record: LeaseRecord, command: CultMeshProviderCommandWire): void { + if (!record.session) return; + const message: CultNetDocumentPutRawMessage = { + schemaVersion: "cultnet.document_put_raw.v0", + messageId: `${this.#options.runtimeId}:command:${command.commandId}`, + document: { + schemaId: cultMeshProviderSessionSchemas.command, + recordKey: `${command.providerId}/${command.serviceInstanceId}/${command.commandId}`, + storedAt: this.#clock.now().toISOString(), + payloadEncoding: "messagepack", + payload: encode(command), + sourceRuntimeId: this.#options.runtimeId, + sourceRole: "provider-session-broker", + }, + }; + record.session.send(message); + } + + #accepted(request: CultNetOperationRequestMessage, leaseId: string, extra: Record = {}): CultNetOperationResponseMessage { + return this.#response(request, "ok", cultMeshProviderSessionSchemas.mutationAcceptance, { + acceptedAtUtc: this.#clock.now().toISOString(), + leaseId, + ...extra, + }); + } + + #response( + request: CultNetOperationRequestMessage, + status: CultMeshProviderOperationStatus, + payloadSchema: string, + payload: unknown, + diagnostics?: string[], + ): CultNetOperationResponseMessage { + const response: CultNetOperationResponseMessage = { + schemaVersion: "cultnet.operation_response.v0", + messageId: request.messageId, + serviceId: request.serviceId, + operation: request.operation, + status, + payloadSchema, + payloadEncoding: "messagepack-base64", + payload: encodeProviderSessionPayload(payload), + sourceRuntimeId: this.#options.runtimeId, + }; + if (diagnostics) response.diagnostics = diagnostics; + return response; + } +} + +class BrokerStatusError extends Error { + public constructor(public readonly status: CultMeshProviderOperationStatus, message: string) { + super(message); + } +} + +class BrokerInfrastructureError extends Error { + public constructor(public readonly cause: unknown) { + super(cause instanceof Error ? cause.message : String(cause)); + } +} + +async function infrastructure(action: () => T | Promise): Promise { + try { + return await action(); + } catch (error) { + throw new BrokerInfrastructureError(error); + } +} + +function expectSchema(request: CultNetOperationRequestMessage, schema: string): void { + if (request.payloadSchema !== schema) throw new Error(`Operation ${request.operation} requires payload schema ${schema}.`); +} + +function validateRegistration(value: CultMeshProviderRegistrationWire): void { + for (const field of ["providerId", "serviceInstanceId", "endpointId", "verseId"] as const) requireText(value[field], field); + if (!Number.isFinite(value.requestedLeaseDurationMs) || value.requestedLeaseDurationMs <= 0) throw new Error("requestedLeaseDurationMs must be positive."); +} + +function validateDocument(document: CultNetRawDocumentRecord): void { + requireText(document?.schemaId, "document.schemaId"); + requireText(document?.recordKey, "document.recordKey"); + if (document.payloadEncoding !== "messagepack" || !(document.payload instanceof Uint8Array)) throw new Error("Provider publications must carry a raw MessagePack document."); +} + +function validateReceipt(receipt: CultMeshProviderCommandReceiptWire): void { + requireText(receipt?.receiptId, "receipt.receiptId"); + requireText(receipt?.commandId, "receipt.commandId"); + requireText(receipt?.commandKind, "receipt.commandKind"); + requireText(receipt?.providerId, "receipt.providerId"); + requireText(receipt?.serviceInstanceId, "receipt.serviceInstanceId"); + if (receipt.state !== "applied" && receipt.state !== "rejected" && receipt.state !== "failed") throw new Error("CultMesh provider-session receipt.state is invalid."); + if (!Number.isFinite(Date.parse(receipt.completedAtUtc))) throw new Error("CultMesh provider-session receipt.completedAtUtc must be RFC3339."); +} + +function identityTuple(identity: CultMeshProviderRegistrationWire): string { + return `${identity.verseId}\u0000${identity.providerId}\u0000${identity.serviceInstanceId}\u0000${identity.endpointId}`; +} + +function documentTuple(document: Pick): string { + return `${document.schemaId}\u0000${document.recordKey}`; +} + +function wireEquivalent(left: unknown, right: unknown): boolean { + return Buffer.from(encode(left)).equals(Buffer.from(encode(right))); +} + +function publicationEntries(record: LeaseRecord): readonly { + publicationId: string; + document: Pick; +}[] { + return [...record.publications].map(([publicationId, document]) => ({ publicationId, document })); +} + +function requireText(value: unknown, name: string): asserts value is string { + if (typeof value !== "string" || value.trim().length === 0) throw new Error(`CultMesh provider-session ${name} must be non-empty.`); +} diff --git a/packages/cultmesh-ts/src/provider-session-wire.ts b/packages/cultmesh-ts/src/provider-session-wire.ts new file mode 100644 index 00000000..e89a3148 --- /dev/null +++ b/packages/cultmesh-ts/src/provider-session-wire.ts @@ -0,0 +1,207 @@ +import { decode, encode } from "@msgpack/msgpack"; +import type { CultNetRawDocumentRecord } from "cultnet-ts"; + +export const CULTMESH_PROVIDER_SESSION_SERVICE_ID = "gamecult.mesh.provider_session"; + +export const cultMeshProviderSessionOperations = { + register: "provider.register", + renew: "provider.renew", + publicationPut: "provider.publication.put", + publicationDelete: "provider.publication.delete", + receiptPut: "provider.receipt.put", + withdraw: "provider.withdraw", +} as const; + +export const cultMeshProviderSessionSchemas = { + registration: "gamecult.mesh.provider_registration.v1", + lease: "gamecult.mesh.provider_lease.v1", + leaseRenewal: "gamecult.mesh.provider_lease_renewal.v1", + publicationPut: "gamecult.mesh.provider_publication_put.v1", + publicationDelete: "gamecult.mesh.provider_publication_delete.v1", + command: "gamecult.mesh.provider_command.v1", + receiptPut: "gamecult.mesh.provider_receipt_put.v1", + withdrawal: "gamecult.mesh.provider_withdrawal.v1", + mutationAcceptance: "gamecult.mesh.provider_mutation_acceptance.v1", +} as const; + +export type CultMeshProviderOperationStatus = + | "ok" + | "conflict" + | "expired" + | "denied" + | "invalid"; + +/** + * Transport evidence carried by a provider's RUDP Connect packet. + * + * `clientSessionId` distinguishes an actual reconnect from retransmission of + * the same Connect packet. The token remains authorization evidence only; it + * is not a transport-session identifier. + */ +export interface CultMeshProviderConnectEvidenceWire { + clientSessionId: string; + sessionToken: string | null; +} + +export interface CultMeshProviderRegistrationWire { + providerId: string; + serviceInstanceId: string; + endpointId: string; + verseId: string; + requestedLeaseDurationMs: number; + authorityLeaseId?: string; +} + +export interface CultMeshProviderLeaseWire { + providerId: string; + serviceInstanceId: string; + endpointId: string; + verseId: string; + leaseId: string; + validFromUtc: string; + expiresAtUtc: string; +} + +export interface CultMeshProviderLeaseRenewalWire { + leaseId: string; + requestedLeaseDurationMs: number; +} + +export interface CultMeshProviderPublicationPutWire { + leaseId: string; + publicationId: string; + document: CultNetRawDocumentRecord; +} + +export interface CultMeshProviderPublicationDeleteWire { + leaseId: string; + publicationId: string; + schemaId: string; + recordKey: string; +} + +export interface CultMeshProviderCommandWire { + commandId: string; + commandKind: string; + providerId: string; + serviceInstanceId: string; + payload: unknown; +} + +export type CultMeshProviderReceiptStateWire = "applied" | "rejected" | "failed"; + +export interface CultMeshProviderCommandReceiptWire { + receiptId: string; + commandId: string; + commandKind: string; + providerId: string; + serviceInstanceId: string; + state: CultMeshProviderReceiptStateWire; + completedAtUtc: string; + result?: unknown; + error?: string; +} + +export interface CultMeshProviderReceiptPutWire { + leaseId: string; + receipt: CultMeshProviderCommandReceiptWire; +} + +export interface CultMeshProviderWithdrawalWire { + leaseId: string; +} + +export interface CultMeshProviderMutationAcceptanceWire { + acceptedAtUtc: string; + leaseId?: string; + publicationId?: string; + commandId?: string; + receiptId?: string; +} + +export function encodeProviderSessionPayload(value: unknown): string { + return Buffer.from(encode(value)).toString("base64"); +} + +export function decodeProviderSessionPayload(payload: string): T { + if (typeof payload !== "string" || payload.length === 0) { + throw new Error("CultMesh provider-session payload must be non-empty MessagePack base64."); + } + return decode(Buffer.from(payload, "base64")) as T; +} + +export function encodeProviderConnectEvidence( + evidence: CultMeshProviderConnectEvidenceWire, +): Uint8Array { + assertProviderConnectEvidence(evidence); + return encode(evidence); +} + +export function decodeProviderConnectEvidence( + payload: Uint8Array, +): CultMeshProviderConnectEvidenceWire { + const evidence = decode(payload) as unknown; + assertProviderConnectEvidence(evidence); + return evidence; +} + +export function assertProviderConnectEvidence( + value: unknown, +): asserts value is CultMeshProviderConnectEvidenceWire { + const evidence = requireObject(value, "provider Connect evidence"); + requireText(evidence.clientSessionId, "clientSessionId"); + if (evidence.sessionToken !== null) { + requireText(evidence.sessionToken, "sessionToken"); + } +} + +export function decodeProviderCommandDocument(document: CultNetRawDocumentRecord): CultMeshProviderCommandWire { + if (document.schemaId !== cultMeshProviderSessionSchemas.command) { + throw new Error(`Expected ${cultMeshProviderSessionSchemas.command}, received ${document.schemaId}.`); + } + if (document.payloadEncoding !== "messagepack") { + throw new Error(`Provider command ${document.recordKey} must use MessagePack.`); + } + const command = decode(document.payload) as Partial; + requireText(command.commandId, "commandId"); + requireText(command.commandKind, "commandKind"); + requireText(command.providerId, "providerId"); + requireText(command.serviceInstanceId, "serviceInstanceId"); + return command as CultMeshProviderCommandWire; +} + +export function assertProviderLease(value: unknown): asserts value is CultMeshProviderLeaseWire { + const lease = requireObject(value, "provider lease"); + requireText(lease.providerId, "providerId"); + requireText(lease.serviceInstanceId, "serviceInstanceId"); + requireText(lease.endpointId, "endpointId"); + requireText(lease.verseId, "verseId"); + requireText(lease.leaseId, "leaseId"); + requireTimestamp(lease.validFromUtc, "validFromUtc"); + requireTimestamp(lease.expiresAtUtc, "expiresAtUtc"); +} + +export function assertMutationAcceptance(value: unknown): asserts value is CultMeshProviderMutationAcceptanceWire { + const acceptance = requireObject(value, "provider mutation acceptance"); + requireTimestamp(acceptance.acceptedAtUtc, "acceptedAtUtc"); +} + +function requireObject(value: unknown, name: string): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error(`CultMesh ${name} must be a MessagePack map.`); + } + return value as Record; +} + +function requireText(value: unknown, name: string): asserts value is string { + if (typeof value !== "string" || value.trim().length === 0) { + throw new Error(`CultMesh provider-session ${name} must be non-empty.`); + } +} + +function requireTimestamp(value: unknown, name: string): asserts value is string { + requireText(value, name); + if (!Number.isFinite(Date.parse(value))) { + throw new Error(`CultMesh provider-session ${name} must be an RFC3339 timestamp.`); + } +} diff --git a/packages/cultmesh-ts/src/provider-session.ts b/packages/cultmesh-ts/src/provider-session.ts new file mode 100644 index 00000000..f63d222c --- /dev/null +++ b/packages/cultmesh-ts/src/provider-session.ts @@ -0,0 +1,884 @@ +export interface CultMeshProviderIdentity { + readonly providerId: string; + readonly serviceInstanceId: string; + readonly endpointId: string; + readonly verseId: string; +} + +export interface CultMeshProviderLease { + readonly leaseId: string; + readonly expiresAt: Date; +} + +export interface CultMeshProviderPublication { + readonly publicationId: string; + readonly documentType: string; + readonly schemaId: string; + readonly recordKey: string; + readonly value: TValue; +} + +export interface CultMeshProviderCommand { + readonly commandId: string; + readonly commandKind: string; + readonly providerId: string; + readonly serviceInstanceId: string; + readonly payload: TPayload; +} + +export type CultMeshProviderReceiptState = "applied" | "rejected" | "failed"; + +export interface CultMeshProviderCommandReceipt { + readonly receiptId: string; + readonly commandId: string; + readonly commandKind: string; + readonly providerId: string; + readonly serviceInstanceId: string; + readonly state: CultMeshProviderReceiptState; + readonly completedAt: Date; + readonly result?: TResult; + readonly error?: string; +} + +export interface CultMeshProviderCommandOutcome { + readonly state: CultMeshProviderReceiptState; + readonly result?: TResult; + readonly error?: string; +} + +export interface CultMeshProviderCommandContext { + readonly identity: CultMeshProviderIdentity; +} + +export type CultMeshProviderCommandHandler = ( + command: CultMeshProviderCommand, + context: CultMeshProviderCommandContext, +) => Promise; + +export interface CultMeshProviderReceiptStore { + get(commandId: string): Promise; + put(receipt: CultMeshProviderCommandReceipt): Promise; + listPending(): Promise; + markPublished(receiptId: string): Promise; +} + +export class CultMeshMemoryProviderReceiptStore implements CultMeshProviderReceiptStore { + readonly #receipts = new Map(); + readonly #pendingReceiptIds = new Set(); + + public async get(commandId: string): Promise { + return this.#receipts.get(commandId); + } + + public async put(receipt: CultMeshProviderCommandReceipt): Promise { + this.#receipts.set(receipt.commandId, receipt); + this.#pendingReceiptIds.add(receipt.receiptId); + } + + public async listPending(): Promise { + return [...this.#receipts.values()] + .filter(receipt => this.#pendingReceiptIds.has(receipt.receiptId)) + .sort((left, right) => left.receiptId.localeCompare(right.receiptId)); + } + + public async markPublished(receiptId: string): Promise { + this.#pendingReceiptIds.delete(receiptId); + } +} + +export interface CultMeshProviderRegistration { + readonly identity: CultMeshProviderIdentity; + readonly requestedLeaseDurationMs: number; +} + +export interface CultMeshProviderWithdrawal { + readonly identity: CultMeshProviderIdentity; + readonly leaseId: string; + readonly publicationIds: readonly string[]; +} + +export type CultMeshProviderCommandListener = ( + command: CultMeshProviderCommand, +) => void | Promise; + +export type CultMeshProviderUnsubscribe = () => void | Promise; + +export interface CultMeshProviderConnection { + register( + registration: CultMeshProviderRegistration, + signal: AbortSignal, + ): Promise; + renew(lease: CultMeshProviderLease): Promise; + publish( + publication: CultMeshProviderPublication, + lease: CultMeshProviderLease, + ): Promise; + withdrawPublication(publicationId: string, lease: CultMeshProviderLease): Promise; + watchCommands(listener: CultMeshProviderCommandListener): CultMeshProviderUnsubscribe; + publishReceipt( + receipt: CultMeshProviderCommandReceipt, + lease: CultMeshProviderLease, + ): Promise; + withdraw(withdrawal: CultMeshProviderWithdrawal): Promise; + close(): void | Promise; +} + +export interface CultMeshProviderTransport { + connect( + identity: CultMeshProviderIdentity, + signal: AbortSignal, + ): Promise; +} + +export interface CultMeshProviderScheduledTask { + cancel(): void; +} + +export interface CultMeshProviderScheduler { + now(): Date; + schedule(delayMs: number, action: () => void | Promise): CultMeshProviderScheduledTask; +} + +export class CultMeshSystemProviderScheduler implements CultMeshProviderScheduler { + public now(): Date { + return new Date(); + } + + public schedule(delayMs: number, action: () => void | Promise): CultMeshProviderScheduledTask { + const timer = setTimeout(() => { + void Promise.resolve(action()).catch(() => undefined); + }, Math.max(0, delayMs)); + return { cancel: () => clearTimeout(timer) }; + } +} + +export type CultMeshProviderSessionStatus = + | "stopped" + | "connecting" + | "active" + | "degraded" + | "reconnecting" + | "withdrawing"; + +export interface CultMeshProviderSessionState { + readonly status: CultMeshProviderSessionStatus; + readonly identity: CultMeshProviderIdentity; + readonly reconnectAttempt: number; + readonly leaseId?: string; + readonly leaseExpiresAt?: Date; + readonly lastError?: string; +} + +export interface CultMeshProviderSessionOptions { + readonly identity: CultMeshProviderIdentity; + readonly transport: CultMeshProviderTransport; + readonly publications?: Iterable; + readonly commandHandlers?: Readonly>; + readonly receiptStore: CultMeshProviderReceiptStore; + readonly scheduler?: CultMeshProviderScheduler; + readonly onObserverError?: (error: unknown) => void; + readonly leaseDurationMs?: number; + readonly renewalLeadMs?: number; + readonly reconnectBaseDelayMs?: number; + readonly reconnectMaxDelayMs?: number; +} + +export class CultMeshProviderSession { + readonly #identity: CultMeshProviderIdentity; + readonly #transport: CultMeshProviderTransport; + readonly #receiptStore: CultMeshProviderReceiptStore; + readonly #scheduler: CultMeshProviderScheduler; + readonly #onObserverError: (error: unknown) => void; + readonly #leaseDurationMs: number; + readonly #renewalLeadMs: number; + readonly #reconnectBaseDelayMs: number; + readonly #reconnectMaxDelayMs: number; + readonly #publications = new Map(); + readonly #handlers = new Map(); + readonly #subscribers = new Set<(state: CultMeshProviderSessionState) => void>(); + readonly #inFlightCommands = new Map; + }>(); + #state: CultMeshProviderSessionState; + #connection?: CultMeshProviderConnection; + #lease?: CultMeshProviderLease; + #unsubscribeCommands?: CultMeshProviderUnsubscribe; + #scheduled?: CultMeshProviderScheduledTask; + #abort?: AbortController; + #running = false; + #generation = 0; + #reconnectAttempt = 0; + #publicationWork: Promise = Promise.resolve(); + #startWork?: Promise; + #stopWork?: Promise; + #lossWork?: { generation: number; work: Promise }; + + public constructor(options: CultMeshProviderSessionOptions) { + this.#identity = validateIdentity(options.identity); + this.#transport = options.transport; + if (!options.receiptStore) { + throw new Error( + "CultMesh provider sessions require an explicit receiptStore so command receipts survive the provider lifecycle.", + ); + } + this.#receiptStore = options.receiptStore; + this.#scheduler = options.scheduler ?? new CultMeshSystemProviderScheduler(); + this.#onObserverError = options.onObserverError ?? (() => undefined); + this.#leaseDurationMs = positive(options.leaseDurationMs ?? 30_000, "leaseDurationMs"); + this.#renewalLeadMs = nonNegative(options.renewalLeadMs ?? 10_000, "renewalLeadMs"); + if (this.#renewalLeadMs >= this.#leaseDurationMs) { + throw new Error("CultMesh provider renewalLeadMs must be less than leaseDurationMs."); + } + this.#reconnectBaseDelayMs = positive( + options.reconnectBaseDelayMs ?? 250, + "reconnectBaseDelayMs", + ); + this.#reconnectMaxDelayMs = positive( + options.reconnectMaxDelayMs ?? 10_000, + "reconnectMaxDelayMs", + ); + if (this.#reconnectMaxDelayMs < this.#reconnectBaseDelayMs) { + throw new Error("CultMesh provider reconnectMaxDelayMs must not be less than reconnectBaseDelayMs."); + } + for (const publication of options.publications ?? []) { + this.#publications.set(validatePublication(publication).publicationId, publication); + } + for (const [kind, handler] of Object.entries(options.commandHandlers ?? {})) { + this.setCommandHandler(kind, handler); + } + this.#state = { + status: "stopped", + identity: this.#identity, + reconnectAttempt: 0, + }; + } + + public get identity(): CultMeshProviderIdentity { + return this.#identity; + } + + public get state(): CultMeshProviderSessionState { + return this.#state; + } + + public get publications(): readonly CultMeshProviderPublication[] { + return [...this.#publications.values()].sort((left, right) => + left.publicationId.localeCompare(right.publicationId), + ); + } + + public watchState(callback: (state: CultMeshProviderSessionState) => void): () => void { + this.#subscribers.add(callback); + try { + callback(this.#state); + } catch (error) { + this.#reportObserverError(error); + } + return () => this.#subscribers.delete(callback); + } + + public setCommandHandler(kind: string, handler: CultMeshProviderCommandHandler): void { + this.#handlers.set(required(kind, "command kind"), handler); + } + + public removeCommandHandler(kind: string): boolean { + return this.#handlers.delete(required(kind, "command kind")); + } + + public upsertPublication(publication: CultMeshProviderPublication): Promise { + const valid = validatePublication(publication); + this.#publications.set(valid.publicationId, valid); + if (this.#connection && this.#lease) { + return this.#enqueuePublication(() => this.#deliverPublication(valid, this.#generation)); + } + return Promise.resolve(); + } + + public async removePublication(publicationId: string): Promise { + const id = required(publicationId, "publicationId"); + const removed = this.#publications.delete(id); + if (removed && this.#connection && this.#lease) { + await this.#enqueuePublication(() => this.#withdrawPublication(id, this.#generation)); + } + return removed; + } + + public start(): Promise { + if (this.#stopWork) { + return Promise.reject(new Error("CultMesh provider cannot start while shutdown is in progress.")); + } + if (this.#startWork) return this.#startWork; + if (this.#running) return Promise.resolve(); + let tracked!: Promise; + tracked = Promise.resolve().then(() => this.#start()).finally(() => { + if (this.#startWork === tracked) this.#startWork = undefined; + }); + this.#startWork = tracked; + return tracked; + } + + async #start(): Promise { + this.#running = true; + this.#reconnectAttempt = 0; + const generation = ++this.#generation; + this.#abort = new AbortController(); + await this.#connect(generation, false); + } + + public stop(): Promise { + if (this.#stopWork) return this.#stopWork; + if (!this.#running && !this.#startWork && this.#state.status === "stopped") { + return Promise.resolve(); + } + let tracked!: Promise; + tracked = Promise.resolve().then(() => this.#stop()).finally(() => { + if (this.#stopWork === tracked) this.#stopWork = undefined; + }); + this.#stopWork = tracked; + return tracked; + } + + async #stop(): Promise { + this.#running = false; + const generation = ++this.#generation; + this.#cancelScheduled(); + this.#abort?.abort(); + this.#setState("withdrawing"); + const connection = this.#connection; + const lease = this.#lease; + const starting = this.#startWork; + const losing = this.#lossWork?.work; + this.#connection = undefined; + this.#lease = undefined; + const errors: unknown[] = []; + try { + await this.#unsubscribe(); + } catch (error) { + errors.push(error); + } + try { + await this.#publicationWork; + } catch (error) { + errors.push(error); + } + for (const lifecycleWork of [starting, losing]) { + if (!lifecycleWork) continue; + try { + await lifecycleWork; + } catch (error) { + errors.push(error); + } + } + this.#cancelScheduled(); + const commandWork = [...this.#inFlightCommands.values()].map(value => value.work); + const commandResults = await Promise.allSettled(commandWork); + for (const result of commandResults) { + if (result.status === "rejected") errors.push(result.reason); + } + if (connection && lease) { + try { + await connection.withdraw({ + identity: this.#identity, + leaseId: lease.leaseId, + publicationIds: this.publications.map(value => value.publicationId), + }); + } catch (error) { + errors.push(error); + } + } + if (connection) { + try { + await connection.close(); + } catch (error) { + errors.push(error); + } + } + if (generation === this.#generation) this.#setState("stopped"); + if (errors.length > 0) { + throw new AggregateError(errors, "CultMesh provider shutdown completed with cleanup failures."); + } + } + + async #connect(generation: number, reconnecting: boolean): Promise { + if (!this.#isCurrent(generation)) return; + this.#scheduled = undefined; + this.#setState(reconnecting ? "reconnecting" : "connecting"); + try { + const connection = await this.#transport.connect(this.#identity, this.#abort!.signal); + if (!this.#isCurrent(generation)) { + await connection.close(); + return; + } + this.#connection = connection; + const lease = validateLease( + await connection.register({ + identity: this.#identity, + requestedLeaseDurationMs: this.#leaseDurationMs, + }, this.#abort!.signal), + this.#scheduler.now(), + ); + if (!this.#isCurrent(generation)) { + await connection.close(); + return; + } + this.#lease = lease; + const initialPublications = this.publications; + await this.#enqueuePublication(async () => { + for (const publication of initialPublications) { + if (!this.#isCurrent(generation)) return; + requireUnexpiredLease(lease, this.#scheduler.now()); + await connection.publish(publication, lease); + } + }); + if (!this.#isCurrent(generation)) return; + const readyLease = await this.#renewIfNeeded(connection, lease, generation); + if (!readyLease || !this.#isCurrent(generation)) return; + this.#lease = readyLease; + this.#reconnectAttempt = 0; + const receiptsReady = await this.#drainPendingReceipts(connection, readyLease, generation); + if (!this.#isCurrent(generation)) return; + if (receiptsReady) { + this.#enableCommands(connection, generation); + this.#setState("active", undefined, readyLease); + } + this.#scheduleRenewal(generation, readyLease); + } catch (error) { + await this.#loseConnection(generation, error); + } + } + + #scheduleRenewal(generation: number, lease: CultMeshProviderLease): void { + if (!this.#isCurrent(generation)) return; + this.#scheduled?.cancel(); + const delay = Math.max( + 1, + lease.expiresAt.getTime() - this.#scheduler.now().getTime() - this.#renewalLeadMs, + ); + this.#scheduled = this.#scheduler.schedule(delay, () => this.#renew(generation)); + } + + async #renew(generation: number): Promise { + if (!this.#isCurrent(generation) || !this.#connection || !this.#lease) return; + this.#scheduled = undefined; + try { + let lease = validateLease( + await this.#connection.renew(this.#lease), + this.#scheduler.now(), + ); + if (!this.#isCurrent(generation)) return; + this.#lease = lease; + const receiptsReady = await this.#drainPendingReceipts(this.#connection, lease, generation); + if (!this.#isCurrent(generation)) return; + if (receiptsReady) { + lease = await this.#renewIfNeeded(this.#connection, lease, generation) ?? lease; + if (!this.#isCurrent(generation)) return; + this.#lease = lease; + this.#enableCommands(this.#connection, generation); + this.#setState("active", undefined, lease); + } + this.#scheduleRenewal(generation, lease); + } catch (error) { + await this.#loseConnection(generation, error); + } + } + + async #deliverPublication( + publication: CultMeshProviderPublication, + generation: number, + ): Promise { + const connection = this.#connection; + const lease = this.#lease; + if (!connection || !lease || !this.#isCurrent(generation)) return; + try { + requireUnexpiredLease(lease, this.#scheduler.now()); + await connection.publish(publication, lease); + } catch (error) { + await this.#loseConnection(generation, error); + } + } + + async #withdrawPublication(publicationId: string, generation: number): Promise { + const connection = this.#connection; + const lease = this.#lease; + if (!connection || !lease || !this.#isCurrent(generation)) return; + try { + requireUnexpiredLease(lease, this.#scheduler.now()); + await connection.withdrawPublication(publicationId, lease); + } catch (error) { + await this.#loseConnection(generation, error); + } + } + + async #receiveCommand(command: CultMeshProviderCommand, generation: number): Promise { + if (!this.#isCurrent(generation) || + command.providerId !== this.#identity.providerId || + command.serviceInstanceId !== this.#identity.serviceInstanceId) { + return; + } + try { + required(command.commandId, "commandId"); + required(command.commandKind, "commandKind"); + } catch (error) { + this.#setState("degraded", errorText(error), this.#lease); + return; + } + const inFlight = this.#inFlightCommands.get(command.commandId); + if (inFlight) { + if (!sameCommandIdentity(inFlight.command, command)) { + this.#setState( + "degraded", + `CultMesh command id '${command.commandId}' was reused with different identity while in flight.`, + this.#lease, + ); + return; + } + await inFlight.work; + return; + } + const work = this.#processCommand(command, generation); + const entry = { command, work }; + this.#inFlightCommands.set(command.commandId, entry); + try { + await work; + } finally { + if (this.#inFlightCommands.get(command.commandId) === entry) { + this.#inFlightCommands.delete(command.commandId); + } + } + } + + async #processCommand(command: CultMeshProviderCommand, generation: number): Promise { + let receipt: CultMeshProviderCommandReceipt; + try { + receipt = await this.#resolveCommand(command); + } catch (error) { + if (this.#isCurrent(generation)) { + await this.#degradeReceiptStore( + `Command receipt persistence failed: ${errorText(error)}`, + generation, + ); + } + return; + } + const connection = this.#connection; + const lease = this.#lease; + if (!connection || !lease || !this.#isCurrent(generation)) return; + try { + await connection.publishReceipt(receipt, lease); + } catch (error) { + await this.#loseConnection(generation, error); + return; + } + try { + await this.#receiptStore.markPublished(receipt.receiptId); + } catch (error) { + if (this.#isCurrent(generation)) { + await this.#degradeReceiptStore( + `Command receipt publication could not be committed: ${errorText(error)}`, + generation, + ); + } + } + } + + async #resolveCommand(command: CultMeshProviderCommand): Promise { + const prior = await this.#receiptStore.get(command.commandId); + if (prior) { + validateStoredReceipt(prior, this.#identity); + if (prior.commandKind !== command.commandKind) { + throw new Error(`CultMesh command id '${command.commandId}' was reused with different identity.`); + } + return prior; + } + const handler = this.#handlers.get(command.commandKind); + let outcome: CultMeshProviderCommandOutcome; + if (!handler) { + outcome = { state: "rejected", error: `No handler for '${command.commandKind}'.` }; + } else { + try { + outcome = await handler(command, { identity: this.#identity }); + validateOutcomeState(outcome?.state); + } catch (error) { + outcome = { state: "failed", error: errorText(error) }; + } + } + const receipt: CultMeshProviderCommandReceipt = { + receiptId: receiptId(this.#identity, command.commandId), + commandId: command.commandId, + commandKind: command.commandKind, + providerId: this.#identity.providerId, + serviceInstanceId: this.#identity.serviceInstanceId, + state: validateOutcomeState(outcome.state), + completedAt: this.#scheduler.now(), + result: outcome.result, + error: outcome.error, + }; + await this.#receiptStore.put(receipt); + return receipt; + } + + async #loseConnection(generation: number, error: unknown): Promise { + if (!this.#isCurrent(generation)) return; + const existing = this.#lossWork; + if (existing?.generation === generation) { + await existing.work; + return; + } + let tracked!: Promise; + tracked = this.#performConnectionLoss(generation, error).finally(() => { + if (this.#lossWork?.work === tracked) this.#lossWork = undefined; + }); + this.#lossWork = { generation, work: tracked }; + await tracked; + } + + async #performConnectionLoss(generation: number, error: unknown): Promise { + this.#cancelScheduled(); + const connection = this.#connection; + this.#connection = undefined; + this.#lease = undefined; + this.#reconnectAttempt++; + const failures = [errorText(error)]; + this.#setState("reconnecting", failures[0]); + try { + await this.#unsubscribe(); + } catch (cleanupError) { + failures.push(`unsubscribe failed: ${errorText(cleanupError)}`); + } + if (connection) { + try { + await connection.close(); + } catch (cleanupError) { + failures.push(`close failed: ${errorText(cleanupError)}`); + } + } + if (!this.#isCurrent(generation)) return; + this.#setState("reconnecting", failures.join("; ")); + const exponent = Math.max(0, this.#reconnectAttempt - 1); + const delay = Math.min( + this.#reconnectMaxDelayMs, + this.#reconnectBaseDelayMs * 2 ** exponent, + ); + this.#scheduled = this.#scheduler.schedule(delay, () => this.#connect(generation, true)); + } + + async #drainPendingReceipts( + connection: CultMeshProviderConnection, + lease: CultMeshProviderLease, + generation: number, + ): Promise { + let pending: readonly CultMeshProviderCommandReceipt[]; + try { + pending = await this.#receiptStore.listPending(); + } catch (error) { + if (this.#isCurrent(generation)) { + await this.#degradeReceiptStore( + `Pending command receipts could not be read: ${errorText(error)}`, + generation, + ); + } + return false; + } + for (const receipt of [...pending].sort((left, right) => left.receiptId.localeCompare(right.receiptId))) { + try { + validateStoredReceipt(receipt, this.#identity); + } catch (error) { + if (this.#isCurrent(generation)) { + await this.#degradeReceiptStore( + `Pending command receipt is invalid: ${errorText(error)}`, + generation, + ); + } + return false; + } + if (!this.#isCurrent(generation)) return false; + requireUnexpiredLease(lease, this.#scheduler.now()); + await connection.publishReceipt(receipt, lease); + try { + await this.#receiptStore.markPublished(receipt.receiptId); + } catch (error) { + if (this.#isCurrent(generation)) { + await this.#degradeReceiptStore( + `Command receipt publication could not be committed: ${errorText(error)}`, + generation, + ); + } + return false; + } + } + return true; + } + + async #renewIfNeeded( + connection: CultMeshProviderConnection, + lease: CultMeshProviderLease, + generation: number, + ): Promise { + if (lease.expiresAt.getTime() - this.#scheduler.now().getTime() > this.#renewalLeadMs) { + return lease; + } + const renewed = validateLease(await connection.renew(lease), this.#scheduler.now()); + return this.#isCurrent(generation) ? renewed : undefined; + } + + #enableCommands(connection: CultMeshProviderConnection, generation: number): void { + if (this.#unsubscribeCommands || !this.#isCurrent(generation)) return; + this.#unsubscribeCommands = connection.watchCommands(command => this.#receiveCommand(command, generation)); + } + + async #degradeReceiptStore(message: string, generation: number): Promise { + try { + await this.#unsubscribe(); + } catch (error) { + this.#reportObserverError(error); + } + if (this.#isCurrent(generation)) this.#setState("degraded", message, this.#lease); + } + + async #unsubscribe(): Promise { + const unsubscribe = this.#unsubscribeCommands; + this.#unsubscribeCommands = undefined; + if (unsubscribe) await unsubscribe(); + } + + #cancelScheduled(): void { + const scheduled = this.#scheduled; + this.#scheduled = undefined; + scheduled?.cancel(); + } + + #enqueuePublication(action: () => Promise): Promise { + const work = this.#publicationWork.then(action, action); + this.#publicationWork = work.catch(() => undefined); + return work; + } + + #isCurrent(generation: number): boolean { + return this.#running && generation === this.#generation; + } + + #setState( + status: CultMeshProviderSessionStatus, + lastError?: string, + lease?: CultMeshProviderLease, + ): void { + this.#state = { + status, + identity: this.#identity, + reconnectAttempt: this.#reconnectAttempt, + leaseId: lease?.leaseId, + leaseExpiresAt: lease?.expiresAt, + lastError, + }; + for (const subscriber of [...this.#subscribers]) { + try { + subscriber(this.#state); + } catch (error) { + this.#reportObserverError(error); + } + } + } + + #reportObserverError(error: unknown): void { + try { + this.#onObserverError(error); + } catch { + // Diagnostics cannot become a provider lifecycle authority. + } + } +} + +function validateIdentity(identity: CultMeshProviderIdentity): CultMeshProviderIdentity { + required(identity.providerId, "providerId"); + required(identity.serviceInstanceId, "serviceInstanceId"); + required(identity.endpointId, "endpointId"); + required(identity.verseId, "verseId"); + return identity; +} + +function validatePublication(publication: CultMeshProviderPublication): CultMeshProviderPublication { + required(publication.publicationId, "publicationId"); + required(publication.documentType, "documentType"); + required(publication.schemaId, "schemaId"); + required(publication.recordKey, "recordKey"); + return publication; +} + +function validateLease(lease: CultMeshProviderLease, now: Date): CultMeshProviderLease { + required(lease.leaseId, "leaseId"); + if (!(lease.expiresAt instanceof Date) || !Number.isFinite(lease.expiresAt.getTime())) { + throw new Error("CultMesh provider lease requires a valid expiresAt date."); + } + if (lease.expiresAt <= now) { + throw new Error("CultMesh provider lease must expire in the future."); + } + return lease; +} + +function requireUnexpiredLease(lease: CultMeshProviderLease, now: Date): void { + if (lease.expiresAt <= now) { + throw new Error(`CultMesh provider lease '${lease.leaseId}' expired during replay.`); + } +} + +function validateOutcomeState(state: CultMeshProviderReceiptState): CultMeshProviderReceiptState { + if (state !== "applied" && state !== "rejected" && state !== "failed") { + throw new Error(`CultMesh provider command handler returned invalid receipt state '${String(state)}'.`); + } + return state; +} + +function sameCommandIdentity( + left: CultMeshProviderCommand, + right: CultMeshProviderCommand, +): boolean { + return left.providerId === right.providerId && + left.serviceInstanceId === right.serviceInstanceId && + left.commandKind === right.commandKind; +} + +function validateStoredReceipt( + receipt: CultMeshProviderCommandReceipt, + identity: CultMeshProviderIdentity, +): void { + required(receipt.commandId, "stored receipt commandId"); + required(receipt.commandKind, "stored receipt commandKind"); + required(receipt.receiptId, "stored receipt receiptId"); + validateOutcomeState(receipt.state); + if (receipt.providerId !== identity.providerId || + receipt.serviceInstanceId !== identity.serviceInstanceId || + receipt.receiptId !== receiptId(identity, receipt.commandId)) { + throw new Error(`CultMesh stored receipt '${receipt.receiptId}' does not belong to this provider session.`); + } +} + +function receiptId(identity: CultMeshProviderIdentity, commandId: string): string { + const parts = [identity.providerId, identity.serviceInstanceId, commandId]; + return `receipt:${parts.map(value => `${value.length}:${value}`).join("")}`; +} + +function required(value: string, name: string): string { + if (!value || value.trim().length === 0) { + throw new Error(`CultMesh provider ${name} must be non-empty.`); + } + return value; +} + +function positive(value: number, name: string): number { + if (!Number.isFinite(value) || value <= 0) { + throw new Error(`CultMesh provider ${name} must be positive.`); + } + return value; +} + +function nonNegative(value: number, name: string): number { + if (!Number.isFinite(value) || value < 0) { + throw new Error(`CultMesh provider ${name} must be non-negative.`); + } + return value; +} + +function errorText(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/packages/cultmesh-ts/test/cultmesh.test.ts b/packages/cultmesh-ts/test/cultmesh.test.ts index d7f5e267..213cc4c4 100644 --- a/packages/cultmesh-ts/test/cultmesh.test.ts +++ b/packages/cultmesh-ts/test/cultmesh.test.ts @@ -626,6 +626,76 @@ test("CultMesh TS document handles read schema publications from single-file sto ]); }); +test("CultMesh TS projects live provider publications as typed document handles", async () => { + let current: unknown = { + noteId: "note:live-provider", + body: "initial publication", + }; + let watcher: ((value: unknown) => void) | undefined; + const calls: string[] = []; + + const document = CultMesh.documentFromPublication( + { + kind: "live-publication", + endpoint: "provider-session:aetheria", + source: { + latest: async (schemaId, recordKey) => { + calls.push(`latest:${schemaId}:${recordKey}`); + return current; + }, + watch: (schemaId, recordKey, callback) => { + calls.push(`watch:${schemaId}:${recordKey}`); + watcher = callback; + return () => { + calls.push("unsubscribed"); + watcher = undefined; + }; + }, + }, + }, + noteDocument, + "note:live-provider", + { documentId: "aetheria.note.live" }, + ); + + assert.deepEqual(await document.latest(), current); + assert.equal(document.routeHint.kind, "network"); + assert.equal(document.routeHint.description, "provider-session:aetheria"); + + const observed: string[] = []; + const unsubscribe = document.watch(value => observed.push(value.body)); + current = { + noteId: "note:live-provider", + body: "ordered live upsert", + }; + watcher?.(current); + unsubscribe(); + + assert.deepEqual(observed, ["ordered live upsert"]); + assert.deepEqual(calls, [ + "latest:cultmesh.note.v0:note:live-provider", + "watch:cultmesh.note.v0:note:live-provider", + "unsubscribed", + ]); + assert.equal(watcher, undefined); +}); + +test("CultMesh TS validates live provider publications through typed document schemas", async () => { + const document = CultMesh.documentFromPublication( + { + kind: "live-publication", + source: { + latest: async () => ({ noteId: 42, body: "invalid" }), + watch: () => () => undefined, + }, + }, + noteDocument, + "note:invalid-live-provider", + ); + + await assert.rejects(document.latest(), /noteId/); +}); + test("CultMesh TS binds publication document catalogs from source resolvers", async () => { const root = await mkdtemp(join(tmpdir(), "cultmesh-ts-publication-catalog-")); const firstPath = join(root, "first.ccmp"); diff --git a/packages/cultmesh-ts/test/provider-rudp-transport.test.ts b/packages/cultmesh-ts/test/provider-rudp-transport.test.ts new file mode 100644 index 00000000..5b44c84b --- /dev/null +++ b/packages/cultmesh-ts/test/provider-rudp-transport.test.ts @@ -0,0 +1,334 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createSocket } from "node:dgram"; +import { decode } from "@msgpack/msgpack"; +import { + CultNetDocumentRegistry, + CultNetRudpSession, + decodeRudpPacket, + encodeRudpPacket, + type CultNetOperationRequestMessage, +} from "cultnet-ts"; + +import { + CultMesh, + CultMeshProviderRudpTransport, + CultMeshProviderSessionBroker, + CULTMESH_PROVIDER_SESSION_SERVICE_ID, + cultMeshProviderSessionOperations, + cultMeshProviderSessionSchemas, + decodeProviderConnectEvidence, + encodeProviderConnectEvidence, + encodeProviderSessionPayload, + type CultMeshProviderCommand, + type CultMeshProviderIdentity, + type CultMeshProviderPublication, +} from "../src"; + +const identity: CultMeshProviderIdentity = { + providerId: "voidbot.swarm", + serviceInstanceId: "voidbot-worker-7", + endpointId: "voidbot-worker-7.rudp", + verseId: "voidbot.local", +}; + +test("RUDP provider transport requires broker acceptance for the full lifecycle", async () => { + const accepted = new Map(); + const acceptedProvenance = new Map(); + const deleted: string[] = []; + const receipts: string[] = []; + let leaseSequence = 0; + const broker = new CultMeshProviderSessionBroker({ + runtimeId: "odin-test", + createLeaseId: () => `lease-${++leaseSequence}`, + authorizeRegistration: (_identity, session) => + session.connectPayload !== undefined + && decodeProviderConnectEvidence(session.connectPayload).sessionToken === "signed-provider-token", + acceptPublication: (_identity, publicationId, document) => { + accepted.set(publicationId, decode(document.payload)); + acceptedProvenance.set(publicationId, { + runtime: document.sourceRuntimeId, + agent: document.sourceAgentId, + }); + }, + deletePublications: (_identity, publications) => { + for (const { publicationId } of publications) { + deleted.push(publicationId); + accepted.delete(publicationId); + } + }, + acceptReceipt: (_identity, receipt) => { + receipts.push(receipt.receiptId); + }, + }); + const server = CultMesh.createRudpDocumentServer("odin-test", 0x43554c54, { + bindPort: 0, + documents: new CultNetDocumentRegistry(), + onOperationRequest: (request, session) => broker.handle(request, session), + onSessionClosed: session => broker.sessionClosed(session), + }); + await server.start(); + + const unauthorizedConnection = await new CultMeshProviderRudpTransport({ + endpoint: `rudp://127.0.0.1:${server.bind.port}`, + runtimeId: "unauthorized-provider", + connectionId: 0x43554c54, + sessionToken: "not-authority", + }).connect(identity, new AbortController().signal); + try { + await assert.rejects( + unauthorizedConnection.register( + { identity, requestedLeaseDurationMs: 10_000 }, + new AbortController().signal, + ), + /denied|not authorized/i, + ); + assert.equal( + broker.activeLeaseCount, + 0, + "a successful RUDP handshake does not grant provider authority", + ); + } finally { + unauthorizedConnection.close(); + } + + const providerSocket = createSocket("udp4"); + const rawSend = providerSocket.send.bind(providerSocket); + let originalConnectWire: Buffer | undefined; + providerSocket.send = ((message: Uint8Array, ...args: unknown[]) => { + if (decodeRudpPacket(message).packetType === "connect" && !originalConnectWire) { + originalConnectWire = Buffer.from(message); + } + return (rawSend as (...parameters: unknown[]) => boolean)(message, ...args); + }) as typeof providerSocket.send; + const transport = new CultMeshProviderRudpTransport({ + endpoint: `rudp://127.0.0.1:${server.bind.port}`, + runtimeId: identity.serviceInstanceId, + connectionId: 0x43554c54, + sessionToken: "signed-provider-token", + socketFactory: () => providerSocket, + }); + const connection = await transport.connect(identity, new AbortController().signal); + const secondIdentity: CultMeshProviderIdentity = { + providerId: "aetheria", + serviceInstanceId: "aetheria-daemon-2", + endpointId: "aetheria-daemon-2.rudp", + verseId: "aetheria.local", + }; + const secondConnection = await new CultMeshProviderRudpTransport({ + endpoint: `rudp://127.0.0.1:${server.bind.port}`, + runtimeId: secondIdentity.serviceInstanceId, + connectionId: 0x43554c54, + sessionToken: "signed-provider-token", + }).connect(secondIdentity, new AbortController().signal); + try { + broker.enqueueCommand({ + commandId: "refresh-1", + commandKind: "voidbot.refresh", + providerId: identity.providerId, + serviceInstanceId: identity.serviceInstanceId, + payload: { force: true }, + }); + const lease = await connection.register({ identity, requestedLeaseDurationMs: 10_000 }, new AbortController().signal); + assert.equal(lease.leaseId, "lease-1"); + assert.ok(originalConnectWire); + await new Promise((resolve, reject) => { + rawSend(originalConnectWire!, server.bind.port, "127.0.0.1", error => error ? reject(error) : resolve()); + }); + await new Promise(resolve => setTimeout(resolve, 25)); + assert.equal(broker.activeLeaseCount, 1, "a duplicate Connect cannot revoke the live provider lease"); + const secondLease = await secondConnection.register({ + identity: secondIdentity, + requestedLeaseDurationMs: 10_000, + }, new AbortController().signal); + assert.equal(secondLease.leaseId, "lease-2"); + assert.equal(broker.activeLeaseCount, 2, "the broker demultiplexes simultaneous physical provider sessions"); + + const publication: CultMeshProviderPublication = { + publicationId: "voidbot.surface", + documentType: "gamecult.eve.surface_state", + schemaId: "gamecult.eve.surface_state.v1", + recordKey: "voidbot.swarm", + value: { generation: 3 }, + }; + await connection.publish(publication, lease); + assert.deepEqual(accepted.get(publication.publicationId), publication.value); + assert.deepEqual(acceptedProvenance.get(publication.publicationId), { + runtime: identity.serviceInstanceId, + agent: identity.providerId, + }, "the broker derives provenance from the fenced identity"); + const secondPublication: CultMeshProviderPublication = { + publicationId: "aetheria.surface", + documentType: "gamecult.eve.surface_state", + schemaId: "gamecult.eve.surface_state.v1", + recordKey: "aetheria.pilot", + value: { generation: 8 }, + }; + await secondConnection.publish(secondPublication, secondLease); + await assert.rejects(secondConnection.publish({ + ...secondPublication, + publicationId: "aetheria.stolen-tuple", + recordKey: publication.recordKey, + }, secondLease), /already owned/); + await assert.rejects( + secondConnection.publish({ ...secondPublication, value: { generation: 9 } }, lease), + /belongs to another physical session/, + ); + + const commandArrived = deferred(); + connection.watchCommands(command => commandArrived.resolve(command)); + const command = await commandArrived.promise; + assert.equal(command.commandId, "refresh-1"); + await connection.publishReceipt({ + receiptId: "receipt-refresh-1", + commandId: command.commandId, + commandKind: command.commandKind, + providerId: identity.providerId, + serviceInstanceId: identity.serviceInstanceId, + state: "applied", + completedAt: new Date(), + result: { refreshed: true }, + }, lease); + assert.deepEqual(receipts, ["receipt-refresh-1"]); + + const renewed = await connection.renew(lease); + assert.equal(renewed.leaseId, "lease-3"); + await assert.rejects(connection.withdrawPublication(publication.publicationId, lease), /expired|fenced/); + await connection.withdraw({ identity, leaseId: renewed.leaseId, publicationIds: [publication.publicationId] }); + await secondConnection.withdraw({ + identity: secondIdentity, + leaseId: secondLease.leaseId, + publicationIds: [secondPublication.publicationId], + }); + assert.deepEqual(deleted, [publication.publicationId, secondPublication.publicationId]); + assert.equal(accepted.size, 0); + assert.equal(broker.activeLeaseCount, 0); + } finally { + connection.close(); + secondConnection.close(); + server.close(); + broker.close(); + } +}); + +test("closed physical sessions cannot finish delayed registration", async () => { + const authorization = deferred(); + const broker = new CultMeshProviderSessionBroker({ + runtimeId: "odin-test", + authorizeRegistration: () => authorization.promise, + acceptPublication: () => undefined, + deletePublications: () => undefined, + acceptReceipt: () => undefined, + }); + const session = { + sessionId: "closed-generation", + remote: { address: "127.0.0.1", family: "IPv4", port: 40000 }, + connectPayload: new Uint8Array(), + send: () => undefined, + }; + const request: CultNetOperationRequestMessage = { + schemaVersion: "cultnet.operation_request.v0", + messageId: "late-register", + serviceId: CULTMESH_PROVIDER_SESSION_SERVICE_ID, + operation: cultMeshProviderSessionOperations.register, + payloadSchema: cultMeshProviderSessionSchemas.registration, + payloadEncoding: "messagepack-base64", + payload: encodeProviderSessionPayload({ ...identity, requestedLeaseDurationMs: 10_000 }), + }; + try { + const pending = broker.handle(request, session); + await new Promise(resolve => setTimeout(resolve, 0)); + broker.sessionClosed(session); + authorization.resolve(true); + const response = await pending; + assert.equal(response.status, "denied"); + assert.equal(broker.activeLeaseCount, 0); + } finally { + broker.close(); + } +}); + +test("a replaced RUDP generation drops operations queued behind an active handler", async () => { + const connectionId = 0x43554c54; + const handlerGate = deferred(); + let handlerCalls = 0; + let closedSessions = 0; + const server = CultMesh.createRudpDocumentServer("odin-queue-test", connectionId, { + bindPort: 0, + documents: new CultNetDocumentRegistry(), + onOperationRequest: async request => { + handlerCalls += 1; + if (handlerCalls === 1) await handlerGate.promise; + return { + schemaVersion: "cultnet.operation_response.v0", + messageId: request.messageId, + serviceId: request.serviceId, + operation: request.operation, + status: "denied", + payloadSchema: cultMeshProviderSessionSchemas.mutationAcceptance, + payloadEncoding: "messagepack-base64", + payload: encodeProviderSessionPayload({}), + }; + }, + onSessionClosed: () => { closedSessions += 1; }, + onError: () => undefined, + }); + await server.start(); + + const socket = createSocket("udp4"); + const rawSend = socket.send.bind(socket); + const connection = await new CultMeshProviderRudpTransport({ + endpoint: `rudp://127.0.0.1:${server.bind.port}`, + runtimeId: identity.serviceInstanceId, + connectionId, + sessionToken: "signed-provider-token", + operationTimeoutMs: 100, + socketFactory: () => socket, + }).connect(identity, new AbortController().signal); + try { + const first = connection.register( + { identity, requestedLeaseDurationMs: 10_000 }, + new AbortController().signal, + ); + const second = connection.register( + { identity, requestedLeaseDurationMs: 10_000 }, + new AbortController().signal, + ); + await waitFor(() => handlerCalls === 1, "first queued provider operation"); + + const replacement = new CultNetRudpSession({ connectionId }); + const replacementWire = encodeRudpPacket(replacement.createConnect( + Date.now(), + Buffer.from(encodeProviderConnectEvidence({ + clientSessionId: "replacement-generation", + sessionToken: "signed-provider-token", + })), + )); + await new Promise((resolve, reject) => { + rawSend(replacementWire, server.bind.port, "127.0.0.1", error => error ? reject(error) : resolve()); + }); + await waitFor(() => closedSessions === 1, "old RUDP generation closure"); + handlerGate.resolve(); + await new Promise(resolve => setTimeout(resolve, 20)); + assert.equal(handlerCalls, 1, "transport-queued work from the closed generation must be dropped"); + + connection.close(); + await Promise.allSettled([first, second]); + } finally { + connection.close(); + server.close(); + } +}); + +function deferred(): { promise: Promise; resolve(value: T): void } { + let resolve!: (value: T) => void; + return { promise: new Promise(done => resolve = done), resolve }; +} + +async function waitFor(predicate: () => boolean, description: string): Promise { + const startedAt = Date.now(); + while (!predicate()) { + if (Date.now() - startedAt > 1_000) throw new Error(`Timed out waiting for ${description}.`); + await new Promise(resolve => setTimeout(resolve, 5)); + } +} diff --git a/packages/cultmesh-ts/test/provider-session-wire.test.ts b/packages/cultmesh-ts/test/provider-session-wire.test.ts new file mode 100644 index 00000000..ac607163 --- /dev/null +++ b/packages/cultmesh-ts/test/provider-session-wire.test.ts @@ -0,0 +1,43 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { + decodeProviderConnectEvidence, + encodeProviderConnectEvidence, + encodeProviderSessionPayload, +} from "../src/provider-session-wire"; + +const REGISTRATION_GOLDEN = "hqpwcm92aWRlcklkqGFldGhlcmlhsXNlcnZpY2VJbnN0YW5jZUlkq2FldGhlcmlhLTQyqmVuZHBvaW50SWSvYWV0aGVyaWEtcHVibGljp3ZlcnNlSWSmcHVibGljuHJlcXVlc3RlZExlYXNlRHVyYXRpb25Nc811MLBhdXRob3JpdHlMZWFzZUlkq2F1dGhvcml0eS03"; +const CONNECT_EVIDENCE_GOLDEN = "gq9jbGllbnRTZXNzaW9uSWSyYWV0aGVyaWEtY2xpZW50LTQyrHNlc3Npb25Ub2tlbrJvZGluLXNlc3Npb24tdG9rZW4="; +const TOKENLESS_CONNECT_EVIDENCE_GOLDEN = "gq9jbGllbnRTZXNzaW9uSWSyYWV0aGVyaWEtY2xpZW50LTQyrHNlc3Npb25Ub2tlbsA="; + +test("provider registration matches the shared C# MessagePack golden payload", () => { + assert.equal(encodeProviderSessionPayload({ + providerId: "aetheria", + serviceInstanceId: "aetheria-42", + endpointId: "aetheria-public", + verseId: "public", + requestedLeaseDurationMs: 30_000, + authorityLeaseId: "authority-7", + }), REGISTRATION_GOLDEN); +}); + +test("provider Connect evidence keeps transport generation separate from authority", () => { + const evidence = { + clientSessionId: "aetheria-client-42", + sessionToken: "odin-session-token", + }; + const encoded = encodeProviderConnectEvidence(evidence); + assert.equal(Buffer.from(encoded).toString("base64"), CONNECT_EVIDENCE_GOLDEN); + assert.deepEqual( + decodeProviderConnectEvidence(encoded), + evidence, + ); + assert.equal( + Buffer.from(encodeProviderConnectEvidence({ + clientSessionId: "aetheria-client-42", + sessionToken: null, + })).toString("base64"), + TOKENLESS_CONNECT_EVIDENCE_GOLDEN, + ); +}); diff --git a/packages/cultmesh-ts/test/provider-session.test.ts b/packages/cultmesh-ts/test/provider-session.test.ts new file mode 100644 index 00000000..8e1c9d50 --- /dev/null +++ b/packages/cultmesh-ts/test/provider-session.test.ts @@ -0,0 +1,791 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + CultMeshMemoryProviderReceiptStore, + CultMeshProviderSession, + type CultMeshProviderCommand, + type CultMeshProviderCommandListener, + type CultMeshProviderCommandReceipt, + type CultMeshProviderConnection, + type CultMeshProviderIdentity, + type CultMeshProviderLease, + type CultMeshProviderPublication, + type CultMeshProviderRegistration, + type CultMeshProviderScheduledTask, + type CultMeshProviderScheduler, + type CultMeshProviderTransport, + type CultMeshProviderWithdrawal, + type CultMeshProviderUnsubscribe, +} from "../src/provider-session"; + +const identity: CultMeshProviderIdentity = { + providerId: "voidbot.swarm", + serviceInstanceId: "voidbot-worker-7", + endpointId: "odin:voidbot-worker-7", + verseId: "voidbot.local", +}; + +const surface: CultMeshProviderPublication = { + publicationId: "voidbot.swarm.surface", + documentType: "gamecult.eve.surface_state", + schemaId: "gamecult.eve.surface_state.v1", + recordKey: "voidbot.swarm", + value: { version: 1 }, +}; + +const advertisement: CultMeshProviderPublication = { + publicationId: "voidbot.swarm.advertisement", + documentType: "gamecult.eve.provider_advertisement", + schemaId: "gamecult.eve.provider_advertisement.v1", + recordKey: "voidbot.swarm", + value: { providerId: "voidbot.swarm" }, +}; + +test("provider session owns registration, renewal, desired publication, and withdrawal", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + const states: string[] = []; + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + publications: [surface, advertisement], + leaseDurationMs: 1_000, + renewalLeadMs: 200, + reconnectBaseDelayMs: 100, + reconnectMaxDelayMs: 1_000, + }); + session.watchState(state => states.push(state.status)); + + await session.start(); + + const connection = transport.connections[0]!; + assert.equal(session.state.status, "active"); + assert.deepEqual(connection.registrations[0]?.identity, identity); + assert.deepEqual( + connection.publications.map(value => value.publicationId), + [advertisement.publicationId, surface.publicationId], + "initial desired state is republished in stable order", + ); + assert.notEqual(identity.providerId, identity.serviceInstanceId); + assert.notEqual(identity.serviceInstanceId, identity.endpointId); + + await scheduler.advance(800); + assert.equal(connection.renewals.length, 1); + assert.equal(session.state.status, "active"); + + const updatedSurface = { ...surface, value: { version: 2 } }; + const finalSurface = { ...surface, value: { version: 3 } }; + const publishBarrier = new Deferred(); + connection.publishBarrier = publishBarrier; + const updating = session.upsertPublication(updatedSurface); + const finalizing = session.upsertPublication(finalSurface); + await settle(); + assert.deepEqual(connection.publications.at(-1), surface, "the second update waits behind the first delivery"); + publishBarrier.resolve(); + await Promise.all([updating, finalizing]); + assert.deepEqual( + connection.publications.slice(-2), + [updatedSurface, finalSurface], + "desired publication updates preserve caller order on the live connection", + ); + + assert.equal(await session.removePublication(surface.publicationId), true); + assert.deepEqual(connection.withdrawnPublications, [surface.publicationId]); + + await session.stop(); + assert.equal(connection.closed, true); + assert.deepEqual(connection.withdrawals[0]?.identity, identity); + assert.deepEqual(connection.withdrawals[0]?.publicationIds, [advertisement.publicationId]); + assert.equal(session.state.status, "stopped"); + assert.ok(states.includes("connecting")); + assert.ok(states.includes("withdrawing")); +}); + +test("stopping during registration prevents a stale connection from publishing", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + transport.registerBarrier = new Deferred(); + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + publications: [advertisement], + leaseDurationMs: 1_000, + renewalLeadMs: 200, + }); + + const starting = session.start(); + await settle(); + const connection = transport.connections[0]!; + const stopping = session.stop(); + transport.registerBarrier.resolve(); + await Promise.all([starting, stopping]); + + assert.equal(session.state.status, "stopped"); + assert.equal(connection.closed, true); + assert.deepEqual(connection.publications, []); + assert.deepEqual(connection.withdrawals, []); +}); + +test("provider session reconnects and republishes desired state after transient failure", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + transport.failConnectCount = 2; + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + publications: [advertisement], + leaseDurationMs: 1_000, + renewalLeadMs: 200, + reconnectBaseDelayMs: 100, + reconnectMaxDelayMs: 400, + }); + + await session.start(); + assert.equal(session.state.status, "reconnecting"); + assert.equal(session.state.reconnectAttempt, 1); + + await scheduler.advance(100); + assert.equal(session.state.status, "reconnecting"); + assert.equal(session.state.reconnectAttempt, 2); + await scheduler.advance(200); + assert.equal(session.state.status, "active"); + assert.equal(transport.connections.length, 1); + assert.deepEqual( + transport.connections[0]?.publications.map(value => value.publicationId), + [advertisement.publicationId], + ); + + transport.connections[0]!.failNextPublish = new Error("partition"); + await session.upsertPublication(surface); + assert.equal(session.state.status, "reconnecting"); + assert.match(session.state.lastError ?? "", /partition/); + assert.equal(transport.connections[0]?.closed, true); + + await scheduler.advance(100); + assert.equal(session.state.status, "active"); + assert.deepEqual( + transport.connections[1]?.publications.map(value => value.publicationId), + [advertisement.publicationId, surface.publicationId], + ); + await session.stop(); +}); + +test("receipt persistence failure degrades the provider without inventing a transport outage", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: { + get: async () => { throw new Error("receipt store offline"); }, + put: async () => undefined, + listPending: async () => [], + markPublished: async () => undefined, + }, + leaseDurationMs: 1_000, + renewalLeadMs: 200, + commandHandlers: { + "swarm.set_heat": async () => ({ state: "applied" }), + }, + }); + await session.start(); + const connection = transport.connections[0]!; + await connection.emit({ + commandId: "heat-store-failure", + commandKind: "swarm.set_heat", + providerId: identity.providerId, + serviceInstanceId: identity.serviceInstanceId, + payload: 0.5, + }); + + assert.equal(session.state.status, "degraded"); + assert.match(session.state.lastError ?? "", /receipt store offline/); + assert.equal(connection.closed, false); + assert.equal(transport.connections.length, 1); + await session.stop(); +}); + +test("provider session dispatches commands once and republishes typed receipts", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + let applyCount = 0; + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + leaseDurationMs: 1_000, + renewalLeadMs: 200, + commandHandlers: { + "swarm.set_heat": async command => { + applyCount++; + await settle(); + return { state: "applied", result: { heat: command.payload } }; + }, + }, + }); + await session.start(); + const connection = transport.connections[0]!; + const command: CultMeshProviderCommand = { + commandId: "heat-1", + commandKind: "swarm.set_heat", + providerId: identity.providerId, + serviceInstanceId: identity.serviceInstanceId, + payload: 0.75, + }; + + await Promise.all([connection.emit(command), connection.emit(command)]); + await connection.emit(command); + + assert.equal(applyCount, 1); + assert.equal(connection.receipts.length, 2, "concurrent duplicates share one delivery; later retries republish"); + assert.ok(connection.receipts.every(receipt => + receipt.receiptId === "receipt:13:voidbot.swarm16:voidbot-worker-76:heat-1")); + assert.ok(connection.receipts.every(receipt => receipt.state === "applied")); + + await connection.emit({ ...command, commandId: "unknown-1", commandKind: "swarm.unknown" }); + assert.equal(connection.receipts.at(-1)?.state, "rejected"); + + await connection.emit({ ...command, commandId: "wrong-instance", serviceInstanceId: "somebody-else" }); + assert.equal(connection.receipts.length, 3, "commands for another service instance are ignored"); + await session.stop(); +}); + +test("persisted receipts survive a transport failure and leave the outbox only after replay", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + const receipts = new CultMeshMemoryProviderReceiptStore(); + let applyCount = 0; + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: receipts, + leaseDurationMs: 1_000, + renewalLeadMs: 200, + reconnectBaseDelayMs: 100, + commandHandlers: { + "swarm.set_heat": async () => { + applyCount++; + return { state: "applied" }; + }, + }, + }); + await session.start(); + transport.connections[0]!.failNextReceipt = new Error("receipt route lost"); + await transport.connections[0]!.emit({ + commandId: "durable-1", + commandKind: "swarm.set_heat", + providerId: identity.providerId, + serviceInstanceId: identity.serviceInstanceId, + payload: 0.25, + }); + + assert.equal(session.state.status, "reconnecting"); + assert.equal((await receipts.listPending()).length, 1); + await scheduler.advance(100); + assert.equal(session.state.status, "active"); + assert.equal(transport.connections[1]!.receipts.length, 1); + assert.equal((await receipts.listPending()).length, 0); + assert.equal(applyCount, 1); + + transport.connections[1]!.failNextPublish = new Error("state route lost"); + await session.upsertPublication(surface); + await scheduler.advance(100); + assert.equal(transport.connections[2]!.receipts.length, 0, "marked receipts are not replayed again"); + await session.stop(); +}); + +test("initial replay and live publication changes share one ordered lane", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + transport.publishBarrier = new Deferred(); + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + publications: [surface], + leaseDurationMs: 1_000, + renewalLeadMs: 200, + }); + + const starting = session.start(); + await settle(); + const connection = transport.connections[0]!; + const updated = { ...surface, value: { version: 2 } }; + const updating = session.upsertPublication(updated); + const removing = session.removePublication(surface.publicationId); + transport.publishBarrier.resolve(); + await Promise.all([starting, updating, removing]); + + assert.deepEqual(connection.publications, [surface, updated]); + assert.deepEqual(connection.withdrawnPublications, [surface.publicationId]); + assert.deepEqual(session.publications, []); + await session.stop(); +}); + +test("state observers cannot become lifecycle authorities", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + const observerErrors: unknown[] = []; + const observed: string[] = []; + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + leaseDurationMs: 1_000, + renewalLeadMs: 200, + onObserverError: error => observerErrors.push(error), + }); + session.watchState(() => { throw new Error("display broken"); }); + session.watchState(state => observed.push(state.status)); + + await session.start(); + await session.stop(); + + assert.equal(session.state.status, "stopped"); + assert.ok(observerErrors.length >= 3); + assert.deepEqual(observed, ["stopped", "connecting", "active", "withdrawing", "stopped"]); +}); + +test("shutdown drains command persistence and always closes after cleanup failures", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + const handlerBarrier = new Deferred(); + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + leaseDurationMs: 1_000, + renewalLeadMs: 200, + commandHandlers: { + "swarm.set_heat": async () => { + await handlerBarrier.promise; + return { state: "applied" }; + }, + }, + }); + await session.start(); + const connection = transport.connections[0]!; + const command = connection.emit({ + commandId: "stop-drain-1", + commandKind: "swarm.set_heat", + providerId: identity.providerId, + serviceInstanceId: identity.serviceInstanceId, + payload: 0.5, + }); + connection.unsubscribeError = new Error("unsubscribe failed"); + connection.withdrawError = new Error("withdraw failed"); + connection.closeError = new Error("close failed"); + let stopped = false; + const stopping = session.stop().finally(() => { stopped = true; }); + await settle(); + assert.equal(stopped, false, "shutdown waits for the authoritative command transaction"); + handlerBarrier.resolve(); + await command; + await assert.rejects(stopping, AggregateError); + + assert.equal(connection.closeAttempts, 1); + assert.equal(session.state.status, "stopped"); +}); + +test("concurrent reuse of a command id with another kind cannot join the first transaction", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + const barrier = new Deferred(); + let heatCount = 0; + let otherCount = 0; + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + leaseDurationMs: 1_000, + renewalLeadMs: 200, + commandHandlers: { + "swarm.set_heat": async () => { + heatCount++; + await barrier.promise; + return { state: "applied" }; + }, + "swarm.other": async () => { + otherCount++; + return { state: "applied" }; + }, + }, + }); + await session.start(); + const connection = transport.connections[0]!; + const first = connection.emit({ + commandId: "collision-1", + commandKind: "swarm.set_heat", + providerId: identity.providerId, + serviceInstanceId: identity.serviceInstanceId, + payload: 0.5, + }); + await settle(); + await connection.emit({ + commandId: "collision-1", + commandKind: "swarm.other", + providerId: identity.providerId, + serviceInstanceId: identity.serviceInstanceId, + payload: null, + }); + assert.equal(session.state.status, "degraded"); + barrier.resolve(); + await first; + assert.equal(heatCount, 1); + assert.equal(otherCount, 0); + await session.stop(); +}); + +test("registration failure closes the connection before retry", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + transport.registerError = new Error("registration rejected"); + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + leaseDurationMs: 1_000, + renewalLeadMs: 200, + reconnectBaseDelayMs: 100, + }); + await session.start(); + assert.equal(transport.connections[0]!.closed, true); + assert.equal(session.state.status, "reconnecting"); + await session.stop(); +}); + +test("an expired replay lease never carries the next pending receipt", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + const receipts = new CultMeshMemoryProviderReceiptStore(); + const pending = (commandId: string): CultMeshProviderCommandReceipt => ({ + receiptId: `receipt:13:voidbot.swarm16:voidbot-worker-7${commandId.length}:${commandId}`, + commandId, + commandKind: "swarm.set_heat", + providerId: identity.providerId, + serviceInstanceId: identity.serviceInstanceId, + state: "applied", + completedAt: scheduler.now(), + }); + await receipts.put(pending("one")); + await receipts.put(pending("two")); + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: receipts, + leaseDurationMs: 1_000, + renewalLeadMs: 200, + reconnectBaseDelayMs: 100, + }); + transport.onFirstConnection = connection => { + connection.afterPublishReceipt = async () => scheduler.advance(1_001); + }; + + await session.start(); + assert.equal(session.state.status, "reconnecting"); + assert.deepEqual( + transport.connections[0]!.receipts.map(value => value.commandId), + ["one"], + "the expired lease is rejected before the next receipt", + ); + assert.deepEqual((await receipts.listPending()).map(value => value.commandId), ["two"]); + await scheduler.advance(100); + assert.equal(session.state.status, "active"); + assert.deepEqual(transport.connections[1]!.receipts.map(value => value.commandId), ["two"]); + assert.equal((await receipts.listPending()).length, 0); + await session.stop(); +}); + +test("overlapping shutdown callers share cleanup and restart waits for its boundary", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + leaseDurationMs: 1_000, + renewalLeadMs: 200, + }); + await session.start(); + const connection = transport.connections[0]!; + connection.withdrawBarrier = new Deferred(); + + const firstStop = session.stop(); + const secondStop = session.stop(); + assert.equal(firstStop, secondStop, "concurrent callers own one shutdown operation"); + await assert.rejects(session.start(), /shutdown is in progress/); + await settle(); + assert.equal(connection.closed, false); + connection.withdrawBarrier.resolve(); + await firstStop; + assert.equal(session.state.status, "stopped"); + + await session.start(); + assert.equal(session.state.status, "active"); + assert.equal(transport.connections.length, 2); + await session.stop(); +}); + +test("loss cleanup failures cannot suppress reconnect scheduling", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: new CultMeshMemoryProviderReceiptStore(), + leaseDurationMs: 1_000, + renewalLeadMs: 200, + reconnectBaseDelayMs: 100, + }); + await session.start(); + const connection = transport.connections[0]!; + connection.unsubscribeError = new Error("watch cleanup failed"); + connection.closeError = new Error("route close failed"); + connection.failNextPublish = new Error("route lost"); + + await session.upsertPublication(surface); + assert.equal(session.state.status, "reconnecting"); + assert.match(session.state.lastError ?? "", /watch cleanup failed/); + assert.match(session.state.lastError ?? "", /route close failed/); + await scheduler.advance(100); + assert.equal(session.state.status, "active"); + await session.stop(); +}); + +test("stop during receipt replay cannot publish active state or leave a renewal timer", async () => { + const scheduler = new ManualScheduler(); + const transport = new FakeTransport(scheduler); + const listBarrier = new Deferred(); + const states: string[] = []; + const session = new CultMeshProviderSession({ + identity, + transport, + scheduler, + receiptStore: { + get: async () => undefined, + put: async () => undefined, + listPending: async () => { + await listBarrier.promise; + return []; + }, + markPublished: async () => undefined, + }, + leaseDurationMs: 1_000, + renewalLeadMs: 200, + }); + session.watchState(state => states.push(state.status)); + const starting = session.start(); + await settle(); + const stopping = session.stop(); + await settle(); + const withdrawingIndex = states.lastIndexOf("withdrawing"); + listBarrier.resolve(); + await Promise.all([starting, stopping]); + + assert.equal(session.state.status, "stopped"); + assert.equal(states.slice(withdrawingIndex + 1).includes("active"), false); + assert.equal(scheduler.pendingTaskCount, 0); +}); + +class ManualScheduler implements CultMeshProviderScheduler { + #nowMs = Date.parse("2026-07-14T00:00:00.000Z"); + readonly #tasks: Array<{ + dueAt: number; + cancelled: boolean; + action: () => void | Promise; + }> = []; + + public now(): Date { + return new Date(this.#nowMs); + } + + public get pendingTaskCount(): number { + return this.#tasks.filter(value => !value.cancelled).length; + } + + public schedule(delayMs: number, action: () => void | Promise): CultMeshProviderScheduledTask { + const task = { dueAt: this.#nowMs + delayMs, cancelled: false, action }; + this.#tasks.push(task); + return { cancel: () => { task.cancelled = true; } }; + } + + public async advance(delayMs: number): Promise { + this.#nowMs += delayMs; + while (true) { + const task = this.#tasks + .filter(value => !value.cancelled && value.dueAt <= this.#nowMs) + .sort((left, right) => left.dueAt - right.dueAt)[0]; + if (!task) return; + task.cancelled = true; + await task.action(); + } + } +} + +class FakeTransport implements CultMeshProviderTransport { + public failConnectCount = 0; + public registerBarrier?: Deferred; + public registerError?: Error; + public publishBarrier?: Deferred; + public onFirstConnection?: (connection: FakeConnection) => void; + public readonly connections: FakeConnection[] = []; + + public constructor(private readonly scheduler: CultMeshProviderScheduler) {} + + public async connect( + connectedIdentity: CultMeshProviderIdentity, + signal: AbortSignal, + ): Promise { + assert.deepEqual(connectedIdentity, identity); + assert.equal(signal.aborted, false); + if (this.failConnectCount-- > 0) throw new Error("bootstrap unavailable"); + const connection = new FakeConnection(this.scheduler); + connection.registerBarrier = this.registerBarrier; + connection.registerError = this.registerError; + connection.publishBarrier = this.publishBarrier; + this.connections.push(connection); + if (this.connections.length === 1) this.onFirstConnection?.(connection); + return connection; + } +} + +class FakeConnection implements CultMeshProviderConnection { + public readonly registrations: CultMeshProviderRegistration[] = []; + public readonly renewals: CultMeshProviderLease[] = []; + public readonly publications: CultMeshProviderPublication[] = []; + public readonly withdrawnPublications: string[] = []; + public readonly receipts: CultMeshProviderCommandReceipt[] = []; + public readonly withdrawals: CultMeshProviderWithdrawal[] = []; + public failNextPublish?: Error; + public failNextReceipt?: Error; + public registerError?: Error; + public registerBarrier?: Deferred; + public publishBarrier?: Deferred; + public unsubscribeError?: Error; + public withdrawError?: Error; + public closeError?: Error; + public closeAttempts = 0; + public afterPublishReceipt?: () => void | Promise; + public withdrawBarrier?: Deferred; + public closed = false; + #listener?: CultMeshProviderCommandListener; + #leaseSequence = 0; + + public constructor(private readonly scheduler: CultMeshProviderScheduler) {} + + public async register( + registration: CultMeshProviderRegistration, + signal: AbortSignal, + ): Promise { + this.registrations.push(registration); + if (this.registerBarrier) { + await Promise.race([ + this.registerBarrier.promise, + new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => reject(new Error("registration aborted")), { once: true }); + }), + ]); + } + if (this.registerError) throw this.registerError; + return this.lease(registration.requestedLeaseDurationMs); + } + + public async renew(lease: CultMeshProviderLease): Promise { + this.renewals.push(lease); + return this.lease(1_000); + } + + public async publish(publication: CultMeshProviderPublication): Promise { + if (this.failNextPublish) { + const error = this.failNextPublish; + this.failNextPublish = undefined; + throw error; + } + const barrier = this.publishBarrier; + this.publishBarrier = undefined; + await barrier?.promise; + this.publications.push(publication); + } + + public async withdrawPublication(publicationId: string): Promise { + this.withdrawnPublications.push(publicationId); + } + + public watchCommands(listener: CultMeshProviderCommandListener): CultMeshProviderUnsubscribe { + this.#listener = listener; + return () => { + this.#listener = undefined; + if (this.unsubscribeError) throw this.unsubscribeError; + }; + } + + public async publishReceipt(receipt: CultMeshProviderCommandReceipt): Promise { + if (this.failNextReceipt) { + const error = this.failNextReceipt; + this.failNextReceipt = undefined; + throw error; + } + this.receipts.push(receipt); + const afterPublish = this.afterPublishReceipt; + this.afterPublishReceipt = undefined; + await afterPublish?.(); + } + + public async withdraw(withdrawal: CultMeshProviderWithdrawal): Promise { + this.withdrawals.push(withdrawal); + await this.withdrawBarrier?.promise; + if (this.withdrawError) throw this.withdrawError; + } + + public close(): void { + this.closeAttempts++; + this.closed = true; + if (this.closeError) throw this.closeError; + } + + public async emit(command: CultMeshProviderCommand): Promise { + await this.#listener?.(command); + } + + private lease(durationMs: number): CultMeshProviderLease { + this.#leaseSequence++; + return { + leaseId: `lease-${this.#leaseSequence}`, + expiresAt: new Date(this.scheduler.now().getTime() + durationMs), + }; + } +} + +async function settle(): Promise { + await new Promise(resolve => setImmediate(resolve)); +} + +class Deferred { + public readonly promise: Promise; + #resolve!: (value: T | PromiseLike) => void; + + public constructor() { + this.promise = new Promise(resolve => { this.#resolve = resolve; }); + } + + public resolve(value?: T): void { + this.#resolve(value as T); + } +} diff --git a/packages/cultnet-rs/src/lib.rs b/packages/cultnet-rs/src/lib.rs index 0b9fbb55..6fb1d38d 100644 --- a/packages/cultnet-rs/src/lib.rs +++ b/packages/cultnet-rs/src/lib.rs @@ -2,6 +2,7 @@ mod contracts; mod cultmesh; mod framing; mod operation_service; +mod provider_session; mod replication; mod rudp; mod schema_discovery; @@ -13,6 +14,7 @@ pub use contracts::*; pub use cultmesh::*; pub use framing::*; pub use operation_service::*; +pub use provider_session::*; pub use replication::*; pub use rudp::*; pub use schema_discovery::*; diff --git a/packages/cultnet-rs/src/provider_session.rs b/packages/cultnet-rs/src/provider_session.rs new file mode 100644 index 00000000..9965b0ef --- /dev/null +++ b/packages/cultnet-rs/src/provider_session.rs @@ -0,0 +1,625 @@ +use anyhow::{Result, anyhow}; +use base64::Engine; +use base64::engine::general_purpose::STANDARD; +use chrono::DateTime; +use rmpv::Value; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +use crate::{CultNetMessage, CultNetRawDocumentRecord}; + +pub const CULTMESH_PROVIDER_SESSION_SERVICE_ID: &str = "gamecult.mesh.provider_session"; +pub const CULTMESH_PROVIDER_SESSION_PAYLOAD_ENCODING: &str = "messagepack-base64"; + +pub const CULTMESH_PROVIDER_REGISTER_OPERATION: &str = "provider.register"; +pub const CULTMESH_PROVIDER_RENEW_OPERATION: &str = "provider.renew"; +pub const CULTMESH_PROVIDER_PUBLICATION_PUT_OPERATION: &str = "provider.publication.put"; +pub const CULTMESH_PROVIDER_PUBLICATION_DELETE_OPERATION: &str = "provider.publication.delete"; +pub const CULTMESH_PROVIDER_RECEIPT_PUT_OPERATION: &str = "provider.receipt.put"; +pub const CULTMESH_PROVIDER_WITHDRAW_OPERATION: &str = "provider.withdraw"; + +pub const CULTMESH_PROVIDER_REGISTRATION_SCHEMA: &str = "gamecult.mesh.provider_registration.v1"; +pub const CULTMESH_PROVIDER_LEASE_SCHEMA: &str = "gamecult.mesh.provider_lease.v1"; +pub const CULTMESH_PROVIDER_LEASE_RENEWAL_SCHEMA: &str = "gamecult.mesh.provider_lease_renewal.v1"; +pub const CULTMESH_PROVIDER_PUBLICATION_PUT_SCHEMA: &str = + "gamecult.mesh.provider_publication_put.v1"; +pub const CULTMESH_PROVIDER_PUBLICATION_DELETE_SCHEMA: &str = + "gamecult.mesh.provider_publication_delete.v1"; +pub const CULTMESH_PROVIDER_COMMAND_SCHEMA: &str = "gamecult.mesh.provider_command.v1"; +pub const CULTMESH_PROVIDER_RECEIPT_PUT_SCHEMA: &str = "gamecult.mesh.provider_receipt_put.v1"; +pub const CULTMESH_PROVIDER_WITHDRAWAL_SCHEMA: &str = "gamecult.mesh.provider_withdrawal.v1"; +pub const CULTMESH_PROVIDER_MUTATION_ACCEPTANCE_SCHEMA: &str = + "gamecult.mesh.provider_mutation_acceptance.v1"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CultMeshProviderOperationStatus { + Ok, + Conflict, + Expired, + Denied, + Invalid, +} + +impl CultMeshProviderOperationStatus { + pub fn as_str(self) -> &'static str { + match self { + Self::Ok => "ok", + Self::Conflict => "conflict", + Self::Expired => "expired", + Self::Denied => "denied", + Self::Invalid => "invalid", + } + } + + pub fn parse(value: &str) -> Result { + match value { + "ok" => Ok(Self::Ok), + "conflict" => Ok(Self::Conflict), + "expired" => Ok(Self::Expired), + "denied" => Ok(Self::Denied), + "invalid" => Ok(Self::Invalid), + _ => Err(anyhow!("Unsupported provider-session status {value:?}")), + } + } +} + +pub trait CultMeshProviderSessionPayload { + fn validate(&self) -> Result<()>; +} + +/// Provider-owned evidence carried verbatim in the RUDP Connect payload. +/// `client_session_id` distinguishes process/session generations; the optional +/// token remains opaque authorization evidence for the receiving service. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderConnectEvidenceWire { + pub client_session_id: String, + #[serde(default)] + pub session_token: Option, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderConnectEvidenceWire { + fn validate(&self) -> Result<()> { + require_text(&self.client_session_id, "clientSessionId")?; + require_optional_text(self.session_token.as_deref(), "sessionToken") + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderRegistrationWire { + pub provider_id: String, + pub service_instance_id: String, + pub endpoint_id: String, + pub verse_id: String, + pub requested_lease_duration_ms: i32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub authority_lease_id: Option, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderRegistrationWire { + fn validate(&self) -> Result<()> { + require_identity( + &self.provider_id, + &self.service_instance_id, + &self.endpoint_id, + &self.verse_id, + )?; + require_positive(self.requested_lease_duration_ms, "requestedLeaseDurationMs")?; + require_optional_text(self.authority_lease_id.as_deref(), "authorityLeaseId") + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderLeaseWire { + pub provider_id: String, + pub service_instance_id: String, + pub endpoint_id: String, + pub verse_id: String, + pub lease_id: String, + pub valid_from_utc: String, + pub expires_at_utc: String, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderLeaseWire { + fn validate(&self) -> Result<()> { + require_identity( + &self.provider_id, + &self.service_instance_id, + &self.endpoint_id, + &self.verse_id, + )?; + require_text(&self.lease_id, "leaseId")?; + let valid_from = require_timestamp(&self.valid_from_utc, "validFromUtc")?; + let expires_at = require_timestamp(&self.expires_at_utc, "expiresAtUtc")?; + if expires_at <= valid_from { + return Err(anyhow!("Provider lease must expire after validFromUtc")); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderLeaseRenewalWire { + pub lease_id: String, + pub requested_lease_duration_ms: i32, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderLeaseRenewalWire { + fn validate(&self) -> Result<()> { + require_text(&self.lease_id, "leaseId")?; + require_positive(self.requested_lease_duration_ms, "requestedLeaseDurationMs") + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderPublicationPutWire { + pub lease_id: String, + pub publication_id: String, + pub document: CultNetRawDocumentRecord, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderPublicationPutWire { + fn validate(&self) -> Result<()> { + require_text(&self.lease_id, "leaseId")?; + require_text(&self.publication_id, "publicationId")?; + validate_raw_document(&self.document) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderPublicationDeleteWire { + pub lease_id: String, + pub publication_id: String, + pub schema_id: String, + pub record_key: String, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderPublicationDeleteWire { + fn validate(&self) -> Result<()> { + require_text(&self.lease_id, "leaseId")?; + require_text(&self.publication_id, "publicationId")?; + require_text(&self.schema_id, "schemaId")?; + require_text(&self.record_key, "recordKey") + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderCommandWire { + pub command_id: String, + pub command_kind: String, + pub provider_id: String, + pub service_instance_id: String, + pub payload: Value, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderCommandWire { + fn validate(&self) -> Result<()> { + require_text(&self.command_id, "commandId")?; + require_text(&self.command_kind, "commandKind")?; + require_text(&self.provider_id, "providerId")?; + require_text(&self.service_instance_id, "serviceInstanceId") + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CultMeshProviderReceiptStateWire { + Applied, + Rejected, + Failed, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderCommandReceiptWire { + pub receipt_id: String, + pub command_id: String, + pub command_kind: String, + pub provider_id: String, + pub service_instance_id: String, + pub state: CultMeshProviderReceiptStateWire, + pub completed_at_utc: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub result: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderCommandReceiptWire { + fn validate(&self) -> Result<()> { + require_text(&self.receipt_id, "receiptId")?; + require_text(&self.command_id, "commandId")?; + require_text(&self.command_kind, "commandKind")?; + require_text(&self.provider_id, "providerId")?; + require_text(&self.service_instance_id, "serviceInstanceId")?; + require_timestamp(&self.completed_at_utc, "completedAtUtc")?; + require_optional_text(self.error.as_deref(), "error") + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderReceiptPutWire { + pub lease_id: String, + pub receipt: CultMeshProviderCommandReceiptWire, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderReceiptPutWire { + fn validate(&self) -> Result<()> { + require_text(&self.lease_id, "leaseId")?; + self.receipt.validate() + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderWithdrawalWire { + pub lease_id: String, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderWithdrawalWire { + fn validate(&self) -> Result<()> { + require_text(&self.lease_id, "leaseId") + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CultMeshProviderMutationAcceptanceWire { + pub accepted_at_utc: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lease_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub publication_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub command_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub receipt_id: Option, +} + +impl CultMeshProviderSessionPayload for CultMeshProviderMutationAcceptanceWire { + fn validate(&self) -> Result<()> { + require_timestamp(&self.accepted_at_utc, "acceptedAtUtc")?; + require_optional_text(self.lease_id.as_deref(), "leaseId")?; + require_optional_text(self.publication_id.as_deref(), "publicationId")?; + require_optional_text(self.command_id.as_deref(), "commandId")?; + require_optional_text(self.receipt_id.as_deref(), "receiptId") + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CultMeshProviderErrorWire {} + +impl CultMeshProviderSessionPayload for CultMeshProviderErrorWire { + fn validate(&self) -> Result<()> { + Ok(()) + } +} + +pub fn encode_provider_session_payload(value: &T) -> Result +where + T: CultMeshProviderSessionPayload + Serialize, +{ + value.validate()?; + Ok(STANDARD.encode(rmp_serde::to_vec_named(value)?)) +} + +pub fn encode_provider_connect_evidence( + evidence: &CultMeshProviderConnectEvidenceWire, +) -> Result> { + evidence.validate()?; + Ok(rmp_serde::to_vec_named(evidence)?) +} + +pub fn decode_provider_connect_evidence( + payload: &[u8], +) -> Result { + if payload.is_empty() { + return Err(anyhow!( + "Provider Connect evidence must be a non-empty MessagePack map" + )); + } + let evidence: CultMeshProviderConnectEvidenceWire = rmp_serde::from_slice(payload)?; + evidence.validate()?; + Ok(evidence) +} + +pub fn decode_provider_session_payload(payload: &str) -> Result +where + T: CultMeshProviderSessionPayload + DeserializeOwned, +{ + require_text(payload, "payload")?; + let bytes = STANDARD + .decode(payload) + .map_err(|error| anyhow!("Provider-session payload must be MessagePack base64: {error}"))?; + let value: T = rmp_serde::from_slice(&bytes)?; + value.validate()?; + Ok(value) +} + +pub fn decode_provider_command_document( + document: &CultNetRawDocumentRecord, +) -> Result { + if document.schema_id != CULTMESH_PROVIDER_COMMAND_SCHEMA { + return Err(anyhow!( + "Expected provider command schema {:?}, received {:?}", + CULTMESH_PROVIDER_COMMAND_SCHEMA, + document.schema_id + )); + } + let command: CultMeshProviderCommandWire = rmp_serde::from_slice(&document.payload)?; + command.validate()?; + Ok(command) +} + +pub fn create_provider_session_request( + message_id: impl Into, + operation: impl Into, + payload_schema: impl Into, + payload: &T, + source_runtime_id: Option, + target_runtime_id: Option, +) -> Result +where + T: CultMeshProviderSessionPayload + Serialize, +{ + let message_id = message_id.into(); + let operation = operation.into(); + let payload_schema = payload_schema.into(); + require_text(&message_id, "messageId")?; + validate_operation_schema(&operation, &payload_schema)?; + Ok(CultNetMessage::OperationRequest { + message_id, + service_id: CULTMESH_PROVIDER_SESSION_SERVICE_ID.to_string(), + operation, + payload_schema, + payload_encoding: CULTMESH_PROVIDER_SESSION_PAYLOAD_ENCODING.to_string(), + payload: encode_provider_session_payload(payload)?, + source_runtime_id, + target_runtime_id, + }) +} + +pub fn decode_provider_session_request( + request: &CultNetMessage, + expected_operation: &str, + expected_payload_schema: &str, +) -> Result +where + T: CultMeshProviderSessionPayload + DeserializeOwned, +{ + let CultNetMessage::OperationRequest { + service_id, + operation, + payload_schema, + payload_encoding, + payload, + .. + } = request + else { + return Err(anyhow!("Expected a CultNet operation request")); + }; + require_envelope( + service_id, + operation, + payload_schema, + payload_encoding, + expected_operation, + expected_payload_schema, + )?; + decode_provider_session_payload(payload) +} + +pub fn create_provider_session_response( + request: &CultNetMessage, + status: CultMeshProviderOperationStatus, + payload_schema: impl Into, + payload: &T, + source_runtime_id: Option, +) -> Result +where + T: CultMeshProviderSessionPayload + Serialize, +{ + let CultNetMessage::OperationRequest { + message_id, + operation, + .. + } = request + else { + return Err(anyhow!("Expected a CultNet operation request")); + }; + require_text(message_id, "messageId")?; + require_text(operation, "operation")?; + let payload_schema = payload_schema.into(); + require_text(&payload_schema, "payloadSchema")?; + Ok(CultNetMessage::OperationResponse { + message_id: message_id.clone(), + service_id: CULTMESH_PROVIDER_SESSION_SERVICE_ID.to_string(), + operation: operation.clone(), + status: status.as_str().to_string(), + payload_schema, + payload_encoding: CULTMESH_PROVIDER_SESSION_PAYLOAD_ENCODING.to_string(), + payload: encode_provider_session_payload(payload)?, + diagnostics: Vec::new(), + source_runtime_id, + }) +} + +pub fn create_provider_session_error_response( + request: &CultNetMessage, + status: CultMeshProviderOperationStatus, + diagnostics: Vec, + source_runtime_id: Option, +) -> Result { + if status == CultMeshProviderOperationStatus::Ok { + return Err(anyhow!( + "Provider-session error responses require a non-ok status" + )); + } + if diagnostics.is_empty() { + return Err(anyhow!( + "Provider-session error responses require diagnostics" + )); + } + for diagnostic in &diagnostics { + require_text(diagnostic, "diagnostics[]")?; + } + let mut response = create_provider_session_response( + request, + status, + CULTMESH_PROVIDER_MUTATION_ACCEPTANCE_SCHEMA, + &CultMeshProviderErrorWire {}, + source_runtime_id, + )?; + let CultNetMessage::OperationResponse { + diagnostics: response_diagnostics, + .. + } = &mut response + else { + unreachable!("provider-session response helper returned a request") + }; + *response_diagnostics = diagnostics; + Ok(response) +} + +pub fn decode_provider_session_response( + response: &CultNetMessage, + expected_operation: &str, + expected_payload_schema: &str, +) -> Result<(CultMeshProviderOperationStatus, T)> +where + T: CultMeshProviderSessionPayload + DeserializeOwned, +{ + let CultNetMessage::OperationResponse { + service_id, + operation, + status, + payload_schema, + payload_encoding, + payload, + .. + } = response + else { + return Err(anyhow!("Expected a CultNet operation response")); + }; + require_envelope( + service_id, + operation, + payload_schema, + payload_encoding, + expected_operation, + expected_payload_schema, + )?; + Ok(( + CultMeshProviderOperationStatus::parse(status)?, + decode_provider_session_payload(payload)?, + )) +} + +fn validate_operation_schema(operation: &str, payload_schema: &str) -> Result<()> { + let expected = match operation { + CULTMESH_PROVIDER_REGISTER_OPERATION => CULTMESH_PROVIDER_REGISTRATION_SCHEMA, + CULTMESH_PROVIDER_RENEW_OPERATION => CULTMESH_PROVIDER_LEASE_RENEWAL_SCHEMA, + CULTMESH_PROVIDER_PUBLICATION_PUT_OPERATION => CULTMESH_PROVIDER_PUBLICATION_PUT_SCHEMA, + CULTMESH_PROVIDER_PUBLICATION_DELETE_OPERATION => { + CULTMESH_PROVIDER_PUBLICATION_DELETE_SCHEMA + } + CULTMESH_PROVIDER_RECEIPT_PUT_OPERATION => CULTMESH_PROVIDER_RECEIPT_PUT_SCHEMA, + CULTMESH_PROVIDER_WITHDRAW_OPERATION => CULTMESH_PROVIDER_WITHDRAWAL_SCHEMA, + _ => { + return Err(anyhow!( + "Unsupported provider-session operation {operation:?}" + )); + } + }; + if payload_schema != expected { + return Err(anyhow!( + "Provider-session operation {operation:?} requires payload schema {expected:?}" + )); + } + Ok(()) +} + +fn require_envelope( + service_id: &str, + operation: &str, + payload_schema: &str, + payload_encoding: &str, + expected_operation: &str, + expected_payload_schema: &str, +) -> Result<()> { + if service_id != CULTMESH_PROVIDER_SESSION_SERVICE_ID { + return Err(anyhow!( + "Unexpected provider-session service id {service_id:?}" + )); + } + if operation != expected_operation { + return Err(anyhow!( + "Unexpected provider-session operation {operation:?}" + )); + } + if payload_schema != expected_payload_schema { + return Err(anyhow!( + "Unexpected provider-session payload schema {payload_schema:?}" + )); + } + if payload_encoding != CULTMESH_PROVIDER_SESSION_PAYLOAD_ENCODING { + return Err(anyhow!( + "Unexpected provider-session payload encoding {payload_encoding:?}" + )); + } + Ok(()) +} + +fn validate_raw_document(document: &CultNetRawDocumentRecord) -> Result<()> { + require_text(&document.schema_id, "document.schemaId")?; + require_text(&document.record_key, "document.recordKey")?; + Ok(()) +} + +fn require_identity( + provider_id: &str, + service_instance_id: &str, + endpoint_id: &str, + verse_id: &str, +) -> Result<()> { + require_text(provider_id, "providerId")?; + require_text(service_instance_id, "serviceInstanceId")?; + require_text(endpoint_id, "endpointId")?; + require_text(verse_id, "verseId") +} + +fn require_text(value: &str, field: &str) -> Result<()> { + if value.trim().is_empty() { + return Err(anyhow!("Provider-session {field} must not be empty")); + } + Ok(()) +} + +fn require_optional_text(value: Option<&str>, field: &str) -> Result<()> { + if let Some(value) = value { + require_text(value, field)?; + } + Ok(()) +} + +fn require_positive(value: i32, field: &str) -> Result<()> { + if value <= 0 { + return Err(anyhow!( + "Provider-session {field} must be greater than zero" + )); + } + Ok(()) +} + +fn require_timestamp(value: &str, field: &str) -> Result> { + require_text(value, field)?; + DateTime::parse_from_rfc3339(value) + .map_err(|error| anyhow!("Provider-session {field} must be RFC3339: {error}")) +} diff --git a/packages/cultnet-rs/src/rudp.rs b/packages/cultnet-rs/src/rudp.rs index 8b47f9e7..ae1ef00b 100644 --- a/packages/cultnet-rs/src/rudp.rs +++ b/packages/cultnet-rs/src/rudp.rs @@ -29,6 +29,8 @@ use crate::encode_cultnet_message_to_vec; const RUDP_MAGIC: [u8; 4] = [0x43, 0x4e, 0x52, 0x30]; const RUDP_VERSION: u8 = 0; const RUDP_FIXED_HEADER_BYTES: usize = 36; +pub const CULTNET_RUDP_DEFAULT_MAX_PAYLOAD_BYTES: usize = 16 * 1024 * 1024; +const RUDP_RECEIVED_SEQUENCE_WINDOW: usize = 4_096; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CultNetRudpPacketType { @@ -127,6 +129,8 @@ pub struct CultNetRudpSession { connection_id: u32, resend_delay_ms: u64, max_pending_reliable_packets: Option, + max_payload_bytes: Option, + max_pending_fragment_sets: usize, initial_sequence: u32, next_sequence: u32, next_fragment_id: u16, @@ -146,6 +150,8 @@ impl CultNetRudpSession { connection_id: options.connection_id, resend_delay_ms: options.resend_delay_ms, max_pending_reliable_packets: options.max_pending_reliable_packets, + max_payload_bytes: None, + max_pending_fragment_sets: 64, initial_sequence: options.initial_sequence, next_sequence: options.initial_sequence, next_fragment_id: 1, @@ -176,10 +182,36 @@ impl CultNetRudpSession { self.pending_reliable.keys().copied().collect() } + fn pending_accept_for_resend(&mut self, now_ms: u64) -> Option { + let pending = self + .pending_reliable + .values_mut() + .find(|pending| pending.packet.packet_type == CultNetRudpPacketType::Accept)?; + pending.last_sent_at_ms = now_ms; + Some(pending.packet.clone()) + } + pub fn last_received_at_ms(&self) -> Option { self.last_received_at_ms } + pub fn set_max_payload_bytes(&mut self, max_payload_bytes: Option) { + self.max_payload_bytes = max_payload_bytes; + } + + pub fn set_max_pending_fragment_sets( + &mut self, + max_pending_fragment_sets: usize, + ) -> Result<()> { + if max_pending_fragment_sets == 0 { + return Err(anyhow!( + "RUDP max_pending_fragment_sets must be greater than zero" + )); + } + self.max_pending_fragment_sets = max_pending_fragment_sets; + Ok(()) + } + pub fn reset_peer_state(&mut self) { self.next_sequence = self.initial_sequence; self.next_fragment_id = 1; @@ -223,6 +255,7 @@ impl CultNetRudpSession { self.ensure_reliable_capacity(1)?; self.remember_received(packet.sequence); + self.last_received_at_ms = Some(now_ms); self.connected = true; let response = self.create_packet( CultNetRudpPacketType::Accept, @@ -260,6 +293,7 @@ impl CultNetRudpSession { "Cannot send RUDP data before the session is connected" )); } + self.require_payload_size(payload.len())?; if let Some(max_fragment_bytes) = max_fragment_bytes { if max_fragment_bytes == 0 { @@ -400,7 +434,11 @@ impl CultNetRudpSession { }); } - let duplicate = self.received_sequences.contains(&packet.sequence); + let duplicate = self.received_sequences.contains(&packet.sequence) + || self.highest_received_sequence.is_some_and(|highest| { + packet.sequence < highest + && highest - packet.sequence >= RUDP_RECEIVED_SEQUENCE_WINDOW as u32 + }); self.remember_received(packet.sequence); if duplicate { return Ok(CultNetRudpReceiveResult { @@ -457,6 +495,24 @@ impl CultNetRudpSession { } } + pub fn create_ack_for(&self, sequence: u32) -> CultNetRudpPacket { + CultNetRudpPacket { + packet_type: CultNetRudpPacketType::Ack, + connection_id: self.connection_id, + sequence: 0, + ack: sequence, + ack_mask: 0, + channel_id: "control".to_string(), + reliable: false, + ordered: false, + sequenced: false, + fragment_id: 0, + fragment_index: 0, + fragment_count: 0, + payload: Vec::new(), + } + } + pub fn create_ping(&mut self, payload: Vec) -> CultNetRudpPacket { self.create_packet( CultNetRudpPacketType::Ping, @@ -603,6 +659,13 @@ impl CultNetRudpSession { { self.highest_received_sequence = Some(sequence); } + if self.received_sequences.len() > RUDP_RECEIVED_SEQUENCE_WINDOW { + let keep_from = self + .highest_received_sequence + .unwrap_or(sequence) + .saturating_sub(RUDP_RECEIVED_SEQUENCE_WINDOW as u32 - 1); + self.received_sequences = self.received_sequences.split_off(&keep_from); + } } fn ack_state(&self) -> (u32, u32) { @@ -621,6 +684,7 @@ impl CultNetRudpSession { packet: &CultNetRudpPacket, ) -> Result> { if packet.fragment_count == 0 { + self.require_payload_size(packet.payload.len())?; return Ok(Some(( CultNetRudpDeliveredFrame { channel_id: packet.channel_id.clone(), @@ -643,6 +707,27 @@ impl CultNetRudpSession { } let key = (packet.channel_id.clone(), packet.fragment_id); + if !self.fragment_buffers.contains_key(&key) + && self.fragment_buffers.len() >= self.max_pending_fragment_sets + { + return Err(anyhow!("RUDP pending fragment-set limit reached")); + } + let buffered_bytes = self + .fragment_buffers + .get(&key) + .map(|buffer| { + buffer + .payloads + .iter() + .filter(|(index, _)| **index != packet.fragment_index) + .map(|(_, payload)| payload.len()) + .sum::() + }) + .unwrap_or(0); + if let Err(error) = self.require_payload_size(buffered_bytes + packet.payload.len()) { + self.fragment_buffers.remove(&key); + return Err(error); + } let buffer = self .fragment_buffers .entry(key.clone()) @@ -694,6 +779,16 @@ impl CultNetRudpSession { ))) } + fn require_payload_size(&self, payload_bytes: usize) -> Result<()> { + if self + .max_payload_bytes + .is_some_and(|max_payload_bytes| payload_bytes > max_payload_bytes) + { + return Err(anyhow!("RUDP payload exceeds max_payload_bytes")); + } + Ok(()) + } + fn deliver_ordered( &mut self, frame: CultNetRudpDeliveredFrame, @@ -889,16 +984,394 @@ pub struct CultNetRudpSocketTransportConnection { pong_payloads: VecDeque>, } -impl CultNetRudpSocketTransportConnection { - pub fn new(options: CultNetRudpSocketTransportOptions) -> Result { +pub struct CultNetRudpServerHubOptions { + pub runtime_id: String, + pub socket: UdpSocket, + pub connection_id: u32, + pub initial_sequence: u32, + pub resend_delay_ms: u64, + pub transport_id: Option, + pub max_payload_bytes: Option, + pub max_fragment_bytes: Option, + pub max_pending_reliable_packets: Option, + pub max_peers: usize, +} + +impl CultNetRudpServerHubOptions { + pub fn new(runtime_id: impl Into, socket: UdpSocket, connection_id: u32) -> Self { + Self { + runtime_id: runtime_id.into(), + socket, + connection_id, + initial_sequence: 1, + resend_delay_ms: 250, + transport_id: None, + max_payload_bytes: None, + max_fragment_bytes: None, + max_pending_reliable_packets: None, + max_peers: 256, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CultNetRudpServerSessionContext { + pub remote_addr: SocketAddr, + pub connection_id: u32, + /// Server-minted generation used to fence work from an older session at + /// the same UDP endpoint. + pub session_generation: u64, + /// Exact bytes supplied by the peer's most recently accepted Connect packet. + /// CultNet does not interpret these bytes; higher layers may use them as + /// transport evidence when making their own authorization decision. + pub connect_payload: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CultNetRudpServerEvent { + Connected { + session: CultNetRudpServerSessionContext, + }, + Frame { + session: CultNetRudpServerSessionContext, + frame: CultNetTransportFrame, + }, + Pong { + session: CultNetRudpServerSessionContext, + payload: Vec, + }, + Disconnected { + session: CultNetRudpServerSessionContext, + reason: Vec, + }, +} + +struct CultNetRudpServerPeer { + session: CultNetRudpSession, + context: CultNetRudpServerSessionContext, +} + +/// One UDP listener with an independent reliable session for every remote peer. +/// +/// The hub owns packet/session mechanics only. Registration, leases, commands, +/// and all other application policy belong to the service using the hub. +pub struct CultNetRudpServerHub { + socket: UdpSocket, + connection_id: u32, + initial_sequence: u32, + resend_delay_ms: u64, + max_pending_reliable_packets: Option, + max_payload_bytes: usize, + max_fragment_bytes: Option, + max_peers: usize, + next_session_generation: u64, + peers: BTreeMap, + pending_events: VecDeque, + pub profile: CultNetTransportProfile, + stats: CultNetTransportStats, +} + +impl CultNetRudpServerHub { + pub fn new(options: CultNetRudpServerHubOptions) -> Result { let local_addr = options.socket.local_addr()?; + if options.max_peers == 0 { + return Err(anyhow!( + "RUDP server hub max_peers must be greater than zero" + )); + } + let max_payload_bytes = options + .max_payload_bytes + .or(Some(CULTNET_RUDP_DEFAULT_MAX_PAYLOAD_BYTES as u32)); let profile = create_rudp_transport_profile( options.runtime_id, RudpTransportProfileOptions { transport_id: options.transport_id, host: Some(local_addr.ip().to_string()), port: Some(local_addr.port()), - max_payload_bytes: options.max_payload_bytes, + max_payload_bytes, + max_fragment_bytes: options.max_fragment_bytes, + max_pending_reliable_packets: options.max_pending_reliable_packets, + reconnect_policy: None, + }, + ); + Ok(Self { + socket: options.socket, + connection_id: options.connection_id, + initial_sequence: options.initial_sequence, + resend_delay_ms: options.resend_delay_ms, + max_pending_reliable_packets: options + .max_pending_reliable_packets + .map(|value| value as usize), + max_payload_bytes: max_payload_bytes.expect("RUDP hub has an effective payload limit") + as usize, + max_fragment_bytes: options.max_fragment_bytes.map(|value| value as usize), + max_peers: options.max_peers, + next_session_generation: 1, + peers: BTreeMap::new(), + pending_events: VecDeque::new(), + profile, + stats: CultNetTransportStats::default(), + }) + } + + pub fn local_addr(&self) -> Result { + Ok(self.socket.local_addr()?) + } + + pub fn stats(&self) -> CultNetTransportStats { + self.stats.clone() + } + + pub fn sessions(&self) -> Vec { + self.peers + .values() + .map(|peer| peer.context.clone()) + .collect() + } + + pub fn session(&self, remote_addr: SocketAddr) -> Option<&CultNetRudpServerSessionContext> { + self.peers.get(&remote_addr).map(|peer| &peer.context) + } + + pub fn send( + &mut self, + session: &CultNetRudpServerSessionContext, + channel_id: &str, + payload: Vec, + ) -> Result<()> { + let remote_addr = session.remote_addr; + let packets = { + let peer = self + .peers + .get_mut(&remote_addr) + .ok_or_else(|| anyhow!("Unknown RUDP server peer {remote_addr}"))?; + if peer.context.session_generation != session.session_generation { + return Err(anyhow!( + "RUDP server session generation {} is no longer active", + session.session_generation + )); + } + peer.session.send_many( + channel_id, + payload, + channel_send_options(channel_id, now_ms()), + self.max_fragment_bytes, + )? + }; + for packet in packets { + self.send_packet(remote_addr, &packet)?; + } + self.stats.frames_sent += 1; + Ok(()) + } + + pub fn send_schema_message( + &mut self, + session: &CultNetRudpServerSessionContext, + message: &CultNetMessage, + ) -> Result<()> { + let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?; + self.send(session, "schema", payload) + } + + pub fn disconnect( + &mut self, + session: &CultNetRudpServerSessionContext, + reason: Vec, + ) -> Result { + let Some(peer) = self.peers.get(&session.remote_addr) else { + return Ok(false); + }; + if peer.context.session_generation != session.session_generation { + return Ok(false); + } + let mut peer = self + .peers + .remove(&session.remote_addr) + .expect("validated RUDP peer exists"); + let packet = peer.session.create_disconnect(reason); + self.send_packet(session.remote_addr, &packet)?; + Ok(true) + } + + pub fn receive_event_once(&mut self) -> Result> { + if let Some(event) = self.pending_events.pop_front() { + return Ok(Some(event)); + } + + let mut wire = vec![0_u8; 65_535]; + let (received, remote_addr) = match self.socket.recv_from(&mut wire) { + Ok(value) => value, + Err(error) + if error.kind() == ErrorKind::WouldBlock || error.kind() == ErrorKind::TimedOut => + { + return Ok(None); + } + Err(error) => return Err(error.into()), + }; + wire.truncate(received); + self.stats.bytes_received += received as u64; + let packet = decode_rudp_packet(&wire)?; + if packet.connection_id != self.connection_id { + return Ok(None); + } + + if packet.packet_type == CultNetRudpPacketType::Connect { + if let Some(peer) = self.peers.get_mut(&remote_addr) + && peer.context.connect_payload == packet.payload + { + let _ = peer.session.receive(&packet, now_ms())?; + let reply = peer + .session + .pending_accept_for_resend(now_ms()) + .unwrap_or_else(|| peer.session.create_ack_for(packet.sequence)); + self.send_packet(remote_addr, &reply)?; + return Ok(None); + } + if !self.peers.contains_key(&remote_addr) && self.peers.len() >= self.max_peers { + return Err(anyhow!("RUDP server hub peer limit reached")); + } + let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: self.connection_id, + initial_sequence: self.initial_sequence, + resend_delay_ms: self.resend_delay_ms, + max_pending_reliable_packets: self.max_pending_reliable_packets, + }); + session.set_max_payload_bytes(Some(self.max_payload_bytes)); + let generation = self.next_session_generation; + self.next_session_generation = self + .next_session_generation + .checked_add(1) + .ok_or_else(|| anyhow!("RUDP server session generation exhausted"))?; + let context = CultNetRudpServerSessionContext { + remote_addr, + connection_id: packet.connection_id, + session_generation: generation, + connect_payload: packet.payload.clone(), + }; + let accept = session.accept_connect(&packet, now_ms(), Vec::new())?; + self.send_packet(remote_addr, &accept)?; + let replaced = self.peers.insert( + remote_addr, + CultNetRudpServerPeer { + session, + context: context.clone(), + }, + ); + if let Some(replaced) = replaced { + self.pending_events + .push_back(CultNetRudpServerEvent::Disconnected { + session: replaced.context, + reason: b"replaced by a new Connect generation".to_vec(), + }); + } + self.pending_events + .push_back(CultNetRudpServerEvent::Connected { session: context }); + return Ok(self.pending_events.pop_front()); + } + + let Some(peer) = self.peers.get_mut(&remote_addr) else { + return Ok(None); + }; + let result = peer.session.receive(&packet, now_ms())?; + let context = peer.context.clone(); + let ack = if packet.reliable { + Some(peer.session.create_ack_for(packet.sequence)) + } else { + None + }; + if let Some(reply) = result.reply { + self.send_packet(remote_addr, &reply)?; + } + if let Some(ack) = ack { + self.send_packet(remote_addr, &ack)?; + } + if result.pong { + self.pending_events.push_back(CultNetRudpServerEvent::Pong { + session: context.clone(), + payload: result.pong_payload, + }); + } + for delivered in result.delivered { + self.stats.frames_received += 1; + self.pending_events + .push_back(CultNetRudpServerEvent::Frame { + session: context.clone(), + frame: CultNetTransportFrame { + channel_id: delivered.channel_id, + payload: delivered.payload, + }, + }); + } + if result.disconnected { + self.pending_events + .push_back(CultNetRudpServerEvent::Disconnected { + session: context, + reason: result.disconnect_reason, + }); + self.peers.remove(&remote_addr); + } + Ok(self.pending_events.pop_front()) + } + + pub fn poll_resends(&mut self) -> Result<()> { + let now = now_ms(); + let mut packets = Vec::new(); + for (remote_addr, peer) in &mut self.peers { + packets.extend( + peer.session + .due_resends(now) + .into_iter() + .map(|packet| (*remote_addr, packet)), + ); + } + for (remote_addr, packet) in packets { + self.send_packet(remote_addr, &packet)?; + } + Ok(()) + } + + pub fn remove_timed_out_sessions( + &mut self, + timeout_ms: u64, + ) -> Vec { + let now = now_ms(); + let timed_out = self + .peers + .iter_mut() + .filter_map(|(remote_addr, peer)| { + peer.session + .check_timeout(now, timeout_ms) + .then_some((*remote_addr, peer.context.clone())) + }) + .collect::>(); + for (remote_addr, _) in &timed_out { + self.peers.remove(remote_addr); + } + timed_out.into_iter().map(|(_, context)| context).collect() + } + + fn send_packet(&mut self, remote_addr: SocketAddr, packet: &CultNetRudpPacket) -> Result<()> { + let wire = encode_rudp_packet(packet)?; + let sent = self.socket.send_to(&wire, remote_addr)?; + self.stats.bytes_sent += sent as u64; + Ok(()) + } +} + +impl CultNetRudpSocketTransportConnection { + pub fn new(options: CultNetRudpSocketTransportOptions) -> Result { + let local_addr = options.socket.local_addr()?; + let max_payload_bytes = options + .max_payload_bytes + .or(Some(CULTNET_RUDP_DEFAULT_MAX_PAYLOAD_BYTES as u32)); + let profile = create_rudp_transport_profile( + options.runtime_id, + RudpTransportProfileOptions { + transport_id: options.transport_id, + host: Some(local_addr.ip().to_string()), + port: Some(local_addr.port()), + max_payload_bytes, max_fragment_bytes: options.max_fragment_bytes, max_pending_reliable_packets: options.max_pending_reliable_packets, reconnect_policy: options.reconnect_policy, @@ -907,14 +1380,16 @@ impl CultNetRudpSocketTransportConnection { let max_pending_reliable_packets = options .max_pending_reliable_packets .map(|value| value as usize); + let mut session = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: options.connection_id, + initial_sequence: options.initial_sequence, + resend_delay_ms: options.resend_delay_ms, + max_pending_reliable_packets, + }); + session.set_max_payload_bytes(max_payload_bytes.map(|value| value as usize)); Ok(Self { socket: options.socket, - session: CultNetRudpSession::new(CultNetRudpSessionOptions { - connection_id: options.connection_id, - initial_sequence: options.initial_sequence, - resend_delay_ms: options.resend_delay_ms, - max_pending_reliable_packets, - }), + session, mode: options.mode, remote_addr: options.remote_addr, profile, @@ -1065,8 +1540,9 @@ impl CultNetRudpSocketTransportConnection { self.stats.frames_received += 1; } let frame = self.delivered_frames.pop_front(); - if packet.packet_type == CultNetRudpPacketType::Accept || frame.is_some() { - let ack = self.session.create_ack(); + if packet.reliable || packet.packet_type == CultNetRudpPacketType::Accept || frame.is_some() + { + let ack = self.session.create_ack_for(packet.sequence); self.send_packet(&ack)?; } Ok(frame) diff --git a/packages/cultnet-rs/tests/provider_session.rs b/packages/cultnet-rs/tests/provider_session.rs new file mode 100644 index 00000000..4ad7c23a --- /dev/null +++ b/packages/cultnet-rs/tests/provider_session.rs @@ -0,0 +1,365 @@ +use anyhow::Result; +use cultnet_rs::*; + +const REGISTRATION_GOLDEN: &str = "hqpwcm92aWRlcklkqGFldGhlcmlhsXNlcnZpY2VJbnN0YW5jZUlkq2FldGhlcmlhLTQyqmVuZHBvaW50SWSvYWV0aGVyaWEtcHVibGljp3ZlcnNlSWSmcHVibGljuHJlcXVlc3RlZExlYXNlRHVyYXRpb25Nc811MLBhdXRob3JpdHlMZWFzZUlkq2F1dGhvcml0eS03"; +const CONNECT_EVIDENCE_GOLDEN: &str = + "gq9jbGllbnRTZXNzaW9uSWSyYWV0aGVyaWEtY2xpZW50LTQyrHNlc3Npb25Ub2tlbrJvZGluLXNlc3Npb24tdG9rZW4="; +const TOKENLESS_CONNECT_EVIDENCE_GOLDEN: &str = + "gq9jbGllbnRTZXNzaW9uSWSwYW5vbnltb3VzLWNsaWVudKxzZXNzaW9uVG9rZW7A"; + +fn registration() -> CultMeshProviderRegistrationWire { + CultMeshProviderRegistrationWire { + provider_id: "aetheria".to_string(), + service_instance_id: "aetheria-42".to_string(), + endpoint_id: "aetheria-public".to_string(), + verse_id: "public".to_string(), + requested_lease_duration_ms: 30_000, + authority_lease_id: Some("authority-7".to_string()), + } +} + +#[test] +fn registration_matches_csharp_and_typescript_golden_payload() -> Result<()> { + let encoded = encode_provider_session_payload(®istration())?; + assert_eq!(encoded, REGISTRATION_GOLDEN); + assert_eq!( + decode_provider_session_payload::(&encoded)?, + registration() + ); + Ok(()) +} + +#[test] +fn connect_evidence_is_a_validated_named_messagepack_map() -> Result<()> { + let evidence = CultMeshProviderConnectEvidenceWire { + client_session_id: "aetheria-client-42".to_string(), + session_token: Some("odin-session-token".to_string()), + }; + let encoded = encode_provider_connect_evidence(&evidence)?; + assert_eq!( + base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &encoded), + CONNECT_EVIDENCE_GOLDEN + ); + assert_eq!(decode_provider_connect_evidence(&encoded)?, evidence); + let value: rmpv::Value = rmp_serde::from_slice(&encoded)?; + let map = value.as_map().expect("Connect evidence is a named map"); + assert_eq!( + map.iter() + .find_map(|(key, value)| (key.as_str() == Some("clientSessionId")).then_some(value)) + .and_then(rmpv::Value::as_str), + Some("aetheria-client-42") + ); + assert_eq!( + map.iter() + .find_map(|(key, value)| (key.as_str() == Some("sessionToken")).then_some(value)) + .and_then(rmpv::Value::as_str), + Some("odin-session-token") + ); + + assert!( + encode_provider_connect_evidence(&CultMeshProviderConnectEvidenceWire { + client_session_id: String::new(), + session_token: None, + }) + .is_err() + ); + assert!( + encode_provider_connect_evidence(&CultMeshProviderConnectEvidenceWire { + client_session_id: "client".to_string(), + session_token: Some(" ".to_string()), + }) + .is_err() + ); + assert!(decode_provider_connect_evidence(&[]).is_err()); + let tokenless = CultMeshProviderConnectEvidenceWire { + client_session_id: "anonymous-client".to_string(), + session_token: None, + }; + let tokenless_encoded = encode_provider_connect_evidence(&tokenless)?; + assert_eq!( + base64::Engine::encode( + &base64::engine::general_purpose::STANDARD, + &tokenless_encoded + ), + TOKENLESS_CONNECT_EVIDENCE_GOLDEN + ); + assert_eq!( + decode_provider_connect_evidence(&tokenless_encoded)?, + tokenless + ); + Ok(()) +} + +#[test] +fn registration_round_trips_inside_canonical_operation_envelope() -> Result<()> { + let request = create_provider_session_request( + "register-1", + CULTMESH_PROVIDER_REGISTER_OPERATION, + CULTMESH_PROVIDER_REGISTRATION_SCHEMA, + ®istration(), + Some("aetheria-42".to_string()), + Some("odin".to_string()), + )?; + let bytes = encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?; + let decoded_request = + decode_cultnet_message_from_slice(&bytes, CultNetWireContract::CultNetSchemaV0)?; + let decoded: CultMeshProviderRegistrationWire = decode_provider_session_request( + &decoded_request, + CULTMESH_PROVIDER_REGISTER_OPERATION, + CULTMESH_PROVIDER_REGISTRATION_SCHEMA, + )?; + assert_eq!(decoded, registration()); + + let lease = CultMeshProviderLeaseWire { + provider_id: "aetheria".to_string(), + service_instance_id: "aetheria-42".to_string(), + endpoint_id: "aetheria-public".to_string(), + verse_id: "public".to_string(), + lease_id: "lease-2".to_string(), + valid_from_utc: "2026-07-14T12:00:00Z".to_string(), + expires_at_utc: "2026-07-14T12:00:10Z".to_string(), + }; + let response = create_provider_session_response( + &decoded_request, + CultMeshProviderOperationStatus::Ok, + CULTMESH_PROVIDER_LEASE_SCHEMA, + &lease, + Some("odin".to_string()), + )?; + let (status, decoded_lease) = decode_provider_session_response::( + &response, + CULTMESH_PROVIDER_REGISTER_OPERATION, + CULTMESH_PROVIDER_LEASE_SCHEMA, + )?; + assert_eq!(status, CultMeshProviderOperationStatus::Ok); + assert_eq!(decoded_lease, lease); + Ok(()) +} + +#[test] +fn publication_and_command_preserve_typed_messagepack_values() -> Result<()> { + let publication = CultMeshProviderPublicationPutWire { + lease_id: "lease-1".to_string(), + publication_id: "surface:pilot".to_string(), + document: CultNetRawDocumentRecord { + schema_id: "gamecult.eve.surface.v1".to_string(), + record_key: "eve:surface:pilot".to_string(), + stored_at: String::new(), + payload_encoding: CultNetRawPayloadEncoding::Messagepack, + payload: vec![0x81, 0xa2, 0x69, 0x64, 0x01], + source_runtime_id: Some("aetheria-42".to_string()), + source_agent_id: None, + source_role: None, + tags: None, + }, + }; + let publication_encoded = encode_provider_session_payload(&publication)?; + assert_eq!( + decode_provider_session_payload::( + &publication_encoded + )?, + publication + ); + + let command = CultMeshProviderCommandWire { + command_id: "cmd-7".to_string(), + command_kind: "pilot.thrust".to_string(), + provider_id: "aetheria".to_string(), + service_instance_id: "aetheria-42".to_string(), + payload: rmpv::Value::Map(vec![(rmpv::Value::from("axis"), rmpv::Value::F64(0.75))]), + }; + let command_bytes = base64::Engine::decode( + &base64::engine::general_purpose::STANDARD, + encode_provider_session_payload(&command)?, + )?; + let decoded_command = decode_provider_command_document(&CultNetRawDocumentRecord { + schema_id: CULTMESH_PROVIDER_COMMAND_SCHEMA.to_string(), + record_key: "provider-command:aetheria:aetheria-42:cmd-7".to_string(), + stored_at: String::new(), + payload_encoding: CultNetRawPayloadEncoding::Messagepack, + payload: command_bytes, + source_runtime_id: Some("odin".to_string()), + source_agent_id: None, + source_role: Some("provider-session-broker".to_string()), + tags: None, + })?; + assert_eq!(decoded_command, command); + Ok(()) +} + +#[test] +fn lifecycle_validation_rejects_split_or_malformed_authority() { + let mismatched = create_provider_session_request( + "bad-schema", + CULTMESH_PROVIDER_REGISTER_OPERATION, + CULTMESH_PROVIDER_PUBLICATION_PUT_SCHEMA, + ®istration(), + None, + None, + ); + assert!(mismatched.is_err()); + + let malformed_lease = CultMeshProviderLeaseWire { + provider_id: "provider".to_string(), + service_instance_id: "instance".to_string(), + endpoint_id: "endpoint".to_string(), + verse_id: "verse".to_string(), + lease_id: "lease".to_string(), + valid_from_utc: "2026-07-14T12:00:10Z".to_string(), + expires_at_utc: "2026-07-14T12:00:00Z".to_string(), + }; + assert!(encode_provider_session_payload(&malformed_lease).is_err()); + + let malformed_request = CultNetMessage::OperationRequest { + message_id: String::new(), + service_id: CULTMESH_PROVIDER_SESSION_SERVICE_ID.to_string(), + operation: String::new(), + payload_schema: CULTMESH_PROVIDER_REGISTRATION_SCHEMA.to_string(), + payload_encoding: CULTMESH_PROVIDER_SESSION_PAYLOAD_ENCODING.to_string(), + payload: REGISTRATION_GOLDEN.to_string(), + source_runtime_id: None, + target_runtime_id: None, + }; + assert!( + create_provider_session_response( + &malformed_request, + CultMeshProviderOperationStatus::Invalid, + CULTMESH_PROVIDER_MUTATION_ACCEPTANCE_SCHEMA, + &CultMeshProviderMutationAcceptanceWire { + accepted_at_utc: "2026-07-14T12:00:00Z".to_string(), + lease_id: None, + publication_id: None, + command_id: None, + receipt_id: None, + }, + None, + ) + .is_err() + ); +} + +#[test] +fn remaining_lifecycle_payloads_round_trip_as_named_maps() -> Result<()> { + let renewal = CultMeshProviderLeaseRenewalWire { + lease_id: "lease-1".to_string(), + requested_lease_duration_ms: 30_000, + }; + assert_eq!( + decode_provider_session_payload::( + &encode_provider_session_payload(&renewal)? + )?, + renewal + ); + + let deletion = CultMeshProviderPublicationDeleteWire { + lease_id: "lease-1".to_string(), + publication_id: "surface:pilot".to_string(), + schema_id: "gamecult.eve.surface.v1".to_string(), + record_key: "eve:surface:pilot".to_string(), + }; + assert_eq!( + decode_provider_session_payload::( + &encode_provider_session_payload(&deletion)? + )?, + deletion + ); + + let receipt = CultMeshProviderReceiptPutWire { + lease_id: "lease-1".to_string(), + receipt: CultMeshProviderCommandReceiptWire { + receipt_id: "receipt-7".to_string(), + command_id: "cmd-7".to_string(), + command_kind: "pilot.thrust".to_string(), + provider_id: "aetheria".to_string(), + service_instance_id: "aetheria-42".to_string(), + state: CultMeshProviderReceiptStateWire::Applied, + completed_at_utc: "2026-07-14T12:01:02.345Z".to_string(), + result: Some(rmpv::Value::Map(vec![( + rmpv::Value::from("accepted"), + rmpv::Value::Boolean(true), + )])), + error: None, + }, + }; + assert_eq!( + decode_provider_session_payload::( + &encode_provider_session_payload(&receipt)? + )?, + receipt + ); + + let withdrawal = CultMeshProviderWithdrawalWire { + lease_id: "lease-1".to_string(), + }; + assert_eq!( + decode_provider_session_payload::( + &encode_provider_session_payload(&withdrawal)? + )?, + withdrawal + ); + + let acceptance = CultMeshProviderMutationAcceptanceWire { + accepted_at_utc: "2026-07-14T12:01:03Z".to_string(), + lease_id: Some("lease-1".to_string()), + publication_id: Some("surface:pilot".to_string()), + command_id: None, + receipt_id: None, + }; + assert_eq!( + decode_provider_session_payload::( + &encode_provider_session_payload(&acceptance)? + )?, + acceptance + ); + Ok(()) +} + +#[test] +fn non_ok_response_uses_correlated_empty_map_and_diagnostics() -> Result<()> { + let request = create_provider_session_request( + "register-denied", + CULTMESH_PROVIDER_REGISTER_OPERATION, + CULTMESH_PROVIDER_REGISTRATION_SCHEMA, + ®istration(), + Some("aetheria-42".to_string()), + Some("odin".to_string()), + )?; + let response = create_provider_session_error_response( + &request, + CultMeshProviderOperationStatus::Denied, + vec!["registration authority rejected the session".to_string()], + Some("odin".to_string()), + )?; + let CultNetMessage::OperationResponse { + message_id, + operation, + status, + payload_schema, + payload, + diagnostics, + .. + } = response + else { + panic!("expected operation response"); + }; + assert_eq!(message_id, "register-denied"); + assert_eq!(operation, CULTMESH_PROVIDER_REGISTER_OPERATION); + assert_eq!(status, "denied"); + assert_eq!(payload_schema, CULTMESH_PROVIDER_MUTATION_ACCEPTANCE_SCHEMA); + assert_eq!(diagnostics.len(), 1); + let bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, payload)?; + assert_eq!( + rmp_serde::from_slice::(&bytes)?, + rmpv::Value::Map(Vec::new()) + ); + assert!( + create_provider_session_error_response( + &request, + CultMeshProviderOperationStatus::Ok, + vec!["not an error".to_string()], + None, + ) + .is_err() + ); + Ok(()) +} diff --git a/packages/cultnet-rs/tests/rudp_server_hub.rs b/packages/cultnet-rs/tests/rudp_server_hub.rs new file mode 100644 index 00000000..a8a2c114 --- /dev/null +++ b/packages/cultnet-rs/tests/rudp_server_hub.rs @@ -0,0 +1,459 @@ +use std::net::UdpSocket; +use std::time::Duration; + +use anyhow::{Result, anyhow}; +use cultnet_rs::*; + +const CONNECTION_ID: u32 = 0x4355_4c54; + +fn socket() -> Result { + let socket = UdpSocket::bind("127.0.0.1:0")?; + socket.set_read_timeout(Some(Duration::from_millis(20)))?; + Ok(socket) +} + +fn client(remote: std::net::SocketAddr) -> Result { + let mut options = + CultNetRudpSocketTransportOptions::client("provider", socket()?, remote, CONNECTION_ID); + options.max_fragment_bytes = Some(2_048); + CultNetRudpSocketTransportConnection::new(options) +} + +fn connect( + hub: &mut CultNetRudpServerHub, + client: &mut CultNetRudpSocketTransportConnection, + evidence: &[u8], +) -> Result { + client.connect(evidence.to_vec())?; + let mut connected = None; + for _ in 0..20 { + if let Some(CultNetRudpServerEvent::Connected { session }) = hub.receive_event_once()? { + connected = Some(session); + break; + } + } + let session = connected.ok_or_else(|| anyhow!("hub did not receive Connect"))?; + let _ = client.receive_once()?; + assert!(client.connected()); + Ok(session) +} + +fn receive_frame(hub: &mut CultNetRudpServerHub) -> Result { + for _ in 0..20 { + if let Some(event @ CultNetRudpServerEvent::Frame { .. }) = hub.receive_event_once()? { + return Ok(event); + } + } + Err(anyhow!("hub did not receive a frame")) +} + +fn receive_message(client: &mut CultNetRudpSocketTransportConnection) -> Result { + for _ in 0..20 { + if let Some(message) = client.receive_schema_message_once()? { + return Ok(message); + } + } + Err(anyhow!("client did not receive a schema message")) +} + +#[test] +fn hub_keeps_independent_peer_sessions_and_exposes_connect_evidence() -> Result<()> { + let server_socket = socket()?; + let server_addr = server_socket.local_addr()?; + let mut hub = CultNetRudpServerHub::new(CultNetRudpServerHubOptions::new( + "odin", + server_socket, + CONNECTION_ID, + ))?; + let mut first = client(server_addr)?; + let mut second = client(server_addr)?; + + let first_session = connect(&mut hub, &mut first, b"session-token-one")?; + let second_session = connect(&mut hub, &mut second, b"session-token-two")?; + assert_ne!(first_session.remote_addr, second_session.remote_addr); + assert_eq!(first_session.connect_payload, b"session-token-one"); + assert_eq!(second_session.connect_payload, b"session-token-two"); + assert_eq!(hub.sessions().len(), 2); + + let first_request = create_provider_session_request( + "register-first", + CULTMESH_PROVIDER_REGISTER_OPERATION, + CULTMESH_PROVIDER_REGISTRATION_SCHEMA, + &CultMeshProviderRegistrationWire { + provider_id: "first".to_string(), + service_instance_id: "first-1".to_string(), + endpoint_id: "first-public".to_string(), + verse_id: "public".to_string(), + requested_lease_duration_ms: 30_000, + authority_lease_id: None, + }, + Some("first-1".to_string()), + Some("odin".to_string()), + )?; + let second_request = create_provider_session_request( + "register-second", + CULTMESH_PROVIDER_REGISTER_OPERATION, + CULTMESH_PROVIDER_REGISTRATION_SCHEMA, + &CultMeshProviderRegistrationWire { + provider_id: "second".to_string(), + service_instance_id: "second-1".to_string(), + endpoint_id: "second-public".to_string(), + verse_id: "public".to_string(), + requested_lease_duration_ms: 30_000, + authority_lease_id: None, + }, + Some("second-1".to_string()), + Some("odin".to_string()), + )?; + first.send_schema_message(&first_request)?; + second.send_schema_message(&second_request)?; + + for _ in 0..2 { + let CultNetRudpServerEvent::Frame { session, frame } = receive_frame(&mut hub)? else { + unreachable!(); + }; + assert_eq!(frame.channel_id, "schema"); + let request = decode_cultnet_message_from_slice( + &frame.payload, + CultNetWireContract::CultNetSchemaV0, + )?; + let CultNetMessage::OperationRequest { message_id, .. } = &request else { + return Err(anyhow!("expected operation request")); + }; + let provider_id = if message_id == "register-first" { + "first" + } else { + "second" + }; + let lease = CultMeshProviderLeaseWire { + provider_id: provider_id.to_string(), + service_instance_id: format!("{provider_id}-1"), + endpoint_id: format!("{provider_id}-public"), + verse_id: "public".to_string(), + lease_id: format!("lease-{provider_id}"), + valid_from_utc: "2026-07-14T12:00:00Z".to_string(), + expires_at_utc: "2026-07-14T12:00:30Z".to_string(), + }; + let response = create_provider_session_response( + &request, + CultMeshProviderOperationStatus::Ok, + CULTMESH_PROVIDER_LEASE_SCHEMA, + &lease, + Some("odin".to_string()), + )?; + hub.send_schema_message(&session, &response)?; + } + + let first_response = receive_message(&mut first)?; + let second_response = receive_message(&mut second)?; + let (_, first_lease) = decode_provider_session_response::( + &first_response, + CULTMESH_PROVIDER_REGISTER_OPERATION, + CULTMESH_PROVIDER_LEASE_SCHEMA, + )?; + let (_, second_lease) = decode_provider_session_response::( + &second_response, + CULTMESH_PROVIDER_REGISTER_OPERATION, + CULTMESH_PROVIDER_LEASE_SCHEMA, + )?; + assert_eq!(first_lease.provider_id, "first"); + assert_eq!(second_lease.provider_id, "second"); + assert_eq!(hub.session(first_session.remote_addr), Some(&first_session)); + assert_eq!( + hub.session(second_session.remote_addr), + Some(&second_session) + ); + Ok(()) +} + +#[test] +fn hub_fences_replaced_generations_and_does_not_replace_connect_retransmits() -> Result<()> { + let server_socket = socket()?; + let server_addr = server_socket.local_addr()?; + let mut hub = CultNetRudpServerHub::new(CultNetRudpServerHubOptions::new( + "odin", + server_socket, + CONNECTION_ID, + ))?; + let mut provider = client(server_addr)?; + let original_evidence = + encode_provider_connect_evidence(&CultMeshProviderConnectEvidenceWire { + client_session_id: "provider-client-1".to_string(), + session_token: Some("shared-session-token".to_string()), + })?; + let replacement_evidence = + encode_provider_connect_evidence(&CultMeshProviderConnectEvidenceWire { + client_session_id: "provider-client-2".to_string(), + session_token: Some("shared-session-token".to_string()), + })?; + let original = connect(&mut hub, &mut provider, &original_evidence)?; + + provider.connect(original_evidence.clone())?; + for _ in 0..3 { + assert!(hub.receive_event_once()?.is_none()); + } + assert_eq!(hub.session(original.remote_addr), Some(&original)); + + provider.connect(replacement_evidence.clone())?; + let mut disconnected = None; + for _ in 0..20 { + if let Some(event @ CultNetRudpServerEvent::Disconnected { .. }) = + hub.receive_event_once()? + { + disconnected = Some(event); + break; + } + } + let disconnected = + disconnected.ok_or_else(|| anyhow!("replacement did not disconnect old generation"))?; + let CultNetRudpServerEvent::Disconnected { session, .. } = disconnected else { + return Err(anyhow!("expected old generation Disconnected event")); + }; + assert_eq!(session, original); + let connected = hub + .receive_event_once()? + .ok_or_else(|| anyhow!("replacement did not connect new generation"))?; + let CultNetRudpServerEvent::Connected { + session: replacement, + } = connected + else { + return Err(anyhow!("expected replacement Connected event")); + }; + assert_ne!(replacement.session_generation, original.session_generation); + let original_decoded = decode_provider_connect_evidence(&original.connect_payload)?; + let replacement_decoded = decode_provider_connect_evidence(&replacement.connect_payload)?; + assert_eq!( + original_decoded.session_token, + replacement_decoded.session_token + ); + assert_ne!( + original_decoded.client_session_id, + replacement_decoded.client_session_id + ); + assert!( + hub.send(&original, "schema", vec![0x80]) + .unwrap_err() + .to_string() + .contains("no longer active") + ); + assert_eq!(hub.session(replacement.remote_addr), Some(&replacement)); + Ok(()) +} + +#[test] +fn identical_connect_retransmit_reuses_pending_accept_after_loss() -> Result<()> { + let server_socket = socket()?; + let server_addr = server_socket.local_addr()?; + let mut hub = CultNetRudpServerHub::new(CultNetRudpServerHubOptions::new( + "odin", + server_socket, + CONNECTION_ID, + ))?; + let client_socket = socket()?; + let mut client_session = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: CONNECTION_ID, + initial_sequence: 1, + resend_delay_ms: 250, + max_pending_reliable_packets: None, + }); + let evidence = encode_provider_connect_evidence(&CultMeshProviderConnectEvidenceWire { + client_session_id: "provider-client-lost-accept".to_string(), + session_token: Some("shared-session-token".to_string()), + })?; + let connect_packet = client_session.create_connect(0, evidence)?; + let connect_wire = encode_rudp_packet(&connect_packet)?; + + client_socket.send_to(&connect_wire, server_addr)?; + let CultNetRudpServerEvent::Connected { session } = hub + .receive_event_once()? + .ok_or_else(|| anyhow!("hub did not accept first Connect"))? + else { + return Err(anyhow!("hub did not emit Connected")); + }; + let mut buffer = vec![0_u8; 65_535]; + let (first_len, _) = client_socket.recv_from(&mut buffer)?; + let lost_accept = decode_rudp_packet(&buffer[..first_len])?; + assert_eq!(lost_accept.packet_type, CultNetRudpPacketType::Accept); + + client_socket.send_to(&connect_wire, server_addr)?; + assert!(hub.receive_event_once()?.is_none()); + let (resent_len, _) = client_socket.recv_from(&mut buffer)?; + let resent_accept = decode_rudp_packet(&buffer[..resent_len])?; + assert_eq!(resent_accept, lost_accept); + assert_eq!(hub.session(session.remote_addr), Some(&session)); + + client_session.receive(&resent_accept, 1)?; + assert!(client_session.connected()); + Ok(()) +} + +#[test] +fn exact_reliable_acks_clear_more_than_one_ack_window_of_fragments() -> Result<()> { + let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: CONNECTION_ID, + initial_sequence: 1, + resend_delay_ms: 250, + max_pending_reliable_packets: None, + }); + let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: CONNECTION_ID, + initial_sequence: 1, + resend_delay_ms: 250, + max_pending_reliable_packets: None, + }); + let connect_packet = sender.create_connect(0, Vec::new())?; + let accept = receiver.accept_connect(&connect_packet, 0, Vec::new())?; + sender.receive(&accept, 0)?; + receiver.receive(&sender.create_ack_for(accept.sequence), 0)?; + + let packets = sender.send_many( + "schema", + vec![0x5a; 40], + CultNetRudpSendOptions { + reliable: true, + ordered: true, + sequenced: false, + now_ms: 1, + }, + Some(1), + )?; + assert_eq!(packets.len(), 40); + let mut delivered = Vec::new(); + for packet in &packets { + let result = receiver.receive(packet, 2)?; + delivered.extend(result.delivered); + sender.receive(&receiver.create_ack_for(packet.sequence), 3)?; + } + assert_eq!(delivered.len(), 1); + assert_eq!(delivered[0].payload, vec![0x5a; 40]); + assert!(sender.pending_reliable_sequences().is_empty()); + Ok(()) +} + +#[test] +fn session_and_hub_reject_configured_memory_bounds() -> Result<()> { + let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: CONNECTION_ID, + initial_sequence: 1, + resend_delay_ms: 250, + max_pending_reliable_packets: None, + }); + receiver.set_max_payload_bytes(Some(4)); + receiver.set_max_pending_fragment_sets(1)?; + let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: CONNECTION_ID, + initial_sequence: 1, + resend_delay_ms: 250, + max_pending_reliable_packets: None, + }); + let connect_packet = sender.create_connect(0, Vec::new())?; + let accept = receiver.accept_connect(&connect_packet, 0, Vec::new())?; + sender.receive(&accept, 0)?; + + let oversized = sender.send_many( + "schema", + vec![1, 2, 3, 4, 5], + CultNetRudpSendOptions { + reliable: true, + ordered: true, + sequenced: false, + now_ms: 1, + }, + Some(2), + )?; + receiver.receive(&oversized[0], 1)?; + receiver.receive(&oversized[1], 1)?; + assert!(receiver.receive(&oversized[2], 1).is_err()); + + let fragment_options = CultNetRudpSendOptions { + reliable: true, + ordered: true, + sequenced: false, + now_ms: 2, + }; + let first_set = sender.send_many( + "schema", + vec![1, 2, 3, 4], + fragment_options.clone(), + Some(2), + )?; + let second_set = sender.send_many("schema", vec![5, 6, 7, 8], fragment_options, Some(2))?; + receiver.receive(&first_set[0], 2)?; + assert!(receiver.receive(&second_set[0], 2).is_err()); + + let server_socket = socket()?; + let server_addr = server_socket.local_addr()?; + let mut options = CultNetRudpServerHubOptions::new("odin", server_socket, CONNECTION_ID); + options.max_peers = 1; + let mut hub = CultNetRudpServerHub::new(options)?; + let mut first = client(server_addr)?; + let mut second = client(server_addr)?; + connect(&mut hub, &mut first, b"first")?; + second.connect(b"second".to_vec())?; + for _ in 0..20 { + match hub.receive_event_once() { + Err(error) => { + assert!(error.to_string().contains("peer limit")); + return Ok(()); + } + Ok(_) => continue, + } + } + Err(anyhow!("hub did not enforce peer limit")) +} + +#[test] +fn replay_history_is_bounded_and_idle_hub_sessions_expire() -> Result<()> { + let mut sender = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: CONNECTION_ID, + initial_sequence: 1, + resend_delay_ms: 250, + max_pending_reliable_packets: None, + }); + let mut receiver = CultNetRudpSession::new(CultNetRudpSessionOptions { + connection_id: CONNECTION_ID, + initial_sequence: 1, + resend_delay_ms: 250, + max_pending_reliable_packets: None, + }); + let connect_packet = sender.create_connect(0, Vec::new())?; + let accept = receiver.accept_connect(&connect_packet, 0, Vec::new())?; + sender.receive(&accept, 0)?; + let mut oldest = None; + for sequence in 0..4_100 { + let packet = sender.send( + "realtime", + vec![(sequence % 251) as u8], + CultNetRudpSendOptions { + reliable: false, + ordered: false, + sequenced: false, + now_ms: sequence, + }, + )?; + if oldest.is_none() { + oldest = Some(packet.clone()); + } + assert_eq!(receiver.receive(&packet, sequence)?.delivered.len(), 1); + } + assert!( + receiver + .receive(&oldest.expect("oldest packet"), 4_101)? + .delivered + .is_empty() + ); + + let server_socket = socket()?; + let server_addr = server_socket.local_addr()?; + let mut hub = CultNetRudpServerHub::new(CultNetRudpServerHubOptions::new( + "odin", + server_socket, + CONNECTION_ID, + ))?; + let mut provider = client(server_addr)?; + let context = connect(&mut hub, &mut provider, b"expiring-session")?; + std::thread::sleep(Duration::from_millis(2)); + assert_eq!(hub.remove_timed_out_sessions(0), vec![context]); + assert!(hub.sessions().is_empty()); + Ok(()) +} diff --git a/packages/cultnet-ts/package.json b/packages/cultnet-ts/package.json index b4c17ade..f0a3e396 100644 --- a/packages/cultnet-ts/package.json +++ b/packages/cultnet-ts/package.json @@ -1,19 +1,27 @@ { "name": "cultnet-ts", - "version": "0.1.0", + "version": "0.1.1", "description": "CultNet-style typed direct-pipe messaging and state replication for TypeScript runtimes.", "main": "dist/index.js", "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "require": "./dist/index.js", + "default": "./dist/index.js" + } + }, "files": [ "dist", "contracts" ], "scripts": { "contracts:generate": "node tools/generate-swarm-contracts.mjs", - "build": "npm run contracts:generate && tsc -p tsconfig.json", - "typecheck": "npm run contracts:generate && tsc -p tsconfig.json --pretty false", - "test": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js", - "test:interop": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/test/interop/*.test.js" + "build": "node tools/generate-swarm-contracts.mjs && node ../../node_modules/typescript/bin/tsc -p tsconfig.json", + "prepack": "node tools/generate-swarm-contracts.mjs && node ../../node_modules/typescript/bin/tsc -p tsconfig.json", + "typecheck": "node tools/generate-swarm-contracts.mjs && node ../../node_modules/typescript/bin/tsc -p tsconfig.json --pretty false", + "test": "node tools/generate-swarm-contracts.mjs && node ../../node_modules/typescript/bin/tsc -p tsconfig.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js", + "test:interop": "node tools/generate-swarm-contracts.mjs && node ../../node_modules/typescript/bin/tsc -p tsconfig.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.test.json && node --test dist-test/test/interop/*.test.js" }, "keywords": [ "messagepack", @@ -25,10 +33,22 @@ ], "author": "metacratic", "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/GameCult/CultLib.git", + "directory": "packages/cultnet-ts" + }, + "bugs": { + "url": "https://github.com/GameCult/CultLib/issues" + }, + "homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultnet-ts#readme", + "engines": { + "node": ">=18" + }, "dependencies": { "@msgpack/msgpack": "^3.1.3", "ajv": "^8.17.1", - "cultcache-ts": "file:../cultcache-ts" + "cultcache-ts": "^0.13.5" }, "devDependencies": { "@types/node": "^24.0.0", diff --git a/packages/cultnet-ts/src/generated/swarm-contracts.generated.ts b/packages/cultnet-ts/src/generated/swarm-contracts.generated.ts index cfa33070..f6f673a3 100644 --- a/packages/cultnet-ts/src/generated/swarm-contracts.generated.ts +++ b/packages/cultnet-ts/src/generated/swarm-contracts.generated.ts @@ -124,13 +124,7 @@ export interface Belief { confidence: number; subject_id?: string; claim_type?: - | 'fact' - | 'identity_inference' - | 'motive_inference' - | 'prediction' - | 'norm' - | 'value_read' - | 'relationship_read'; + 'fact' | 'identity_inference' | 'motive_inference' | 'prediction' | 'norm' | 'value_read' | 'relationship_read'; evidence_event_ids?: string[]; visibility?: 'private' | 'shared' | 'public' | 'rumor'; emotional_charge?: number; diff --git a/packages/cultnet-ts/src/rudp.ts b/packages/cultnet-ts/src/rudp.ts index 06c09bc3..7a38cb1d 100644 --- a/packages/cultnet-ts/src/rudp.ts +++ b/packages/cultnet-ts/src/rudp.ts @@ -207,10 +207,18 @@ export class CultNetRudpSession { throw new Error(`Expected RUDP connect packet, got ${packet.packetType}.`); } - const wasConnected = this.#connected; - if (!wasConnected) { - this.#ensureReliableCapacity(1); + const pendingAccept = [...this.#pendingReliable.values()] + .find(pending => pending.packet.packetType === "accept"); + if (pendingAccept) { + this.#rememberReceived(packet.sequence); + this.#lastReceivedAtMs = nowMs; + pendingAccept.lastSentAtMs = nowMs; + return { + ...pendingAccept.packet, + payload: new Uint8Array(pendingAccept.packet.payload ?? new Uint8Array()), + }; } + this.#ensureReliableCapacity(1); this.#rememberReceived(packet.sequence); this.#lastReceivedAtMs = nowMs; this.#connected = true; @@ -221,9 +229,7 @@ export class CultNetRudpSession { ordered: true, payload, }); - if (!wasConnected) { - this.#trackReliable(response, nowMs); - } + this.#trackReliable(response, nowMs); return response; } @@ -386,6 +392,24 @@ export class CultNetRudpSession { }; } + createAckFor(sequence: number): CultNetRudpPacket { + return { + packetType: "ack", + connectionId: this.connectionId, + sequence: 0, + ack: toUint32(sequence, "ack sequence"), + ackMask: 0, + channelId: "control", + reliable: false, + ordered: false, + sequenced: false, + fragmentId: 0, + fragmentIndex: 0, + fragmentCount: 0, + payload: new Uint8Array(), + }; + } + createPing(payload = new Uint8Array()): CultNetRudpPacket { return this.#createPacket({ packetType: "ping", diff --git a/packages/cultnet-ts/test/cultnet.test.ts b/packages/cultnet-ts/test/cultnet.test.ts index 0677d421..46e7cb6f 100644 --- a/packages/cultnet-ts/test/cultnet.test.ts +++ b/packages/cultnet-ts/test/cultnet.test.ts @@ -415,6 +415,14 @@ test("rudp session handshake acks reliable connect and accept packets", () => { assert.equal(server.connected, true); assert.deepEqual(server.pendingReliableSequences, [100]); + const retransmittedAccept = server.acceptConnect(connect, 15, Buffer.from("ok", "utf8")); + assert.deepEqual( + encodeRudpPacket(retransmittedAccept), + encodeRudpPacket(accept), + "a retransmitted Connect reuses the pending Accept packet", + ); + assert.deepEqual(server.pendingReliableSequences, [100]); + client.receive(accept, 20); assert.equal(client.connected, true); assert.deepEqual(client.pendingReliableSequences, []); diff --git a/scripts/build-quic-native.ps1 b/scripts/build-quic-native.ps1 new file mode 100644 index 00000000..2de12bde --- /dev/null +++ b/scripts/build-quic-native.ps1 @@ -0,0 +1,54 @@ +param( + [string] $Configuration = "Release", + [string] $Architecture = "x64", + [string] $OutputDirectory = "artifacts\quic-native" +) + +$ErrorActionPreference = "Stop" +if ($Architecture -ne "x64") { + throw "The first CultMesh native QUIC package supports x64 Windows desktop only." +} + +$repoRoot = Split-Path -Parent $PSScriptRoot +$version = "2.5.9" +$expectedPackageSha256 = "9877A919E1AA73AA4800F1E8A06B6539021F376228910138EB04540CD956617B" +$cacheRoot = Join-Path $repoRoot "artifacts\dependencies\msquic-schannel-$version" +$packagePath = Join-Path $cacheRoot "Microsoft.Native.Quic.MsQuic.Schannel.$version.zip" +$extractRoot = Join-Path $cacheRoot "package" +$nativeRoot = Join-Path $extractRoot "build\native" +$buildRoot = Join-Path $repoRoot "artifacts\quic-native-build\$Architecture\$Configuration" +$outputRoot = if ([IO.Path]::IsPathRooted($OutputDirectory)) { + $OutputDirectory +} else { + Join-Path $repoRoot $OutputDirectory +} + +New-Item -ItemType Directory -Force -Path $cacheRoot | Out-Null +if (-not (Test-Path -LiteralPath $packagePath)) { + & curl.exe -L --fail --silent --show-error ` + -o $packagePath ` + "https://www.nuget.org/api/v2/package/Microsoft.Native.Quic.MsQuic.Schannel/$version" + if ($LASTEXITCODE -ne 0) { throw "MsQuic package download failed with exit code $LASTEXITCODE" } +} +if ((Get-FileHash -LiteralPath $packagePath -Algorithm SHA256).Hash -ne $expectedPackageSha256) { + throw "MsQuic package digest does not match the pinned release." +} +if (-not (Test-Path -LiteralPath (Join-Path $nativeRoot "include\msquic.h"))) { + if (Test-Path -LiteralPath $extractRoot) { Remove-Item -LiteralPath $extractRoot -Recurse -Force } + Expand-Archive -LiteralPath $packagePath -DestinationPath $extractRoot +} + +cmake -S (Join-Path $repoRoot "native\GameCult.Mesh.Quic.Native") -B $buildRoot -A x64 ` + "-DMSQUIC_ROOT=$($nativeRoot.Replace('\', '/'))" +if ($LASTEXITCODE -ne 0) { throw "CultMesh native QUIC configure failed with exit code $LASTEXITCODE" } +cmake --build $buildRoot --config $Configuration +if ($LASTEXITCODE -ne 0) { throw "CultMesh native QUIC build failed with exit code $LASTEXITCODE" } + +New-Item -ItemType Directory -Force -Path $outputRoot | Out-Null +Copy-Item -LiteralPath (Join-Path $buildRoot "bin\$Configuration\gamecult_mesh_quic_native.dll") ` + -Destination $outputRoot -Force +Copy-Item -LiteralPath (Join-Path $nativeRoot "bin\x64\msquic.dll") -Destination $outputRoot -Force +Copy-Item -LiteralPath (Join-Path $extractRoot "LICENSE") -Destination (Join-Path $outputRoot "MSQUIC-LICENSE.txt") -Force + +Write-Host "CultMesh native QUIC runtime: $outputRoot" +Get-ChildItem -LiteralPath $outputRoot -File | Select-Object Name,Length diff --git a/scripts/build-unity-package.ps1 b/scripts/build-unity-package.ps1 index 6ba396e8..dbc01233 100644 --- a/scripts/build-unity-package.ps1 +++ b/scripts/build-unity-package.ps1 @@ -1,14 +1,18 @@ param( [string] $Configuration = "Release", - [string] $OutputDirectory = "artifacts\unity\org.gamecult.cultlib" + [string] $OutputDirectory = "artifacts\unity\org.gamecult.cultlib", + [switch] $UpdateTemplate ) $ErrorActionPreference = "Stop" $repoRoot = Split-Path -Parent $PSScriptRoot $projectPath = Join-Path $repoRoot "src\GameCult.Mesh\GameCult.Mesh.csproj" +$quicProjectPath = Join-Path $repoRoot "src\GameCult.Mesh.Quic.Native\GameCult.Mesh.Quic.Native.csproj" $templateRoot = Join-Path $repoRoot "unity\org.gamecult.cultlib" $publishRoot = Join-Path $repoRoot "artifacts\unity-publish" +$quicPublishRoot = Join-Path $repoRoot "artifacts\unity-quic-publish" +$quicNativeRoot = Join-Path $repoRoot "artifacts\unity-quic-native" $outputRoot = if ([System.IO.Path]::IsPathRooted($OutputDirectory)) { $OutputDirectory } else { @@ -23,6 +27,7 @@ $expectedAssemblies = @( "GameCult.Caching.MessagePack.dll", "GameCult.Logging.dll", "GameCult.Mesh.dll", + "GameCult.Mesh.Quic.Native.dll", "GameCult.Networking.dll", "Isopoh.Cryptography.Argon2.dll", "Isopoh.Cryptography.Blake2b.dll", @@ -47,6 +52,7 @@ $ownedAssemblies = @( "GameCult.Caching.MessagePack.dll", "GameCult.Logging.dll", "GameCult.Mesh.dll", + "GameCult.Mesh.Quic.Native.dll", "GameCult.Networking.dll" ) $expectedPdbs = $ownedAssemblies | ForEach-Object { [System.IO.Path]::ChangeExtension($_, ".pdb") } @@ -94,6 +100,9 @@ Assert-SameNames $asmdef.precompiledReferences $expectedAssemblies "asmdef preco if (Test-Path -LiteralPath $publishRoot) { Remove-Item -LiteralPath $publishRoot -Recurse -Force } +if (Test-Path -LiteralPath $quicPublishRoot) { + Remove-Item -LiteralPath $quicPublishRoot -Recurse -Force +} if (Test-Path -LiteralPath $outputRoot) { Remove-Item -LiteralPath $outputRoot -Recurse -Force } @@ -103,11 +112,22 @@ dotnet publish $projectPath -c $Configuration -o $publishRoot --disable-build-se if ($LASTEXITCODE -ne 0) { throw "CultLib publish failed with exit code $LASTEXITCODE" } +dotnet publish $quicProjectPath -c $Configuration -o $quicPublishRoot --disable-build-servers ` + -p:UseSharedCompilation=false -m:1 -p:Version=$($manifest.version) +if ($LASTEXITCODE -ne 0) { + throw "CultLib native QUIC managed publish failed with exit code $LASTEXITCODE" +} +& (Join-Path $PSScriptRoot "build-quic-native.ps1") ` + -Configuration $Configuration ` + -OutputDirectory $quicNativeRoot $publishedByName = @{} foreach ($assembly in Get-ChildItem -LiteralPath $publishRoot -Filter "*.dll") { $publishedByName[$assembly.Name] = $assembly } +foreach ($assembly in Get-ChildItem -LiteralPath $quicPublishRoot -Filter "*.dll") { + $publishedByName[$assembly.Name] = $assembly +} foreach ($assemblyName in $expectedAssemblies) { if (-not $publishedByName.ContainsKey($assemblyName)) { throw "CultLib Unity package is missing expected assembly: $assemblyName" @@ -119,13 +139,22 @@ foreach ($assemblyName in $expectedAssemblies) { Copy-Item -LiteralPath $publishedByName[$assemblyName].FullName -Destination $pluginRoot -Force } foreach ($pdbName in $expectedPdbs) { - $pdbPath = Join-Path $publishRoot $pdbName + $pdbPath = @($publishRoot, $quicPublishRoot) | + ForEach-Object { Join-Path $_ $pdbName } | + Where-Object { Test-Path -LiteralPath $_ } | + Select-Object -First 1 if (-not (Test-Path -LiteralPath $pdbPath)) { throw "CultLib Unity package is missing expected symbols: $pdbName" } Copy-Item -LiteralPath $pdbPath -Destination $pluginRoot -Force } +$nativePluginRoot = Join-Path $pluginRoot "x86_64" +Copy-Item -LiteralPath (Join-Path $quicNativeRoot "gamecult_mesh_quic_native.dll") -Destination $nativePluginRoot -Force +Copy-Item -LiteralPath (Join-Path $quicNativeRoot "msquic.dll") -Destination $nativePluginRoot -Force +Copy-Item -LiteralPath (Join-Path $quicNativeRoot "MSQUIC-LICENSE.txt") ` + -Destination (Join-Path $outputRoot "Third Party Notices\MSQUIC-LICENSE.txt") -Force + Assert-SameNames ` (Get-ChildItem -LiteralPath $pluginRoot -Filter "*.dll" | Select-Object -ExpandProperty Name) ` $expectedAssemblies ` @@ -142,7 +171,7 @@ foreach ($assemblyName in $ownedAssemblies) { if ($fileVersion -ne $expectedFileVersion) { throw "$assemblyName has file version $fileVersion; expected $expectedFileVersion." } - $freshHash = (Get-FileHash -LiteralPath (Join-Path $publishRoot $assemblyName) -Algorithm SHA256).Hash + $freshHash = (Get-FileHash -LiteralPath $publishedByName[$assemblyName].FullName -Algorithm SHA256).Hash $stagedHash = (Get-FileHash -LiteralPath $assemblyPath -Algorithm SHA256).Hash if ($freshHash -ne $stagedHash) { throw "$assemblyName differs between the fresh publish and staged package." @@ -155,9 +184,29 @@ $resolverAssemblyMetadata = [System.Text.Encoding]::UTF8.GetString( if (-not $resolverAssemblyMetadata.Contains("CultDocumentMessagePackResolversAttribute")) { throw "GameCult.Caching.MessagePack.dll lacks CultDocumentMessagePackResolversAttribute." } +$meshAssemblyMetadata = [System.Text.Encoding]::UTF8.GetString( + [System.IO.File]::ReadAllBytes((Join-Path $pluginRoot "GameCult.Mesh.dll"))) +if (-not $meshAssemblyMetadata.Contains("ICultMeshBodyReadLease")) { + throw "GameCult.Mesh.dll lacks ICultMeshBodyReadLease." +} + +if ($UpdateTemplate) { + foreach ($name in $expectedAssemblies + $expectedPdbs) { + Copy-Item -LiteralPath (Join-Path $pluginRoot $name) -Destination $templatePluginRoot -Force + } + Copy-Item -LiteralPath (Join-Path $nativePluginRoot "gamecult_mesh_quic_native.dll") ` + -Destination (Join-Path $templatePluginRoot "x86_64") -Force + Copy-Item -LiteralPath (Join-Path $nativePluginRoot "msquic.dll") ` + -Destination (Join-Path $templatePluginRoot "x86_64") -Force + Copy-Item -LiteralPath (Join-Path $outputRoot "Third Party Notices\MSQUIC-LICENSE.txt") ` + -Destination (Join-Path $templateRoot "Third Party Notices") -Force + Write-Host "Updated tracked Unity package assemblies: $templatePluginRoot" +} Write-Host "CultLib Unity package: $outputRoot" Write-Host "Package: $($manifest.name)@$($manifest.version)" Write-Host "Managed assemblies: $($expectedAssemblies.Count)" Write-Host "Verified owned assembly version: $expectedFileVersion" Write-Host "Verified Stage 1 MessagePack resolver attribute." +Write-Host "Verified ICultMeshBodyReadLease." +Write-Host "Native realtime: MsQuic Schannel 2.5.9 (Windows x64)" diff --git a/scripts/run-typescript-workspaces.mjs b/scripts/run-typescript-workspaces.mjs new file mode 100644 index 00000000..f2cf74bc --- /dev/null +++ b/scripts/run-typescript-workspaces.mjs @@ -0,0 +1,30 @@ +import { execFileSync } from "node:child_process"; +import { dirname, join } from "node:path"; + +const command = process.argv[2]; +if (!command) throw new Error("Usage: node scripts/run-typescript-workspaces.mjs