Merge CultMesh reliability into Geometry Unity release
This commit is contained in:
commit
e3e1ac0420
152 changed files with 26486 additions and 753 deletions
30
CultLib.sln
30
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
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@
|
|||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
<Copyright>© Meta Vens and contributors</Copyright>
|
||||
<PublishRepositoryUrl>true</PublishRepositoryUrl>
|
||||
<Version>1.0.3</Version>
|
||||
<Version>1.0.33</Version>
|
||||
<CultMathCandidateFeed Condition="'$(CultMathCandidateFeed)' == ''">$(MSBuildThisFileDirectory)..\CultMath\.tools\local-feed</CultMathCandidateFeed>
|
||||
<RestoreAdditionalProjectSources Condition="Exists('$(CultMathCandidateFeed)')">$(RestoreAdditionalProjectSources);$(CultMathCandidateFeed)</RestoreAdditionalProjectSources>
|
||||
|
||||
|
|
|
|||
61
docs/cultmesh-provider-session.md
Normal file
61
docs/cultmesh-provider-session.md
Normal file
|
|
@ -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.
|
||||
|
|
@ -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
|
||||
```
|
||||
|
|
|
|||
20
native/GameCult.Mesh.Quic.Native/CMakeLists.txt
Normal file
20
native/GameCult.Mesh.Quic.Native/CMakeLists.txt
Normal file
|
|
@ -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")
|
||||
10
native/GameCult.Mesh.Quic.Native/README.md
Normal file
10
native/GameCult.Mesh.Quic.Native/README.md
Normal file
|
|
@ -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.
|
||||
440
native/GameCult.Mesh.Quic.Native/cultmesh_quic_native.cpp
Normal file
440
native/GameCult.Mesh.Quic.Native/cultmesh_quic_native.cpp
Normal file
|
|
@ -0,0 +1,440 @@
|
|||
#include <windows.h>
|
||||
#include <wincrypt.h>
|
||||
#include <bcrypt.h>
|
||||
#include <msquic.h>
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<uint8_t> 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<uint8_t, 32> certificate_pin{};
|
||||
std::atomic<ClientState> state{ClientState::Connecting};
|
||||
std::atomic<bool> closing{false};
|
||||
std::mutex gate;
|
||||
std::deque<std::vector<uint8_t>> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<uint8_t>(value - '0');
|
||||
else if (value >= 'a' && value <= 'f') nibble = static_cast<uint8_t>(value - 'a' + 10);
|
||||
else if (value >= 'A' && value <= 'F') nibble = static_cast<uint8_t>(value - 'A' + 10);
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ParsePin(const char* value, std::array<uint8_t, 32>& 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<uint8_t>((high << 4) | low);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
uint32_t ReadUInt32LittleEndian(const uint8_t* value) {
|
||||
return static_cast<uint32_t>(value[0]) |
|
||||
(static_cast<uint32_t>(value[1]) << 8) |
|
||||
(static_cast<uint32_t>(value[2]) << 16) |
|
||||
(static_cast<uint32_t>(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<size_t>(length);
|
||||
if (bytes.size() < framed_length) return true;
|
||||
std::vector<uint8_t> frame(length);
|
||||
std::memcpy(frame.data(), bytes.data() + sizeof(uint32_t), length);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(stream->owner->gate);
|
||||
stream->owner->received.emplace_back(std::move(frame));
|
||||
}
|
||||
bytes.erase(bytes.begin(), bytes.begin() + static_cast<std::ptrdiff_t>(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<StreamContext*>(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<const QUIC_BUFFER*>(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<wchar_t, 32768> path{};
|
||||
const auto length = GetModuleFileNameW(module, path.data(), static_cast<DWORD>(path.size()));
|
||||
if (length == 0 || length >= path.size()) return "unresolved";
|
||||
const auto required = WideCharToMultiByte(
|
||||
CP_UTF8, 0, path.data(), static_cast<int>(length), nullptr, 0, nullptr, nullptr);
|
||||
if (required <= 0) return "unresolved";
|
||||
std::string utf8(static_cast<size_t>(required), '\0');
|
||||
WideCharToMultiByte(
|
||||
CP_UTF8, 0, path.data(), static_cast<int>(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<Client*>(context);
|
||||
AppendTrace(client, "event=" + std::to_string(static_cast<int>(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<void*>(StreamCallback),
|
||||
stream);
|
||||
break;
|
||||
}
|
||||
case QUIC_CONNECTION_EVENT_PEER_CERTIFICATE_RECEIVED:
|
||||
{
|
||||
AppendTrace(
|
||||
client,
|
||||
"certificate-status=" +
|
||||
Hex(static_cast<uint64_t>(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<uint64_t>(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<uint64_t>(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<Client>();
|
||||
if (!ParsePin(certificate_sha256, client->certificate_pin)) return -2;
|
||||
|
||||
QUIC_STATUS status = MsQuicOpenVersion(
|
||||
kApiVersion,
|
||||
reinterpret_cast<const void**>(&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<uint32_t>(sizeof(kAlpn) - 1),
|
||||
reinterpret_cast<uint8_t*>(const_cast<char*>(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_FLAGS>(
|
||||
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<int32_t>(ClientState::Failed);
|
||||
return static_cast<int32_t>(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<std::mutex> 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<size_t>(INT32_MAX)) return -3;
|
||||
*required_length = static_cast<int32_t>(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<std::mutex> lock(client->gate);
|
||||
const size_t count = (std::min)(client->error.size(), static_cast<size_t>(destination_length - 1));
|
||||
std::memcpy(destination, client->error.data(), count);
|
||||
destination[count] = '\0';
|
||||
return static_cast<int32_t>(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;
|
||||
}
|
||||
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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 `.<uuid>.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
|
||||
|
||||
|
|
|
|||
|
|
@ -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<Vec<CultCacheEnvelope>>;
|
||||
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<T>(&self, action: impl FnOnce() -> Result<T>) -> Result<T> {
|
||||
self.with_exclusive_lock_using_unlock(action, |lock| fs2::FileExt::unlock(lock))
|
||||
}
|
||||
|
||||
fn with_exclusive_lock_using_unlock<T>(
|
||||
&self,
|
||||
action: impl FnOnce() -> Result<T>,
|
||||
unlock: impl FnOnce(&File) -> std::io::Result<()>,
|
||||
) -> Result<T> {
|
||||
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<File> {
|
||||
|
|
@ -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::<Vec<_>>();
|
||||
let candidate = candidate_name.encode_wide().collect::<Vec<_>>();
|
||||
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::<std::result::Result<Vec<_>, _>>()
|
||||
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<Vec<PathBuf>> {
|
||||
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::<Vec<_>>();
|
||||
let target_wide = target
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
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::<CommittedSnapshotDurabilityUncertain>()
|
||||
.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::<CommittedSnapshotDurabilityUncertain>()
|
||||
.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::<CommittedSnapshotDurabilityUncertain>()
|
||||
.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()?;
|
||||
|
|
|
|||
70
packages/cultcache-ts/package-lock.json
generated
70
packages/cultcache-ts/package-lock.json
generated
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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<unknown>;
|
||||
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<CultNetPeer>);
|
||||
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<CultMeshRudpDocumentReceipt | void>;
|
||||
onOperationRequest?: (
|
||||
request: CultNetOperationRequestMessage,
|
||||
session: CultMeshRudpServerSession,
|
||||
) => CultNetOperationResponseMessage | Promise<CultNetOperationResponseMessage>;
|
||||
onSessionClosed?: (session: CultMeshRudpServerSession) => void | Promise<void>;
|
||||
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<void>;
|
||||
|
|
@ -5558,9 +5623,14 @@ export class CultMesh {
|
|||
const bind = { host, port };
|
||||
const socket = options.socket ?? createSocket(host.includes(":") ? "udp6" : "udp4");
|
||||
const sessions = new Map<string, {
|
||||
sessionId: string;
|
||||
remote: { address: string; family: string; port: number };
|
||||
session: CultNetRudpSession;
|
||||
connectPayload: Uint8Array;
|
||||
closed: boolean;
|
||||
work: Promise<void>;
|
||||
}>();
|
||||
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<void> {
|
||||
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,
|
||||
|
|
|
|||
395
packages/cultmesh-ts/src/provider-rudp-transport.ts
Normal file
395
packages/cultmesh-ts/src/provider-rudp-transport.ts
Normal file
|
|
@ -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<CultMeshProviderConnection> {
|
||||
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<CultMeshProviderCommandListener>();
|
||||
readonly #pending = new Map<string, {
|
||||
operation: string;
|
||||
payloadSchema: string;
|
||||
resolve: (response: CultNetOperationResponseMessage) => void;
|
||||
reject: (error: Error) => void;
|
||||
timer: NodeJS.Timeout;
|
||||
}>();
|
||||
readonly #publications = new Map<string, CultMeshProviderPublication>();
|
||||
readonly #bufferedCommands = new Map<string, CultMeshProviderCommand>();
|
||||
#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<CultMeshProviderLease> {
|
||||
this.#requestedLeaseDurationMs = registration.requestedLeaseDurationMs;
|
||||
const response = await this.#operation(
|
||||
cultMeshProviderSessionOperations.register,
|
||||
cultMeshProviderSessionSchemas.registration,
|
||||
cultMeshProviderSessionSchemas.lease,
|
||||
{ ...registration.identity, requestedLeaseDurationMs: registration.requestedLeaseDurationMs },
|
||||
signal,
|
||||
);
|
||||
const wire = decodeProviderSessionPayload<CultMeshProviderLeaseWire>(response.payload);
|
||||
assertProviderLease(wire);
|
||||
assertIdentity(this.#identity, wire);
|
||||
return { leaseId: wire.leaseId, expiresAt: new Date(wire.expiresAtUtc) };
|
||||
}
|
||||
|
||||
public async renew(lease: CultMeshProviderLease): Promise<CultMeshProviderLease> {
|
||||
const response = await this.#operation(
|
||||
cultMeshProviderSessionOperations.renew,
|
||||
cultMeshProviderSessionSchemas.leaseRenewal,
|
||||
cultMeshProviderSessionSchemas.lease,
|
||||
{ leaseId: lease.leaseId, requestedLeaseDurationMs: this.#requestedLeaseDurationMs },
|
||||
);
|
||||
const wire = decodeProviderSessionPayload<CultMeshProviderLeaseWire>(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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<CultMeshProviderMutationAcceptanceWire> {
|
||||
const response = await this.#operation(operation, payloadSchema, cultMeshProviderSessionSchemas.mutationAcceptance, payload);
|
||||
const acceptance = decodeProviderSessionPayload<CultMeshProviderMutationAcceptanceWire>(response.payload);
|
||||
assertMutationAcceptance(acceptance);
|
||||
return acceptance;
|
||||
}
|
||||
|
||||
async #operation(
|
||||
operation: string,
|
||||
payloadSchema: string,
|
||||
responsePayloadSchema: string,
|
||||
payload: unknown,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CultNetOperationResponseMessage> {
|
||||
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<CultNetOperationResponseMessage>((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<void> {
|
||||
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<void> {
|
||||
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;
|
||||
}
|
||||
528
packages/cultmesh-ts/src/provider-session-broker.ts
Normal file
528
packages/cultmesh-ts/src/provider-session-broker.ts
Normal file
|
|
@ -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<boolean>;
|
||||
readonly acceptPublication: (
|
||||
identity: CultMeshProviderRegistrationWire,
|
||||
publicationId: string,
|
||||
document: CultNetRawDocumentRecord,
|
||||
) => void | Promise<void>;
|
||||
readonly deletePublications: (
|
||||
identity: CultMeshProviderRegistrationWire,
|
||||
publications: readonly {
|
||||
publicationId: string;
|
||||
document: Pick<CultNetRawDocumentRecord, "schemaId" | "recordKey">;
|
||||
}[],
|
||||
) => void | Promise<void>;
|
||||
readonly acceptReceipt: (
|
||||
identity: CultMeshProviderRegistrationWire,
|
||||
receipt: CultMeshProviderCommandReceiptWire,
|
||||
) => void | Promise<void>;
|
||||
}
|
||||
|
||||
interface LeaseRecord {
|
||||
identity: CultMeshProviderRegistrationWire;
|
||||
lease: CultMeshProviderLeaseWire;
|
||||
session?: CultMeshRudpServerSession;
|
||||
publications: Map<string, CultNetRawDocumentRecord>;
|
||||
}
|
||||
|
||||
export class CultMeshProviderSessionBroker {
|
||||
readonly #options: CultMeshProviderSessionBrokerOptions;
|
||||
readonly #clock: CultMeshProviderBrokerClock;
|
||||
readonly #leases = new Map<string, LeaseRecord>();
|
||||
readonly #identityLeases = new Map<string, string>();
|
||||
readonly #sessionLeases = new Map<string, Set<string>>();
|
||||
readonly #commands = new Map<string, CultMeshProviderCommandWire>();
|
||||
readonly #receipts = new Map<string, CultMeshProviderCommandReceiptWire>();
|
||||
readonly #publicationOwners = new Map<string, { identityKey: string; publicationId: string }>();
|
||||
readonly #closedSessions = new Set<string>();
|
||||
readonly #inFlightBySession = new Map<string, number>();
|
||||
readonly #expiryTimer: NodeJS.Timeout;
|
||||
#work: Promise<void> = 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<CultNetOperationResponseMessage> {
|
||||
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<CultNetOperationResponseMessage> {
|
||||
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<void> {
|
||||
const work = this.#work.then(() => this.#expireLeases());
|
||||
this.#work = work.then(() => undefined, () => undefined);
|
||||
await work;
|
||||
}
|
||||
|
||||
async #expireLeases(): Promise<void> {
|
||||
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<CultNetOperationResponseMessage> {
|
||||
expectSchema(request, cultMeshProviderSessionSchemas.registration);
|
||||
const identity = decodeProviderSessionPayload<CultMeshProviderRegistrationWire>(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<string, CultNetRawDocumentRecord>();
|
||||
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<CultNetOperationResponseMessage> {
|
||||
expectSchema(request, cultMeshProviderSessionSchemas.leaseRenewal);
|
||||
const renewal = decodeProviderSessionPayload<CultMeshProviderLeaseRenewalWire>(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<CultNetOperationResponseMessage> {
|
||||
expectSchema(request, cultMeshProviderSessionSchemas.publicationPut);
|
||||
const mutation = decodeProviderSessionPayload<CultMeshProviderPublicationPutWire>(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<CultNetOperationResponseMessage> {
|
||||
expectSchema(request, cultMeshProviderSessionSchemas.publicationDelete);
|
||||
const mutation = decodeProviderSessionPayload<CultMeshProviderPublicationDeleteWire>(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<CultNetOperationResponseMessage> {
|
||||
expectSchema(request, cultMeshProviderSessionSchemas.receiptPut);
|
||||
const mutation = decodeProviderSessionPayload<CultMeshProviderReceiptPutWire>(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<CultNetOperationResponseMessage> {
|
||||
expectSchema(request, cultMeshProviderSessionSchemas.withdrawal);
|
||||
const mutation = decodeProviderSessionPayload<CultMeshProviderWithdrawalWire>(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<string, string> = {}): 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<T>(action: () => T | Promise<T>): Promise<T> {
|
||||
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<CultNetRawDocumentRecord, "schemaId" | "recordKey">): 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<CultNetRawDocumentRecord, "schemaId" | "recordKey">;
|
||||
}[] {
|
||||
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.`);
|
||||
}
|
||||
207
packages/cultmesh-ts/src/provider-session-wire.ts
Normal file
207
packages/cultmesh-ts/src/provider-session-wire.ts
Normal file
|
|
@ -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<T>(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<CultMeshProviderCommandWire>;
|
||||
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<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new Error(`CultMesh ${name} must be a MessagePack map.`);
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
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.`);
|
||||
}
|
||||
}
|
||||
884
packages/cultmesh-ts/src/provider-session.ts
Normal file
884
packages/cultmesh-ts/src/provider-session.ts
Normal file
|
|
@ -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<TValue = unknown> {
|
||||
readonly publicationId: string;
|
||||
readonly documentType: string;
|
||||
readonly schemaId: string;
|
||||
readonly recordKey: string;
|
||||
readonly value: TValue;
|
||||
}
|
||||
|
||||
export interface CultMeshProviderCommand<TPayload = unknown> {
|
||||
readonly commandId: string;
|
||||
readonly commandKind: string;
|
||||
readonly providerId: string;
|
||||
readonly serviceInstanceId: string;
|
||||
readonly payload: TPayload;
|
||||
}
|
||||
|
||||
export type CultMeshProviderReceiptState = "applied" | "rejected" | "failed";
|
||||
|
||||
export interface CultMeshProviderCommandReceipt<TResult = unknown> {
|
||||
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<TResult = unknown> {
|
||||
readonly state: CultMeshProviderReceiptState;
|
||||
readonly result?: TResult;
|
||||
readonly error?: string;
|
||||
}
|
||||
|
||||
export interface CultMeshProviderCommandContext {
|
||||
readonly identity: CultMeshProviderIdentity;
|
||||
}
|
||||
|
||||
export type CultMeshProviderCommandHandler = (
|
||||
command: CultMeshProviderCommand,
|
||||
context: CultMeshProviderCommandContext,
|
||||
) => Promise<CultMeshProviderCommandOutcome>;
|
||||
|
||||
export interface CultMeshProviderReceiptStore {
|
||||
get(commandId: string): Promise<CultMeshProviderCommandReceipt | undefined>;
|
||||
put(receipt: CultMeshProviderCommandReceipt): Promise<void>;
|
||||
listPending(): Promise<readonly CultMeshProviderCommandReceipt[]>;
|
||||
markPublished(receiptId: string): Promise<void>;
|
||||
}
|
||||
|
||||
export class CultMeshMemoryProviderReceiptStore implements CultMeshProviderReceiptStore {
|
||||
readonly #receipts = new Map<string, CultMeshProviderCommandReceipt>();
|
||||
readonly #pendingReceiptIds = new Set<string>();
|
||||
|
||||
public async get(commandId: string): Promise<CultMeshProviderCommandReceipt | undefined> {
|
||||
return this.#receipts.get(commandId);
|
||||
}
|
||||
|
||||
public async put(receipt: CultMeshProviderCommandReceipt): Promise<void> {
|
||||
this.#receipts.set(receipt.commandId, receipt);
|
||||
this.#pendingReceiptIds.add(receipt.receiptId);
|
||||
}
|
||||
|
||||
public async listPending(): Promise<readonly CultMeshProviderCommandReceipt[]> {
|
||||
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<void> {
|
||||
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<void>;
|
||||
|
||||
export type CultMeshProviderUnsubscribe = () => void | Promise<void>;
|
||||
|
||||
export interface CultMeshProviderConnection {
|
||||
register(
|
||||
registration: CultMeshProviderRegistration,
|
||||
signal: AbortSignal,
|
||||
): Promise<CultMeshProviderLease>;
|
||||
renew(lease: CultMeshProviderLease): Promise<CultMeshProviderLease>;
|
||||
publish(
|
||||
publication: CultMeshProviderPublication,
|
||||
lease: CultMeshProviderLease,
|
||||
): Promise<void>;
|
||||
withdrawPublication(publicationId: string, lease: CultMeshProviderLease): Promise<void>;
|
||||
watchCommands(listener: CultMeshProviderCommandListener): CultMeshProviderUnsubscribe;
|
||||
publishReceipt(
|
||||
receipt: CultMeshProviderCommandReceipt,
|
||||
lease: CultMeshProviderLease,
|
||||
): Promise<void>;
|
||||
withdraw(withdrawal: CultMeshProviderWithdrawal): Promise<void>;
|
||||
close(): void | Promise<void>;
|
||||
}
|
||||
|
||||
export interface CultMeshProviderTransport {
|
||||
connect(
|
||||
identity: CultMeshProviderIdentity,
|
||||
signal: AbortSignal,
|
||||
): Promise<CultMeshProviderConnection>;
|
||||
}
|
||||
|
||||
export interface CultMeshProviderScheduledTask {
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
export interface CultMeshProviderScheduler {
|
||||
now(): Date;
|
||||
schedule(delayMs: number, action: () => void | Promise<void>): CultMeshProviderScheduledTask;
|
||||
}
|
||||
|
||||
export class CultMeshSystemProviderScheduler implements CultMeshProviderScheduler {
|
||||
public now(): Date {
|
||||
return new Date();
|
||||
}
|
||||
|
||||
public schedule(delayMs: number, action: () => void | Promise<void>): 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<CultMeshProviderPublication>;
|
||||
readonly commandHandlers?: Readonly<Record<string, CultMeshProviderCommandHandler>>;
|
||||
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<string, CultMeshProviderPublication>();
|
||||
readonly #handlers = new Map<string, CultMeshProviderCommandHandler>();
|
||||
readonly #subscribers = new Set<(state: CultMeshProviderSessionState) => void>();
|
||||
readonly #inFlightCommands = new Map<string, {
|
||||
command: CultMeshProviderCommand;
|
||||
work: Promise<void>;
|
||||
}>();
|
||||
#state: CultMeshProviderSessionState;
|
||||
#connection?: CultMeshProviderConnection;
|
||||
#lease?: CultMeshProviderLease;
|
||||
#unsubscribeCommands?: CultMeshProviderUnsubscribe;
|
||||
#scheduled?: CultMeshProviderScheduledTask;
|
||||
#abort?: AbortController;
|
||||
#running = false;
|
||||
#generation = 0;
|
||||
#reconnectAttempt = 0;
|
||||
#publicationWork: Promise<void> = Promise.resolve();
|
||||
#startWork?: Promise<void>;
|
||||
#stopWork?: Promise<void>;
|
||||
#lossWork?: { generation: number; work: Promise<void> };
|
||||
|
||||
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<void> {
|
||||
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<boolean> {
|
||||
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<void> {
|
||||
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<void>;
|
||||
tracked = Promise.resolve().then(() => this.#start()).finally(() => {
|
||||
if (this.#startWork === tracked) this.#startWork = undefined;
|
||||
});
|
||||
this.#startWork = tracked;
|
||||
return tracked;
|
||||
}
|
||||
|
||||
async #start(): Promise<void> {
|
||||
this.#running = true;
|
||||
this.#reconnectAttempt = 0;
|
||||
const generation = ++this.#generation;
|
||||
this.#abort = new AbortController();
|
||||
await this.#connect(generation, false);
|
||||
}
|
||||
|
||||
public stop(): Promise<void> {
|
||||
if (this.#stopWork) return this.#stopWork;
|
||||
if (!this.#running && !this.#startWork && this.#state.status === "stopped") {
|
||||
return Promise.resolve();
|
||||
}
|
||||
let tracked!: Promise<void>;
|
||||
tracked = Promise.resolve().then(() => this.#stop()).finally(() => {
|
||||
if (this.#stopWork === tracked) this.#stopWork = undefined;
|
||||
});
|
||||
this.#stopWork = tracked;
|
||||
return tracked;
|
||||
}
|
||||
|
||||
async #stop(): Promise<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<CultMeshProviderCommandReceipt> {
|
||||
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<void> {
|
||||
if (!this.#isCurrent(generation)) return;
|
||||
const existing = this.#lossWork;
|
||||
if (existing?.generation === generation) {
|
||||
await existing.work;
|
||||
return;
|
||||
}
|
||||
let tracked!: Promise<void>;
|
||||
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<void> {
|
||||
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<boolean> {
|
||||
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<CultMeshProviderLease | undefined> {
|
||||
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<void> {
|
||||
try {
|
||||
await this.#unsubscribe();
|
||||
} catch (error) {
|
||||
this.#reportObserverError(error);
|
||||
}
|
||||
if (this.#isCurrent(generation)) this.#setState("degraded", message, this.#lease);
|
||||
}
|
||||
|
||||
async #unsubscribe(): Promise<void> {
|
||||
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<void>): Promise<void> {
|
||||
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);
|
||||
}
|
||||
|
|
@ -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");
|
||||
|
|
|
|||
334
packages/cultmesh-ts/test/provider-rudp-transport.test.ts
Normal file
334
packages/cultmesh-ts/test/provider-rudp-transport.test.ts
Normal file
|
|
@ -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<string, unknown>();
|
||||
const acceptedProvenance = new Map<string, { runtime?: string; agent?: string }>();
|
||||
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<void>((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<CultMeshProviderCommand>();
|
||||
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<boolean>();
|
||||
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<void>();
|
||||
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<void>((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<T>(): { promise: Promise<T>; resolve(value: T): void } {
|
||||
let resolve!: (value: T) => void;
|
||||
return { promise: new Promise<T>(done => resolve = done), resolve };
|
||||
}
|
||||
|
||||
async function waitFor(predicate: () => boolean, description: string): Promise<void> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
43
packages/cultmesh-ts/test/provider-session-wire.test.ts
Normal file
43
packages/cultmesh-ts/test/provider-session-wire.test.ts
Normal file
|
|
@ -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,
|
||||
);
|
||||
});
|
||||
791
packages/cultmesh-ts/test/provider-session.test.ts
Normal file
791
packages/cultmesh-ts/test/provider-session.test.ts
Normal file
|
|
@ -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<void>();
|
||||
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<void>();
|
||||
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<void>();
|
||||
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<void>();
|
||||
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<void>();
|
||||
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<void>();
|
||||
|
||||
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<void>();
|
||||
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<void>;
|
||||
}> = [];
|
||||
|
||||
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<void>): 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<void> {
|
||||
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<void>;
|
||||
public registerError?: Error;
|
||||
public publishBarrier?: Deferred<void>;
|
||||
public onFirstConnection?: (connection: FakeConnection) => void;
|
||||
public readonly connections: FakeConnection[] = [];
|
||||
|
||||
public constructor(private readonly scheduler: CultMeshProviderScheduler) {}
|
||||
|
||||
public async connect(
|
||||
connectedIdentity: CultMeshProviderIdentity,
|
||||
signal: AbortSignal,
|
||||
): Promise<CultMeshProviderConnection> {
|
||||
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<void>;
|
||||
public publishBarrier?: Deferred<void>;
|
||||
public unsubscribeError?: Error;
|
||||
public withdrawError?: Error;
|
||||
public closeError?: Error;
|
||||
public closeAttempts = 0;
|
||||
public afterPublishReceipt?: () => void | Promise<void>;
|
||||
public withdrawBarrier?: Deferred<void>;
|
||||
public closed = false;
|
||||
#listener?: CultMeshProviderCommandListener;
|
||||
#leaseSequence = 0;
|
||||
|
||||
public constructor(private readonly scheduler: CultMeshProviderScheduler) {}
|
||||
|
||||
public async register(
|
||||
registration: CultMeshProviderRegistration,
|
||||
signal: AbortSignal,
|
||||
): Promise<CultMeshProviderLease> {
|
||||
this.registrations.push(registration);
|
||||
if (this.registerBarrier) {
|
||||
await Promise.race([
|
||||
this.registerBarrier.promise,
|
||||
new Promise<never>((_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<CultMeshProviderLease> {
|
||||
this.renewals.push(lease);
|
||||
return this.lease(1_000);
|
||||
}
|
||||
|
||||
public async publish(publication: CultMeshProviderPublication): Promise<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
}
|
||||
|
||||
class Deferred<T> {
|
||||
public readonly promise: Promise<T>;
|
||||
#resolve!: (value: T | PromiseLike<T>) => void;
|
||||
|
||||
public constructor() {
|
||||
this.promise = new Promise<T>(resolve => { this.#resolve = resolve; });
|
||||
}
|
||||
|
||||
public resolve(value?: T): void {
|
||||
this.#resolve(value as T);
|
||||
}
|
||||
}
|
||||
|
|
@ -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::*;
|
||||
|
|
|
|||
625
packages/cultnet-rs/src/provider_session.rs
Normal file
625
packages/cultnet-rs/src/provider_session.rs
Normal file
|
|
@ -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<Self> {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
}
|
||||
|
||||
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<Value>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub publication_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub command_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub receipt_id: Option<String>,
|
||||
}
|
||||
|
||||
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<T>(value: &T) -> Result<String>
|
||||
where
|
||||
T: CultMeshProviderSessionPayload + Serialize,
|
||||
{
|
||||
value.validate()?;
|
||||
Ok(STANDARD.encode(rmp_serde::to_vec_named(value)?))
|
||||
}
|
||||
|
||||
pub fn encode_provider_connect_evidence(
|
||||
evidence: &CultMeshProviderConnectEvidenceWire,
|
||||
) -> Result<Vec<u8>> {
|
||||
evidence.validate()?;
|
||||
Ok(rmp_serde::to_vec_named(evidence)?)
|
||||
}
|
||||
|
||||
pub fn decode_provider_connect_evidence(
|
||||
payload: &[u8],
|
||||
) -> Result<CultMeshProviderConnectEvidenceWire> {
|
||||
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<T>(payload: &str) -> Result<T>
|
||||
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<CultMeshProviderCommandWire> {
|
||||
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<T>(
|
||||
message_id: impl Into<String>,
|
||||
operation: impl Into<String>,
|
||||
payload_schema: impl Into<String>,
|
||||
payload: &T,
|
||||
source_runtime_id: Option<String>,
|
||||
target_runtime_id: Option<String>,
|
||||
) -> Result<CultNetMessage>
|
||||
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<T>(
|
||||
request: &CultNetMessage,
|
||||
expected_operation: &str,
|
||||
expected_payload_schema: &str,
|
||||
) -> Result<T>
|
||||
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<T>(
|
||||
request: &CultNetMessage,
|
||||
status: CultMeshProviderOperationStatus,
|
||||
payload_schema: impl Into<String>,
|
||||
payload: &T,
|
||||
source_runtime_id: Option<String>,
|
||||
) -> Result<CultNetMessage>
|
||||
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<String>,
|
||||
source_runtime_id: Option<String>,
|
||||
) -> Result<CultNetMessage> {
|
||||
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<T>(
|
||||
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<DateTime<chrono::FixedOffset>> {
|
||||
require_text(value, field)?;
|
||||
DateTime::parse_from_rfc3339(value)
|
||||
.map_err(|error| anyhow!("Provider-session {field} must be RFC3339: {error}"))
|
||||
}
|
||||
|
|
@ -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<usize>,
|
||||
max_payload_bytes: Option<usize>,
|
||||
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<CultNetRudpPacket> {
|
||||
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<u64> {
|
||||
self.last_received_at_ms
|
||||
}
|
||||
|
||||
pub fn set_max_payload_bytes(&mut self, max_payload_bytes: Option<usize>) {
|
||||
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<u8>) -> 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<Option<(CultNetRudpDeliveredFrame, bool, u32)>> {
|
||||
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::<usize>()
|
||||
})
|
||||
.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<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl CultNetRudpSocketTransportConnection {
|
||||
pub fn new(options: CultNetRudpSocketTransportOptions) -> Result<Self> {
|
||||
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<String>,
|
||||
pub max_payload_bytes: Option<u32>,
|
||||
pub max_fragment_bytes: Option<u32>,
|
||||
pub max_pending_reliable_packets: Option<u32>,
|
||||
pub max_peers: usize,
|
||||
}
|
||||
|
||||
impl CultNetRudpServerHubOptions {
|
||||
pub fn new(runtime_id: impl Into<String>, 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<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum CultNetRudpServerEvent {
|
||||
Connected {
|
||||
session: CultNetRudpServerSessionContext,
|
||||
},
|
||||
Frame {
|
||||
session: CultNetRudpServerSessionContext,
|
||||
frame: CultNetTransportFrame,
|
||||
},
|
||||
Pong {
|
||||
session: CultNetRudpServerSessionContext,
|
||||
payload: Vec<u8>,
|
||||
},
|
||||
Disconnected {
|
||||
session: CultNetRudpServerSessionContext,
|
||||
reason: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
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<usize>,
|
||||
max_payload_bytes: usize,
|
||||
max_fragment_bytes: Option<usize>,
|
||||
max_peers: usize,
|
||||
next_session_generation: u64,
|
||||
peers: BTreeMap<SocketAddr, CultNetRudpServerPeer>,
|
||||
pending_events: VecDeque<CultNetRudpServerEvent>,
|
||||
pub profile: CultNetTransportProfile,
|
||||
stats: CultNetTransportStats,
|
||||
}
|
||||
|
||||
impl CultNetRudpServerHub {
|
||||
pub fn new(options: CultNetRudpServerHubOptions) -> Result<Self> {
|
||||
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<SocketAddr> {
|
||||
Ok(self.socket.local_addr()?)
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> CultNetTransportStats {
|
||||
self.stats.clone()
|
||||
}
|
||||
|
||||
pub fn sessions(&self) -> Vec<CultNetRudpServerSessionContext> {
|
||||
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<u8>,
|
||||
) -> 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<u8>,
|
||||
) -> Result<bool> {
|
||||
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<Option<CultNetRudpServerEvent>> {
|
||||
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<CultNetRudpServerSessionContext> {
|
||||
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::<Vec<_>>();
|
||||
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<Self> {
|
||||
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)
|
||||
|
|
|
|||
365
packages/cultnet-rs/tests/provider_session.rs
Normal file
365
packages/cultnet-rs/tests/provider_session.rs
Normal file
|
|
@ -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::<CultMeshProviderRegistrationWire>(&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::<CultMeshProviderLeaseWire>(
|
||||
&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::<CultMeshProviderPublicationPutWire>(
|
||||
&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::<CultMeshProviderLeaseRenewalWire>(
|
||||
&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::<CultMeshProviderPublicationDeleteWire>(
|
||||
&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::<CultMeshProviderReceiptPutWire>(
|
||||
&encode_provider_session_payload(&receipt)?
|
||||
)?,
|
||||
receipt
|
||||
);
|
||||
|
||||
let withdrawal = CultMeshProviderWithdrawalWire {
|
||||
lease_id: "lease-1".to_string(),
|
||||
};
|
||||
assert_eq!(
|
||||
decode_provider_session_payload::<CultMeshProviderWithdrawalWire>(
|
||||
&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::<CultMeshProviderMutationAcceptanceWire>(
|
||||
&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::<rmpv::Value>(&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(())
|
||||
}
|
||||
459
packages/cultnet-rs/tests/rudp_server_hub.rs
Normal file
459
packages/cultnet-rs/tests/rudp_server_hub.rs
Normal file
|
|
@ -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<UdpSocket> {
|
||||
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<CultNetRudpSocketTransportConnection> {
|
||||
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<CultNetRudpServerSessionContext> {
|
||||
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<CultNetRudpServerEvent> {
|
||||
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<CultNetMessage> {
|
||||
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::<CultMeshProviderLeaseWire>(
|
||||
&first_response,
|
||||
CULTMESH_PROVIDER_REGISTER_OPERATION,
|
||||
CULTMESH_PROVIDER_LEASE_SCHEMA,
|
||||
)?;
|
||||
let (_, second_lease) = decode_provider_session_response::<CultMeshProviderLeaseWire>(
|
||||
&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(())
|
||||
}
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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, []);
|
||||
|
|
|
|||
54
scripts/build-quic-native.ps1
Normal file
54
scripts/build-quic-native.ps1
Normal file
|
|
@ -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
|
||||
|
|
@ -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)"
|
||||
|
|
|
|||
30
scripts/run-typescript-workspaces.mjs
Normal file
30
scripts/run-typescript-workspaces.mjs
Normal file
|
|
@ -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 <script>");
|
||||
|
||||
const npmCli = process.env.npm_execpath ??
|
||||
join(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
|
||||
const workspaces = ["cultcache-ts", "cultnet-ts", "cultmesh-ts"];
|
||||
const childEnv = process.platform === "win32"
|
||||
? {
|
||||
...process.env,
|
||||
PATH: [
|
||||
dirname(process.execPath),
|
||||
`${process.env.SystemRoot}\\System32`,
|
||||
process.env.SystemRoot,
|
||||
`${process.env.USERPROFILE}\\AppData\\Local\\Microsoft\\WindowsApps`,
|
||||
`${process.env.USERPROFILE}\\.cargo\\bin`,
|
||||
"C:\\Program Files\\dotnet",
|
||||
"C:\\Program Files\\Git\\cmd",
|
||||
].join(";"),
|
||||
}
|
||||
: process.env;
|
||||
|
||||
for (const workspace of workspaces) {
|
||||
execFileSync(process.execPath, [npmCli, "--workspace", workspace, "run", command], {
|
||||
env: childEnv,
|
||||
stdio: "inherit",
|
||||
});
|
||||
}
|
||||
118
scripts/test-typescript-package-closure.mjs
Normal file
118
scripts/test-typescript-package-closure.mjs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const workspacePackages = ["cultcache-ts", "cultnet-ts", "cultmesh-ts"];
|
||||
const npmCli = process.env.npm_execpath ??
|
||||
join(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
|
||||
const childEnv = process.platform === "win32"
|
||||
? {
|
||||
...process.env,
|
||||
PATH: `${dirname(process.execPath)};${process.env.SystemRoot}\\System32;${process.env.SystemRoot}`,
|
||||
}
|
||||
: process.env;
|
||||
const smokeRoot = mkdtempSync(join(tmpdir(), "cultlib-ts-package-smoke-"));
|
||||
const tarballRoot = join(smokeRoot, "tarballs");
|
||||
const consumerRoot = join(smokeRoot, "consumer");
|
||||
mkdirSync(tarballRoot);
|
||||
mkdirSync(consumerRoot);
|
||||
|
||||
function npm(...args) {
|
||||
return execFileSync(process.execPath, [npmCli, ...args], {
|
||||
cwd: repoRoot,
|
||||
encoding: "utf8",
|
||||
env: childEnv,
|
||||
stdio: ["ignore", "pipe", "inherit"],
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const tarballs = [];
|
||||
for (const packageName of workspacePackages) {
|
||||
const packageRoot = join(repoRoot, "packages", packageName);
|
||||
const packed = JSON.parse(npm("pack", packageRoot, "--json", "--pack-destination", tarballRoot));
|
||||
assert.equal(packed.length, 1, `${packageName} must produce exactly one tarball`);
|
||||
const files = packed[0].files.map(file => file.path);
|
||||
assert.ok(files.includes("dist/index.js"), `${packageName} tarball is missing dist/index.js`);
|
||||
assert.ok(files.includes("dist/index.d.ts"), `${packageName} tarball is missing dist/index.d.ts`);
|
||||
tarballs.push(join(tarballRoot, packed[0].filename));
|
||||
}
|
||||
|
||||
writeFileSync(join(consumerRoot, "package.json"), JSON.stringify({
|
||||
name: "cultlib-ts-package-smoke",
|
||||
version: "1.0.0",
|
||||
private: true,
|
||||
}, null, 2));
|
||||
|
||||
execFileSync(process.execPath, [npmCli,
|
||||
"install",
|
||||
"--ignore-scripts",
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
...tarballs,
|
||||
], { cwd: consumerRoot, env: childEnv, stdio: "inherit" });
|
||||
|
||||
writeFileSync(join(consumerRoot, "runtime-smoke.cjs"), `
|
||||
const assert = require("node:assert/strict");
|
||||
const cache = require("cultcache-ts");
|
||||
const net = require("cultnet-ts");
|
||||
const mesh = require("cultmesh-ts");
|
||||
assert.equal(typeof cache.defineDocumentType, "function");
|
||||
assert.equal(typeof net.CultNetPeer, "function");
|
||||
assert.equal(typeof mesh.CultMesh, "function");
|
||||
assert.equal(typeof mesh.CultMeshProviderSession, "function");
|
||||
assert.deepEqual(mesh.CultMesh.vec2(3, 4), { x: 3, y: 4 });
|
||||
`);
|
||||
execFileSync(process.execPath, ["runtime-smoke.cjs"], { cwd: consumerRoot, stdio: "inherit" });
|
||||
|
||||
writeFileSync(join(consumerRoot, "types-smoke.ts"), `
|
||||
import { defineDocumentType } from "cultcache-ts";
|
||||
import { CultNetPeer } from "cultnet-ts";
|
||||
import {
|
||||
CultMesh,
|
||||
CultMeshProviderSession,
|
||||
type CultMeshProviderIdentity,
|
||||
type CultMeshProviderTransport,
|
||||
type CultMeshVec2,
|
||||
} from "cultmesh-ts";
|
||||
|
||||
const point: CultMeshVec2 = CultMesh.vec2(3, 4);
|
||||
const defineDocument: typeof defineDocumentType = defineDocumentType;
|
||||
const peerType: typeof CultNetPeer = CultNetPeer;
|
||||
const providerSessionType: typeof CultMeshProviderSession = CultMeshProviderSession;
|
||||
const providerIdentity: CultMeshProviderIdentity = {
|
||||
providerId: "smoke.provider",
|
||||
serviceInstanceId: "smoke.instance",
|
||||
endpointId: "odin:smoke.instance",
|
||||
verseId: "smoke",
|
||||
};
|
||||
let providerTransport: CultMeshProviderTransport | undefined;
|
||||
void point;
|
||||
void defineDocument;
|
||||
void peerType;
|
||||
void providerSessionType;
|
||||
void providerIdentity;
|
||||
void providerTransport;
|
||||
`);
|
||||
const tsc = join(repoRoot, "node_modules", "typescript", "bin", "tsc");
|
||||
assert.ok(readFileSync(tsc, "utf8").length > 0, "workspace TypeScript compiler is unavailable");
|
||||
execFileSync(process.execPath, [
|
||||
tsc,
|
||||
"--noEmit",
|
||||
"--strict",
|
||||
"--target", "ES2022",
|
||||
"--module", "CommonJS",
|
||||
"--moduleResolution", "Node",
|
||||
"--skipLibCheck",
|
||||
"types-smoke.ts",
|
||||
], { cwd: consumerRoot, stdio: "inherit" });
|
||||
|
||||
console.log("TypeScript package closure smoke: passed");
|
||||
for (const tarball of tarballs) console.log(`Packed: ${tarball}`);
|
||||
} finally {
|
||||
rmSync(smokeRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
|
@ -51,6 +51,14 @@ public sealed class CultDocumentMessagePackGenerator : IIncrementalGenerator
|
|||
|
||||
var members = DiscoverMembers(typeSymbol);
|
||||
var nameMember = members.FirstOrDefault(member => member.IsName);
|
||||
var canConstructForDeserialization = typeSymbol.TypeKind == TypeKind.Struct ||
|
||||
typeSymbol.InstanceConstructors.Any(constructor =>
|
||||
constructor.Parameters.Length == 0 &&
|
||||
constructor.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal);
|
||||
var hasDenseSlots = members
|
||||
.OrderBy(member => member.Slot)
|
||||
.Select((member, index) => member.Slot == index)
|
||||
.All(matches => matches);
|
||||
return new DocumentShape(
|
||||
typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
|
||||
schemaName,
|
||||
|
|
@ -61,7 +69,9 @@ public sealed class CultDocumentMessagePackGenerator : IIncrementalGenerator
|
|||
members.Where(member => member.IndexAlias != null)
|
||||
.Select(member => new IndexAccessorShape(member.IndexAlias!, member.IndexAccessorMethodName!))
|
||||
.ToImmutableArray(),
|
||||
members.ToImmutableArray());
|
||||
members.ToImmutableArray(),
|
||||
canConstructForDeserialization,
|
||||
hasDenseSlots);
|
||||
}
|
||||
|
||||
private static ImmutableArray<MemberShape> DiscoverMembers(INamedTypeSymbol typeSymbol)
|
||||
|
|
@ -191,10 +201,10 @@ public sealed class CultDocumentMessagePackGenerator : IIncrementalGenerator
|
|||
builder.AppendLine(document.NameAccessorMethodName == null
|
||||
? " null,"
|
||||
: $" {document.NameAccessorMethodName},");
|
||||
builder.AppendLine(canEmitPayloadCodecs
|
||||
builder.AppendLine(canEmitPayloadCodecs && document.HasDenseSlots
|
||||
? $" {document.PayloadSerializerMethodName},"
|
||||
: " null,");
|
||||
builder.AppendLine(canEmitPayloadCodecs
|
||||
builder.AppendLine(canEmitPayloadCodecs && document.HasDenseSlots && document.CanConstructForDeserialization
|
||||
? $" {document.PayloadDeserializerMethodName},"
|
||||
: " null,");
|
||||
builder.AppendLine(" new global::GameCult.Caching.CultGeneratedDocumentIndexAccessor[]");
|
||||
|
|
@ -235,10 +245,13 @@ public sealed class CultDocumentMessagePackGenerator : IIncrementalGenerator
|
|||
|
||||
foreach (var document in documents)
|
||||
{
|
||||
if (canEmitPayloadCodecs)
|
||||
if (canEmitPayloadCodecs && document.HasDenseSlots)
|
||||
{
|
||||
EmitPayloadSerializer(builder, document);
|
||||
EmitPayloadDeserializer(builder, document);
|
||||
if (document.CanConstructForDeserialization)
|
||||
{
|
||||
EmitPayloadDeserializer(builder, document);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var member in document.Members.Where(member => member.AccessorMethodName != null))
|
||||
|
|
@ -531,7 +544,9 @@ public sealed class CultDocumentMessagePackGenerator : IIncrementalGenerator
|
|||
string? nameMember,
|
||||
string? nameAccessorMethodName,
|
||||
ImmutableArray<IndexAccessorShape> indexAccessors,
|
||||
ImmutableArray<MemberShape> members)
|
||||
ImmutableArray<MemberShape> members,
|
||||
bool canConstructForDeserialization,
|
||||
bool hasDenseSlots)
|
||||
{
|
||||
DocumentTypeName = documentTypeName;
|
||||
SchemaName = schemaName;
|
||||
|
|
@ -544,6 +559,8 @@ public sealed class CultDocumentMessagePackGenerator : IIncrementalGenerator
|
|||
PayloadDeserializerMethodName = $"Deserialize_{safeStem}_Payload";
|
||||
IndexAccessors = indexAccessors;
|
||||
Members = members;
|
||||
CanConstructForDeserialization = canConstructForDeserialization;
|
||||
HasDenseSlots = hasDenseSlots;
|
||||
}
|
||||
|
||||
public string DocumentTypeName { get; }
|
||||
|
|
@ -556,6 +573,8 @@ public sealed class CultDocumentMessagePackGenerator : IIncrementalGenerator
|
|||
public string PayloadDeserializerMethodName { get; }
|
||||
public ImmutableArray<IndexAccessorShape> IndexAccessors { get; }
|
||||
public ImmutableArray<MemberShape> Members { get; }
|
||||
public bool CanConstructForDeserialization { get; }
|
||||
public bool HasDenseSlots { get; }
|
||||
}
|
||||
|
||||
private sealed class IndexAccessorShape
|
||||
|
|
|
|||
|
|
@ -49,6 +49,12 @@ namespace GameCult.Caching.MessagePack
|
|||
/// </summary>
|
||||
public string? DirectoryStorePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the records to hydrate when opening a paged directory store.
|
||||
/// The directory manifest is always read; rejected record payloads are never opened.
|
||||
/// </summary>
|
||||
public Func<CultPersistedRecordMetadata, bool>? DirectoryStoreHydrationFilter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets an optional callback used to customize the directory backing store before opening.
|
||||
/// </summary>
|
||||
|
|
@ -64,15 +70,39 @@ namespace GameCult.Caching.MessagePack
|
|||
/// Creates a cache with the canonical single-file MessagePack backing store attached.
|
||||
/// </summary>
|
||||
public static CultCache Create(string filePath, CultCacheOpenOptions? options = null)
|
||||
{
|
||||
options ??= new CultCacheOpenOptions();
|
||||
return CreateCore(filePath, options, initializeGlobals: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a cache with the canonical single-file MessagePack backing store attached and optionally pulls the on-disk snapshot.
|
||||
/// </summary>
|
||||
public static async Task<CultCache> OpenAsync(string filePath, CultCacheOpenOptions? options = null)
|
||||
{
|
||||
options ??= new CultCacheOpenOptions();
|
||||
var cache = CreateCore(filePath, options, initializeGlobals: false);
|
||||
if (options.PullOnOpen)
|
||||
{
|
||||
await cache.PullAllBackingStoresAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
cache.MaterializeMissingGlobals();
|
||||
|
||||
return cache;
|
||||
}
|
||||
|
||||
private static CultCache CreateCore(
|
||||
string filePath,
|
||||
CultCacheOpenOptions options,
|
||||
bool initializeGlobals)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(filePath))
|
||||
{
|
||||
throw new ArgumentException("File path must be non-empty.", nameof(filePath));
|
||||
}
|
||||
|
||||
options ??= new CultCacheOpenOptions();
|
||||
|
||||
var cache = new CultCache(options.Registry)
|
||||
var cache = new CultCache(options.Registry, initializeGlobals)
|
||||
{
|
||||
FlushAttachedStoresOnDispose = options.FlushOnDispose
|
||||
};
|
||||
|
|
@ -82,7 +112,8 @@ namespace GameCult.Caching.MessagePack
|
|||
{
|
||||
var directoryStore = new DirectoryMessagePackBackingStore(filePath, options.DirectoryStorePath)
|
||||
{
|
||||
FlushOnDispose = options.StoreFlushOnDispose
|
||||
FlushOnDispose = options.StoreFlushOnDispose,
|
||||
HydrationFilter = options.DirectoryStoreHydrationFilter
|
||||
};
|
||||
options.ConfigureDirectoryStore?.Invoke(directoryStore);
|
||||
cache.AddBackingStore(directoryStore);
|
||||
|
|
@ -99,20 +130,5 @@ namespace GameCult.Caching.MessagePack
|
|||
|
||||
return cache;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a cache with the canonical single-file MessagePack backing store attached and optionally pulls the on-disk snapshot.
|
||||
/// </summary>
|
||||
public static async Task<CultCache> OpenAsync(string filePath, CultCacheOpenOptions? options = null)
|
||||
{
|
||||
options ??= new CultCacheOpenOptions();
|
||||
var cache = Create(filePath, options);
|
||||
if (options.PullOnOpen)
|
||||
{
|
||||
await cache.PullAllBackingStoresAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return cache;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,9 +117,18 @@ public static class CultDocumentMessagePackSerialization
|
|||
/// </summary>
|
||||
public static byte[] SerializeUntyped(object value, Type type)
|
||||
{
|
||||
return SerializeUntyped(value, type, CultDocumentRegistry.Shared);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serializes a value through an explicitly owned document registry.
|
||||
/// </summary>
|
||||
public static byte[] SerializeUntyped(object value, Type type, CultDocumentRegistry registry)
|
||||
{
|
||||
if (registry == null) throw new ArgumentNullException(nameof(registry));
|
||||
if (value != null)
|
||||
{
|
||||
var descriptor = CultDocumentRegistry.Shared.GetRequired(type);
|
||||
var descriptor = registry.GetRequired(type);
|
||||
if (descriptor.GeneratedPayloadSerializer != null)
|
||||
{
|
||||
return descriptor.GeneratedPayloadSerializer(value);
|
||||
|
|
@ -134,7 +143,16 @@ public static class CultDocumentMessagePackSerialization
|
|||
/// </summary>
|
||||
public static object DeserializeUntyped(Type type, byte[] payload)
|
||||
{
|
||||
var descriptor = CultDocumentRegistry.Shared.GetRequired(type);
|
||||
return DeserializeUntyped(type, payload, CultDocumentRegistry.Shared);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes a value through an explicitly owned document registry.
|
||||
/// </summary>
|
||||
public static object DeserializeUntyped(Type type, byte[] payload, CultDocumentRegistry registry)
|
||||
{
|
||||
if (registry == null) throw new ArgumentNullException(nameof(registry));
|
||||
var descriptor = registry.GetRequired(type);
|
||||
if (descriptor.GeneratedPayloadDeserializer != null)
|
||||
{
|
||||
return descriptor.GeneratedPayloadDeserializer(payload);
|
||||
|
|
@ -519,7 +537,7 @@ public class SingleFileMessagePackBackingStore : SingleFileBackingStore
|
|||
/// </summary>
|
||||
protected override byte[] SerializePayload(object document)
|
||||
{
|
||||
return CultDocumentMessagePackSerialization.SerializeUntyped(document, document.GetType());
|
||||
return CultDocumentMessagePackSerialization.SerializeUntyped(document, document.GetType(), Registry);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -527,6 +545,6 @@ public class SingleFileMessagePackBackingStore : SingleFileBackingStore
|
|||
/// </summary>
|
||||
protected override object DeserializePayload(Type documentType, byte[] payload)
|
||||
{
|
||||
return CultDocumentMessagePackSerialization.DeserializeUntyped(documentType, payload);
|
||||
return CultDocumentMessagePackSerialization.DeserializeUntyped(documentType, payload, Registry);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MessagePack;
|
||||
|
||||
namespace GameCult.Caching.MessagePack;
|
||||
|
|
@ -15,10 +17,22 @@ namespace GameCult.Caching.MessagePack;
|
|||
/// </summary>
|
||||
public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
||||
{
|
||||
private const string IndexedFormatVersion = "cultcache.store.v2.directory-indexed";
|
||||
private readonly FileInfo _manifestFile;
|
||||
private readonly DirectoryInfo _recordDirectory;
|
||||
private readonly ConcurrentDictionary<string, bool> _dirtyKeys = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, bool> _deletedKeys = new(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> _hydratedKeys = new(StringComparer.Ordinal);
|
||||
private Dictionary<string, CultPersistedRecord> _durableIndex = new(StringComparer.Ordinal);
|
||||
private Dictionary<string, CultPersistedRecord> _legacyInlineRecords = new(StringComparer.Ordinal);
|
||||
private CultSchemaCatalogEntry[] _durableCatalog = Array.Empty<CultSchemaCatalogEntry>();
|
||||
private bool _needsIndexUpgrade;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the predicate that selects indexed record payloads for hydration.
|
||||
/// A null predicate hydrates every record.
|
||||
/// </summary>
|
||||
public Func<CultPersistedRecordMetadata, bool>? HydrationFilter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a paged MessagePack backing store.
|
||||
|
|
@ -42,7 +56,20 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
/// <inheritdoc />
|
||||
public override void PullAll()
|
||||
{
|
||||
if (!_manifestFile.Exists && !_recordDirectory.Exists)
|
||||
var traceStartup = string.Equals(
|
||||
Environment.GetEnvironmentVariable("CULTCACHE_TRACE_STARTUP_PHASES"),
|
||||
"1",
|
||||
StringComparison.Ordinal);
|
||||
var startupPhase = Stopwatch.StartNew();
|
||||
void Trace(string phase)
|
||||
{
|
||||
if (traceStartup)
|
||||
Console.WriteLine($"CultCache directory-pull phase {phase} took {startupPhase.Elapsed.TotalMilliseconds:0.###}ms.");
|
||||
startupPhase.Restart();
|
||||
}
|
||||
|
||||
_recordDirectory.Refresh();
|
||||
if (!File.Exists(_manifestFile.FullName) && !_recordDirectory.Exists)
|
||||
{
|
||||
SetLastSchemaMigrationReports(Array.Empty<CultSchemaMigrationReport>());
|
||||
IsDirty = false;
|
||||
|
|
@ -50,38 +77,104 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
}
|
||||
|
||||
var manifest = ReadManifest();
|
||||
Trace($"manifest records={manifest.Records.Length}");
|
||||
_durableCatalog = manifest.SchemaCatalog;
|
||||
var reports = new List<CultSchemaMigrationReport>();
|
||||
foreach (var record in manifest.Records)
|
||||
var loaded = new Dictionary<string, CultStoredDocument>(StringComparer.Ordinal);
|
||||
var indexed = string.Equals(manifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal);
|
||||
if (indexed)
|
||||
{
|
||||
var catalog = ResolveCatalogForRecord(record, manifest.SchemaCatalog);
|
||||
reports.Add(Registry.ResolvePersistedSchemaReport(record.SchemaId, catalog));
|
||||
var stored = ToStoredDocument(record, catalog, CultDocumentMessagePackSerialization.DeserializeUntyped);
|
||||
Entries[stored.Key.Value] = stored;
|
||||
_dirtyKeys[stored.Key.Value] = true;
|
||||
EntryAdded.OnNext(stored);
|
||||
_needsIndexUpgrade = false;
|
||||
_durableIndex = manifest.Records
|
||||
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
|
||||
.GroupBy(record => record.Key, StringComparer.Ordinal)
|
||||
.ToDictionary(group => group.Key, group => group.Last(), StringComparer.Ordinal);
|
||||
|
||||
LoadIndexedRecords(manifest, loaded, reports);
|
||||
Trace($"indexed-pages loaded={loaded.Count}");
|
||||
}
|
||||
else
|
||||
{
|
||||
// V1 manifests have no page index. Hydrate once to discover the durable keys;
|
||||
// the next flush replaces this compatibility path with the indexed manifest.
|
||||
_needsIndexUpgrade = true;
|
||||
var legacyRecords = LoadLegacyRecords(manifest, loaded, reports);
|
||||
_durableIndex = legacyRecords
|
||||
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
|
||||
.GroupBy(record => record.Key, StringComparer.Ordinal)
|
||||
.ToDictionary(group => group.Key, group => ToIndexRecord(group.Last()), StringComparer.Ordinal);
|
||||
Trace($"legacy-pages loaded={loaded.Count}");
|
||||
}
|
||||
|
||||
if (_recordDirectory.Exists)
|
||||
foreach (var pair in loaded)
|
||||
{
|
||||
foreach (var recordFile in _recordDirectory.EnumerateFiles("*.msgpack").OrderBy(file => file.Name, StringComparer.Ordinal))
|
||||
if (_dirtyKeys.ContainsKey(pair.Key) || _deletedKeys.ContainsKey(pair.Key))
|
||||
continue;
|
||||
|
||||
if (Entries.TryGetValue(pair.Key, out var existing) &&
|
||||
string.Equals(existing.StoredAt, pair.Value.StoredAt, StringComparison.Ordinal) &&
|
||||
string.Equals(existing.Descriptor.SchemaId, pair.Value.Descriptor.SchemaId, StringComparison.Ordinal))
|
||||
{
|
||||
var record = CultDocumentMessagePackSerialization.DeserializePersistedRecord(File.ReadAllBytes(recordFile.FullName));
|
||||
var catalog = ResolveCatalogForRecord(record, manifest.SchemaCatalog);
|
||||
reports.Add(Registry.ResolvePersistedSchemaReport(record.SchemaId, catalog));
|
||||
var stored = ToStoredDocument(record, catalog, CultDocumentMessagePackSerialization.DeserializeUntyped);
|
||||
Entries[stored.Key.Value] = stored;
|
||||
EntryAdded.OnNext(stored);
|
||||
continue;
|
||||
}
|
||||
|
||||
Entries[pair.Key] = pair.Value;
|
||||
if (existing == null)
|
||||
EntryAdded.OnNext(pair.Value);
|
||||
else
|
||||
EntryUpdated.OnNext(pair.Value);
|
||||
}
|
||||
|
||||
foreach (var removedKey in _hydratedKeys.Where(key => !loaded.ContainsKey(key)).ToArray())
|
||||
{
|
||||
if (_dirtyKeys.ContainsKey(removedKey) || _deletedKeys.ContainsKey(removedKey))
|
||||
continue;
|
||||
|
||||
if (Entries.TryRemove(removedKey, out var removed))
|
||||
EntryDeleted.OnNext(removed);
|
||||
_hydratedKeys.Remove(removedKey);
|
||||
}
|
||||
|
||||
foreach (var key in loaded.Keys)
|
||||
_hydratedKeys.Add(key);
|
||||
|
||||
SetLastSchemaMigrationReports(reports);
|
||||
if (manifest.Records.Length == 0)
|
||||
IsDirty = !_dirtyKeys.IsEmpty || !_deletedKeys.IsEmpty;
|
||||
Trace("publish");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void PullSelected(Func<CultPersistedRecordMetadata, bool> selector)
|
||||
{
|
||||
if (selector == null) throw new ArgumentNullException(nameof(selector));
|
||||
var manifest = ReadManifest();
|
||||
if (!string.Equals(manifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal))
|
||||
{
|
||||
_dirtyKeys.Clear();
|
||||
PullAll();
|
||||
return;
|
||||
}
|
||||
|
||||
_deletedKeys.Clear();
|
||||
IsDirty = _dirtyKeys.Count > 0;
|
||||
_durableCatalog = manifest.SchemaCatalog;
|
||||
_durableIndex = manifest.Records
|
||||
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
|
||||
.GroupBy(record => record.Key, StringComparer.Ordinal)
|
||||
.ToDictionary(group => group.Key, group => group.Last(), StringComparer.Ordinal);
|
||||
var selected = manifest.Records
|
||||
.Where(record => selector(ToMetadata(record)))
|
||||
.OrderBy(record => record.Key, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
var loaded = new Dictionary<string, CultStoredDocument>(StringComparer.Ordinal);
|
||||
var reports = new List<CultSchemaMigrationReport>();
|
||||
LoadRecordPages(selected, manifest.SchemaCatalog, loaded, reports);
|
||||
PublishSelected(loaded, selected.Select(record => record.Key).ToHashSet(StringComparer.Ordinal));
|
||||
SetLastSchemaMigrationReports(reports);
|
||||
IsDirty = !_dirtyKeys.IsEmpty || !_deletedKeys.IsEmpty;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool ContainsDurableRecord(CultRecordKey key)
|
||||
{
|
||||
return _durableIndex.ContainsKey(key.Value) || base.ContainsDurableRecord(key);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
|
@ -105,10 +198,78 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
/// <inheritdoc />
|
||||
public override void PushAll(bool soft = false)
|
||||
{
|
||||
if (!IsDirty && !_needsIndexUpgrade)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(_manifestFile.DirectoryName!);
|
||||
Directory.CreateDirectory(_recordDirectory.FullName);
|
||||
|
||||
var currentManifest = ReadManifest();
|
||||
var currentIndex = string.Equals(currentManifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal)
|
||||
? currentManifest.Records.ToDictionary(record => record.Key, record => record, StringComparer.Ordinal)
|
||||
: new Dictionary<string, CultPersistedRecord>(_durableIndex, StringComparer.Ordinal);
|
||||
var precommitIndex = currentIndex.Values
|
||||
.Select(ToIndexRecord)
|
||||
.OrderBy(record => record.Key, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
foreach (var key in _deletedKeys.Keys)
|
||||
currentIndex.Remove(key);
|
||||
foreach (var key in _dirtyKeys.Keys)
|
||||
{
|
||||
if (Entries.TryGetValue(key, out var stored))
|
||||
currentIndex[key] = ToIndexRecord(stored);
|
||||
}
|
||||
|
||||
var catalogCandidates = currentManifest.SchemaCatalog
|
||||
.Concat(_durableCatalog)
|
||||
.Concat(Entries.Values.Select(entry => entry.Descriptor.ToCatalogEntry()))
|
||||
.GroupBy(entry => entry.SchemaId, StringComparer.Ordinal)
|
||||
.Select(group => group.Last())
|
||||
.ToArray();
|
||||
var usedSchemaIds = currentIndex.Values.Select(record => record.SchemaId).ToHashSet(StringComparer.Ordinal);
|
||||
var targetCatalog = catalogCandidates
|
||||
.Where(entry => usedSchemaIds.Contains(entry.SchemaId))
|
||||
.OrderBy(entry => entry.SchemaName, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
var precommitCatalog = currentManifest.SchemaCatalog
|
||||
.Concat(targetCatalog)
|
||||
.GroupBy(entry => entry.SchemaId, StringComparer.Ordinal)
|
||||
.Select(group => group.Last())
|
||||
.OrderBy(entry => entry.SchemaName, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
|
||||
WriteManifest(precommitCatalog, precommitIndex);
|
||||
|
||||
var keysToWrite = (_needsIndexUpgrade ? Entries.Keys : _dirtyKeys.Keys)
|
||||
.OrderBy(value => value, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
foreach (var key in keysToWrite)
|
||||
{
|
||||
if (!Entries.TryGetValue(key, out var stored))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var record = ToPersistedRecord(stored, document =>
|
||||
CultDocumentMessagePackSerialization.SerializeUntyped(
|
||||
document,
|
||||
stored.Descriptor.DocumentType,
|
||||
Registry));
|
||||
WriteFileAtomically(RecordPath(key), CultDocumentMessagePackSerialization.SerializePersistedRecord(record));
|
||||
}
|
||||
|
||||
foreach (var pair in _legacyInlineRecords.OrderBy(pair => pair.Key, StringComparer.Ordinal))
|
||||
{
|
||||
if (_deletedKeys.ContainsKey(pair.Key) || _dirtyKeys.ContainsKey(pair.Key))
|
||||
continue;
|
||||
WriteFileAtomically(
|
||||
RecordPath(pair.Key),
|
||||
CultDocumentMessagePackSerialization.SerializePersistedRecord(pair.Value));
|
||||
}
|
||||
|
||||
foreach (var key in _deletedKeys.Keys.OrderBy(value => value, StringComparer.Ordinal))
|
||||
{
|
||||
var path = RecordPath(key);
|
||||
if (File.Exists(path))
|
||||
|
|
@ -117,50 +278,251 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
}
|
||||
}
|
||||
|
||||
foreach (var key in _dirtyKeys.Keys.OrderBy(value => value, StringComparer.Ordinal))
|
||||
{
|
||||
if (!Entries.TryGetValue(key, out var stored))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var record = ToPersistedRecord(stored, document =>
|
||||
CultDocumentMessagePackSerialization.SerializeUntyped(document, stored.Descriptor.DocumentType));
|
||||
WriteFileAtomically(RecordPath(key), CultDocumentMessagePackSerialization.SerializePersistedRecord(record));
|
||||
}
|
||||
|
||||
var manifest = new CultPersistedStoreSnapshot
|
||||
{
|
||||
FormatVersion = "cultcache.store.v1.directory",
|
||||
SchemaCatalog = Entries.Values
|
||||
.Select(entry => entry.Descriptor.ToCatalogEntry())
|
||||
.GroupBy(entry => entry.SchemaId, StringComparer.Ordinal)
|
||||
.Select(group => group.First())
|
||||
.OrderBy(entry => entry.SchemaName, StringComparer.Ordinal)
|
||||
.ToArray(),
|
||||
Records = Array.Empty<CultPersistedRecord>()
|
||||
};
|
||||
WriteFileAtomically(_manifestFile.FullName, CultDocumentMessagePackSerialization.SerializeSnapshot(manifest));
|
||||
WriteManifest(targetCatalog, currentIndex.Values
|
||||
.OrderBy(record => record.Key, StringComparer.Ordinal)
|
||||
.ToArray());
|
||||
|
||||
_durableCatalog = targetCatalog;
|
||||
_durableIndex = currentIndex;
|
||||
_legacyInlineRecords.Clear();
|
||||
_needsIndexUpgrade = false;
|
||||
_dirtyKeys.Clear();
|
||||
_deletedKeys.Clear();
|
||||
MarkFlushSucceeded();
|
||||
}
|
||||
|
||||
private void WriteManifest(CultSchemaCatalogEntry[] catalog, CultPersistedRecord[] index)
|
||||
{
|
||||
var manifest = new CultPersistedStoreSnapshot
|
||||
{
|
||||
FormatVersion = IndexedFormatVersion,
|
||||
SchemaCatalog = catalog,
|
||||
Records = index
|
||||
};
|
||||
WriteFileAtomically(_manifestFile.FullName, CultDocumentMessagePackSerialization.SerializeSnapshot(manifest));
|
||||
}
|
||||
|
||||
private void LoadIndexedRecords(
|
||||
CultPersistedStoreSnapshot manifest,
|
||||
Dictionary<string, CultStoredDocument> loaded,
|
||||
List<CultSchemaMigrationReport> reports)
|
||||
{
|
||||
var selected = manifest.Records
|
||||
.Where(ShouldHydrate)
|
||||
.OrderBy(record => record.Key, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
LoadRecordPages(selected, manifest.SchemaCatalog, loaded, reports);
|
||||
}
|
||||
|
||||
private CultPersistedRecord[] LoadLegacyRecords(
|
||||
CultPersistedStoreSnapshot manifest,
|
||||
Dictionary<string, CultStoredDocument> loaded,
|
||||
List<CultSchemaMigrationReport> reports)
|
||||
{
|
||||
_legacyInlineRecords = manifest.Records
|
||||
.Where(record => !string.IsNullOrWhiteSpace(record.Key))
|
||||
.GroupBy(record => record.Key, StringComparer.Ordinal)
|
||||
.ToDictionary(group => group.Key, group => group.Last(), StringComparer.Ordinal);
|
||||
foreach (var record in manifest.Records.Where(ShouldHydrate))
|
||||
{
|
||||
var catalog = ResolveLegacyUncataloguedRecordCatalog(record, manifest.SchemaCatalog);
|
||||
reports.Add(Registry.ResolvePersistedSchemaReport(record.SchemaId, catalog));
|
||||
var stored = ToStoredDocument(
|
||||
record,
|
||||
catalog,
|
||||
(type, payload) => CultDocumentMessagePackSerialization.DeserializeUntyped(type, payload, Registry));
|
||||
loaded[stored.Key.Value] = stored;
|
||||
}
|
||||
|
||||
if (!_recordDirectory.Exists)
|
||||
return manifest.Records;
|
||||
|
||||
var pages = _recordDirectory.EnumerateFiles("*.msgpack")
|
||||
.OrderBy(file => file.Name, StringComparer.Ordinal)
|
||||
.Select(file => CultDocumentMessagePackSerialization.DeserializePersistedRecord(ReadAllBytesShared(file.FullName)))
|
||||
.ToArray();
|
||||
LoadPersistedRecords(pages.Where(ShouldHydrate).ToArray(), manifest.SchemaCatalog, loaded, reports);
|
||||
return manifest.Records.Concat(pages).ToArray();
|
||||
}
|
||||
|
||||
private void LoadRecordPages(
|
||||
CultPersistedRecord[] records,
|
||||
IReadOnlyCollection<CultSchemaCatalogEntry> catalogEntries,
|
||||
Dictionary<string, CultStoredDocument> loaded,
|
||||
List<CultSchemaMigrationReport> reports)
|
||||
{
|
||||
var tracePages = string.Equals(
|
||||
Environment.GetEnvironmentVariable("CULTCACHE_TRACE_STARTUP_PHASES"),
|
||||
"1",
|
||||
StringComparison.Ordinal);
|
||||
var recordReports = new CultSchemaMigrationReport[records.Length];
|
||||
var storedRecords = new CultStoredDocument?[records.Length];
|
||||
var pageBytes = tracePages ? new long[records.Length] : Array.Empty<long>();
|
||||
var pageElapsedTicks = tracePages ? new long[records.Length] : Array.Empty<long>();
|
||||
Parallel.For(
|
||||
0,
|
||||
records.Length,
|
||||
new ParallelOptions { MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 8) },
|
||||
index =>
|
||||
{
|
||||
var started = tracePages ? Stopwatch.GetTimestamp() : 0L;
|
||||
var metadata = records[index];
|
||||
var path = RecordPath(metadata.Key);
|
||||
if (!File.Exists(path))
|
||||
return;
|
||||
var pagePayload = ReadAllBytesShared(path);
|
||||
var record = CultDocumentMessagePackSerialization.DeserializePersistedRecord(pagePayload);
|
||||
if (!string.Equals(record.Key, metadata.Key, StringComparison.Ordinal))
|
||||
throw new InvalidDataException($"Record page '{path}' contains key '{record.Key}', expected '{metadata.Key}'.");
|
||||
var catalog = ResolveLegacyUncataloguedRecordCatalog(record, catalogEntries);
|
||||
recordReports[index] = Registry.ResolvePersistedSchemaReport(record.SchemaId, catalog);
|
||||
storedRecords[index] = ToStoredDocument(
|
||||
record,
|
||||
catalog,
|
||||
(type, payload) => CultDocumentMessagePackSerialization.DeserializeUntyped(type, payload, Registry));
|
||||
if (tracePages)
|
||||
{
|
||||
pageBytes[index] = pagePayload.LongLength;
|
||||
pageElapsedTicks[index] = Stopwatch.GetTimestamp() - started;
|
||||
}
|
||||
});
|
||||
|
||||
if (tracePages)
|
||||
{
|
||||
var schemaNames = catalogEntries.ToDictionary(entry => entry.SchemaId, entry => entry.SchemaName, StringComparer.Ordinal);
|
||||
foreach (var group in records
|
||||
.Select((record, index) => new { record.SchemaId, Index = index })
|
||||
.Where(item => pageElapsedTicks[item.Index] > 0)
|
||||
.GroupBy(item => item.SchemaId, StringComparer.Ordinal)
|
||||
.Select(group => new
|
||||
{
|
||||
SchemaId = group.Key,
|
||||
Count = group.Count(),
|
||||
Bytes = group.Sum(item => pageBytes[item.Index]),
|
||||
TotalMs = group.Sum(item => pageElapsedTicks[item.Index]) * 1000d / Stopwatch.Frequency,
|
||||
MaxMs = group.Max(item => pageElapsedTicks[item.Index]) * 1000d / Stopwatch.Frequency
|
||||
})
|
||||
.OrderByDescending(group => group.TotalMs)
|
||||
.Take(10))
|
||||
{
|
||||
var schemaName = schemaNames.TryGetValue(group.SchemaId, out var name) ? name : group.SchemaId;
|
||||
Console.WriteLine(
|
||||
$"CultCache directory-page schema={schemaName} count={group.Count} bytes={group.Bytes} " +
|
||||
$"cumulative={group.TotalMs:0.###}ms max={group.MaxMs:0.###}ms.");
|
||||
}
|
||||
}
|
||||
|
||||
for (var index = 0; index < storedRecords.Length; index++)
|
||||
{
|
||||
var stored = storedRecords[index];
|
||||
if (stored == null)
|
||||
continue;
|
||||
reports.Add(recordReports[index]);
|
||||
loaded[stored.Key.Value] = stored;
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadPersistedRecords(
|
||||
CultPersistedRecord[] records,
|
||||
IReadOnlyCollection<CultSchemaCatalogEntry> catalogEntries,
|
||||
Dictionary<string, CultStoredDocument> loaded,
|
||||
List<CultSchemaMigrationReport> reports)
|
||||
{
|
||||
var recordReports = new CultSchemaMigrationReport[records.Length];
|
||||
var storedRecords = new CultStoredDocument[records.Length];
|
||||
Parallel.For(
|
||||
0,
|
||||
records.Length,
|
||||
new ParallelOptions { MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 8) },
|
||||
index =>
|
||||
{
|
||||
var record = records[index];
|
||||
var catalog = ResolveLegacyUncataloguedRecordCatalog(record, catalogEntries);
|
||||
recordReports[index] = Registry.ResolvePersistedSchemaReport(record.SchemaId, catalog);
|
||||
storedRecords[index] = ToStoredDocument(
|
||||
record,
|
||||
catalog,
|
||||
(type, payload) => CultDocumentMessagePackSerialization.DeserializeUntyped(type, payload, Registry));
|
||||
});
|
||||
|
||||
for (var index = 0; index < storedRecords.Length; index++)
|
||||
{
|
||||
reports.Add(recordReports[index]);
|
||||
var stored = storedRecords[index];
|
||||
loaded[stored.Key.Value] = stored;
|
||||
}
|
||||
}
|
||||
|
||||
private bool ShouldHydrate(CultPersistedRecord record) =>
|
||||
HydrationFilter?.Invoke(ToMetadata(record)) ?? true;
|
||||
|
||||
private static CultPersistedRecordMetadata ToMetadata(CultPersistedRecord record) =>
|
||||
new(record.Key, record.SchemaId, record.StoredAt);
|
||||
|
||||
private void PublishSelected(
|
||||
IReadOnlyDictionary<string, CultStoredDocument> loaded,
|
||||
HashSet<string> selectedKeys)
|
||||
{
|
||||
foreach (var pair in loaded)
|
||||
{
|
||||
if (_dirtyKeys.ContainsKey(pair.Key) || _deletedKeys.ContainsKey(pair.Key))
|
||||
continue;
|
||||
|
||||
if (Entries.TryGetValue(pair.Key, out var existing) &&
|
||||
string.Equals(existing.StoredAt, pair.Value.StoredAt, StringComparison.Ordinal) &&
|
||||
string.Equals(existing.Descriptor.SchemaId, pair.Value.Descriptor.SchemaId, StringComparison.Ordinal))
|
||||
continue;
|
||||
|
||||
Entries[pair.Key] = pair.Value;
|
||||
if (existing == null)
|
||||
EntryAdded.OnNext(pair.Value);
|
||||
else
|
||||
EntryUpdated.OnNext(pair.Value);
|
||||
}
|
||||
|
||||
foreach (var missingKey in selectedKeys.Where(key => !loaded.ContainsKey(key)).ToArray())
|
||||
{
|
||||
if (_dirtyKeys.ContainsKey(missingKey) || _deletedKeys.ContainsKey(missingKey))
|
||||
continue;
|
||||
if (Entries.TryRemove(missingKey, out var removed))
|
||||
EntryDeleted.OnNext(removed);
|
||||
_hydratedKeys.Remove(missingKey);
|
||||
}
|
||||
|
||||
foreach (var key in loaded.Keys)
|
||||
_hydratedKeys.Add(key);
|
||||
}
|
||||
|
||||
private static CultPersistedRecord ToIndexRecord(CultStoredDocument stored) => new()
|
||||
{
|
||||
Key = stored.Key.Value,
|
||||
SchemaId = stored.Descriptor.SchemaId,
|
||||
StoredAt = stored.StoredAt,
|
||||
Payload = Array.Empty<byte>()
|
||||
};
|
||||
|
||||
private static CultPersistedRecord ToIndexRecord(CultPersistedRecord record) => new()
|
||||
{
|
||||
Key = record.Key,
|
||||
SchemaId = record.SchemaId,
|
||||
StoredAt = record.StoredAt,
|
||||
Payload = Array.Empty<byte>()
|
||||
};
|
||||
|
||||
private CultPersistedStoreSnapshot ReadManifest()
|
||||
{
|
||||
if (_manifestFile.Exists)
|
||||
if (File.Exists(_manifestFile.FullName))
|
||||
{
|
||||
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(_manifestFile.FullName));
|
||||
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(ReadAllBytesShared(_manifestFile.FullName));
|
||||
if (snapshot.SchemaCatalog.Length > 0 || snapshot.Records.Length == 0)
|
||||
{
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
|
||||
if (_manifestFile.Exists)
|
||||
if (File.Exists(_manifestFile.FullName))
|
||||
{
|
||||
return CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(_manifestFile.FullName));
|
||||
return CultDocumentMessagePackSerialization.DeserializeSnapshot(ReadAllBytesShared(_manifestFile.FullName));
|
||||
}
|
||||
|
||||
return new CultPersistedStoreSnapshot
|
||||
|
|
@ -171,7 +533,8 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
};
|
||||
}
|
||||
|
||||
private IReadOnlyCollection<CultSchemaCatalogEntry> ResolveCatalogForRecord(
|
||||
// Explicit compatibility path for records written before catalog precommit existed.
|
||||
private IReadOnlyCollection<CultSchemaCatalogEntry> ResolveLegacyUncataloguedRecordCatalog(
|
||||
CultPersistedRecord record,
|
||||
IReadOnlyCollection<CultSchemaCatalogEntry> manifestCatalog)
|
||||
{
|
||||
|
|
@ -291,6 +654,14 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
}
|
||||
}
|
||||
|
||||
private static byte[] ReadAllBytesShared(string path)
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
using var buffer = new MemoryStream();
|
||||
stream.CopyTo(buffer);
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
private static void ReplaceExistingFile(string sourcePath, string destinationPath)
|
||||
{
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
|
|
|
|||
|
|
@ -404,11 +404,8 @@ namespace GameCult.Caching
|
|||
private static readonly Lazy<CultDocumentRegistry> SharedRegistry =
|
||||
new(() => new CultDocumentRegistry());
|
||||
|
||||
private readonly ConcurrentDictionary<Type, CultDocumentDescriptor> _byType = new();
|
||||
private readonly ConcurrentDictionary<string, CultDocumentDescriptor> _bySchemaId =
|
||||
new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, CultDocumentDescriptor> _bySchemaName =
|
||||
new(StringComparer.Ordinal);
|
||||
private volatile RegistryIndexes _indexes = new();
|
||||
private readonly object _registrationGate = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shared process-wide document registry.
|
||||
|
|
@ -423,31 +420,56 @@ namespace GameCult.Caching
|
|||
Refresh();
|
||||
}
|
||||
|
||||
private CultDocumentRegistry(bool discoverLoadedDocuments)
|
||||
{
|
||||
if (discoverLoadedDocuments)
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a registry containing exactly the requested document types without scanning loaded assemblies.
|
||||
/// </summary>
|
||||
public static CultDocumentRegistry ForTypes(IEnumerable<Type> documentTypes)
|
||||
{
|
||||
if (documentTypes == null) throw new ArgumentNullException(nameof(documentTypes));
|
||||
var registry = new CultDocumentRegistry(discoverLoadedDocuments: false);
|
||||
foreach (var type in documentTypes.Distinct())
|
||||
{
|
||||
registry.GetRequired(type ?? throw new ArgumentException(
|
||||
"Document type collections cannot contain null entries.",
|
||||
nameof(documentTypes)));
|
||||
}
|
||||
return registry;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all known document descriptors.
|
||||
/// </summary>
|
||||
public IEnumerable<CultDocumentDescriptor> AllDescriptors => _byType.Values.OrderBy(d => d.SchemaName, StringComparer.Ordinal);
|
||||
public IEnumerable<CultDocumentDescriptor> AllDescriptors =>
|
||||
_indexes.ByType.Values.OrderBy(d => d.SchemaName, StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the registry from generated metadata and reflected document attributes.
|
||||
/// </summary>
|
||||
public void Refresh()
|
||||
{
|
||||
_byType.Clear();
|
||||
_bySchemaId.Clear();
|
||||
_bySchemaName.Clear();
|
||||
|
||||
var generatedTypes = new HashSet<Type>();
|
||||
foreach (var definition in CultGeneratedDocumentMetadataLoader.LoadDefinitions())
|
||||
lock (_registrationGate)
|
||||
{
|
||||
var descriptor = BuildDescriptor(definition);
|
||||
RegisterDescriptor(descriptor);
|
||||
generatedTypes.Add(descriptor.DocumentType);
|
||||
}
|
||||
var rebuilt = new RegistryIndexes();
|
||||
var generatedTypes = new HashSet<Type>();
|
||||
foreach (var definition in CultGeneratedDocumentMetadataLoader.LoadDefinitions())
|
||||
{
|
||||
var descriptor = BuildDescriptor(definition);
|
||||
RegisterDescriptor(rebuilt, descriptor);
|
||||
generatedTypes.Add(descriptor.DocumentType);
|
||||
}
|
||||
|
||||
foreach (var type in ReflectionExtensions.GetAttributedDocumentTypes().Where(type => !generatedTypes.Contains(type)))
|
||||
{
|
||||
RegisterDescriptor(BuildDescriptor(type));
|
||||
foreach (var type in ReflectionExtensions.GetAttributedDocumentTypes().Where(type => !generatedTypes.Contains(type)))
|
||||
{
|
||||
RegisterDescriptor(rebuilt, BuildDescriptor(type));
|
||||
}
|
||||
|
||||
_indexes = rebuilt;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -456,7 +478,7 @@ namespace GameCult.Caching
|
|||
/// </summary>
|
||||
public CultDocumentDescriptor GetRequired(Type type)
|
||||
{
|
||||
if (_byType.TryGetValue(type, out var descriptor))
|
||||
if (_indexes.ByType.TryGetValue(type, out var descriptor))
|
||||
{
|
||||
return descriptor;
|
||||
}
|
||||
|
|
@ -464,8 +486,7 @@ namespace GameCult.Caching
|
|||
descriptor = TryBuildGeneratedDescriptor(type);
|
||||
if (descriptor != null)
|
||||
{
|
||||
RegisterDescriptor(descriptor);
|
||||
return descriptor;
|
||||
return RegisterDescriptor(descriptor);
|
||||
}
|
||||
|
||||
var attribute = type.GetCustomAttribute<CultDocumentAttribute>();
|
||||
|
|
@ -476,8 +497,7 @@ namespace GameCult.Caching
|
|||
}
|
||||
|
||||
descriptor = BuildDescriptor(type);
|
||||
RegisterDescriptor(descriptor);
|
||||
return descriptor;
|
||||
return RegisterDescriptor(descriptor);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -493,7 +513,7 @@ namespace GameCult.Caching
|
|||
/// </summary>
|
||||
public CultDocumentDescriptor GetRequiredBySchemaId(string schemaId)
|
||||
{
|
||||
if (_bySchemaId.TryGetValue(schemaId, out var descriptor))
|
||||
if (_indexes.BySchemaId.TryGetValue(schemaId, out var descriptor))
|
||||
{
|
||||
return descriptor;
|
||||
}
|
||||
|
|
@ -519,7 +539,8 @@ namespace GameCult.Caching
|
|||
|
||||
internal CultSchemaResolutionResult ResolvePersistedSchemaDetailed(string schemaId, IReadOnlyCollection<CultSchemaCatalogEntry> catalog)
|
||||
{
|
||||
if (_bySchemaId.TryGetValue(schemaId, out var exact))
|
||||
var indexes = _indexes;
|
||||
if (indexes.BySchemaId.TryGetValue(schemaId, out var exact))
|
||||
{
|
||||
return new CultSchemaResolutionResult(
|
||||
exact,
|
||||
|
|
@ -541,26 +562,121 @@ namespace GameCult.Caching
|
|||
|
||||
foreach (var compatibleSchemaId in persisted.CompatibleSchemaIds.Where(candidate => !string.IsNullOrWhiteSpace(candidate)))
|
||||
{
|
||||
if (_bySchemaId.TryGetValue(compatibleSchemaId, out var compatibleLocal))
|
||||
if (indexes.BySchemaId.TryGetValue(compatibleSchemaId, out var compatibleLocal))
|
||||
{
|
||||
return BuildCompatibleResolutionResult(persisted, compatibleLocal);
|
||||
}
|
||||
}
|
||||
|
||||
if (_bySchemaName.TryGetValue(persisted.SchemaName, out var local))
|
||||
if (indexes.BySchemaName.TryGetValue(persisted.SchemaName, out var localVersions))
|
||||
{
|
||||
return BuildCompatibleResolutionResult(persisted, local);
|
||||
if (localVersions.Length == 1)
|
||||
{
|
||||
return BuildCompatibleResolutionResult(persisted, localVersions[0]);
|
||||
}
|
||||
|
||||
throw new InvalidOperationException(
|
||||
$"CultCache schema name '{persisted.SchemaName}' is ambiguous across local versions " +
|
||||
$"[{string.Join(", ", localVersions.Select(candidate => candidate.SchemaVersion).OrderBy(version => version, StringComparer.Ordinal))}]. " +
|
||||
"Persisted schema compatibility must identify an explicit schema id.");
|
||||
}
|
||||
|
||||
throw new InvalidOperationException(
|
||||
$"No local CultCache schema matches persisted schema '{persisted.SchemaName}' ({schemaId}).");
|
||||
}
|
||||
|
||||
private void RegisterDescriptor(CultDocumentDescriptor descriptor)
|
||||
private CultDocumentDescriptor RegisterDescriptor(CultDocumentDescriptor descriptor)
|
||||
{
|
||||
_byType[descriptor.DocumentType] = descriptor;
|
||||
_bySchemaId[descriptor.SchemaId] = descriptor;
|
||||
_bySchemaName[descriptor.SchemaName] = descriptor;
|
||||
lock (_registrationGate)
|
||||
{
|
||||
var current = _indexes;
|
||||
if (current.ByType.TryGetValue(descriptor.DocumentType, out var registered))
|
||||
return registered;
|
||||
|
||||
var updated = new RegistryIndexes(current);
|
||||
registered = RegisterDescriptor(updated, descriptor);
|
||||
_indexes = updated;
|
||||
return registered;
|
||||
}
|
||||
}
|
||||
|
||||
private static CultDocumentDescriptor RegisterDescriptor(
|
||||
RegistryIndexes indexes,
|
||||
CultDocumentDescriptor descriptor)
|
||||
{
|
||||
if (indexes.ByType.TryGetValue(descriptor.DocumentType, out var registered))
|
||||
return registered;
|
||||
|
||||
indexes.BySchemaName.TryGetValue(descriptor.SchemaName, out var schemaNameVersions);
|
||||
var schemaVersionOwner = schemaNameVersions?.FirstOrDefault(candidate =>
|
||||
string.Equals(candidate.SchemaVersion, descriptor.SchemaVersion, StringComparison.Ordinal));
|
||||
if (schemaVersionOwner != null)
|
||||
{
|
||||
if (IsExactWireAlias(schemaVersionOwner, descriptor))
|
||||
{
|
||||
indexes.ByType[descriptor.DocumentType] = descriptor;
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
throw DuplicateSchemaRegistration(
|
||||
$"schema name '{descriptor.SchemaName}' version '{descriptor.SchemaVersion}'",
|
||||
schemaVersionOwner.DocumentType,
|
||||
descriptor.DocumentType);
|
||||
}
|
||||
|
||||
if (indexes.BySchemaId.TryGetValue(descriptor.SchemaId, out var schemaIdOwner))
|
||||
{
|
||||
throw DuplicateSchemaRegistration(
|
||||
$"schema id '{descriptor.SchemaId}'",
|
||||
schemaIdOwner.DocumentType,
|
||||
descriptor.DocumentType);
|
||||
}
|
||||
|
||||
indexes.ByType[descriptor.DocumentType] = descriptor;
|
||||
indexes.BySchemaId[descriptor.SchemaId] = descriptor;
|
||||
indexes.BySchemaName[descriptor.SchemaName] = schemaNameVersions == null
|
||||
? [descriptor]
|
||||
: [.. schemaNameVersions, descriptor];
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
private static bool IsExactWireAlias(
|
||||
CultDocumentDescriptor canonical,
|
||||
CultDocumentDescriptor candidate) =>
|
||||
string.Equals(canonical.SchemaName, candidate.SchemaName, StringComparison.Ordinal) &&
|
||||
string.Equals(canonical.SchemaVersion, candidate.SchemaVersion, StringComparison.Ordinal) &&
|
||||
string.Equals(canonical.SchemaId, candidate.SchemaId, StringComparison.Ordinal) &&
|
||||
string.Equals(canonical.ContentHash, candidate.ContentHash, StringComparison.Ordinal) &&
|
||||
string.Equals(canonical.CanonicalSchemaJson, candidate.CanonicalSchemaJson, StringComparison.Ordinal);
|
||||
|
||||
private static InvalidOperationException DuplicateSchemaRegistration(
|
||||
string identity,
|
||||
Type existingType,
|
||||
Type claimedType) =>
|
||||
new(
|
||||
$"CultCache {identity} is already registered to CLR type " +
|
||||
$"'{existingType.FullName}' and cannot also be claimed by '{claimedType.FullName}'. " +
|
||||
"Schema compatibility must be declared through explicit persisted-schema alias metadata.");
|
||||
|
||||
private sealed class RegistryIndexes
|
||||
{
|
||||
public RegistryIndexes()
|
||||
{
|
||||
ByType = new Dictionary<Type, CultDocumentDescriptor>();
|
||||
BySchemaId = new Dictionary<string, CultDocumentDescriptor>(StringComparer.Ordinal);
|
||||
BySchemaName = new Dictionary<string, CultDocumentDescriptor[]>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public RegistryIndexes(RegistryIndexes source)
|
||||
{
|
||||
ByType = new Dictionary<Type, CultDocumentDescriptor>(source.ByType);
|
||||
BySchemaId = new Dictionary<string, CultDocumentDescriptor>(source.BySchemaId, StringComparer.Ordinal);
|
||||
BySchemaName = new Dictionary<string, CultDocumentDescriptor[]>(source.BySchemaName, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public Dictionary<Type, CultDocumentDescriptor> ByType { get; }
|
||||
public Dictionary<string, CultDocumentDescriptor> BySchemaId { get; }
|
||||
public Dictionary<string, CultDocumentDescriptor[]> BySchemaName { get; }
|
||||
}
|
||||
|
||||
private static CultDocumentDescriptor? TryBuildGeneratedDescriptor(Type type)
|
||||
|
|
@ -1168,8 +1284,29 @@ namespace GameCult.Caching
|
|||
/// Creates a cache using the supplied document registry or the shared registry.
|
||||
/// </summary>
|
||||
public CultCache(CultDocumentRegistry? registry = null)
|
||||
: this(registry, initializeGlobals: true)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a cache using the supplied document registry, optionally deferring global defaults
|
||||
/// until a durable backing store has been hydrated.
|
||||
/// </summary>
|
||||
public CultCache(CultDocumentRegistry? registry, bool initializeGlobals)
|
||||
{
|
||||
_registry = registry ?? CultDocumentRegistry.Shared;
|
||||
if (initializeGlobals)
|
||||
{
|
||||
MaterializeMissingGlobals();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates default instances for global document types that do not already have a record.
|
||||
/// Durable open paths call this after hydration so persisted globals remain authoritative.
|
||||
/// </summary>
|
||||
public void MaterializeMissingGlobals()
|
||||
{
|
||||
InitializeGlobals();
|
||||
}
|
||||
|
||||
|
|
@ -1298,6 +1435,22 @@ namespace GameCult.Caching
|
|||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pulls persisted records selected by durable metadata from every attached backing store.
|
||||
/// Stores without indexed selection support preserve correctness by performing a full pull.
|
||||
/// </summary>
|
||||
public async Task PullBackingStoreRecordsAsync(Func<CultPersistedRecordMetadata, bool> selector)
|
||||
{
|
||||
if (selector == null) throw new ArgumentNullException(nameof(selector));
|
||||
foreach (var store in _backingStores)
|
||||
{
|
||||
store.PullSelected(selector);
|
||||
}
|
||||
|
||||
_hasUnflushedMutations = _backingStores.Any(store => store.IsDirty);
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flushes all attached backing stores.
|
||||
/// </summary>
|
||||
|
|
@ -1668,6 +1821,13 @@ namespace GameCult.Caching
|
|||
{
|
||||
foreach (var descriptor in _registry.AllDescriptors.Where(candidate => candidate.IsGlobal))
|
||||
{
|
||||
var key = new CultRecordKey($"global:{descriptor.SchemaId}");
|
||||
if (_entries.ContainsKey(key.Value) ||
|
||||
_backingStores.Any(store => store.ContainsDurableRecord(key)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (descriptor.DocumentType.GetConstructor(Type.EmptyTypes) == null)
|
||||
{
|
||||
continue;
|
||||
|
|
@ -1681,7 +1841,7 @@ namespace GameCult.Caching
|
|||
|
||||
AddStoredDocumentInternal(
|
||||
new CultStoredDocument(
|
||||
new CultRecordKey($"global:{descriptor.SchemaId}"),
|
||||
key,
|
||||
DateTimeOffset.UtcNow.ToString("O"),
|
||||
descriptor,
|
||||
instance),
|
||||
|
|
@ -1798,6 +1958,27 @@ namespace GameCult.Caching
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Durable metadata available before a backing store hydrates a record payload.
|
||||
/// </summary>
|
||||
public sealed class CultPersistedRecordMetadata
|
||||
{
|
||||
/// <summary>Creates durable record metadata.</summary>
|
||||
public CultPersistedRecordMetadata(string key, string schemaId, string storedAt)
|
||||
{
|
||||
Key = key;
|
||||
SchemaId = schemaId;
|
||||
StoredAt = storedAt;
|
||||
}
|
||||
|
||||
/// <summary>Gets the durable record key.</summary>
|
||||
public string Key { get; }
|
||||
/// <summary>Gets the durable schema identity.</summary>
|
||||
public string SchemaId { get; }
|
||||
/// <summary>Gets the record commit timestamp.</summary>
|
||||
public string StoredAt { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base class for CultCache persistence adapters.
|
||||
/// </summary>
|
||||
|
|
@ -1876,6 +2057,21 @@ namespace GameCult.Caching
|
|||
/// </summary>
|
||||
public abstract void PullAll();
|
||||
/// <summary>
|
||||
/// Pulls records selected by durable metadata. Non-indexed stores fall back to a full pull.
|
||||
/// </summary>
|
||||
public virtual void PullSelected(Func<CultPersistedRecordMetadata, bool> selector)
|
||||
{
|
||||
if (selector == null) throw new ArgumentNullException(nameof(selector));
|
||||
PullAll();
|
||||
}
|
||||
/// <summary>
|
||||
/// Returns whether the backing store knows a record is durable, including records left cold by selective hydration.
|
||||
/// </summary>
|
||||
public virtual bool ContainsDurableRecord(CultRecordKey key)
|
||||
{
|
||||
return Entries.ContainsKey(key.Value);
|
||||
}
|
||||
/// <summary>
|
||||
/// Pushes one stored document into the backing store.
|
||||
/// </summary>
|
||||
public abstract void Push(CultStoredDocument entry);
|
||||
|
|
@ -1990,6 +2186,7 @@ namespace GameCult.Caching
|
|||
/// </summary>
|
||||
public override void PullAll()
|
||||
{
|
||||
FileInfo.Refresh();
|
||||
if (!FileInfo.Exists)
|
||||
{
|
||||
SetLastSchemaMigrationReports(Array.Empty<CultSchemaMigrationReport>());
|
||||
|
|
@ -1997,14 +2194,49 @@ namespace GameCult.Caching
|
|||
return;
|
||||
}
|
||||
|
||||
var snapshot = DeserializeSnapshot(File.ReadAllBytes(FileInfo.FullName));
|
||||
// A single-file snapshot cannot distinguish local dirty keys from clean keys.
|
||||
// Pulling while local mutations are staged would let an older disk snapshot
|
||||
// erase those mutations before the next flush. Flush first; clean readers can
|
||||
// still poll external snapshots incrementally.
|
||||
if (IsDirty)
|
||||
return;
|
||||
|
||||
CultPersistedStoreSnapshot snapshot;
|
||||
try
|
||||
{
|
||||
snapshot = DeserializeSnapshot(ReadAllBytesShared(FileInfo.FullName));
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
FileInfo.Refresh();
|
||||
if (!FileInfo.Exists)
|
||||
return;
|
||||
snapshot = DeserializeSnapshot(ReadAllBytesShared(FileInfo.FullName));
|
||||
}
|
||||
var reports = new List<CultSchemaMigrationReport>(snapshot.Records.Length);
|
||||
var persistedKeys = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var record in snapshot.Records)
|
||||
{
|
||||
persistedKeys.Add(record.Key);
|
||||
reports.Add(Registry.ResolvePersistedSchemaReport(record.SchemaId, snapshot.SchemaCatalog));
|
||||
var stored = ToStoredDocument(record, snapshot.SchemaCatalog, DeserializePayload);
|
||||
if (Entries.TryGetValue(stored.Key.Value, out var existing) &&
|
||||
string.Equals(existing.StoredAt, stored.StoredAt, StringComparison.Ordinal) &&
|
||||
string.Equals(existing.Descriptor.SchemaId, stored.Descriptor.SchemaId, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Entries[stored.Key.Value] = stored;
|
||||
EntryAdded.OnNext(stored);
|
||||
if (existing == null)
|
||||
EntryAdded.OnNext(stored);
|
||||
else
|
||||
EntryUpdated.OnNext(stored);
|
||||
}
|
||||
|
||||
foreach (var removedKey in Entries.Keys.Where(key => !persistedKeys.Contains(key)).ToArray())
|
||||
{
|
||||
if (Entries.TryRemove(removedKey, out var removed))
|
||||
EntryDeleted.OnNext(removed);
|
||||
}
|
||||
|
||||
SetLastSchemaMigrationReports(reports);
|
||||
|
|
@ -2089,5 +2321,13 @@ namespace GameCult.Caching
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] ReadAllBytesShared(string path)
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
using var buffer = new MemoryStream();
|
||||
stream.CopyTo(buffer);
|
||||
return buffer.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,257 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Mesh;
|
||||
|
||||
namespace GameCult.Mesh.Quic.Native
|
||||
{
|
||||
public sealed class CultMeshNativeQuicRealtimeConnectorOptions
|
||||
{
|
||||
public TimeSpan HandshakeTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
||||
public TimeSpan PollInterval { get; set; } = TimeSpan.FromMilliseconds(2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates receive-capable MsQuic sessions on Unity-compatible managed runtimes.
|
||||
/// Commands and receipts remain on their typed control plane.
|
||||
/// </summary>
|
||||
public sealed class CultMeshNativeQuicRealtimeTransportConnector : ICultMeshRealtimeTransportConnector
|
||||
{
|
||||
public const string Scheme = "cultmesh-state+quic";
|
||||
private readonly CultMeshNativeQuicRealtimeConnectorOptions _options;
|
||||
|
||||
public CultMeshNativeQuicRealtimeTransportConnector(
|
||||
CultMeshNativeQuicRealtimeConnectorOptions? options = null)
|
||||
{
|
||||
_options = options ?? new CultMeshNativeQuicRealtimeConnectorOptions();
|
||||
if (_options.HandshakeTimeout <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(options), "QUIC handshake timeout must be positive.");
|
||||
if (_options.PollInterval <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(options), "QUIC poll interval must be positive.");
|
||||
}
|
||||
|
||||
public string ConnectorId => "msquic-native-realtime";
|
||||
public int Priority => 0;
|
||||
|
||||
public bool CanConnect(CultMeshTransportCandidate candidate) =>
|
||||
candidate != null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
|
||||
TryParseEndpoint(candidate.Endpoint, out _, out _, out _);
|
||||
|
||||
public async Task<ICultMeshRealtimeTransport> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshEndpointId endpointId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
|
||||
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
|
||||
if (!TryParseEndpoint(candidate.Endpoint, out var host, out var port, out var pin))
|
||||
throw new NotSupportedException($"Native QUIC connector does not support '{candidate.Endpoint}'.");
|
||||
|
||||
IntPtr handle;
|
||||
int opened;
|
||||
try
|
||||
{
|
||||
opened = NativeMethods.Open(host, checked((ushort)port), pin, out handle);
|
||||
}
|
||||
catch (DllNotFoundException error)
|
||||
{
|
||||
throw new PlatformNotSupportedException(
|
||||
"CultMesh native QUIC requires gamecult_mesh_quic_native and msquic beside the managed runtime.",
|
||||
error);
|
||||
}
|
||||
catch (EntryPointNotFoundException error)
|
||||
{
|
||||
throw new PlatformNotSupportedException("The installed CultMesh native QUIC bridge is incompatible.", error);
|
||||
}
|
||||
if (opened != 0 || handle == IntPtr.Zero)
|
||||
throw new IOException($"CultMesh native QUIC initialization failed with status 0x{opened:X8}.");
|
||||
|
||||
var transport = new CultMeshNativeQuicRealtimeTransport(
|
||||
candidate.Endpoint,
|
||||
handle,
|
||||
_options.PollInterval);
|
||||
try
|
||||
{
|
||||
await transport.WaitUntilConnectedAsync(_options.HandshakeTimeout, cancellationToken).ConfigureAwait(false);
|
||||
return transport;
|
||||
}
|
||||
catch
|
||||
{
|
||||
transport.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryParseEndpoint(
|
||||
string? endpoint,
|
||||
out string host,
|
||||
out int port,
|
||||
out string certificatePin)
|
||||
{
|
||||
host = string.Empty;
|
||||
port = 0;
|
||||
certificatePin = string.Empty;
|
||||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
|
||||
!string.Equals(uri.Scheme, Scheme, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.IsNullOrWhiteSpace(uri.Host) || uri.Port <= 0)
|
||||
return false;
|
||||
var pin = ParseQueryValue(uri.Query, "cert-sha256");
|
||||
if (pin == null || pin.Length != 64) return false;
|
||||
for (var index = 0; index < pin.Length; index++)
|
||||
if (!Uri.IsHexDigit(pin[index])) return false;
|
||||
host = uri.Host;
|
||||
port = uri.Port;
|
||||
certificatePin = pin.ToUpperInvariant();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string? ParseQueryValue(string query, string key)
|
||||
{
|
||||
foreach (var component in query.TrimStart('?').Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var separator = component.IndexOf('=');
|
||||
var candidateKey = separator < 0 ? component : component.Substring(0, separator);
|
||||
if (!string.Equals(Uri.UnescapeDataString(candidateKey), key, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
return separator < 0 ? string.Empty : Uri.UnescapeDataString(component.Substring(separator + 1));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class CultMeshNativeQuicRealtimeTransport : ICultMeshRealtimeTransport
|
||||
{
|
||||
private readonly object _gate = new object();
|
||||
private readonly TimeSpan _pollInterval;
|
||||
private IntPtr _handle;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshNativeQuicRealtimeTransport(string endpoint, IntPtr handle, TimeSpan pollInterval)
|
||||
{
|
||||
Endpoint = endpoint;
|
||||
_handle = handle;
|
||||
_pollInterval = pollInterval;
|
||||
}
|
||||
|
||||
public string TransportId => "msquic-native-realtime";
|
||||
public string Endpoint { get; }
|
||||
|
||||
public Task SendAsync(CultMeshRealtimeFrame frame, CancellationToken cancellationToken = default) =>
|
||||
Task.FromException(new NotSupportedException(
|
||||
"The Unity-compatible native QUIC connector currently owns provider-to-client state only."));
|
||||
|
||||
public async Task<CultMeshRealtimeFrame> ReceiveAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
byte[]? bytes = null;
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var state = NativeMethods.State(_handle);
|
||||
if (state == 2) throw new IOException(ReadNativeError(_handle));
|
||||
var first = NativeMethods.Poll(_handle, IntPtr.Zero, 0, out var required);
|
||||
if (first < 0) throw new IOException(ReadNativeError(_handle));
|
||||
if (first == 2 && required > 0)
|
||||
{
|
||||
bytes = new byte[required];
|
||||
var pinned = GCHandle.Alloc(bytes, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
var second = NativeMethods.Poll(
|
||||
_handle,
|
||||
pinned.AddrOfPinnedObject(),
|
||||
bytes.Length,
|
||||
out var received);
|
||||
if (second != 1 || received != bytes.Length)
|
||||
throw new IOException("CultMesh native QUIC frame changed while it was acquired.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
pinned.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (bytes != null) return CultMeshRealtimeWireProtocol.DecodeFrame(bytes);
|
||||
await Task.Delay(_pollInterval, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task WaitUntilConnectedAsync(TimeSpan timeout, CancellationToken cancellationToken)
|
||||
{
|
||||
var deadline = DateTimeOffset.UtcNow + timeout;
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var state = NativeMethods.State(_handle);
|
||||
if (state == 1) return;
|
||||
if (state == 2) throw new IOException(ReadNativeError(_handle));
|
||||
}
|
||||
if (DateTimeOffset.UtcNow >= deadline)
|
||||
throw new TimeoutException($"CultMesh native QUIC handshake with '{Endpoint}' timed out.");
|
||||
await Task.Delay(_pollInterval, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
if (_handle != IntPtr.Zero) NativeMethods.Close(_handle);
|
||||
_handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed || _handle == IntPtr.Zero)
|
||||
throw new ObjectDisposedException(nameof(CultMeshNativeQuicRealtimeTransport));
|
||||
}
|
||||
|
||||
private static string ReadNativeError(IntPtr handle)
|
||||
{
|
||||
var bytes = new byte[1024];
|
||||
var pinned = GCHandle.Alloc(bytes, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
var count = NativeMethods.Error(handle, pinned.AddrOfPinnedObject(), bytes.Length);
|
||||
return count > 0
|
||||
? Encoding.UTF8.GetString(bytes, 0, count)
|
||||
: "CultMesh native QUIC transport failed.";
|
||||
}
|
||||
finally
|
||||
{
|
||||
pinned.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class NativeMethods
|
||||
{
|
||||
private const string Library = "gamecult_mesh_quic_native";
|
||||
|
||||
[DllImport(Library, EntryPoint = "cultmesh_quic_open", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
|
||||
internal static extern int Open(string host, ushort port, string certificateSha256, out IntPtr client);
|
||||
|
||||
[DllImport(Library, EntryPoint = "cultmesh_quic_state", CallingConvention = CallingConvention.Cdecl)]
|
||||
internal static extern int State(IntPtr client);
|
||||
|
||||
[DllImport(Library, EntryPoint = "cultmesh_quic_poll", CallingConvention = CallingConvention.Cdecl)]
|
||||
internal static extern int Poll(IntPtr client, IntPtr destination, int destinationLength, out int requiredLength);
|
||||
|
||||
[DllImport(Library, EntryPoint = "cultmesh_quic_error", CallingConvention = CallingConvention.Cdecl)]
|
||||
internal static extern int Error(IntPtr client, IntPtr destination, int destinationLength);
|
||||
|
||||
[DllImport(Library, EntryPoint = "cultmesh_quic_close", CallingConvention = CallingConvention.Cdecl)]
|
||||
internal static extern void Close(IntPtr client);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<AssemblyName>GameCult.Mesh.Quic.Native</AssemblyName>
|
||||
<RootNamespace>GameCult.Mesh.Quic.Native</RootNamespace>
|
||||
<Description>Native MsQuic CultMesh realtime connector for Unity and other netstandard runtimes.</Description>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\GameCult.Mesh\GameCult.Mesh.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
656
src/GameCult.Mesh.Quic/CultMeshQuicRealtimeTransport.cs
Normal file
656
src/GameCult.Mesh.Quic/CultMeshQuicRealtimeTransport.cs
Normal file
|
|
@ -0,0 +1,656 @@
|
|||
using System.Buffers.Binary;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Net.Quic;
|
||||
using System.Net.Security;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading.Channels;
|
||||
|
||||
namespace GameCult.Mesh.Quic;
|
||||
|
||||
/// <summary>Configures identity-bound CultMesh QUIC client connections.</summary>
|
||||
public sealed class CultMeshQuicRealtimeConnectorOptions
|
||||
{
|
||||
/// <summary>Application protocol negotiated during the TLS handshake.</summary>
|
||||
public SslApplicationProtocol ApplicationProtocol { get; set; } = CultMeshQuicRealtimeProtocol.ApplicationProtocol;
|
||||
|
||||
/// <summary>Maximum time permitted for connection establishment.</summary>
|
||||
public TimeSpan HandshakeTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>
|
||||
/// Optional provider-aware certificate validator. Standard TLS validation is used when omitted.
|
||||
/// </summary>
|
||||
public Func<CultMeshEndpointId, X509Certificate2?, X509Chain?, SslPolicyErrors, bool>?
|
||||
ValidateProviderCertificate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Creates MsQuic-backed realtime state connections for .NET runtimes.</summary>
|
||||
public sealed class CultMeshQuicRealtimeTransportConnector : ICultMeshRealtimeTransportConnector
|
||||
{
|
||||
/// <summary>Discovery scheme owned by this connector.</summary>
|
||||
public const string Scheme = "cultmesh-state+quic";
|
||||
|
||||
private readonly CultMeshQuicRealtimeConnectorOptions _options;
|
||||
|
||||
/// <summary>Creates a QUIC connector.</summary>
|
||||
public CultMeshQuicRealtimeTransportConnector(CultMeshQuicRealtimeConnectorOptions? options = null)
|
||||
{
|
||||
_options = options ?? new CultMeshQuicRealtimeConnectorOptions();
|
||||
if (_options.HandshakeTimeout <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(options), "QUIC handshake timeout must be positive.");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ConnectorId => "msquic-realtime";
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Priority => 0;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanConnect(CultMeshTransportCandidate candidate) =>
|
||||
candidate != null && TryParseEndpoint(candidate.Endpoint, out _, out _);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ICultMeshRealtimeTransport> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshEndpointId endpointId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
|
||||
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
|
||||
if (!QuicConnection.IsSupported)
|
||||
throw new PlatformNotSupportedException("QUIC is unavailable. Install a supported MsQuic runtime.");
|
||||
if (!TryParseEndpoint(candidate.Endpoint, out var host, out var port))
|
||||
throw new NotSupportedException($"QUIC realtime connector does not support '{candidate.Endpoint}'.");
|
||||
|
||||
var validator = _options.ValidateProviderCertificate;
|
||||
EndPoint remoteEndPoint = IPAddress.TryParse(host, out var address)
|
||||
? new IPEndPoint(address, port)
|
||||
: new DnsEndPoint(host, port);
|
||||
var connection = await QuicConnection.ConnectAsync(new QuicClientConnectionOptions
|
||||
{
|
||||
RemoteEndPoint = remoteEndPoint,
|
||||
DefaultCloseErrorCode = CultMeshQuicRealtimeProtocol.ConnectionCloseCode,
|
||||
DefaultStreamErrorCode = CultMeshQuicRealtimeProtocol.StreamAbortCode,
|
||||
MaxInboundUnidirectionalStreams = 1024,
|
||||
HandshakeTimeout = _options.HandshakeTimeout,
|
||||
ClientAuthenticationOptions = new SslClientAuthenticationOptions
|
||||
{
|
||||
ApplicationProtocols = new List<SslApplicationProtocol> { _options.ApplicationProtocol },
|
||||
EnabledSslProtocols = SslProtocols.Tls13,
|
||||
RemoteCertificateValidationCallback = (_, certificate, chain, errors) =>
|
||||
{
|
||||
var providerCertificate = certificate as X509Certificate2 ??
|
||||
(certificate == null ? null : new X509Certificate2(certificate));
|
||||
return validator?.Invoke(endpointId, providerCertificate, chain, errors) ??
|
||||
errors == SslPolicyErrors.None ||
|
||||
MatchesAdvertisedCertificatePin(candidate.Endpoint, providerCertificate);
|
||||
}
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return new CultMeshQuicRealtimeTransport(candidate.Endpoint, connection);
|
||||
}
|
||||
|
||||
private static bool TryParseEndpoint(string? endpoint, out string host, out int port)
|
||||
{
|
||||
host = string.Empty;
|
||||
port = 0;
|
||||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
|
||||
!string.Equals(uri.Scheme, Scheme, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.IsNullOrWhiteSpace(uri.Host) || uri.Port <= 0)
|
||||
return false;
|
||||
host = uri.Host;
|
||||
port = uri.Port;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool MatchesAdvertisedCertificatePin(string endpoint, X509Certificate2? certificate)
|
||||
{
|
||||
if (certificate == null || !Uri.TryCreate(endpoint, UriKind.Absolute, out var uri))
|
||||
return false;
|
||||
var advertised = ParseQueryValue(uri.Query, "cert-sha256");
|
||||
if (string.IsNullOrWhiteSpace(advertised)) return false;
|
||||
var actual = Convert.ToHexString(SHA256.HashData(certificate.RawData));
|
||||
return string.Equals(advertised, actual, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string? ParseQueryValue(string query, string key)
|
||||
{
|
||||
foreach (var component in query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var separator = component.IndexOf('=');
|
||||
var candidateKey = separator < 0 ? component : component[..separator];
|
||||
if (!string.Equals(Uri.UnescapeDataString(candidateKey), key, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
return separator < 0 ? string.Empty : Uri.UnescapeDataString(component[(separator + 1)..]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Configures an authenticated CultMesh QUIC realtime listener.</summary>
|
||||
public sealed class CultMeshQuicRealtimeServerOptions
|
||||
{
|
||||
/// <summary>Local endpoint to bind.</summary>
|
||||
public IPEndPoint ListenEndPoint { get; set; } = new(IPAddress.Loopback, 0);
|
||||
|
||||
/// <summary>Server certificate used by QUIC TLS 1.3.</summary>
|
||||
public X509Certificate2 ServerCertificate { get; set; } = null!;
|
||||
|
||||
/// <summary>Application protocol negotiated during the TLS handshake.</summary>
|
||||
public SslApplicationProtocol ApplicationProtocol { get; set; } = CultMeshQuicRealtimeProtocol.ApplicationProtocol;
|
||||
|
||||
/// <summary>Maximum time permitted for connection establishment.</summary>
|
||||
public TimeSpan HandshakeTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Accepts .NET QUIC realtime sessions. It owns physical connections only; provider
|
||||
/// authorization and the meaning of frames remain outside this adapter.
|
||||
/// </summary>
|
||||
public sealed class CultMeshQuicRealtimeServer : IAsyncDisposable
|
||||
{
|
||||
private readonly QuicListener _listener;
|
||||
private readonly CancellationTokenSource _shutdown = new();
|
||||
private readonly ConcurrentDictionary<CultMeshQuicRealtimeTransport, byte> _clients = new();
|
||||
private readonly CultMeshRealtimeInbox _received = new();
|
||||
private readonly TaskCompletionSource<Exception> _backgroundFailure = new(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly Task _acceptLoop;
|
||||
private bool _disposed;
|
||||
|
||||
private CultMeshQuicRealtimeServer(QuicListener listener)
|
||||
{
|
||||
_listener = listener;
|
||||
_acceptLoop = AcceptLoopAsync(_shutdown.Token);
|
||||
}
|
||||
|
||||
/// <summary>Bound listener endpoint.</summary>
|
||||
public IPEndPoint LocalEndPoint => (IPEndPoint)_listener.LocalEndPoint;
|
||||
|
||||
/// <summary>Number of active physical client connections.</summary>
|
||||
public int ConnectionCount => _clients.Count;
|
||||
|
||||
/// <summary>Completes if the listener's background accept loop fails.</summary>
|
||||
public Task<Exception> BackgroundFailure => _backgroundFailure.Task;
|
||||
|
||||
/// <summary>Creates and starts an authenticated QUIC listener.</summary>
|
||||
public static async Task<CultMeshQuicRealtimeServer> ListenAsync(
|
||||
CultMeshQuicRealtimeServerOptions options,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
if (options.ServerCertificate == null)
|
||||
throw new ArgumentException("A QUIC server certificate is required.", nameof(options));
|
||||
if (options.HandshakeTimeout <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(options), "QUIC handshake timeout must be positive.");
|
||||
if (!QuicListener.IsSupported)
|
||||
throw new PlatformNotSupportedException("QUIC is unavailable. Install a supported MsQuic runtime.");
|
||||
|
||||
var listener = await QuicListener.ListenAsync(new QuicListenerOptions
|
||||
{
|
||||
ListenEndPoint = options.ListenEndPoint,
|
||||
ApplicationProtocols = new List<SslApplicationProtocol> { options.ApplicationProtocol },
|
||||
ConnectionOptionsCallback = (_, _, _) => ValueTask.FromResult(new QuicServerConnectionOptions
|
||||
{
|
||||
DefaultCloseErrorCode = CultMeshQuicRealtimeProtocol.ConnectionCloseCode,
|
||||
DefaultStreamErrorCode = CultMeshQuicRealtimeProtocol.StreamAbortCode,
|
||||
MaxInboundUnidirectionalStreams = 1024,
|
||||
HandshakeTimeout = options.HandshakeTimeout,
|
||||
ServerAuthenticationOptions = new SslServerAuthenticationOptions
|
||||
{
|
||||
ApplicationProtocols = new List<SslApplicationProtocol> { options.ApplicationProtocol },
|
||||
EnabledSslProtocols = SslProtocols.Tls13,
|
||||
ServerCertificate = options.ServerCertificate
|
||||
}
|
||||
})
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return new CultMeshQuicRealtimeServer(listener);
|
||||
}
|
||||
|
||||
/// <summary>Broadcasts one state frame to the currently connected clients.</summary>
|
||||
public async Task BroadcastAsync(
|
||||
CultMeshRealtimeFrame frame,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (frame == null) throw new ArgumentNullException(nameof(frame));
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (frame.Delivery == CultMeshRealtimeDelivery.LatestOnly)
|
||||
{
|
||||
foreach (var client in _clients.Keys)
|
||||
{
|
||||
if (client.TryPublishLatest(frame)) continue;
|
||||
if (_clients.TryRemove(client, out _)) client.Dispose();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var sends = _clients.Keys.Select(client => SendToConnectedClientAsync(client, frame, cancellationToken)).ToArray();
|
||||
if (sends.Length > 0) await Task.WhenAll(sends).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task SendToConnectedClientAsync(
|
||||
CultMeshQuicRealtimeTransport client,
|
||||
CultMeshRealtimeFrame frame,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await client.SendAsync(frame, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (_clients.TryRemove(client, out _))
|
||||
client.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Receives the next client-originated state frame.</summary>
|
||||
public Task<CultMeshRealtimeFrame> ReceiveAsync(CancellationToken cancellationToken = default) =>
|
||||
_received.ReceiveAsync(cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_shutdown.Cancel();
|
||||
await _listener.DisposeAsync().ConfigureAwait(false);
|
||||
foreach (var client in _clients.Keys) client.Dispose();
|
||||
_clients.Clear();
|
||||
_received.Complete();
|
||||
try { await _acceptLoop.ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) { }
|
||||
_shutdown.Dispose();
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var connection = await _listener.AcceptConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
var transport = new CultMeshQuicRealtimeTransport(
|
||||
connection.RemoteEndPoint?.ToString() ?? "quic-peer",
|
||||
connection,
|
||||
frame => _received.Publish(frame));
|
||||
_clients.TryAdd(transport, 0);
|
||||
_ = transport.Completion.ContinueWith(
|
||||
completed =>
|
||||
{
|
||||
_clients.TryRemove(transport, out _);
|
||||
transport.Dispose();
|
||||
},
|
||||
CancellationToken.None,
|
||||
TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (ObjectDisposedException) when (_disposed)
|
||||
{
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
_backgroundFailure.TrySetResult(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class CultMeshQuicRealtimeTransport : ICultMeshRealtimeTransport
|
||||
{
|
||||
private readonly QuicConnection _connection;
|
||||
private readonly CancellationTokenSource _shutdown = new();
|
||||
private readonly CultMeshRealtimeInbox _received = new();
|
||||
private readonly ConcurrentDictionary<string, CultMeshGeneration> _latestGenerations = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<int, Task> _streamReaders = new();
|
||||
private readonly SemaphoreSlim _reliableSendGate = new(1, 1);
|
||||
private readonly CultMeshRealtimeInbox _outbound = new();
|
||||
private readonly Action<CultMeshRealtimeFrame>? _observer;
|
||||
private readonly Task _acceptLoop;
|
||||
private readonly Task _outboundLoop;
|
||||
private readonly Task _completion;
|
||||
private QuicStream? _reliableOutbound;
|
||||
private int _nextReaderId;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshQuicRealtimeTransport(
|
||||
string endpoint,
|
||||
QuicConnection connection,
|
||||
Action<CultMeshRealtimeFrame>? observer = null)
|
||||
{
|
||||
Endpoint = endpoint;
|
||||
_connection = connection;
|
||||
_observer = observer;
|
||||
_acceptLoop = AcceptStreamsAsync(_shutdown.Token);
|
||||
_outboundLoop = SendPublishedFramesAsync(_shutdown.Token);
|
||||
_completion = Task.WhenAll(_acceptLoop, _outboundLoop);
|
||||
}
|
||||
|
||||
public string TransportId => "msquic-realtime";
|
||||
public string Endpoint { get; }
|
||||
public Task Completion => _completion;
|
||||
|
||||
internal bool TryPublishLatest(CultMeshRealtimeFrame frame)
|
||||
{
|
||||
if (_disposed || frame.Delivery != CultMeshRealtimeDelivery.LatestOnly) return false;
|
||||
return _outbound.Publish(frame);
|
||||
}
|
||||
|
||||
public async Task SendAsync(CultMeshRealtimeFrame frame, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshQuicRealtimeTransport));
|
||||
if (frame == null) throw new ArgumentNullException(nameof(frame));
|
||||
if (frame.Delivery == CultMeshRealtimeDelivery.Unreliable)
|
||||
throw new NotSupportedException(
|
||||
"System.Net.Quic exposes streams but not QUIC datagrams; unreliable delivery requires a native MsQuic connector.");
|
||||
|
||||
var payload = CultMeshQuicRealtimeProtocol.EncodeFrame(frame);
|
||||
if (frame.Delivery == CultMeshRealtimeDelivery.ReliableOrdered)
|
||||
{
|
||||
await _reliableSendGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
_reliableOutbound ??= await OpenStreamAsync(
|
||||
CultMeshQuicRealtimeProtocol.ReliableStream,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
await CultMeshQuicRealtimeProtocol.WriteFramedAsync(
|
||||
_reliableOutbound,
|
||||
payload,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_reliableSendGate.Release();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await using var stream = await OpenStreamAsync(
|
||||
CultMeshQuicRealtimeProtocol.LatestOnlyStream,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
await CultMeshQuicRealtimeProtocol.WriteFramedAsync(stream, payload, cancellationToken).ConfigureAwait(false);
|
||||
stream.CompleteWrites();
|
||||
}
|
||||
|
||||
public Task<CultMeshRealtimeFrame> ReceiveAsync(CancellationToken cancellationToken = default) =>
|
||||
_received.ReceiveAsync(cancellationToken);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_outbound.Complete();
|
||||
_shutdown.Cancel();
|
||||
_reliableOutbound?.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
_connection.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
_received.Complete();
|
||||
_reliableSendGate.Dispose();
|
||||
_shutdown.Dispose();
|
||||
}
|
||||
|
||||
private async Task SendPublishedFramesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var frame = await _outbound.ReceiveAsync(cancellationToken).ConfigureAwait(false);
|
||||
await SendAsync(frame, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch
|
||||
{
|
||||
_shutdown.Cancel();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<QuicStream> OpenStreamAsync(byte kind, CancellationToken cancellationToken)
|
||||
{
|
||||
var stream = await _connection.OpenOutboundStreamAsync(
|
||||
QuicStreamType.Unidirectional,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
await stream.WriteAsync(new[] { kind }, cancellationToken).ConfigureAwait(false);
|
||||
return stream;
|
||||
}
|
||||
|
||||
private async Task AcceptStreamsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var stream = await _connection.AcceptInboundStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
var readerId = Interlocked.Increment(ref _nextReaderId);
|
||||
var reader = ReadStreamOwnedAsync(readerId, stream, cancellationToken);
|
||||
_streamReaders.TryAdd(readerId, reader);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (QuicException) when (_disposed)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(_streamReaders.Values).ConfigureAwait(false);
|
||||
_received.Complete();
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
_received.Complete(error);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReadStreamOwnedAsync(
|
||||
int readerId,
|
||||
QuicStream stream,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ReadStreamAsync(stream, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception error) when (!_disposed && error is not OperationCanceledException)
|
||||
{
|
||||
_received.Complete(error);
|
||||
_shutdown.Cancel();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_streamReaders.TryRemove(readerId, out _);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReadStreamAsync(QuicStream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
await using (stream.ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
var kind = await CultMeshQuicRealtimeProtocol.ReadByteAsync(stream, cancellationToken).ConfigureAwait(false);
|
||||
if (kind != CultMeshQuicRealtimeProtocol.ReliableStream &&
|
||||
kind != CultMeshQuicRealtimeProtocol.LatestOnlyStream)
|
||||
throw new InvalidDataException($"Unknown CultMesh QUIC stream kind {kind}.");
|
||||
|
||||
do
|
||||
{
|
||||
var payload = await CultMeshQuicRealtimeProtocol.ReadFramedAsync(stream, cancellationToken).ConfigureAwait(false);
|
||||
if (payload == null) break;
|
||||
var frame = CultMeshQuicRealtimeProtocol.DecodeFrame(payload);
|
||||
if (kind == CultMeshQuicRealtimeProtocol.ReliableStream &&
|
||||
frame.Delivery != CultMeshRealtimeDelivery.ReliableOrdered)
|
||||
throw new InvalidDataException("Reliable QUIC stream carried incompatible delivery semantics.");
|
||||
if (kind == CultMeshQuicRealtimeProtocol.LatestOnlyStream &&
|
||||
frame.Delivery != CultMeshRealtimeDelivery.LatestOnly)
|
||||
throw new InvalidDataException("Latest-only QUIC stream carried incompatible delivery semantics.");
|
||||
PublishReceived(frame);
|
||||
}
|
||||
while (kind == CultMeshQuicRealtimeProtocol.ReliableStream);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (QuicException) when (_disposed)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void PublishReceived(CultMeshRealtimeFrame frame)
|
||||
{
|
||||
if (frame.Delivery == CultMeshRealtimeDelivery.LatestOnly)
|
||||
{
|
||||
var key = frame.ChannelId + "\u001f" + frame.BodyId;
|
||||
var generation = new CultMeshGeneration(frame.ProducerEpoch, frame.Sequence);
|
||||
while (true)
|
||||
{
|
||||
if (_latestGenerations.TryGetValue(key, out var current))
|
||||
{
|
||||
if (generation.CompareTo(current) <= 0) return;
|
||||
if (!_latestGenerations.TryUpdate(key, generation, current)) continue;
|
||||
}
|
||||
else if (!_latestGenerations.TryAdd(key, generation))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
_observer?.Invoke(frame);
|
||||
_received.Publish(frame);
|
||||
}
|
||||
|
||||
private readonly record struct CultMeshGeneration(long ProducerEpoch, long Sequence) : IComparable<CultMeshGeneration>
|
||||
{
|
||||
public int CompareTo(CultMeshGeneration other)
|
||||
{
|
||||
var epochOrder = ProducerEpoch.CompareTo(other.ProducerEpoch);
|
||||
return epochOrder != 0 ? epochOrder : Sequence.CompareTo(other.Sequence);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class CultMeshRealtimeInbox
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly Channel<InboxToken> _ready = Channel.CreateUnbounded<InboxToken>(
|
||||
new UnboundedChannelOptions { SingleReader = false, SingleWriter = false });
|
||||
private readonly Dictionary<string, CultMeshRealtimeFrame> _latest = new(StringComparer.Ordinal);
|
||||
private bool _completed;
|
||||
|
||||
public bool Publish(CultMeshRealtimeFrame frame)
|
||||
{
|
||||
if (frame.Delivery != CultMeshRealtimeDelivery.LatestOnly)
|
||||
{
|
||||
return _ready.Writer.TryWrite(new InboxToken(frame, null));
|
||||
}
|
||||
|
||||
var key = frame.ChannelId + "\u001f" + frame.BodyId;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_completed) return false;
|
||||
var alreadyPending = _latest.ContainsKey(key);
|
||||
_latest[key] = frame;
|
||||
return alreadyPending || _ready.Writer.TryWrite(new InboxToken(null, key));
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<CultMeshRealtimeFrame> ReceiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var token = await _ready.Reader.ReadAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (token.Frame != null) return token.Frame;
|
||||
lock (_gate)
|
||||
{
|
||||
if (token.LatestKey != null && _latest.Remove(token.LatestKey, out var latest))
|
||||
return latest;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Complete(Exception? error = null)
|
||||
{
|
||||
lock (_gate) _completed = true;
|
||||
_ready.Writer.TryComplete(error);
|
||||
}
|
||||
|
||||
private sealed record InboxToken(CultMeshRealtimeFrame? Frame, string? LatestKey);
|
||||
}
|
||||
|
||||
internal static class CultMeshQuicRealtimeProtocol
|
||||
{
|
||||
public static readonly SslApplicationProtocol ApplicationProtocol =
|
||||
new(CultMeshRealtimeWireProtocol.ApplicationProtocolName);
|
||||
public const long ConnectionCloseCode = CultMeshRealtimeWireProtocol.ConnectionCloseCode;
|
||||
public const long StreamAbortCode = CultMeshRealtimeWireProtocol.StreamAbortCode;
|
||||
public const byte ReliableStream = CultMeshRealtimeWireProtocol.ReliableStream;
|
||||
public const byte LatestOnlyStream = CultMeshRealtimeWireProtocol.LatestOnlyStream;
|
||||
|
||||
public static byte[] EncodeFrame(CultMeshRealtimeFrame frame) =>
|
||||
CultMeshRealtimeWireProtocol.EncodeFrame(frame);
|
||||
|
||||
public static CultMeshRealtimeFrame DecodeFrame(byte[] bytes) =>
|
||||
CultMeshRealtimeWireProtocol.DecodeFrame(bytes);
|
||||
|
||||
public static async Task WriteFramedAsync(Stream stream, byte[] payload, CancellationToken cancellationToken)
|
||||
{
|
||||
var header = new byte[4];
|
||||
BinaryPrimitives.WriteInt32LittleEndian(header, payload.Length);
|
||||
await stream.WriteAsync(header, cancellationToken).ConfigureAwait(false);
|
||||
await stream.WriteAsync(payload, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public static async Task<byte[]?> ReadFramedAsync(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var header = new byte[4];
|
||||
var first = await stream.ReadAsync(header.AsMemory(0, 1), cancellationToken).ConfigureAwait(false);
|
||||
if (first == 0) return null;
|
||||
await ReadExactlyAsync(stream, header.AsMemory(1), cancellationToken).ConfigureAwait(false);
|
||||
var length = BinaryPrimitives.ReadInt32LittleEndian(header);
|
||||
if (length <= 0 || length > CultMeshRealtimeWireProtocol.MaximumEncodedFrameBytes)
|
||||
throw new InvalidDataException("Realtime QUIC frame length is invalid.");
|
||||
var payload = new byte[length];
|
||||
await ReadExactlyAsync(stream, payload, cancellationToken).ConfigureAwait(false);
|
||||
return payload;
|
||||
}
|
||||
|
||||
public static async Task<byte> ReadByteAsync(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var value = new byte[1];
|
||||
await ReadExactlyAsync(stream, value, cancellationToken).ConfigureAwait(false);
|
||||
return value[0];
|
||||
}
|
||||
|
||||
private static async Task ReadExactlyAsync(Stream stream, Memory<byte> destination, CancellationToken cancellationToken)
|
||||
{
|
||||
var offset = 0;
|
||||
while (offset < destination.Length)
|
||||
{
|
||||
var read = await stream.ReadAsync(destination[offset..], cancellationToken).ConfigureAwait(false);
|
||||
if (read == 0) throw new EndOfStreamException("QUIC stream ended before its frame was complete.");
|
||||
offset += read;
|
||||
}
|
||||
}
|
||||
}
|
||||
16
src/GameCult.Mesh.Quic/GameCult.Mesh.Quic.csproj
Normal file
16
src/GameCult.Mesh.Quic/GameCult.Mesh.Quic.csproj
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Description>MsQuic-backed realtime state transport for CultMesh</Description>
|
||||
<PackageId>GameCult.Mesh.Quic</PackageId>
|
||||
<PackageTags>game;distributed;realtime;mesh;quic;msquic</PackageTags>
|
||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||
<NoWarn>$(NoWarn);CA1416</NoWarn>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\GameCult.Mesh\GameCult.Mesh.csproj" />
|
||||
<None Include="README.md" Pack="true" PackagePath="\" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
76
src/GameCult.Mesh.Quic/README.md
Normal file
76
src/GameCult.Mesh.Quic/README.md
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
# GameCult.Mesh.Quic
|
||||
|
||||
`GameCult.Mesh.Quic` is the optional MsQuic-backed realtime state plane for
|
||||
CultMesh daemons and .NET tools. It implements the transport-neutral contracts
|
||||
from `GameCult.Mesh`; it does not own discovery, provider authorization, state
|
||||
meaning, commands, receipts, schemas, or immutable content.
|
||||
|
||||
The package targets .NET 10. It uses `System.Net.Quic`, which requires a
|
||||
supported MsQuic runtime and TLS 1.3. Unity runtimes do not consume this package;
|
||||
their generic CultMesh lowerer needs a native MsQuic connector implementing the
|
||||
same `ICultMeshRealtimeTransportConnector` contract.
|
||||
|
||||
## Provider
|
||||
|
||||
```csharp
|
||||
using GameCult.Mesh.Quic;
|
||||
|
||||
await using var server = await CultMeshQuicRealtimeServer.ListenAsync(
|
||||
new CultMeshQuicRealtimeServerOptions
|
||||
{
|
||||
ListenEndPoint = new IPEndPoint(IPAddress.Any, 7443),
|
||||
ServerCertificate = providerCertificate
|
||||
});
|
||||
|
||||
await server.BroadcastAsync(new CultMeshRealtimeFrame
|
||||
{
|
||||
ChannelId = "aetheria.entities",
|
||||
SchemaId = "eve.entity_soa.v1",
|
||||
BodyId = "body:aetheria:entities",
|
||||
ProducerEpoch = epoch,
|
||||
Sequence = sequence,
|
||||
Delivery = CultMeshRealtimeDelivery.LatestOnly,
|
||||
Payload = encodedSoa
|
||||
});
|
||||
```
|
||||
|
||||
Advertise the listener as `cultmesh-state+quic://host:port`. Certificate
|
||||
identity and provider identity must be bound by the application trust policy;
|
||||
accepting every certificate is appropriate only in isolated tests.
|
||||
For directly trusted discovery records, a provider may append its uppercase
|
||||
SHA-256 certificate fingerprint as `?cert-sha256=...`. The default connector
|
||||
accepts a self-signed certificate only when its raw certificate bytes match that
|
||||
advertised pin. A caller-supplied validator remains authoritative when present.
|
||||
|
||||
## Consumer
|
||||
|
||||
```csharp
|
||||
var connector = new CultMeshQuicRealtimeTransportConnector(
|
||||
new CultMeshQuicRealtimeConnectorOptions
|
||||
{
|
||||
ValidateProviderCertificate = ValidateAdvertisedProvider
|
||||
});
|
||||
|
||||
using var sessions = new CultMeshSessionManager(
|
||||
discovery,
|
||||
schemaConnectors,
|
||||
contentConnectors,
|
||||
new ICultMeshRealtimeTransportConnector[] { connector });
|
||||
|
||||
var session = await sessions.ConnectRealtimeAsync(providerId);
|
||||
var frame = await session.ReceiveAsync(cancellationToken);
|
||||
```
|
||||
|
||||
## Delivery modes
|
||||
|
||||
- `ReliableOrdered` uses one ordered QUIC stream.
|
||||
- `LatestOnly` uses independent streams and keeps at most one pending frame per
|
||||
channel and body. A newer `(producer epoch, sequence)` generation replaces
|
||||
queued state.
|
||||
- `Unreliable` fails closed in this adapter because `System.Net.Quic` does not
|
||||
expose QUIC datagrams. Use a native MsQuic connector when datagram semantics
|
||||
are required.
|
||||
|
||||
Schemas, commands, receipts, manifests, and immutable content remain on their
|
||||
TCP planes. Same-machine SoA should negotiate mapped/shared memory instead of
|
||||
crossing QUIC.
|
||||
|
|
@ -5,6 +5,7 @@ using System.Linq;
|
|||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
|
|
@ -2852,6 +2853,128 @@ namespace GameCult.Mesh
|
|||
return new CultMeshRudpEndpoint(host, uri.Port, $"rudp://{uriHost}:{uri.Port}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens one exact hot-body subscription and advertises every body plane this runtime can
|
||||
/// actually open. The provider derives locality and publishes only the selected plane.
|
||||
/// </summary>
|
||||
public static Task<IReadOnlyList<object>> SubscribeHotBodyAsync(
|
||||
CultNetDatabaseSubscriptionClient subscriptions,
|
||||
IEnumerable<CultMeshBodyTransportKind> supportedBodyTransports,
|
||||
CultMeshHotBodySubscription subscription,
|
||||
CultNetDatabaseSubscriptionDeliveryMode deliveryMode = CultNetDatabaseSubscriptionDeliveryMode.Live)
|
||||
{
|
||||
if (subscriptions == null) throw new ArgumentNullException(nameof(subscriptions));
|
||||
if (supportedBodyTransports == null) throw new ArgumentNullException(nameof(supportedBodyTransports));
|
||||
if (subscription == null) throw new ArgumentNullException(nameof(subscription));
|
||||
var transports = supportedBodyTransports.Distinct().ToArray();
|
||||
if (transports.Length == 0)
|
||||
throw new ArgumentException("At least one readable body transport is required.", nameof(supportedBodyTransports));
|
||||
return subscriptions.SubscribeAsync(
|
||||
subscription.SubscriptionId,
|
||||
recordKeys: subscription.RecordKeys,
|
||||
schemaIds: subscription.SchemaIds,
|
||||
consumerRuntimeId: subscription.ConsumerRuntimeId,
|
||||
bodyIds: new[] { subscription.BodyId },
|
||||
supportedBodyTransports: transports.Select(value => value.ToString()),
|
||||
deliveryMode: deliveryMode);
|
||||
}
|
||||
|
||||
/// <summary>Opens an exact hot-body subscription using a resolver's readable planes.</summary>
|
||||
public static Task<IReadOnlyList<object>> SubscribeHotBodyAsync(
|
||||
CultNetDatabaseSubscriptionClient subscriptions,
|
||||
CultMeshBodyPublicationResolver bodyResolver,
|
||||
CultMeshHotBodySubscription subscription,
|
||||
CultNetDatabaseSubscriptionDeliveryMode deliveryMode = CultNetDatabaseSubscriptionDeliveryMode.Live)
|
||||
{
|
||||
if (bodyResolver == null) throw new ArgumentNullException(nameof(bodyResolver));
|
||||
return SubscribeHotBodyAsync(subscriptions, bodyResolver.SupportedTransports, subscription, deliveryMode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to one logical body's latest descriptor as ephemeral control state and declares
|
||||
/// demand for the body itself. Body bytes are opened separately through the fastest valid plane.
|
||||
/// </summary>
|
||||
public static async Task<CultMeshLiveBody> SubscribeLiveBodyAsync(
|
||||
CultNetDatabaseSubscriptionClient subscriptions,
|
||||
CultMeshBodyPublicationResolver bodyResolver,
|
||||
CultMeshLiveBodySubscription subscription,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (subscriptions == null) throw new ArgumentNullException(nameof(subscriptions));
|
||||
if (bodyResolver == null) throw new ArgumentNullException(nameof(bodyResolver));
|
||||
if (subscription == null) throw new ArgumentNullException(nameof(subscription));
|
||||
var transports = bodyResolver.SupportedTransports.Distinct().ToArray();
|
||||
if (transports.Length == 0)
|
||||
throw new InvalidOperationException("The body resolver has no readable transport planes.");
|
||||
|
||||
var liveBody = new CultMeshLiveBody(subscriptions, bodyResolver, subscription);
|
||||
try
|
||||
{
|
||||
var initial = await subscriptions.SubscribeAsync(
|
||||
subscription.SubscriptionId,
|
||||
recordKeys: new[] { subscription.PublicationRecordKey },
|
||||
schemaIds: new[] { CultMeshBodyPublicationSchemaVersions.Publication },
|
||||
consumerRuntimeId: subscription.ConsumerRuntimeId,
|
||||
bodyIds: new[] { subscription.BodyId },
|
||||
supportedBodyTransports: transports.Select(value => value.ToString()),
|
||||
deliveryMode: CultNetDatabaseSubscriptionDeliveryMode.Live,
|
||||
cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var publications = initial.OfType<CultMeshBodyPublicationDocument>().ToArray();
|
||||
if (publications.Length > 1)
|
||||
throw new InvalidOperationException(
|
||||
$"Live body subscription '{subscription.SubscriptionId}' expected at most one publication for " +
|
||||
$"'{subscription.BodyId}' but received {publications.Length}.");
|
||||
if (publications.Length == 1)
|
||||
liveBody.Initialize(publications[0]);
|
||||
return liveBody;
|
||||
}
|
||||
catch
|
||||
{
|
||||
liveBody.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resolves a CultMesh URI or RUDP endpoint into a concrete RUDP endpoint.</summary>
|
||||
public static CultMeshRudpEndpoint ResolveRudpEndpoint(string endpointOrUri)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(endpointOrUri))
|
||||
throw new ArgumentException("Value must be non-empty.", nameof(endpointOrUri));
|
||||
if (!Uri.TryCreate(endpointOrUri, UriKind.Absolute, out var uri))
|
||||
return ParseRudpEndpoint(NormalizeBareRudpEndpoint(endpointOrUri));
|
||||
if (string.Equals(uri.Scheme, "rudp", StringComparison.OrdinalIgnoreCase))
|
||||
return ParseRudpEndpoint(endpointOrUri);
|
||||
if (!string.Equals(uri.Scheme, "cultmesh", StringComparison.OrdinalIgnoreCase))
|
||||
throw new ArgumentException("RUDP endpoint must use the cultmesh:// or rudp:// scheme.", nameof(endpointOrUri));
|
||||
if (string.IsNullOrWhiteSpace(uri.Host))
|
||||
throw new ArgumentException("CultMesh URI must include an authority.", nameof(endpointOrUri));
|
||||
|
||||
var authorityKey = MakeCultMeshAuthorityEnvironmentKey(uri.Host);
|
||||
var endpoint = Environment.GetEnvironmentVariable($"CULTMESH_URI_{authorityKey}_RUDP") ??
|
||||
Environment.GetEnvironmentVariable($"{authorityKey}_CULTMESH_RUDP_ENDPOINT");
|
||||
if (string.IsNullOrWhiteSpace(endpoint))
|
||||
throw new InvalidOperationException(
|
||||
$"CultMesh URI '{endpointOrUri}' is unresolved. Set CULTMESH_URI_{authorityKey}_RUDP to a rudp:// endpoint.");
|
||||
return ParseRudpEndpoint(endpoint);
|
||||
}
|
||||
|
||||
private static string NormalizeBareRudpEndpoint(string endpoint)
|
||||
{
|
||||
var trimmed = endpoint.Trim();
|
||||
return trimmed.Contains("://", StringComparison.Ordinal) ? trimmed : $"rudp://{trimmed}";
|
||||
}
|
||||
|
||||
private static string MakeCultMeshAuthorityEnvironmentKey(string authority)
|
||||
{
|
||||
var chars = authority.Select(static value =>
|
||||
((value >= 'a' && value <= 'z') || (value >= 'A' && value <= 'Z') || (value >= '0' && value <= '9'))
|
||||
? char.ToUpperInvariant(value)
|
||||
: '_');
|
||||
var key = string.Concat(chars).Trim('_');
|
||||
return string.IsNullOrWhiteSpace(key) ? "ODIN" : key;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a CultNet RUDP server transport with CultMesh-branded defaults.
|
||||
/// </summary>
|
||||
|
|
@ -2914,7 +3037,7 @@ namespace GameCult.Mesh
|
|||
string endpoint,
|
||||
CultMeshRudpSocketOptions? options = null)
|
||||
{
|
||||
return CreateRudpClient(runtimeId, connectionId, ParseRudpEndpoint(endpoint), options);
|
||||
return CreateRudpClient(runtimeId, connectionId, ResolveRudpEndpoint(endpoint), options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -2939,6 +3062,7 @@ namespace GameCult.Mesh
|
|||
/// <summary>
|
||||
/// Creates a CultNet RUDP client transport from the first peer authorized for a Verse role.
|
||||
/// </summary>
|
||||
[Obsolete("Supply CultMeshAuthorityResolver and an explicit authority epoch. This compatibility path denies unverifiable leases.")]
|
||||
public static CultNetRudpSocketTransportConnection CreateRudpClientForAuthorizedPeer(
|
||||
string runtimeId,
|
||||
uint connectionId,
|
||||
|
|
@ -2952,7 +3076,27 @@ namespace GameCult.Mesh
|
|||
{
|
||||
if (peers == null) throw new ArgumentNullException(nameof(peers));
|
||||
if (leases == null) throw new ArgumentNullException(nameof(leases));
|
||||
var peer = peers.FirstAuthorized(verseId, role, leases, shardId, at);
|
||||
var resolver = CultMeshAuthorityResolver.CreateDenyByDefault(leases,
|
||||
at.HasValue ? new CultMeshFixedAuthorityClock(at.Value) : null);
|
||||
return CreateRudpClientForAuthorizedPeer(runtimeId, connectionId, peers, resolver, 0, verseId, role, shardId, null, options);
|
||||
}
|
||||
|
||||
/// <summary>Creates a RUDP client from the first contact accepted by the authority resolver.</summary>
|
||||
public static CultNetRudpSocketTransportConnection CreateRudpClientForAuthorizedPeer(
|
||||
string runtimeId,
|
||||
uint connectionId,
|
||||
CultMeshPeerCatalog peers,
|
||||
CultMeshAuthorityResolver authority,
|
||||
long authorityEpoch,
|
||||
string verseId,
|
||||
string role,
|
||||
string? shardId = null,
|
||||
string? resourceScope = null,
|
||||
CultMeshRudpSocketOptions? options = null)
|
||||
{
|
||||
if (peers == null) throw new ArgumentNullException(nameof(peers));
|
||||
if (authority == null) throw new ArgumentNullException(nameof(authority));
|
||||
var peer = peers.FirstAuthorized(verseId, role, authority, authorityEpoch, shardId, resourceScope);
|
||||
if (peer == null)
|
||||
{
|
||||
throw new InvalidOperationException($"No authorized RUDP peer for role {role} in Verse {verseId}.");
|
||||
|
|
@ -3015,6 +3159,7 @@ namespace GameCult.Mesh
|
|||
/// <summary>
|
||||
/// Creates and handshakes a CultNet RUDP client transport from the first peer authorized for a Verse role.
|
||||
/// </summary>
|
||||
[Obsolete("Supply CultMeshAuthorityResolver and an explicit authority epoch. This compatibility path denies unverifiable leases.")]
|
||||
public static CultNetRudpSocketTransportConnection ConnectRudpClientForAuthorizedPeer(
|
||||
string runtimeId,
|
||||
uint connectionId,
|
||||
|
|
@ -3028,7 +3173,27 @@ namespace GameCult.Mesh
|
|||
{
|
||||
if (peers == null) throw new ArgumentNullException(nameof(peers));
|
||||
if (leases == null) throw new ArgumentNullException(nameof(leases));
|
||||
var peer = peers.FirstAuthorized(verseId, role, leases, shardId, at);
|
||||
var resolver = CultMeshAuthorityResolver.CreateDenyByDefault(leases,
|
||||
at.HasValue ? new CultMeshFixedAuthorityClock(at.Value) : null);
|
||||
return ConnectRudpClientForAuthorizedPeer(runtimeId, connectionId, peers, resolver, 0, verseId, role, shardId, null, options);
|
||||
}
|
||||
|
||||
/// <summary>Creates and handshakes a RUDP client from the first contact accepted by the authority resolver.</summary>
|
||||
public static CultNetRudpSocketTransportConnection ConnectRudpClientForAuthorizedPeer(
|
||||
string runtimeId,
|
||||
uint connectionId,
|
||||
CultMeshPeerCatalog peers,
|
||||
CultMeshAuthorityResolver authority,
|
||||
long authorityEpoch,
|
||||
string verseId,
|
||||
string role,
|
||||
string? shardId = null,
|
||||
string? resourceScope = null,
|
||||
CultMeshRudpClientOptions? options = null)
|
||||
{
|
||||
if (peers == null) throw new ArgumentNullException(nameof(peers));
|
||||
if (authority == null) throw new ArgumentNullException(nameof(authority));
|
||||
var peer = peers.FirstAuthorized(verseId, role, authority, authorityEpoch, shardId, resourceScope);
|
||||
if (peer == null)
|
||||
{
|
||||
throw new InvalidOperationException($"No authorized RUDP peer for role {role} in Verse {verseId}.");
|
||||
|
|
@ -3037,6 +3202,14 @@ namespace GameCult.Mesh
|
|||
return ConnectRudpClientForPeer(runtimeId, connectionId, peer, options);
|
||||
}
|
||||
|
||||
private sealed class CultMeshFixedAuthorityClock : ICultMeshClock
|
||||
{
|
||||
public CultMeshFixedAuthorityClock(DateTimeOffset utcNow) => UtcNow = utcNow;
|
||||
public DateTimeOffset UtcNow { get; }
|
||||
public System.Threading.Tasks.Task DelayAsync(TimeSpan delay, System.Threading.CancellationToken cancellationToken = default) =>
|
||||
System.Threading.Tasks.Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a committer for writing quorum simulation facts to a mesh database.
|
||||
/// </summary>
|
||||
|
|
@ -3226,9 +3399,16 @@ namespace GameCult.Mesh
|
|||
private static TDocument ReadRequired<TDocument>(CultCache cache, CultRecordKey key)
|
||||
where TDocument : class
|
||||
{
|
||||
return cache.Get<TDocument>(key)
|
||||
?? throw new KeyNotFoundException(
|
||||
$"CultMesh document '{key.Value}' was not found as {typeof(TDocument).FullName}.");
|
||||
var document = cache.Get<TDocument>(key);
|
||||
if (document != null)
|
||||
return document;
|
||||
|
||||
var untyped = cache.Get(key);
|
||||
if (untyped != null && IsSameCultDocumentSchema<TDocument>(untyped.GetType()))
|
||||
return ConvertUntypedDocument<TDocument>(untyped);
|
||||
|
||||
throw new KeyNotFoundException(
|
||||
$"CultMesh document '{key.Value}' was not found as {typeof(TDocument).FullName}.");
|
||||
}
|
||||
|
||||
private static async Task<TDocument> ReadRequiredAsync<TDocument>(
|
||||
|
|
|
|||
|
|
@ -1,17 +1,15 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Grants one peer authority to perform roles for a Verse over a bounded interval.
|
||||
/// </summary>
|
||||
public sealed class CultMeshAuthorityLease
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an authority lease.
|
||||
/// </summary>
|
||||
public const string CurrentSchemaVersion = "gamecult.mesh.authority_lease.v1";
|
||||
public const string LegacySchemaVersion = "gamecult.mesh.authority_lease.v0";
|
||||
|
||||
public CultMeshAuthorityLease(
|
||||
string leaseId,
|
||||
string verseId,
|
||||
|
|
@ -21,7 +19,10 @@ namespace GameCult.Mesh
|
|||
string issuerRuntimeId,
|
||||
DateTimeOffset validFrom,
|
||||
DateTimeOffset expiresAt,
|
||||
string? signature = null)
|
||||
string? signature = null,
|
||||
long? authorityEpoch = null,
|
||||
IEnumerable<string>? resourceScopes = null,
|
||||
string? schemaVersion = null)
|
||||
{
|
||||
LeaseId = RequireNonEmpty(leaseId, nameof(leaseId));
|
||||
VerseId = RequireNonEmpty(verseId, nameof(verseId));
|
||||
|
|
@ -32,109 +33,239 @@ namespace GameCult.Mesh
|
|||
ValidFrom = validFrom;
|
||||
ExpiresAt = expiresAt;
|
||||
Signature = signature;
|
||||
if (expiresAt <= validFrom)
|
||||
{
|
||||
throw new ArgumentException("Lease expiry must be after its valid-from timestamp.", nameof(expiresAt));
|
||||
}
|
||||
AuthorityEpoch = authorityEpoch;
|
||||
ResourceScopes = Clean(resourceScopes);
|
||||
SchemaVersion = schemaVersion ?? (authorityEpoch.HasValue ? CurrentSchemaVersion : LegacySchemaVersion);
|
||||
if (expiresAt <= validFrom) throw new ArgumentException("Lease expiry must be after its valid-from timestamp.", nameof(expiresAt));
|
||||
if (authorityEpoch < 0) throw new ArgumentOutOfRangeException(nameof(authorityEpoch));
|
||||
}
|
||||
|
||||
/// <summary>Gets the stable lease id.</summary>
|
||||
public string LeaseId { get; }
|
||||
/// <summary>Gets the Verse id governed by the lease.</summary>
|
||||
public string VerseId { get; }
|
||||
/// <summary>Gets the peer id receiving authority.</summary>
|
||||
public string PeerId { get; }
|
||||
/// <summary>Gets the roles granted by this lease.</summary>
|
||||
public IReadOnlyList<string> Roles { get; }
|
||||
/// <summary>Gets shard ids covered by this lease. Empty means every shard in the Verse.</summary>
|
||||
public IReadOnlyList<string> ShardIds { get; }
|
||||
/// <summary>Gets the runtime that issued the lease.</summary>
|
||||
public string IssuerRuntimeId { get; }
|
||||
/// <summary>Gets the first timestamp when the lease is valid.</summary>
|
||||
public DateTimeOffset ValidFrom { get; }
|
||||
/// <summary>Gets the timestamp when the lease expires.</summary>
|
||||
public DateTimeOffset ExpiresAt { get; }
|
||||
/// <summary>Gets an optional signature over the lease.</summary>
|
||||
public string? Signature { get; }
|
||||
public long? AuthorityEpoch { get; }
|
||||
public IReadOnlyList<string> ResourceScopes { get; }
|
||||
public string SchemaVersion { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns whether this lease is valid at the supplied time.
|
||||
/// </summary>
|
||||
public bool IsValidAt(DateTimeOffset at)
|
||||
{
|
||||
return at >= ValidFrom && at < ExpiresAt;
|
||||
}
|
||||
public bool IsValidAt(DateTimeOffset at) => at >= ValidFrom && at < ExpiresAt;
|
||||
|
||||
/// <summary>
|
||||
/// Returns whether this lease covers a peer card, role, and shard.
|
||||
/// </summary>
|
||||
[Obsolete("Authority decisions belong to CultMeshAuthorityResolver. This method denies leases that lack v1 signed authority evidence.")]
|
||||
public bool Covers(CultMeshPeerCard peer, string role, string? shardId = null, DateTimeOffset? at = null)
|
||||
{
|
||||
if (peer == null) throw new ArgumentNullException(nameof(peer));
|
||||
if (string.IsNullOrWhiteSpace(role)) throw new ArgumentException("Value must be non-empty.", nameof(role));
|
||||
var time = at ?? DateTimeOffset.UtcNow;
|
||||
return IsValidAt(time) &&
|
||||
string.Equals(VerseId, peer.VerseId, StringComparison.Ordinal) &&
|
||||
string.Equals(PeerId, peer.PeerId, StringComparison.Ordinal) &&
|
||||
string.Equals(LeaseId, peer.AuthorityLeaseId, StringComparison.Ordinal) &&
|
||||
Roles.Contains(role, StringComparer.Ordinal) &&
|
||||
peer.Roles.Contains(role, StringComparer.Ordinal) &&
|
||||
(string.IsNullOrWhiteSpace(shardId) ||
|
||||
ShardIds.Count == 0 ||
|
||||
ShardIds.Contains(shardId!, StringComparer.Ordinal));
|
||||
var resolver = CultMeshAuthorityResolver.CreateDenyByDefault(
|
||||
new SingleLeaseSource(this),
|
||||
at.HasValue ? new FixedClock(at.Value) : CultMeshSystemClock.Instance);
|
||||
return resolver.Resolve(new CultMeshAuthorityRequest(peer, role, shardId, AuthorityEpoch ?? -1)).IsAuthorized;
|
||||
}
|
||||
|
||||
private static string[] Clean(IEnumerable<string>? values)
|
||||
private static string[] Clean(IEnumerable<string>? values) =>
|
||||
values?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray() ?? Array.Empty<string>();
|
||||
|
||||
private static string RequireNonEmpty(string value, string paramName) =>
|
||||
string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Value must be non-empty.", paramName) : value;
|
||||
|
||||
private sealed class SingleLeaseSource : ICultMeshAuthorityLeaseSource
|
||||
{
|
||||
return values?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray()
|
||||
?? Array.Empty<string>();
|
||||
private readonly CultMeshAuthorityLease _lease;
|
||||
public SingleLeaseSource(CultMeshAuthorityLease lease) => _lease = lease;
|
||||
public CultMeshAuthorityLease? Get(string leaseId) => string.Equals(leaseId, _lease.LeaseId, StringComparison.Ordinal) ? _lease : null;
|
||||
}
|
||||
|
||||
private static string RequireNonEmpty(string value, string paramName)
|
||||
private sealed class FixedClock : ICultMeshClock
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value)
|
||||
? throw new ArgumentException("Value must be non-empty.", paramName)
|
||||
: value;
|
||||
public FixedClock(DateTimeOffset now) => UtcNow = now;
|
||||
public DateTimeOffset UtcNow { get; }
|
||||
public System.Threading.Tasks.Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken = default) =>
|
||||
System.Threading.Tasks.Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Local authority lease catalog.
|
||||
/// </summary>
|
||||
public sealed class CultMeshAuthorityLeaseCatalog
|
||||
public interface ICultMeshAuthorityLeaseSource
|
||||
{
|
||||
private readonly Dictionary<string, CultMeshAuthorityLease> _leases = new(StringComparer.Ordinal);
|
||||
CultMeshAuthorityLease? Get(string leaseId);
|
||||
}
|
||||
|
||||
/// <summary>Gets all known leases.</summary>
|
||||
public IReadOnlyList<CultMeshAuthorityLease> Leases => _leases.Values.OrderBy(lease => lease.LeaseId, StringComparer.Ordinal).ToArray();
|
||||
public interface ICultMeshAuthoritySignatureVerifier
|
||||
{
|
||||
bool Verify(CultMeshAuthorityLease lease);
|
||||
}
|
||||
|
||||
/// <summary>Adds or replaces an authority lease.</summary>
|
||||
public void Upsert(CultMeshAuthorityLease lease)
|
||||
public interface ICultMeshAuthorityRevocationSource
|
||||
{
|
||||
bool IsRevoked(string leaseId, long authorityEpoch);
|
||||
}
|
||||
|
||||
public enum CultMeshAuthorityDenialReason
|
||||
{
|
||||
None,
|
||||
MissingLeaseReference,
|
||||
LeaseNotFound,
|
||||
UnsupportedLeaseVersion,
|
||||
MissingSignature,
|
||||
InvalidSignature,
|
||||
NotYetValid,
|
||||
Expired,
|
||||
Revoked,
|
||||
VerseMismatch,
|
||||
PeerMismatch,
|
||||
LeaseReferenceMismatch,
|
||||
RoleNotGranted,
|
||||
RoleNotAdvertised,
|
||||
ShardNotGranted,
|
||||
ShardNotAdvertised,
|
||||
EpochMismatch,
|
||||
ResourceScopeNotGranted
|
||||
}
|
||||
|
||||
public sealed class CultMeshAuthorityRequest
|
||||
{
|
||||
public CultMeshAuthorityRequest(CultMeshPeerCard peer, string role, string? shardId, long authorityEpoch, string? resourceScope = null)
|
||||
{
|
||||
if (lease == null) throw new ArgumentNullException(nameof(lease));
|
||||
_leases[lease.LeaseId] = lease;
|
||||
Peer = peer ?? throw new ArgumentNullException(nameof(peer));
|
||||
Role = string.IsNullOrWhiteSpace(role) ? throw new ArgumentException("Value must be non-empty.", nameof(role)) : role;
|
||||
if (authorityEpoch < 0) throw new ArgumentOutOfRangeException(nameof(authorityEpoch));
|
||||
ShardId = shardId;
|
||||
AuthorityEpoch = authorityEpoch;
|
||||
ResourceScope = resourceScope;
|
||||
}
|
||||
|
||||
/// <summary>Gets a lease by id, if known.</summary>
|
||||
public CultMeshPeerCard Peer { get; }
|
||||
public string Role { get; }
|
||||
public string? ShardId { get; }
|
||||
public long AuthorityEpoch { get; }
|
||||
public string? ResourceScope { get; }
|
||||
}
|
||||
|
||||
public sealed class CultMeshAuthorityDecision
|
||||
{
|
||||
internal CultMeshAuthorityDecision(CultMeshAuthorityRequest request, CultMeshAuthorityLease? lease, CultMeshAuthorityDenialReason reason)
|
||||
{
|
||||
Request = request;
|
||||
Lease = lease;
|
||||
DenialReason = reason;
|
||||
}
|
||||
|
||||
public CultMeshAuthorityRequest Request { get; }
|
||||
public CultMeshAuthorityLease? Lease { get; }
|
||||
public bool IsAuthorized => DenialReason == CultMeshAuthorityDenialReason.None;
|
||||
public CultMeshAuthorityDenialReason DenialReason { get; }
|
||||
public string? LeaseId => Lease?.LeaseId ?? Request.Peer.AuthorityLeaseId;
|
||||
public string? IssuerRuntimeId => Lease?.IssuerRuntimeId;
|
||||
}
|
||||
|
||||
public sealed class CultMeshAuthorityResolver
|
||||
{
|
||||
private readonly ICultMeshAuthorityLeaseSource _leases;
|
||||
private readonly ICultMeshAuthoritySignatureVerifier _signatures;
|
||||
private readonly ICultMeshAuthorityRevocationSource _revocations;
|
||||
private readonly ICultMeshClock _clock;
|
||||
private readonly ICultMeshDiagnosticSink _diagnostics;
|
||||
private long _diagnosticSequence;
|
||||
|
||||
public CultMeshAuthorityResolver(
|
||||
ICultMeshAuthorityLeaseSource leases,
|
||||
ICultMeshAuthoritySignatureVerifier signatures,
|
||||
ICultMeshAuthorityRevocationSource revocations,
|
||||
ICultMeshClock clock,
|
||||
ICultMeshDiagnosticSink? diagnostics = null)
|
||||
{
|
||||
_leases = leases ?? throw new ArgumentNullException(nameof(leases));
|
||||
_signatures = signatures ?? throw new ArgumentNullException(nameof(signatures));
|
||||
_revocations = revocations ?? throw new ArgumentNullException(nameof(revocations));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_diagnostics = diagnostics ?? CultMeshNullDiagnosticSink.Instance;
|
||||
}
|
||||
|
||||
public CultMeshAuthorityDecision Resolve(CultMeshAuthorityRequest request)
|
||||
{
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
var leaseId = request.Peer.AuthorityLeaseId;
|
||||
if (string.IsNullOrWhiteSpace(leaseId)) return Decide(request, null, CultMeshAuthorityDenialReason.MissingLeaseReference);
|
||||
var lease = _leases.Get(leaseId!);
|
||||
if (lease == null) return Decide(request, null, CultMeshAuthorityDenialReason.LeaseNotFound);
|
||||
if (!string.Equals(lease.SchemaVersion, CultMeshAuthorityLease.CurrentSchemaVersion, StringComparison.Ordinal) || !lease.AuthorityEpoch.HasValue)
|
||||
return Decide(request, lease, CultMeshAuthorityDenialReason.UnsupportedLeaseVersion);
|
||||
if (string.IsNullOrWhiteSpace(lease.Signature)) return Decide(request, lease, CultMeshAuthorityDenialReason.MissingSignature);
|
||||
if (!_signatures.Verify(lease)) return Decide(request, lease, CultMeshAuthorityDenialReason.InvalidSignature);
|
||||
if (_clock.UtcNow < lease.ValidFrom) return Decide(request, lease, CultMeshAuthorityDenialReason.NotYetValid);
|
||||
if (_clock.UtcNow >= lease.ExpiresAt) return Decide(request, lease, CultMeshAuthorityDenialReason.Expired);
|
||||
if (_revocations.IsRevoked(lease.LeaseId, lease.AuthorityEpoch.Value)) return Decide(request, lease, CultMeshAuthorityDenialReason.Revoked);
|
||||
if (!string.Equals(lease.VerseId, request.Peer.VerseId, StringComparison.Ordinal)) return Decide(request, lease, CultMeshAuthorityDenialReason.VerseMismatch);
|
||||
if (!string.Equals(lease.PeerId, request.Peer.PeerId, StringComparison.Ordinal)) return Decide(request, lease, CultMeshAuthorityDenialReason.PeerMismatch);
|
||||
if (!string.Equals(lease.LeaseId, leaseId, StringComparison.Ordinal)) return Decide(request, lease, CultMeshAuthorityDenialReason.LeaseReferenceMismatch);
|
||||
if (!lease.Roles.Contains(request.Role, StringComparer.Ordinal)) return Decide(request, lease, CultMeshAuthorityDenialReason.RoleNotGranted);
|
||||
if (!request.Peer.Roles.Contains(request.Role, StringComparer.Ordinal)) return Decide(request, lease, CultMeshAuthorityDenialReason.RoleNotAdvertised);
|
||||
if (!string.IsNullOrWhiteSpace(request.ShardId) && lease.ShardIds.Count != 0 && !lease.ShardIds.Contains(request.ShardId!, StringComparer.Ordinal))
|
||||
return Decide(request, lease, CultMeshAuthorityDenialReason.ShardNotGranted);
|
||||
if (!string.IsNullOrWhiteSpace(request.ShardId) && request.Peer.ShardIds.Count != 0 && !request.Peer.ShardIds.Contains(request.ShardId!, StringComparer.Ordinal))
|
||||
return Decide(request, lease, CultMeshAuthorityDenialReason.ShardNotAdvertised);
|
||||
if (lease.AuthorityEpoch.Value != request.AuthorityEpoch) return Decide(request, lease, CultMeshAuthorityDenialReason.EpochMismatch);
|
||||
if (!string.IsNullOrWhiteSpace(request.ResourceScope) && !lease.ResourceScopes.Contains(request.ResourceScope!, StringComparer.Ordinal))
|
||||
return Decide(request, lease, CultMeshAuthorityDenialReason.ResourceScopeNotGranted);
|
||||
return Decide(request, lease, CultMeshAuthorityDenialReason.None);
|
||||
}
|
||||
|
||||
internal static CultMeshAuthorityResolver CreateDenyByDefault(ICultMeshAuthorityLeaseSource leases, ICultMeshClock? clock = null) =>
|
||||
new CultMeshAuthorityResolver(leases, DenyAllSignatures.Instance, NoRevocations.Instance, clock ?? CultMeshSystemClock.Instance);
|
||||
|
||||
private CultMeshAuthorityDecision Decide(CultMeshAuthorityRequest request, CultMeshAuthorityLease? lease, CultMeshAuthorityDenialReason reason)
|
||||
{
|
||||
var decision = new CultMeshAuthorityDecision(request, lease, reason);
|
||||
_diagnostics.Emit(new CultMeshDiagnosticEvent(
|
||||
Interlocked.Increment(ref _diagnosticSequence), _clock.UtcNow, CultMeshReliabilityOrgan.Authority,
|
||||
CultMeshDiagnosticKind.AuthorityDecision, lease?.LeaseId ?? request.Peer.AuthorityLeaseId ?? "lease:missing",
|
||||
request.Peer.PeerId, decision.IsAuthorized ? "authorized" : "denied", reason.ToString(), lease?.IssuerRuntimeId ?? "",
|
||||
schemaVersion: "gamecult.mesh.authority_decision.v1"));
|
||||
return decision;
|
||||
}
|
||||
|
||||
private sealed class DenyAllSignatures : ICultMeshAuthoritySignatureVerifier
|
||||
{
|
||||
public static DenyAllSignatures Instance { get; } = new DenyAllSignatures();
|
||||
public bool Verify(CultMeshAuthorityLease lease) => false;
|
||||
}
|
||||
|
||||
private sealed class NoRevocations : ICultMeshAuthorityRevocationSource
|
||||
{
|
||||
public static NoRevocations Instance { get; } = new NoRevocations();
|
||||
public bool IsRevoked(string leaseId, long authorityEpoch) => false;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshAuthorityLeaseCatalog : ICultMeshAuthorityLeaseSource
|
||||
{
|
||||
private readonly Dictionary<string, CultMeshAuthorityLease> _leases = new(StringComparer.Ordinal);
|
||||
public IReadOnlyList<CultMeshAuthorityLease> Leases => _leases.Values.OrderBy(lease => lease.LeaseId, StringComparer.Ordinal).ToArray();
|
||||
public void Upsert(CultMeshAuthorityLease lease) { if (lease == null) throw new ArgumentNullException(nameof(lease)); _leases[lease.LeaseId] = lease; }
|
||||
public CultMeshAuthorityLease? Get(string leaseId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(leaseId)) throw new ArgumentException("Value must be non-empty.", nameof(leaseId));
|
||||
return _leases.TryGetValue(leaseId, out var lease) ? lease : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns whether a peer card is authorized for a role and optional shard.
|
||||
/// </summary>
|
||||
[Obsolete("Authority decisions belong to CultMeshAuthorityResolver. This compatibility path denies unsigned and unverifiable leases.")]
|
||||
public bool IsAuthorized(CultMeshPeerCard peer, string role, string? shardId = null, DateTimeOffset? at = null)
|
||||
{
|
||||
if (peer == null) throw new ArgumentNullException(nameof(peer));
|
||||
if (string.IsNullOrWhiteSpace(peer.AuthorityLeaseId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var lease = string.IsNullOrWhiteSpace(peer.AuthorityLeaseId) ? null : Get(peer.AuthorityLeaseId!);
|
||||
var epoch = lease?.AuthorityEpoch ?? -1;
|
||||
if (epoch < 0) return false;
|
||||
var resolver = CultMeshAuthorityResolver.CreateDenyByDefault(this, at.HasValue ? new CatalogFixedClock(at.Value) : null);
|
||||
return resolver.Resolve(new CultMeshAuthorityRequest(peer, role, shardId, epoch)).IsAuthorized;
|
||||
}
|
||||
|
||||
return _leases.TryGetValue(peer.AuthorityLeaseId!, out var lease) &&
|
||||
lease.Covers(peer, role, shardId, at);
|
||||
private sealed class CatalogFixedClock : ICultMeshClock
|
||||
{
|
||||
public CatalogFixedClock(DateTimeOffset now) => UtcNow = now;
|
||||
public DateTimeOffset UtcNow { get; }
|
||||
public System.Threading.Tasks.Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken = default) => System.Threading.Tasks.Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
640
src/GameCult.Mesh/CultMeshBodies.cs
Normal file
640
src/GameCult.Mesh/CultMeshBodies.cs
Normal file
|
|
@ -0,0 +1,640 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.IO.MemoryMappedFiles;
|
||||
using System.Security.Cryptography;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using MessagePack;
|
||||
|
||||
#nullable enable
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
public enum CultMeshBodyAccessMode
|
||||
{
|
||||
ReadOnly = 0,
|
||||
ReadWrite = 1
|
||||
}
|
||||
|
||||
public enum CultMeshBodySynchronization
|
||||
{
|
||||
ImmutableSequence = 0,
|
||||
EpochSequence = 1,
|
||||
TripleBuffer = 2
|
||||
}
|
||||
|
||||
public enum CultMeshBodyTransportKind
|
||||
{
|
||||
Network = 0,
|
||||
SharedFileMapping = 1,
|
||||
SharedMemory = 2
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshBodyDescriptor
|
||||
{
|
||||
[Key(0)] public string BodyId { get; set; } = string.Empty;
|
||||
[Key(1)] public string SchemaId { get; set; } = string.Empty;
|
||||
[Key(2)] public int LayoutVersion { get; set; }
|
||||
[Key(3)] public long ByteSize { get; set; }
|
||||
[Key(4)] public int Capacity { get; set; }
|
||||
[Key(5)] public long ProducerEpoch { get; set; }
|
||||
[Key(6)] public long Sequence { get; set; }
|
||||
[Key(7)] public CultMeshBodyAccessMode AccessMode { get; set; } = CultMeshBodyAccessMode.ReadOnly;
|
||||
[Key(8)] public CultMeshBodySynchronization Synchronization { get; set; } = CultMeshBodySynchronization.ImmutableSequence;
|
||||
[Key(9)] public long LeaseExpiresAtUnixMs { get; set; }
|
||||
[Key(10)] public CultMeshBodyTransportKind TransportKind { get; set; } = CultMeshBodyTransportKind.Network;
|
||||
[Key(11)] public string CapabilityToken { get; set; } = string.Empty;
|
||||
[Key(12)] public string SemanticHash { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public sealed class CultMeshBodyValidationRequest
|
||||
{
|
||||
public string BodyId { get; set; } = string.Empty;
|
||||
public string SchemaId { get; set; } = string.Empty;
|
||||
public int LayoutVersion { get; set; }
|
||||
public long ProducerEpoch { get; set; }
|
||||
public long? Sequence { get; set; }
|
||||
public int? Capacity { get; set; }
|
||||
public CultMeshBodyAccessMode AccessMode { get; set; } = CultMeshBodyAccessMode.ReadOnly;
|
||||
public DateTimeOffset NowUtc { get; set; } = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
public static class CultMeshBodyDescriptorValidator
|
||||
{
|
||||
public static string ComputeSemanticHash(ReadOnlySpan<byte> body)
|
||||
{
|
||||
using var sha256 = SHA256.Create();
|
||||
Span<byte> digest = stackalloc byte[32];
|
||||
if (!sha256.TryComputeHash(body, digest, out var written) || written != digest.Length)
|
||||
throw new CryptographicException("Unable to compute the CultMesh body semantic digest.");
|
||||
return BitConverter.ToString(digest.ToArray())
|
||||
.Replace("-", string.Empty)
|
||||
.ToLowerInvariant();
|
||||
}
|
||||
|
||||
public static void Validate(CultMeshBodyDescriptor descriptor, CultMeshBodyValidationRequest request)
|
||||
{
|
||||
if (descriptor == null) throw new ArgumentNullException(nameof(descriptor));
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
if (string.IsNullOrWhiteSpace(descriptor.BodyId) ||
|
||||
!string.Equals(descriptor.BodyId, request.BodyId, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException("CultMesh body identity mismatch.");
|
||||
if (string.IsNullOrWhiteSpace(descriptor.SchemaId) ||
|
||||
!string.Equals(descriptor.SchemaId, request.SchemaId, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException("CultMesh body schema mismatch.");
|
||||
if (descriptor.LayoutVersion != request.LayoutVersion)
|
||||
throw new InvalidOperationException("CultMesh body layout version mismatch.");
|
||||
if (descriptor.ProducerEpoch != request.ProducerEpoch)
|
||||
throw new InvalidOperationException("CultMesh body producer epoch mismatch.");
|
||||
if (request.Sequence.HasValue && descriptor.Sequence != request.Sequence.Value)
|
||||
throw new InvalidOperationException("CultMesh body sequence mismatch.");
|
||||
if (request.Capacity.HasValue && descriptor.Capacity != request.Capacity.Value)
|
||||
throw new InvalidOperationException("CultMesh body capacity mismatch.");
|
||||
if (descriptor.ByteSize < 0 || descriptor.Capacity < 0)
|
||||
throw new InvalidOperationException("CultMesh body size and logical capacity must be non-negative.");
|
||||
if (descriptor.Sequence < 0)
|
||||
throw new InvalidOperationException("CultMesh body sequence must be non-negative.");
|
||||
if (descriptor.LeaseExpiresAtUnixMs <= request.NowUtc.ToUnixTimeMilliseconds())
|
||||
throw new InvalidOperationException("CultMesh body lease has expired.");
|
||||
if (request.AccessMode != CultMeshBodyAccessMode.ReadOnly ||
|
||||
descriptor.AccessMode != CultMeshBodyAccessMode.ReadOnly)
|
||||
throw new UnauthorizedAccessException("CultMesh body consumers are read-only by default.");
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshBodyNegotiationResult
|
||||
{
|
||||
internal CultMeshBodyNegotiationResult(
|
||||
ICultMeshBodyReadLease lease,
|
||||
CultMeshBodyTransportKind preferredTransport,
|
||||
Exception? preferredFailure)
|
||||
{
|
||||
Lease = lease;
|
||||
PreferredTransport = preferredTransport;
|
||||
PreferredFailure = preferredFailure;
|
||||
}
|
||||
|
||||
public ICultMeshBodyReadLease Lease { get; }
|
||||
public CultMeshBodyTransportKind PreferredTransport { get; }
|
||||
public CultMeshBodyTransportKind SelectedTransport => Lease.TransportKind;
|
||||
public Exception? PreferredFailure { get; }
|
||||
public bool UsedFallback => SelectedTransport != PreferredTransport;
|
||||
}
|
||||
|
||||
public interface ICultMeshBodyReadLease : IDisposable
|
||||
{
|
||||
CultMeshBodyDescriptor Descriptor { get; }
|
||||
CultMeshBodyTransportKind TransportKind { get; }
|
||||
byte ReadByte(long offset);
|
||||
int ReadInt32(long offset);
|
||||
long ReadInt64(long offset);
|
||||
float ReadSingle(long offset);
|
||||
double ReadDouble(long offset);
|
||||
int CopyTo(long offset, byte[] destination, int destinationOffset, int count);
|
||||
}
|
||||
|
||||
public interface ICultMeshBodyTransportAdapter
|
||||
{
|
||||
CultMeshBodyTransportKind TransportKind { get; }
|
||||
bool CanOpen(CultMeshBodyDescriptor descriptor);
|
||||
ICultMeshBodyReadLease OpenReadOnly(
|
||||
CultMeshBodyDescriptor descriptor,
|
||||
CultMeshBodyValidationRequest request);
|
||||
}
|
||||
|
||||
public sealed class CultMeshBodyTransportService
|
||||
{
|
||||
private readonly IReadOnlyDictionary<CultMeshBodyTransportKind, ICultMeshBodyTransportAdapter> _adapters;
|
||||
private readonly Func<CultMeshBodyDescriptor, bool> _authorizeProducer;
|
||||
private readonly Func<string, CultMeshBodyDescriptor, bool>? _authorizeNamedProducer;
|
||||
|
||||
/// <summary>Gets locally available body planes in fastest-local-first order.</summary>
|
||||
public IReadOnlyList<CultMeshBodyTransportKind> SupportedTransports => _adapters.Keys
|
||||
.OrderByDescending(TransportPreference)
|
||||
.ToArray();
|
||||
|
||||
public CultMeshBodyTransportService(
|
||||
IEnumerable<ICultMeshBodyTransportAdapter> adapters,
|
||||
Func<CultMeshBodyDescriptor, bool> authorizeProducer)
|
||||
{
|
||||
_adapters = (adapters ?? throw new ArgumentNullException(nameof(adapters)))
|
||||
.ToDictionary(adapter => adapter.TransportKind);
|
||||
_authorizeProducer = authorizeProducer ?? throw new ArgumentNullException(nameof(authorizeProducer));
|
||||
}
|
||||
|
||||
public CultMeshBodyTransportService(
|
||||
IEnumerable<ICultMeshBodyTransportAdapter> adapters,
|
||||
Func<string, CultMeshBodyDescriptor, bool> authorizeProducer)
|
||||
{
|
||||
_adapters = (adapters ?? throw new ArgumentNullException(nameof(adapters)))
|
||||
.ToDictionary(adapter => adapter.TransportKind);
|
||||
_authorizeProducer = _ => true;
|
||||
_authorizeNamedProducer = authorizeProducer ?? throw new ArgumentNullException(nameof(authorizeProducer));
|
||||
}
|
||||
|
||||
public ICultMeshBodyReadLease OpenReadOnly(
|
||||
CultMeshBodyDescriptor preferred,
|
||||
CultMeshBodyDescriptor networkFallback,
|
||||
CultMeshBodyValidationRequest request,
|
||||
out Exception? localFailure)
|
||||
{
|
||||
var result = NegotiateReadOnly(preferred, networkFallback, request);
|
||||
localFailure = result.PreferredFailure;
|
||||
return result.Lease;
|
||||
}
|
||||
|
||||
public CultMeshBodyNegotiationResult NegotiateReadOnly(
|
||||
CultMeshBodyDescriptor preferred,
|
||||
CultMeshBodyDescriptor networkFallback,
|
||||
CultMeshBodyValidationRequest request)
|
||||
{
|
||||
return NegotiateReadOnly(null, new[] { preferred, networkFallback }, request);
|
||||
}
|
||||
|
||||
internal CultMeshBodyNegotiationResult NegotiateReadOnly(
|
||||
string? producerId,
|
||||
CultMeshBodyDescriptor preferred,
|
||||
CultMeshBodyDescriptor networkFallback,
|
||||
CultMeshBodyValidationRequest request)
|
||||
{
|
||||
return NegotiateReadOnly(producerId, new[] { preferred, networkFallback }, request);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects the first representation the consumer can validate and open. Representation order is
|
||||
/// publisher preference; adapter availability and capability validity decide the actual plane.
|
||||
/// </summary>
|
||||
public CultMeshBodyNegotiationResult NegotiateReadOnly(
|
||||
IReadOnlyList<CultMeshBodyDescriptor> representations,
|
||||
CultMeshBodyValidationRequest request) =>
|
||||
NegotiateReadOnly(null, representations, request);
|
||||
|
||||
internal CultMeshBodyNegotiationResult NegotiateReadOnly(
|
||||
string? producerId,
|
||||
IReadOnlyList<CultMeshBodyDescriptor> representations,
|
||||
CultMeshBodyValidationRequest request)
|
||||
{
|
||||
if (representations == null) throw new ArgumentNullException(nameof(representations));
|
||||
if (representations.Count == 0 || representations.Any(value => value == null))
|
||||
throw new ArgumentException("At least one body representation is required.", nameof(representations));
|
||||
var preferred = representations[0];
|
||||
foreach (var representation in representations)
|
||||
{
|
||||
if (!SameLogicalGeneration(preferred, representation))
|
||||
throw new InvalidOperationException("CultMesh representations describe different logical body generations.");
|
||||
CultMeshBodyDescriptorValidator.Validate(representation, request);
|
||||
}
|
||||
var authorized = _authorizeNamedProducer == null
|
||||
? _authorizeProducer(preferred)
|
||||
: !string.IsNullOrWhiteSpace(producerId) && _authorizeNamedProducer(producerId!, preferred);
|
||||
if (!authorized)
|
||||
throw new UnauthorizedAccessException("CultMesh body producer is not authorized for this logical body.");
|
||||
|
||||
Exception? preferredFailure = null;
|
||||
foreach (var representation in representations)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_adapters.TryGetValue(representation.TransportKind, out var adapter))
|
||||
throw new NotSupportedException($"No CultMesh {representation.TransportKind} body adapter is available.");
|
||||
if (!adapter.CanOpen(representation))
|
||||
throw new NotSupportedException($"The CultMesh {representation.TransportKind} body adapter declined its descriptor.");
|
||||
var lease = adapter.OpenReadOnly(representation, request);
|
||||
return new CultMeshBodyNegotiationResult(
|
||||
lease,
|
||||
preferred.TransportKind,
|
||||
preferredFailure);
|
||||
}
|
||||
catch (Exception error) when (!(error is UnauthorizedAccessException))
|
||||
{
|
||||
preferredFailure ??= error;
|
||||
}
|
||||
}
|
||||
|
||||
throw new NotSupportedException(
|
||||
"No advertised CultMesh body representation could be opened by this consumer.",
|
||||
preferredFailure);
|
||||
}
|
||||
|
||||
private static bool SameLogicalGeneration(CultMeshBodyDescriptor left, CultMeshBodyDescriptor right) =>
|
||||
string.Equals(left.BodyId, right.BodyId, StringComparison.Ordinal) &&
|
||||
string.Equals(left.SchemaId, right.SchemaId, StringComparison.Ordinal) &&
|
||||
left.LayoutVersion == right.LayoutVersion &&
|
||||
left.ProducerEpoch == right.ProducerEpoch &&
|
||||
left.Sequence == right.Sequence &&
|
||||
left.ByteSize == right.ByteSize &&
|
||||
left.Capacity == right.Capacity &&
|
||||
left.AccessMode == right.AccessMode &&
|
||||
left.Synchronization == right.Synchronization &&
|
||||
string.Equals(left.SemanticHash, right.SemanticHash, StringComparison.Ordinal);
|
||||
|
||||
private static int TransportPreference(CultMeshBodyTransportKind transport) => transport switch
|
||||
{
|
||||
CultMeshBodyTransportKind.SharedMemory => 3,
|
||||
CultMeshBodyTransportKind.SharedFileMapping => 2,
|
||||
_ => 1
|
||||
};
|
||||
}
|
||||
|
||||
public sealed class CultMeshMappedBodyPublisher
|
||||
{
|
||||
private readonly string _rootPath;
|
||||
private readonly TimeSpan _leaseDuration;
|
||||
|
||||
public CultMeshMappedBodyPublisher(string rootPath, TimeSpan? leaseDuration = null)
|
||||
{
|
||||
_rootPath = string.IsNullOrWhiteSpace(rootPath)
|
||||
? throw new ArgumentException("Mapped body root is required.", nameof(rootPath))
|
||||
: Path.GetFullPath(rootPath);
|
||||
_leaseDuration = leaseDuration ?? TimeSpan.FromSeconds(5);
|
||||
if (_leaseDuration <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(leaseDuration));
|
||||
Directory.CreateDirectory(_rootPath);
|
||||
}
|
||||
|
||||
public CultMeshBodyDescriptor Publish(
|
||||
string bodyId,
|
||||
string schemaId,
|
||||
int layoutVersion,
|
||||
int logicalCapacity,
|
||||
long producerEpoch,
|
||||
long sequence,
|
||||
ReadOnlySpan<byte> body,
|
||||
DateTimeOffset nowUtc)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(bodyId)) throw new ArgumentException("Body identity is required.", nameof(bodyId));
|
||||
if (string.IsNullOrWhiteSpace(schemaId)) throw new ArgumentException("Schema identity is required.", nameof(schemaId));
|
||||
if (layoutVersion < 0) throw new ArgumentOutOfRangeException(nameof(layoutVersion));
|
||||
if (logicalCapacity < 0) throw new ArgumentOutOfRangeException(nameof(logicalCapacity));
|
||||
if (producerEpoch < 0) throw new ArgumentOutOfRangeException(nameof(producerEpoch));
|
||||
if (sequence < 0) throw new ArgumentOutOfRangeException(nameof(sequence));
|
||||
|
||||
var token = CreateCapabilityToken();
|
||||
var finalPath = ResolveTokenPath(token);
|
||||
var temporaryPath = finalPath + ".tmp";
|
||||
using (var stream = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
|
||||
stream.Write(body);
|
||||
File.Move(temporaryPath, finalPath);
|
||||
return new CultMeshBodyDescriptor
|
||||
{
|
||||
BodyId = bodyId,
|
||||
SchemaId = schemaId,
|
||||
LayoutVersion = layoutVersion,
|
||||
ByteSize = body.Length,
|
||||
Capacity = logicalCapacity,
|
||||
ProducerEpoch = producerEpoch,
|
||||
Sequence = sequence,
|
||||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
Synchronization = CultMeshBodySynchronization.ImmutableSequence,
|
||||
LeaseExpiresAtUnixMs = nowUtc.Add(_leaseDuration).ToUnixTimeMilliseconds(),
|
||||
TransportKind = CultMeshBodyTransportKind.SharedFileMapping,
|
||||
CapabilityToken = token,
|
||||
SemanticHash = CultMeshBodyDescriptorValidator.ComputeSemanticHash(body)
|
||||
};
|
||||
}
|
||||
|
||||
public void Revoke(CultMeshBodyDescriptor descriptor)
|
||||
{
|
||||
if (descriptor == null || string.IsNullOrWhiteSpace(descriptor.CapabilityToken)) return;
|
||||
var path = ResolveTokenPath(descriptor.CapabilityToken);
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
|
||||
private string ResolveTokenPath(string token)
|
||||
{
|
||||
if (token.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || token.Contains(".."))
|
||||
throw new InvalidOperationException("Invalid CultMesh body capability token.");
|
||||
var path = Path.GetFullPath(Path.Combine(_rootPath, token + ".body"));
|
||||
if (!path.StartsWith(_rootPath + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException("CultMesh body token escaped the broker root.");
|
||||
return path;
|
||||
}
|
||||
|
||||
private static string CreateCapabilityToken()
|
||||
{
|
||||
var bytes = new byte[32];
|
||||
using (var random = RandomNumberGenerator.Create()) random.GetBytes(bytes);
|
||||
return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshMappedBodyAdapter : ICultMeshBodyTransportAdapter
|
||||
{
|
||||
private readonly string? _rootPath;
|
||||
private readonly CultMeshVerifiedBodyMappingBroker? _verifiedBodies;
|
||||
|
||||
public CultMeshMappedBodyAdapter(string rootPath) =>
|
||||
_rootPath = Path.GetFullPath(string.IsNullOrWhiteSpace(rootPath)
|
||||
? throw new ArgumentException("Mapped body root is required.", nameof(rootPath))
|
||||
: rootPath);
|
||||
|
||||
public CultMeshMappedBodyAdapter(CultMeshVerifiedBodyMappingBroker verifiedBodies) =>
|
||||
_verifiedBodies = verifiedBodies ?? throw new ArgumentNullException(nameof(verifiedBodies));
|
||||
|
||||
public CultMeshBodyTransportKind TransportKind => CultMeshBodyTransportKind.SharedFileMapping;
|
||||
|
||||
public bool CanOpen(CultMeshBodyDescriptor descriptor) =>
|
||||
descriptor != null && descriptor.TransportKind == TransportKind;
|
||||
|
||||
public ICultMeshBodyReadLease OpenReadOnly(
|
||||
CultMeshBodyDescriptor descriptor,
|
||||
CultMeshBodyValidationRequest request)
|
||||
{
|
||||
CultMeshBodyDescriptorValidator.Validate(descriptor, request);
|
||||
if (descriptor.TransportKind != CultMeshBodyTransportKind.SharedFileMapping)
|
||||
throw new NotSupportedException($"CultMesh body transport '{descriptor.TransportKind}' is not a file mapping.");
|
||||
if (string.IsNullOrWhiteSpace(descriptor.CapabilityToken))
|
||||
throw new InvalidOperationException("Mapped CultMesh body descriptor has no transport capability token.");
|
||||
var path = _verifiedBodies != null
|
||||
? _verifiedBodies.Resolve(descriptor.CapabilityToken, request.NowUtc)
|
||||
: ResolvePublisherPath(descriptor.CapabilityToken);
|
||||
var info = new FileInfo(path);
|
||||
if (!info.Exists || info.Length != descriptor.ByteSize)
|
||||
throw new InvalidDataException("Mapped CultMesh body size does not match its descriptor.");
|
||||
return new CultMeshMappedBodyLease(descriptor, path);
|
||||
}
|
||||
|
||||
private string ResolvePublisherPath(string token)
|
||||
{
|
||||
if (token.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || token.Contains(".."))
|
||||
throw new UnauthorizedAccessException("Invalid CultMesh body capability token.");
|
||||
var path = Path.GetFullPath(Path.Combine(_rootPath!, token + ".body"));
|
||||
if (!path.StartsWith(_rootPath + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||
throw new UnauthorizedAccessException("CultMesh body token escaped the broker root.");
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshVerifiedBodyMappingBroker
|
||||
{
|
||||
private sealed class Grant
|
||||
{
|
||||
public string Path { get; set; } = string.Empty;
|
||||
public long ExpiresAtUnixMs { get; set; }
|
||||
}
|
||||
|
||||
private readonly string _cacheDirectory;
|
||||
private readonly ConcurrentDictionary<string, Grant> _grants = new(StringComparer.Ordinal);
|
||||
|
||||
public CultMeshVerifiedBodyMappingBroker(string cacheDirectory) =>
|
||||
_cacheDirectory = Path.GetFullPath(string.IsNullOrWhiteSpace(cacheDirectory)
|
||||
? throw new ArgumentException("Verified body cache directory is required.", nameof(cacheDirectory))
|
||||
: cacheDirectory);
|
||||
|
||||
internal CultMeshBodyDescriptor GrantVerified(
|
||||
string contentHash,
|
||||
string verifiedPath,
|
||||
CultMeshBodyDescriptor networkDescriptor,
|
||||
DateTimeOffset expiresAtUtc)
|
||||
{
|
||||
if (networkDescriptor == null) throw new ArgumentNullException(nameof(networkDescriptor));
|
||||
var expectedPath = Path.Combine(_cacheDirectory, contentHash + ".body");
|
||||
if (!string.Equals(Path.GetFullPath(verifiedPath), expectedPath, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException("Only the transfer-owned verified body may be mapped.");
|
||||
var info = new FileInfo(expectedPath);
|
||||
if (!info.Exists || info.Length != networkDescriptor.ByteSize)
|
||||
throw new InvalidDataException("Verified CultMesh body size does not match its network descriptor.");
|
||||
|
||||
var token = CreateCapabilityToken();
|
||||
var expiresAtUnixMs = expiresAtUtc.ToUnixTimeMilliseconds();
|
||||
_grants[token] = new Grant { Path = expectedPath, ExpiresAtUnixMs = expiresAtUnixMs };
|
||||
return new CultMeshBodyDescriptor
|
||||
{
|
||||
BodyId = networkDescriptor.BodyId,
|
||||
SchemaId = networkDescriptor.SchemaId,
|
||||
LayoutVersion = networkDescriptor.LayoutVersion,
|
||||
ByteSize = networkDescriptor.ByteSize,
|
||||
Capacity = networkDescriptor.Capacity,
|
||||
ProducerEpoch = networkDescriptor.ProducerEpoch,
|
||||
Sequence = networkDescriptor.Sequence,
|
||||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
Synchronization = networkDescriptor.Synchronization,
|
||||
LeaseExpiresAtUnixMs = expiresAtUnixMs,
|
||||
TransportKind = CultMeshBodyTransportKind.SharedFileMapping,
|
||||
CapabilityToken = token,
|
||||
SemanticHash = networkDescriptor.SemanticHash
|
||||
};
|
||||
}
|
||||
|
||||
internal string Resolve(string token, DateTimeOffset nowUtc)
|
||||
{
|
||||
if (!_grants.TryGetValue(token, out var grant))
|
||||
throw new UnauthorizedAccessException("Unknown verified body capability token.");
|
||||
if (grant.ExpiresAtUnixMs <= nowUtc.ToUnixTimeMilliseconds())
|
||||
{
|
||||
_grants.TryRemove(token, out _);
|
||||
throw new InvalidOperationException("Verified body capability has expired.");
|
||||
}
|
||||
return grant.Path;
|
||||
}
|
||||
|
||||
private static string CreateCapabilityToken()
|
||||
{
|
||||
var bytes = new byte[32];
|
||||
using (var random = RandomNumberGenerator.Create()) random.GetBytes(bytes);
|
||||
return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshSharedMemoryBodyAdapter : ICultMeshBodyTransportAdapter
|
||||
{
|
||||
public CultMeshBodyTransportKind TransportKind => CultMeshBodyTransportKind.SharedMemory;
|
||||
public bool CanOpen(CultMeshBodyDescriptor descriptor) =>
|
||||
descriptor != null && descriptor.TransportKind == TransportKind;
|
||||
|
||||
public ICultMeshBodyReadLease OpenReadOnly(
|
||||
CultMeshBodyDescriptor descriptor,
|
||||
CultMeshBodyValidationRequest request)
|
||||
{
|
||||
CultMeshBodyDescriptorValidator.Validate(descriptor, request);
|
||||
if (string.IsNullOrWhiteSpace(descriptor.CapabilityToken))
|
||||
throw new InvalidOperationException("Shared-memory CultMesh body descriptor has no transport capability token.");
|
||||
if (CultMeshFrameBodyPublisher.IsFrameCapability(descriptor.CapabilityToken))
|
||||
return CultMeshFrameBodyPublisher.OpenReadOnly(descriptor);
|
||||
MemoryMappedFile mapping;
|
||||
try
|
||||
{
|
||||
mapping = MemoryMappedFile.OpenExisting(descriptor.CapabilityToken, MemoryMappedFileRights.Read);
|
||||
}
|
||||
catch (FileNotFoundException error)
|
||||
{
|
||||
throw new InvalidDataException("CultMesh shared-memory capability is unavailable or revoked.", error);
|
||||
}
|
||||
try
|
||||
{
|
||||
return new CultMeshMappedBodyLease(descriptor, mapping);
|
||||
}
|
||||
catch
|
||||
{
|
||||
mapping.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshMappedBodyLease : ICultMeshBodyReadLease
|
||||
{
|
||||
private readonly MemoryMappedFile _mapping;
|
||||
private readonly MemoryMappedViewAccessor _view;
|
||||
private bool _disposed;
|
||||
|
||||
internal CultMeshMappedBodyLease(CultMeshBodyDescriptor descriptor, string path)
|
||||
: this(descriptor, MemoryMappedFile.CreateFromFile(path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read))
|
||||
{
|
||||
}
|
||||
|
||||
internal CultMeshMappedBodyLease(
|
||||
CultMeshBodyDescriptor descriptor,
|
||||
MemoryMappedFile mapping,
|
||||
long offset = 0,
|
||||
Action? release = null)
|
||||
{
|
||||
Descriptor = descriptor;
|
||||
_mapping = mapping;
|
||||
_release = release;
|
||||
_view = _mapping.CreateViewAccessor(offset, descriptor.ByteSize, MemoryMappedFileAccess.Read);
|
||||
}
|
||||
|
||||
private readonly Action? _release;
|
||||
|
||||
public CultMeshBodyDescriptor Descriptor { get; }
|
||||
public CultMeshBodyTransportKind TransportKind => Descriptor.TransportKind;
|
||||
public byte ReadByte(long offset) { ValidateRange(offset, 1); return _view.ReadByte(offset); }
|
||||
public int ReadInt32(long offset) { ValidateRange(offset, sizeof(int)); return _view.ReadInt32(offset); }
|
||||
public long ReadInt64(long offset) { ValidateRange(offset, sizeof(long)); return _view.ReadInt64(offset); }
|
||||
public float ReadSingle(long offset) { ValidateRange(offset, sizeof(float)); return _view.ReadSingle(offset); }
|
||||
public double ReadDouble(long offset) { ValidateRange(offset, sizeof(double)); return _view.ReadDouble(offset); }
|
||||
public int CopyTo(long offset, byte[] destination, int destinationOffset, int count)
|
||||
{
|
||||
if (destination == null) throw new ArgumentNullException(nameof(destination));
|
||||
ValidateRange(offset, count);
|
||||
return _view.ReadArray(offset, destination, destinationOffset, count);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_view.Dispose();
|
||||
_mapping.Dispose();
|
||||
_release?.Invoke();
|
||||
}
|
||||
|
||||
private void ValidateRange(long offset, long length)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshMappedBodyLease));
|
||||
if (offset < 0 || length < 0 || offset > Descriptor.ByteSize - length)
|
||||
throw new ArgumentOutOfRangeException(nameof(offset));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshNetworkBodyAdapter : ICultMeshBodyTransportAdapter
|
||||
{
|
||||
private readonly Func<CultMeshBodyDescriptor, byte[]> _fetch;
|
||||
private readonly bool _fetchIsVerified;
|
||||
|
||||
public CultMeshNetworkBodyAdapter(Func<CultMeshBodyDescriptor, byte[]> fetch) =>
|
||||
_fetch = fetch ?? throw new ArgumentNullException(nameof(fetch));
|
||||
|
||||
/// <summary>Uses a session provider that already verifies the response against the descriptor.</summary>
|
||||
public CultMeshNetworkBodyAdapter(CultMeshSessionBodyProvider provider)
|
||||
{
|
||||
if (provider == null) throw new ArgumentNullException(nameof(provider));
|
||||
_fetch = provider.CreateFetchDelegate();
|
||||
_fetchIsVerified = true;
|
||||
}
|
||||
|
||||
public CultMeshBodyTransportKind TransportKind => CultMeshBodyTransportKind.Network;
|
||||
public bool CanOpen(CultMeshBodyDescriptor descriptor) =>
|
||||
descriptor != null && descriptor.TransportKind == TransportKind;
|
||||
|
||||
public ICultMeshBodyReadLease OpenReadOnly(
|
||||
CultMeshBodyDescriptor descriptor,
|
||||
CultMeshBodyValidationRequest request)
|
||||
{
|
||||
CultMeshBodyDescriptorValidator.Validate(descriptor, request);
|
||||
var bytes = _fetch(descriptor) ?? throw new InvalidDataException("CultMesh network body returned no bytes.");
|
||||
if (bytes.LongLength != descriptor.ByteSize)
|
||||
throw new InvalidDataException("CultMesh network body size does not match its descriptor.");
|
||||
if (string.IsNullOrWhiteSpace(descriptor.SemanticHash))
|
||||
throw new InvalidDataException("CultMesh network body descriptor has no semantic digest.");
|
||||
if (!_fetchIsVerified)
|
||||
{
|
||||
var actualHash = CultMeshBodyDescriptorValidator.ComputeSemanticHash(bytes);
|
||||
if (!string.Equals(actualHash, descriptor.SemanticHash, StringComparison.Ordinal))
|
||||
throw new InvalidDataException("CultMesh network body semantic digest does not match its descriptor.");
|
||||
}
|
||||
return new CultMeshBufferedBodyLease(descriptor, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class CultMeshBufferedBodyLease : ICultMeshBodyReadLease
|
||||
{
|
||||
private byte[] _body;
|
||||
public CultMeshBufferedBodyLease(CultMeshBodyDescriptor descriptor, byte[] body)
|
||||
{
|
||||
Descriptor = descriptor;
|
||||
_body = body;
|
||||
}
|
||||
public CultMeshBodyDescriptor Descriptor { get; }
|
||||
public CultMeshBodyTransportKind TransportKind => CultMeshBodyTransportKind.Network;
|
||||
public byte ReadByte(long offset) { Validate(offset, 1); return _body[(int)offset]; }
|
||||
public int ReadInt32(long offset) { Validate(offset, 4); return BitConverter.ToInt32(_body, (int)offset); }
|
||||
public long ReadInt64(long offset) { Validate(offset, 8); return BitConverter.ToInt64(_body, (int)offset); }
|
||||
public float ReadSingle(long offset) { Validate(offset, 4); return BitConverter.ToSingle(_body, (int)offset); }
|
||||
public double ReadDouble(long offset) { Validate(offset, 8); return BitConverter.ToDouble(_body, (int)offset); }
|
||||
public int CopyTo(long offset, byte[] destination, int destinationOffset, int count)
|
||||
{
|
||||
Validate(offset, count);
|
||||
Buffer.BlockCopy(_body, (int)offset, destination, destinationOffset, count);
|
||||
return count;
|
||||
}
|
||||
public void Dispose() { _body = Array.Empty<byte>(); }
|
||||
private void Validate(long offset, int count)
|
||||
{
|
||||
if (offset < 0 || count < 0 || offset > _body.LongLength - count)
|
||||
throw new ArgumentOutOfRangeException(nameof(offset));
|
||||
}
|
||||
}
|
||||
}
|
||||
363
src/GameCult.Mesh/CultMeshBodyDemand.cs
Normal file
363
src/GameCult.Mesh/CultMeshBodyDemand.cs
Normal file
|
|
@ -0,0 +1,363 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using GameCult.Networking;
|
||||
|
||||
#nullable enable
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Declares one logical body demand. CultMesh owns locality detection and transport selection;
|
||||
/// consumers name the body and the planes they can actually read.
|
||||
/// </summary>
|
||||
public sealed class CultMeshLiveBodySubscription
|
||||
{
|
||||
public CultMeshLiveBodySubscription(
|
||||
string subscriptionId,
|
||||
string consumerRuntimeId,
|
||||
string bodyId)
|
||||
{
|
||||
SubscriptionId = Require(subscriptionId, nameof(subscriptionId));
|
||||
ConsumerRuntimeId = Require(consumerRuntimeId, nameof(consumerRuntimeId));
|
||||
BodyId = Require(bodyId, nameof(bodyId));
|
||||
}
|
||||
|
||||
public string SubscriptionId { get; }
|
||||
public string ConsumerRuntimeId { get; }
|
||||
public string BodyId { get; }
|
||||
public string PublicationRecordKey =>
|
||||
CultMeshBodyPublicationDocument.CreateLatestRecordKey(BodyId).Value;
|
||||
|
||||
private static string Require(string value, string parameterName) =>
|
||||
string.IsNullOrWhiteSpace(value)
|
||||
? throw new ArgumentException("Value is required.", parameterName)
|
||||
: value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One ephemeral body subscription. Publication metadata remains reactive control state while
|
||||
/// body bytes stay on the negotiated body plane.
|
||||
/// </summary>
|
||||
public sealed class CultMeshLiveBody : IDisposable
|
||||
{
|
||||
private readonly CultNetDatabaseSubscriptionClient _owner;
|
||||
private readonly CultMeshBodyPublicationResolver _resolver;
|
||||
private readonly CultMeshLiveBodySubscription _subscription;
|
||||
private readonly object _gate = new();
|
||||
private CultMeshBodyPublicationDocument? _current;
|
||||
private bool _hasValue;
|
||||
private bool _disposed;
|
||||
|
||||
internal CultMeshLiveBody(
|
||||
CultNetDatabaseSubscriptionClient owner,
|
||||
CultMeshBodyPublicationResolver resolver,
|
||||
CultMeshLiveBodySubscription subscription)
|
||||
{
|
||||
_owner = owner ?? throw new ArgumentNullException(nameof(owner));
|
||||
_resolver = resolver ?? throw new ArgumentNullException(nameof(resolver));
|
||||
_subscription = subscription ?? throw new ArgumentNullException(nameof(subscription));
|
||||
_owner.Changed += OnChanged;
|
||||
}
|
||||
|
||||
/// <summary>Raised when the provider publishes a new generation descriptor.</summary>
|
||||
public event Action<CultMeshBodyPublicationDocument>? Changed;
|
||||
|
||||
/// <summary>Raised when the provider withdraws the logical body.</summary>
|
||||
public event Action? Removed;
|
||||
|
||||
public string BodyId => _subscription.BodyId;
|
||||
|
||||
public bool HasValue
|
||||
{
|
||||
get { lock (_gate) return _hasValue; }
|
||||
}
|
||||
|
||||
public CultMeshBodyPublicationDocument Current
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
return _hasValue
|
||||
? _current!
|
||||
: throw new InvalidOperationException(
|
||||
$"Live body '{_subscription.BodyId}' is not currently published.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the current generation read-only using the fastest valid advertised representation.
|
||||
/// The caller owns the returned lease and should dispose it before opening a later generation.
|
||||
/// </summary>
|
||||
public CultMeshBodyNegotiationResult OpenCurrentReadOnly(DateTimeOffset? nowUtc = null)
|
||||
{
|
||||
CultMeshBodyPublicationDocument publication;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshLiveBody));
|
||||
if (!_hasValue)
|
||||
throw new InvalidOperationException(
|
||||
$"Live body '{_subscription.BodyId}' is not currently published.");
|
||||
publication = _current!;
|
||||
}
|
||||
|
||||
return _resolver.NegotiateReadOnly(publication, new CultMeshBodyValidationRequest
|
||||
{
|
||||
BodyId = publication.BodyId,
|
||||
SchemaId = publication.SchemaId,
|
||||
LayoutVersion = publication.LayoutVersion,
|
||||
ProducerEpoch = publication.ProducerEpoch,
|
||||
Sequence = publication.Sequence,
|
||||
Capacity = publication.Capacity,
|
||||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
NowUtc = nowUtc ?? DateTimeOffset.UtcNow
|
||||
});
|
||||
}
|
||||
|
||||
internal void Initialize(CultMeshBodyPublicationDocument publication)
|
||||
{
|
||||
CultMeshBodyPublicationValidator.Validate(publication, expectedBodyId: _subscription.BodyId);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || _hasValue) return;
|
||||
_current = publication;
|
||||
_hasValue = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_current = null;
|
||||
_hasValue = false;
|
||||
}
|
||||
_owner.Changed -= OnChanged;
|
||||
_owner.Unsubscribe(_subscription.SubscriptionId);
|
||||
}
|
||||
|
||||
private void OnChanged(CultNetReplicatedDocumentChange change)
|
||||
{
|
||||
if (!string.Equals(change.SubscriptionId, _subscription.SubscriptionId, StringComparison.Ordinal) ||
|
||||
!string.Equals(change.RecordKey, _subscription.PublicationRecordKey, StringComparison.Ordinal))
|
||||
return;
|
||||
|
||||
if (string.Equals(change.ChangeKind, "removed", StringComparison.Ordinal))
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_current = null;
|
||||
_hasValue = false;
|
||||
}
|
||||
Removed?.Invoke();
|
||||
return;
|
||||
}
|
||||
|
||||
if (change.Document is not CultMeshBodyPublicationDocument publication)
|
||||
return;
|
||||
CultMeshBodyPublicationValidator.Validate(publication, expectedBodyId: _subscription.BodyId);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_current = publication;
|
||||
_hasValue = true;
|
||||
}
|
||||
Changed?.Invoke(publication);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One exact hot-body subscription. The view record, latest-publication record, consumer body
|
||||
/// demand, and locally supported planes are one contract so callers cannot accidentally stream
|
||||
/// body bytes through retained document snapshots.
|
||||
/// </summary>
|
||||
public sealed class CultMeshHotBodySubscription
|
||||
{
|
||||
public CultMeshHotBodySubscription(
|
||||
string subscriptionId,
|
||||
string consumerRuntimeId,
|
||||
string viewRecordKey,
|
||||
string viewSchemaId,
|
||||
string bodyId,
|
||||
IEnumerable<string>? additionalRecordKeys = null,
|
||||
IEnumerable<string>? additionalSchemaIds = null)
|
||||
{
|
||||
SubscriptionId = Require(subscriptionId, nameof(subscriptionId));
|
||||
ConsumerRuntimeId = Require(consumerRuntimeId, nameof(consumerRuntimeId));
|
||||
BodyId = Require(bodyId, nameof(bodyId));
|
||||
RecordKeys = new[]
|
||||
{
|
||||
Require(viewRecordKey, nameof(viewRecordKey)),
|
||||
CultMeshBodyPublicationDocument.CreateLatestRecordKey(bodyId).Value
|
||||
}
|
||||
.Concat(additionalRecordKeys ?? Array.Empty<string>())
|
||||
.Where(value => !string.IsNullOrWhiteSpace(value))
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
SchemaIds = new[]
|
||||
{
|
||||
Require(viewSchemaId, nameof(viewSchemaId)),
|
||||
CultMeshBodyPublicationSchemaVersions.Publication
|
||||
}
|
||||
.Concat(additionalSchemaIds ?? Array.Empty<string>())
|
||||
.Where(value => !string.IsNullOrWhiteSpace(value))
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
public string SubscriptionId { get; }
|
||||
public string ConsumerRuntimeId { get; }
|
||||
public string BodyId { get; }
|
||||
public IReadOnlyList<string> RecordKeys { get; }
|
||||
public IReadOnlyList<string> SchemaIds { get; }
|
||||
|
||||
private static string Require(string value, string parameterName) =>
|
||||
string.IsNullOrWhiteSpace(value)
|
||||
? throw new ArgumentException("Value is required.", parameterName)
|
||||
: value;
|
||||
}
|
||||
|
||||
/// <summary>Derived transport work for one logical hot body.</summary>
|
||||
public sealed class CultMeshBodyDemandPlan
|
||||
{
|
||||
internal CultMeshBodyDemandPlan(
|
||||
string bodyId,
|
||||
IReadOnlyList<CultMeshBodyConsumerRoute> consumers)
|
||||
{
|
||||
BodyId = bodyId;
|
||||
Consumers = consumers;
|
||||
RequiresSharedMemory = consumers.Any(value => value.Transport == CultMeshBodyTransportKind.SharedMemory);
|
||||
RequiresSharedFileMapping = consumers.Any(value => value.Transport == CultMeshBodyTransportKind.SharedFileMapping);
|
||||
RequiresNetwork = consumers.Any(value => value.Transport == CultMeshBodyTransportKind.Network);
|
||||
}
|
||||
|
||||
public string BodyId { get; }
|
||||
public bool HasConsumers => Consumers.Count > 0;
|
||||
public bool RequiresSharedMemory { get; }
|
||||
public bool RequiresSharedFileMapping { get; }
|
||||
public bool RequiresNetwork { get; }
|
||||
public IReadOnlyList<CultMeshBodyConsumerRoute> Consumers { get; }
|
||||
}
|
||||
|
||||
/// <summary>One consumer's owner-derived route for one logical body.</summary>
|
||||
public sealed class CultMeshBodyConsumerRoute
|
||||
{
|
||||
internal CultMeshBodyConsumerRoute(
|
||||
string consumerRuntimeId,
|
||||
string subscriptionId,
|
||||
CultMeshBodyTransportKind transport)
|
||||
{
|
||||
ConsumerRuntimeId = consumerRuntimeId;
|
||||
SubscriptionId = subscriptionId;
|
||||
Transport = transport;
|
||||
}
|
||||
|
||||
public string ConsumerRuntimeId { get; }
|
||||
public string SubscriptionId { get; }
|
||||
public CultMeshBodyTransportKind Transport { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Owns the live projection from exact state subscriptions to required body transport planes.
|
||||
/// A same-machine claim is transport evidence only; shared memory is selected only when both
|
||||
/// the server peer and consumer capability agree.
|
||||
/// </summary>
|
||||
public sealed class CultMeshBodyDemandTracker : IDisposable
|
||||
{
|
||||
private readonly CultNetDatabaseSubscriptionServer? _subscriptions;
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, CultNetDatabaseSubscriptionDemand> _demands =
|
||||
new(StringComparer.Ordinal);
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshBodyDemandTracker(CultNetDatabaseSubscriptionServer subscriptions)
|
||||
{
|
||||
_subscriptions = subscriptions ?? throw new ArgumentNullException(nameof(subscriptions));
|
||||
_subscriptions.DemandChanged += OnDemandChanged;
|
||||
}
|
||||
|
||||
/// <summary>Creates a tracker fed explicitly by a subscription/session control plane.</summary>
|
||||
public CultMeshBodyDemandTracker()
|
||||
{
|
||||
}
|
||||
|
||||
public CultMeshBodyDemandPlan Plan(string bodyId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(bodyId)) throw new ArgumentException("Body identity is required.", nameof(bodyId));
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var routes = _demands.Values
|
||||
.Where(value => value.BodyIds.Contains(bodyId, StringComparer.Ordinal))
|
||||
.Select(value => Route(value))
|
||||
.Where(value => value != null)
|
||||
.Cast<CultMeshBodyConsumerRoute>()
|
||||
.OrderBy(value => value.ConsumerRuntimeId, StringComparer.Ordinal)
|
||||
.ThenBy(value => value.SubscriptionId, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
return new CultMeshBodyDemandPlan(bodyId, routes);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
if (_subscriptions != null) _subscriptions.DemandChanged -= OnDemandChanged;
|
||||
_demands.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Applies one active or withdrawn typed body-demand observation.</summary>
|
||||
public void Observe(CultNetDatabaseSubscriptionDemand demand)
|
||||
{
|
||||
if (demand == null) throw new ArgumentNullException(nameof(demand));
|
||||
if (demand.BodyIds.Count == 0) return;
|
||||
var key = demand.ConsumerRuntimeId + "\u001f" + demand.SubscriptionId;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
if (demand.Active) _demands[key] = demand;
|
||||
else _demands.Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDemandChanged(CultNetDatabaseSubscriptionDemand demand) => Observe(demand);
|
||||
|
||||
private static CultMeshBodyConsumerRoute? Route(CultNetDatabaseSubscriptionDemand demand)
|
||||
{
|
||||
var supported = demand.SupportedBodyTransports;
|
||||
if (demand.SameMachine && Supports(supported, CultMeshBodyTransportKind.SharedMemory))
|
||||
return new CultMeshBodyConsumerRoute(
|
||||
demand.ConsumerRuntimeId,
|
||||
demand.SubscriptionId,
|
||||
CultMeshBodyTransportKind.SharedMemory);
|
||||
if (demand.SameMachine && Supports(supported, CultMeshBodyTransportKind.SharedFileMapping))
|
||||
return new CultMeshBodyConsumerRoute(
|
||||
demand.ConsumerRuntimeId,
|
||||
demand.SubscriptionId,
|
||||
CultMeshBodyTransportKind.SharedFileMapping);
|
||||
if (Supports(supported, CultMeshBodyTransportKind.Network))
|
||||
return new CultMeshBodyConsumerRoute(
|
||||
demand.ConsumerRuntimeId,
|
||||
demand.SubscriptionId,
|
||||
CultMeshBodyTransportKind.Network);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool Supports(
|
||||
IReadOnlyList<string> supported,
|
||||
CultMeshBodyTransportKind transport) =>
|
||||
supported.Any(value => string.Equals(value, transport.ToString(), StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshBodyDemandTracker));
|
||||
}
|
||||
}
|
||||
}
|
||||
201
src/GameCult.Mesh/CultMeshBodyPublications.cs
Normal file
201
src/GameCult.Mesh/CultMeshBodyPublications.cs
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
using System;
|
||||
using System.Globalization;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Networking;
|
||||
using MessagePack;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
public static class CultMeshBodyPublicationSchemaVersions
|
||||
{
|
||||
public const string Publication = "gamecult.mesh.body_publication.v2";
|
||||
}
|
||||
|
||||
public sealed class CultMeshBodyGeneration
|
||||
{
|
||||
public string BodyId { get; set; } = string.Empty;
|
||||
public string ProducerId { get; set; } = string.Empty;
|
||||
public string SchemaId { get; set; } = string.Empty;
|
||||
public int LayoutVersion { get; set; }
|
||||
public int Capacity { get; set; }
|
||||
public long ProducerEpoch { get; set; }
|
||||
public long Sequence { get; set; }
|
||||
public CultMeshBodySynchronization Synchronization { get; set; } = CultMeshBodySynchronization.ImmutableSequence;
|
||||
public long LeaseExpiresAtUnixMs { get; set; }
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[CultDocument("gamecult.mesh.body_publication", CultMeshBodyPublicationSchemaVersions.Publication)]
|
||||
public sealed class CultMeshBodyPublicationDocument
|
||||
{
|
||||
[Key(0), CultName] public string BodyId { get; set; } = string.Empty;
|
||||
[Key(1), CultIndex] public string ProducerId { get; set; } = string.Empty;
|
||||
[Key(2)] public string SchemaId { get; set; } = string.Empty;
|
||||
[Key(3)] public int LayoutVersion { get; set; }
|
||||
[Key(4)] public long ByteSize { get; set; }
|
||||
[Key(5)] public int Capacity { get; set; }
|
||||
[Key(6)] public long ProducerEpoch { get; set; }
|
||||
[Key(7)] public long Sequence { get; set; }
|
||||
[Key(8)] public CultMeshBodySynchronization Synchronization { get; set; }
|
||||
[Key(9)] public long LivenessExpiresAtUnixMs { get; set; }
|
||||
[Key(10)] public CultMeshBodyDescriptor[] Representations { get; set; } = Array.Empty<CultMeshBodyDescriptor>();
|
||||
|
||||
public static CultRecordKey CreateRecordKey(string bodyId, long producerEpoch, long sequence)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(bodyId))
|
||||
throw new ArgumentException("Logical body identity is required.", nameof(bodyId));
|
||||
if (producerEpoch < 0) throw new ArgumentOutOfRangeException(nameof(producerEpoch));
|
||||
if (sequence < 0) throw new ArgumentOutOfRangeException(nameof(sequence));
|
||||
using var stream = new MemoryStream();
|
||||
using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true))
|
||||
{
|
||||
writer.Write(bodyId);
|
||||
writer.Write(producerEpoch);
|
||||
writer.Write(sequence);
|
||||
}
|
||||
using var sha256 = SHA256.Create();
|
||||
var generationId = string.Concat(sha256.ComputeHash(stream.ToArray())
|
||||
.Select(value => value.ToString("x2", CultureInfo.InvariantCulture)));
|
||||
return new CultRecordKey("mesh:body-generation:" + generationId);
|
||||
}
|
||||
|
||||
public static CultRecordKey CreateLatestRecordKey(string bodyId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(bodyId))
|
||||
throw new ArgumentException("Logical body identity is required.", nameof(bodyId));
|
||||
return new CultRecordKey("mesh:body:" + bodyId);
|
||||
}
|
||||
|
||||
[IgnoreMember]
|
||||
public CultRecordKey RecordKey => CreateRecordKey(BodyId, ProducerEpoch, Sequence);
|
||||
}
|
||||
|
||||
public sealed class CultMeshBodyPublicationHandle
|
||||
{
|
||||
public CultMeshBodyPublicationHandle(string bodyId, long producerEpoch, long sequence)
|
||||
{
|
||||
BodyId = string.IsNullOrWhiteSpace(bodyId)
|
||||
? throw new ArgumentException("Logical body identity is required.", nameof(bodyId))
|
||||
: bodyId;
|
||||
ProducerEpoch = producerEpoch >= 0
|
||||
? producerEpoch
|
||||
: throw new ArgumentOutOfRangeException(nameof(producerEpoch));
|
||||
Sequence = sequence >= 0
|
||||
? sequence
|
||||
: throw new ArgumentOutOfRangeException(nameof(sequence));
|
||||
RecordKey = CultMeshBodyPublicationDocument.CreateRecordKey(bodyId, producerEpoch, sequence);
|
||||
}
|
||||
|
||||
public string BodyId { get; }
|
||||
public long ProducerEpoch { get; }
|
||||
public long Sequence { get; }
|
||||
public CultRecordKey RecordKey { get; }
|
||||
|
||||
public void Validate(CultMeshBodyPublicationDocument publication) =>
|
||||
CultMeshBodyPublicationValidator.Validate(publication, BodyId, ProducerEpoch, Sequence, RecordKey);
|
||||
}
|
||||
|
||||
public static class CultMeshBodyPublicationValidator
|
||||
{
|
||||
public static void Validate(
|
||||
CultMeshBodyPublicationDocument publication,
|
||||
string? expectedBodyId = null,
|
||||
long? expectedProducerEpoch = null,
|
||||
long? expectedSequence = null,
|
||||
CultRecordKey? expectedRecordKey = null)
|
||||
{
|
||||
if (publication == null) throw new ArgumentNullException(nameof(publication));
|
||||
if (string.IsNullOrWhiteSpace(publication.BodyId))
|
||||
throw new InvalidOperationException("CultMesh body publication has no logical body identity.");
|
||||
if (expectedBodyId != null && !string.Equals(publication.BodyId, expectedBodyId, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException("CultMesh body publication handle identity mismatch.");
|
||||
if (expectedProducerEpoch.HasValue && publication.ProducerEpoch != expectedProducerEpoch.Value)
|
||||
throw new InvalidOperationException("CultMesh body publication handle producer epoch mismatch.");
|
||||
if (expectedSequence.HasValue && publication.Sequence != expectedSequence.Value)
|
||||
throw new InvalidOperationException("CultMesh body publication handle sequence mismatch.");
|
||||
if (string.IsNullOrWhiteSpace(publication.ProducerId))
|
||||
throw new InvalidOperationException("CultMesh body publication has no producer identity.");
|
||||
if (string.IsNullOrWhiteSpace(publication.SchemaId))
|
||||
throw new InvalidOperationException("CultMesh body publication has no schema identity.");
|
||||
if (publication.LayoutVersion < 0 || publication.ByteSize < 0 || publication.Capacity < 0 ||
|
||||
publication.ProducerEpoch < 0 || publication.Sequence < 0)
|
||||
throw new InvalidOperationException("CultMesh body publication generation values must be non-negative.");
|
||||
if (expectedRecordKey.HasValue && !publication.RecordKey.Equals(expectedRecordKey.Value))
|
||||
throw new InvalidOperationException("CultMesh body publication record key disagrees with its generation envelope.");
|
||||
var representations = publication.Representations ?? Array.Empty<CultMeshBodyDescriptor>();
|
||||
if (representations.Length == 0)
|
||||
throw new InvalidOperationException("CultMesh body publication has no transport representations.");
|
||||
if (representations.Select(value => value?.TransportKind).Distinct().Count() != representations.Length)
|
||||
throw new InvalidOperationException("CultMesh body publication advertises the same transport representation more than once.");
|
||||
foreach (var representation in representations)
|
||||
ValidateDescriptor(publication, representation, representation?.TransportKind.ToString() ?? "missing");
|
||||
}
|
||||
|
||||
private static void ValidateDescriptor(
|
||||
CultMeshBodyPublicationDocument publication,
|
||||
CultMeshBodyDescriptor descriptor,
|
||||
string label)
|
||||
{
|
||||
if (descriptor == null)
|
||||
throw new InvalidOperationException($"CultMesh body publication has no {label} descriptor.");
|
||||
if (!string.Equals(descriptor.BodyId, publication.BodyId, StringComparison.Ordinal) ||
|
||||
!string.Equals(descriptor.SchemaId, publication.SchemaId, StringComparison.Ordinal) ||
|
||||
descriptor.LayoutVersion != publication.LayoutVersion ||
|
||||
descriptor.ByteSize != publication.ByteSize ||
|
||||
descriptor.Capacity != publication.Capacity ||
|
||||
descriptor.ProducerEpoch != publication.ProducerEpoch ||
|
||||
descriptor.Sequence != publication.Sequence ||
|
||||
descriptor.Synchronization != publication.Synchronization ||
|
||||
descriptor.LeaseExpiresAtUnixMs != publication.LivenessExpiresAtUnixMs)
|
||||
throw new InvalidOperationException($"CultMesh {label} descriptor disagrees with its publication envelope.");
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshBodyPublicationResolver
|
||||
{
|
||||
private readonly CultMeshBodyTransportService _transport;
|
||||
|
||||
public CultMeshBodyPublicationResolver(CultMeshBodyTransportService transport) =>
|
||||
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
||||
|
||||
/// <summary>Gets the body planes this resolver can actually open.</summary>
|
||||
public IReadOnlyList<CultMeshBodyTransportKind> SupportedTransports => _transport.SupportedTransports;
|
||||
|
||||
public ICultMeshBodyReadLease ResolveReadOnly(
|
||||
CultMeshBodyPublicationDocument publication,
|
||||
CultMeshBodyValidationRequest request) =>
|
||||
NegotiateReadOnly(publication, request).Lease;
|
||||
|
||||
public CultMeshBodyNegotiationResult NegotiateReadOnly(
|
||||
CultMeshBodyPublicationDocument publication,
|
||||
CultMeshBodyValidationRequest request)
|
||||
{
|
||||
CultMeshBodyPublicationValidator.Validate(publication);
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
if (publication.LivenessExpiresAtUnixMs <= request.NowUtc.ToUnixTimeMilliseconds())
|
||||
throw new InvalidOperationException("CultMesh body publication is no longer live.");
|
||||
return _transport.NegotiateReadOnly(
|
||||
publication.ProducerId,
|
||||
publication.Representations,
|
||||
request);
|
||||
}
|
||||
}
|
||||
|
||||
public static partial class CultMesh
|
||||
{
|
||||
public static CultNetDocumentRegistry CreateBodyPublicationDocumentRegistry(
|
||||
CultDocumentRegistry? documents = null)
|
||||
{
|
||||
documents ??= CultDocumentRegistry.Shared;
|
||||
return new CultNetDocumentRegistry(documents)
|
||||
.Register(CultNetDocumentBinding.ForDocument<CultMeshBodyPublicationDocument>(documents))
|
||||
.Register(CultNetDocumentBinding.ForDocument<CultMeshCdnArtifactManifest>(documents))
|
||||
.Register(CultNetDocumentBinding.ForDocument<CultMeshCdnArtifactChunk>(documents));
|
||||
}
|
||||
}
|
||||
}
|
||||
342
src/GameCult.Mesh/CultMeshBodySessions.cs
Normal file
342
src/GameCult.Mesh/CultMeshBodySessions.cs
Normal file
|
|
@ -0,0 +1,342 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Networking;
|
||||
|
||||
#nullable enable
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Owns a bounded set of immutable network body generations. This is ephemeral transport state,
|
||||
/// not a CultCache document store and not world truth.
|
||||
/// </summary>
|
||||
public sealed class CultMeshNetworkBodyStore : IDisposable
|
||||
{
|
||||
public const long DefaultMaximumBodyBytes = 16L * 1024L * 1024L;
|
||||
public const int DefaultRetainedGenerations = 8;
|
||||
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, Entry> _entries = new(StringComparer.Ordinal);
|
||||
private readonly byte[] _capabilitySecret = new byte[32];
|
||||
private readonly long _maximumBodyBytes;
|
||||
private readonly int _retainedGenerations;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshNetworkBodyStore(
|
||||
long maximumBodyBytes = DefaultMaximumBodyBytes,
|
||||
int retainedGenerations = DefaultRetainedGenerations)
|
||||
{
|
||||
if (maximumBodyBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maximumBodyBytes));
|
||||
if (retainedGenerations <= 0) throw new ArgumentOutOfRangeException(nameof(retainedGenerations));
|
||||
_maximumBodyBytes = maximumBodyBytes;
|
||||
_retainedGenerations = retainedGenerations;
|
||||
using var random = RandomNumberGenerator.Create();
|
||||
random.GetBytes(_capabilitySecret);
|
||||
}
|
||||
|
||||
public CultMeshBodyDescriptor Publish(CultMeshBodyGeneration generation, ReadOnlySpan<byte> body)
|
||||
{
|
||||
return PublishCore(generation, body.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a body buffer by transferring its ownership to the ephemeral store. The caller
|
||||
/// must not mutate the array after this call; this avoids an extra full-frame copy.
|
||||
/// </summary>
|
||||
public CultMeshBodyDescriptor PublishOwned(CultMeshBodyGeneration generation, byte[] body)
|
||||
{
|
||||
if (body == null) throw new ArgumentNullException(nameof(body));
|
||||
return PublishCore(generation, body);
|
||||
}
|
||||
|
||||
private CultMeshBodyDescriptor PublishCore(CultMeshBodyGeneration generation, byte[] bytes)
|
||||
{
|
||||
ValidateGeneration(generation);
|
||||
if (bytes.LongLength > _maximumBodyBytes)
|
||||
throw new InvalidOperationException(
|
||||
$"CultMesh network body exceeds the configured {_maximumBodyBytes}-byte live-body bound.");
|
||||
|
||||
var hash = CultMeshBodyDescriptorValidator.ComputeSemanticHash(bytes);
|
||||
var token = CapabilityToken(generation);
|
||||
var descriptor = new CultMeshBodyDescriptor
|
||||
{
|
||||
BodyId = generation.BodyId,
|
||||
SchemaId = generation.SchemaId,
|
||||
LayoutVersion = generation.LayoutVersion,
|
||||
ByteSize = bytes.LongLength,
|
||||
Capacity = generation.Capacity,
|
||||
ProducerEpoch = generation.ProducerEpoch,
|
||||
Sequence = generation.Sequence,
|
||||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
Synchronization = generation.Synchronization,
|
||||
LeaseExpiresAtUnixMs = generation.LeaseExpiresAtUnixMs,
|
||||
TransportKind = CultMeshBodyTransportKind.Network,
|
||||
CapabilityToken = token,
|
||||
SemanticHash = hash
|
||||
};
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
PruneExpired(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
|
||||
if (_entries.TryGetValue(token, out var existing))
|
||||
{
|
||||
if (!SameDescriptor(existing.Descriptor, descriptor) ||
|
||||
!string.Equals(existing.Descriptor.SemanticHash, hash, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException("CultMesh network body generation is immutable.");
|
||||
Array.Clear(bytes, 0, bytes.Length);
|
||||
return Clone(existing.Descriptor);
|
||||
}
|
||||
|
||||
_entries.Add(token, new Entry(Clone(descriptor), bytes));
|
||||
TrimOldest();
|
||||
return descriptor;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryRead(CultMeshBodyReadRequestMessage request, DateTimeOffset nowUtc, out CultMeshBodyDescriptor descriptor, out byte[] body)
|
||||
{
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
PruneExpired(nowUtc.ToUnixTimeMilliseconds());
|
||||
if (!_entries.TryGetValue(request.CapabilityToken ?? string.Empty, out var entry) ||
|
||||
!MatchesRequest(entry.Descriptor, request))
|
||||
{
|
||||
descriptor = new CultMeshBodyDescriptor();
|
||||
body = Array.Empty<byte>();
|
||||
return false;
|
||||
}
|
||||
descriptor = Clone(entry.Descriptor);
|
||||
body = (byte[])entry.Body.Clone();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
foreach (var entry in _entries.Values) Array.Clear(entry.Body, 0, entry.Body.Length);
|
||||
_entries.Clear();
|
||||
Array.Clear(_capabilitySecret, 0, _capabilitySecret.Length);
|
||||
}
|
||||
}
|
||||
|
||||
private string CapabilityToken(CultMeshBodyGeneration generation)
|
||||
{
|
||||
var input = Encoding.UTF8.GetBytes(string.Join("\u001f", generation.ProducerId, generation.BodyId,
|
||||
generation.ProducerEpoch, generation.Sequence));
|
||||
using var hmac = new HMACSHA256(_capabilitySecret);
|
||||
return string.Concat(hmac.ComputeHash(input).Select(value => value.ToString("x2")));
|
||||
}
|
||||
|
||||
private void PruneExpired(long nowUnixMs)
|
||||
{
|
||||
foreach (var key in _entries.Where(pair => pair.Value.Descriptor.LeaseExpiresAtUnixMs <= nowUnixMs)
|
||||
.Select(pair => pair.Key).ToArray())
|
||||
Remove(key);
|
||||
}
|
||||
|
||||
private void TrimOldest()
|
||||
{
|
||||
while (_entries.Count > _retainedGenerations)
|
||||
{
|
||||
var oldest = _entries.OrderBy(pair => pair.Value.Descriptor.ProducerEpoch)
|
||||
.ThenBy(pair => pair.Value.Descriptor.Sequence)
|
||||
.First().Key;
|
||||
Remove(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
private void Remove(string token)
|
||||
{
|
||||
if (!_entries.Remove(token, out var removed)) return;
|
||||
Array.Clear(removed.Body, 0, removed.Body.Length);
|
||||
}
|
||||
|
||||
private static bool MatchesRequest(CultMeshBodyDescriptor descriptor, CultMeshBodyReadRequestMessage request) =>
|
||||
string.Equals(descriptor.CapabilityToken, request.CapabilityToken, StringComparison.Ordinal) &&
|
||||
string.Equals(descriptor.BodyId, request.BodyId, StringComparison.Ordinal) &&
|
||||
string.Equals(descriptor.SchemaId, request.BodySchemaId, StringComparison.Ordinal) &&
|
||||
descriptor.LayoutVersion == request.LayoutVersion &&
|
||||
descriptor.ProducerEpoch == request.ProducerEpoch && descriptor.Sequence == request.Sequence &&
|
||||
descriptor.ByteSize == request.ExpectedSizeBytes &&
|
||||
string.Equals(descriptor.SemanticHash, request.SemanticHash, StringComparison.Ordinal);
|
||||
|
||||
private static bool SameDescriptor(CultMeshBodyDescriptor left, CultMeshBodyDescriptor right) =>
|
||||
left.BodyId == right.BodyId && left.SchemaId == right.SchemaId &&
|
||||
left.LayoutVersion == right.LayoutVersion && left.ByteSize == right.ByteSize &&
|
||||
left.Capacity == right.Capacity && left.ProducerEpoch == right.ProducerEpoch &&
|
||||
left.Sequence == right.Sequence && left.Synchronization == right.Synchronization &&
|
||||
left.LeaseExpiresAtUnixMs == right.LeaseExpiresAtUnixMs;
|
||||
|
||||
private static CultMeshBodyDescriptor Clone(CultMeshBodyDescriptor value) => new()
|
||||
{
|
||||
BodyId = value.BodyId, SchemaId = value.SchemaId, LayoutVersion = value.LayoutVersion,
|
||||
ByteSize = value.ByteSize, Capacity = value.Capacity, ProducerEpoch = value.ProducerEpoch,
|
||||
Sequence = value.Sequence, AccessMode = value.AccessMode, Synchronization = value.Synchronization,
|
||||
LeaseExpiresAtUnixMs = value.LeaseExpiresAtUnixMs, TransportKind = value.TransportKind,
|
||||
CapabilityToken = value.CapabilityToken, SemanticHash = value.SemanticHash
|
||||
};
|
||||
|
||||
private static void ValidateGeneration(CultMeshBodyGeneration generation)
|
||||
{
|
||||
if (generation == null) throw new ArgumentNullException(nameof(generation));
|
||||
if (string.IsNullOrWhiteSpace(generation.BodyId) || string.IsNullOrWhiteSpace(generation.ProducerId) ||
|
||||
string.IsNullOrWhiteSpace(generation.SchemaId))
|
||||
throw new ArgumentException("Body, producer, and schema identities are required.", nameof(generation));
|
||||
if (generation.LayoutVersion < 0 || generation.Capacity < 0 || generation.ProducerEpoch < 0 ||
|
||||
generation.Sequence < 0 || generation.LeaseExpiresAtUnixMs <= 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(generation));
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshNetworkBodyStore));
|
||||
}
|
||||
|
||||
private sealed class Entry
|
||||
{
|
||||
public Entry(CultMeshBodyDescriptor descriptor, byte[] body) { Descriptor = descriptor; Body = body; }
|
||||
public CultMeshBodyDescriptor Descriptor { get; }
|
||||
public byte[] Body { get; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Serves capability-bound live bodies directly over an existing CultNet host.</summary>
|
||||
public sealed class CultMeshBodyServer : IDisposable
|
||||
{
|
||||
private readonly ICultNetSchemaServer _server;
|
||||
private readonly CultMeshNetworkBodyStore _bodies;
|
||||
private readonly Func<CultMeshBodyReadRequestMessage, ICultNetSchemaServerPeer, Task> _handler;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshBodyServer(ICultNetSchemaServer server, CultMeshNetworkBodyStore bodies)
|
||||
{
|
||||
_server = server ?? throw new ArgumentNullException(nameof(server));
|
||||
_bodies = bodies ?? throw new ArgumentNullException(nameof(bodies));
|
||||
_handler = HandleAsync;
|
||||
_server.OnCultNet(_handler);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_server.RemoveCultNetMessageListener<CultMeshBodyReadRequestMessage>(_handler);
|
||||
}
|
||||
|
||||
private Task HandleAsync(CultMeshBodyReadRequestMessage request, ICultNetSchemaServerPeer peer)
|
||||
{
|
||||
var response = new CultMeshBodyReadResponseMessage
|
||||
{
|
||||
MessageId = request?.MessageId ?? string.Empty,
|
||||
CapabilityToken = request?.CapabilityToken ?? string.Empty
|
||||
};
|
||||
try
|
||||
{
|
||||
if (request == null || string.IsNullOrWhiteSpace(request.MessageId))
|
||||
throw new InvalidDataException("Body read request requires a message identity.");
|
||||
if (!_bodies.TryRead(request, DateTimeOffset.UtcNow, out var descriptor, out var bytes))
|
||||
throw new FileNotFoundException("Body capability is unavailable or does not match its generation.");
|
||||
response.Found = true;
|
||||
response.BodyId = descriptor.BodyId;
|
||||
response.ProducerEpoch = descriptor.ProducerEpoch;
|
||||
response.Sequence = descriptor.Sequence;
|
||||
response.SizeBytes = descriptor.ByteSize;
|
||||
response.SemanticHash = descriptor.SemanticHash;
|
||||
response.Payload = bytes;
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
response.Found = false;
|
||||
response.Error = error.GetType().Name + ": " + error.Message;
|
||||
response.Payload = Array.Empty<byte>();
|
||||
}
|
||||
peer.SendCultNet(response);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshSessionBodyProviderOptions
|
||||
{
|
||||
public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance;
|
||||
public TimeSpan ResponseTimeout { get; set; } = TimeSpan.FromSeconds(2);
|
||||
}
|
||||
|
||||
/// <summary>Reads live body generations through one reusable identity-first body session.</summary>
|
||||
public sealed class CultMeshSessionBodyProvider
|
||||
{
|
||||
private readonly CultMeshSessionManager _sessions;
|
||||
private readonly CultMeshEndpointId _endpointId;
|
||||
private readonly CultMeshSessionBodyProviderOptions _options;
|
||||
|
||||
public CultMeshSessionBodyProvider(string providerId, CultMeshSessionManager sessions,
|
||||
CultMeshEndpointId endpointId, CultMeshSessionBodyProviderOptions? options = null)
|
||||
{
|
||||
ProviderId = string.IsNullOrWhiteSpace(providerId) ? throw new ArgumentException("Provider identity is required.", nameof(providerId)) : providerId;
|
||||
_sessions = sessions ?? throw new ArgumentNullException(nameof(sessions));
|
||||
_endpointId = endpointId ?? throw new ArgumentNullException(nameof(endpointId));
|
||||
_options = options ?? new CultMeshSessionBodyProviderOptions();
|
||||
if (_options.ResponseTimeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(options));
|
||||
}
|
||||
|
||||
public string ProviderId { get; }
|
||||
public Func<CultMeshBodyDescriptor, byte[]> CreateFetchDelegate() =>
|
||||
descriptor => FetchAsync(descriptor).GetAwaiter().GetResult();
|
||||
|
||||
public async Task<byte[]> FetchAsync(CultMeshBodyDescriptor descriptor, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (descriptor == null) throw new ArgumentNullException(nameof(descriptor));
|
||||
if (descriptor.TransportKind != CultMeshBodyTransportKind.Network)
|
||||
throw new NotSupportedException("Direct body provider requires a network descriptor.");
|
||||
var session = await _sessions.ConnectAsync(_endpointId, CultMeshProtocols.Bodies, cancellationToken).ConfigureAwait(false);
|
||||
var messageId = Guid.NewGuid().ToString("N");
|
||||
var completion = new TaskCompletionSource<CultMeshBodyReadResponseMessage>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var responseSubscription = session.OnCultNet<CultMeshBodyReadResponseMessage>(response =>
|
||||
{
|
||||
if (string.Equals(response.MessageId, messageId, StringComparison.Ordinal)) completion.TrySetResult(response);
|
||||
});
|
||||
using var errorSubscription = session.OnCultNet<CultNetErrorMessage>(error => completion.TrySetException(new IOException(error.Error)));
|
||||
session.SendCultNet(new CultMeshBodyReadRequestMessage
|
||||
{
|
||||
MessageId = messageId, CapabilityToken = descriptor.CapabilityToken, BodyId = descriptor.BodyId,
|
||||
BodySchemaId = descriptor.SchemaId, LayoutVersion = descriptor.LayoutVersion,
|
||||
ProducerEpoch = descriptor.ProducerEpoch, Sequence = descriptor.Sequence,
|
||||
ExpectedSizeBytes = descriptor.ByteSize, SemanticHash = descriptor.SemanticHash
|
||||
});
|
||||
var response = await WaitAsync(completion.Task, cancellationToken).ConfigureAwait(false);
|
||||
if (!response.Found) throw new FileNotFoundException(
|
||||
$"Body provider '{ProviderId}' rejected '{descriptor.BodyId}' generation {descriptor.Sequence}: {response.Error}");
|
||||
var body = response.Payload ?? Array.Empty<byte>();
|
||||
if (!string.Equals(response.CapabilityToken, descriptor.CapabilityToken, StringComparison.Ordinal) ||
|
||||
!string.Equals(response.BodyId, descriptor.BodyId, StringComparison.Ordinal) ||
|
||||
response.ProducerEpoch != descriptor.ProducerEpoch || response.Sequence != descriptor.Sequence ||
|
||||
response.SizeBytes != descriptor.ByteSize || body.LongLength != descriptor.ByteSize ||
|
||||
!string.Equals(response.SemanticHash, descriptor.SemanticHash, StringComparison.Ordinal) ||
|
||||
!string.Equals(CultMeshBodyDescriptorValidator.ComputeSemanticHash(body), descriptor.SemanticHash, StringComparison.Ordinal))
|
||||
throw new InvalidDataException("Direct body response disagrees with its advertised generation.");
|
||||
return body;
|
||||
}
|
||||
|
||||
private async Task<CultMeshBodyReadResponseMessage> WaitAsync(Task<CultMeshBodyReadResponseMessage> response, CancellationToken cancellationToken)
|
||||
{
|
||||
using var deadlineCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
var deadline = _options.Clock.DelayAsync(_options.ResponseTimeout, deadlineCancellation.Token);
|
||||
var completed = await Task.WhenAny(response, deadline).ConfigureAwait(false);
|
||||
if (completed == response) { deadlineCancellation.Cancel(); return await response.ConfigureAwait(false); }
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
throw new TimeoutException($"Timed out fetching live body from provider '{ProviderId}'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -42,7 +42,7 @@ namespace GameCult.Mesh
|
|||
public sealed class CultMeshCdnPackOptions
|
||||
{
|
||||
/// <summary>Default CDN chunk size.</summary>
|
||||
public const int DefaultChunkSizeBytes = 256 * 1024;
|
||||
public const int DefaultChunkSizeBytes = 4 * 1024 * 1024;
|
||||
|
||||
/// <summary>Maximum bytes per content chunk.</summary>
|
||||
public int ChunkSizeBytes { get; set; } = DefaultChunkSizeBytes;
|
||||
|
|
@ -364,6 +364,10 @@ namespace GameCult.Mesh
|
|||
if (manifest == null) throw new ArgumentNullException(nameof(manifest));
|
||||
|
||||
ValidateManifestShape(manifest);
|
||||
if (manifest.SizeBytes > int.MaxValue)
|
||||
{
|
||||
throw new InvalidDataException("CDN artifact is too large to materialize into one byte array.");
|
||||
}
|
||||
var output = new byte[checked((int)manifest.SizeBytes)];
|
||||
foreach (var reference in manifest.Chunks.OrderBy(chunk => chunk.Offset))
|
||||
{
|
||||
|
|
@ -395,26 +399,21 @@ namespace GameCult.Mesh
|
|||
if (database == null) throw new ArgumentNullException(nameof(database));
|
||||
if (manifest == null) throw new ArgumentNullException(nameof(manifest));
|
||||
|
||||
ValidateManifestShape(manifest);
|
||||
var output = new byte[checked((int)manifest.SizeBytes)];
|
||||
foreach (var reference in manifest.Chunks.OrderBy(chunk => chunk.Offset))
|
||||
var directory = Path.Combine(Path.GetTempPath(), "cultmesh-content", Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
var recordKey = string.IsNullOrWhiteSpace(reference.RecordKey)
|
||||
? CultMeshCdnArtifactChunk.CreateRecordKey(reference.ChunkHash)
|
||||
: new CultRecordKey(reference.RecordKey);
|
||||
var chunk = await database.GetAsync<CultMeshCdnArtifactChunk>(recordKey).ConfigureAwait(false)
|
||||
?? throw new FileNotFoundException("CDN artifact chunk is missing from the database.", recordKey.Value);
|
||||
ValidateChunk(reference, chunk);
|
||||
Buffer.BlockCopy(chunk.Payload, 0, output, checked((int)reference.Offset), reference.SizeBytes);
|
||||
using var state = new CultCache();
|
||||
var service = new CultMeshContentTransferService(
|
||||
state,
|
||||
new[] { new CultMeshDatabaseContentProvider("legacy-database", database) },
|
||||
new CultMeshContentTransferOptions(directory));
|
||||
var path = await service.FetchAsync(manifest).ConfigureAwait(false);
|
||||
return await File.ReadAllBytesAsync(path).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var actualHash = HashBytes(output);
|
||||
if (!string.Equals(NormalizeHash(manifest.ContentHash, nameof(manifest.ContentHash)), actualHash, StringComparison.Ordinal))
|
||||
finally
|
||||
{
|
||||
throw new InvalidDataException("CDN artifact content hash does not match its manifest.");
|
||||
if (Directory.Exists(directory)) Directory.Delete(directory, true);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -492,6 +491,11 @@ namespace GameCult.Mesh
|
|||
}
|
||||
}
|
||||
|
||||
internal static void ValidateManifest(CultMeshCdnArtifactManifest manifest)
|
||||
{
|
||||
ValidateManifestShape(manifest);
|
||||
}
|
||||
|
||||
private static void ValidateManifestShape(CultMeshCdnArtifactManifest manifest)
|
||||
{
|
||||
if (manifest.SizeBytes < 0)
|
||||
|
|
@ -499,11 +503,6 @@ namespace GameCult.Mesh
|
|||
throw new InvalidDataException("CDN artifact manifest has a negative size.");
|
||||
}
|
||||
|
||||
if (manifest.SizeBytes > int.MaxValue)
|
||||
{
|
||||
throw new InvalidDataException("CDN artifact is too large to materialize into one byte array.");
|
||||
}
|
||||
|
||||
var expectedOffset = 0L;
|
||||
foreach (var reference in manifest.Chunks.OrderBy(chunk => chunk.Offset))
|
||||
{
|
||||
|
|
@ -526,6 +525,11 @@ namespace GameCult.Mesh
|
|||
}
|
||||
}
|
||||
|
||||
internal static void ValidateChunkPayload(CultMeshCdnChunkRef reference, CultMeshCdnArtifactChunk chunk)
|
||||
{
|
||||
ValidateChunk(reference, chunk);
|
||||
}
|
||||
|
||||
private static void ValidateChunk(CultMeshCdnChunkRef reference, CultMeshCdnArtifactChunk chunk)
|
||||
{
|
||||
if (chunk.Payload.Length != reference.SizeBytes ||
|
||||
|
|
|
|||
604
src/GameCult.Mesh/CultMeshClient.cs
Normal file
604
src/GameCult.Mesh/CultMeshClient.cs
Normal file
|
|
@ -0,0 +1,604 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Networking;
|
||||
using R3;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>Configures one application-lifetime CultMesh client.</summary>
|
||||
public sealed class CultMeshClientOptions
|
||||
{
|
||||
/// <summary>Gets or sets the rendezvous endpoints used to bootstrap stable identities.</summary>
|
||||
public IReadOnlyList<string> RendezvousEndpoints { get; set; } = Array.Empty<string>();
|
||||
|
||||
/// <summary>Gets or sets Verse discovery transport and persistence options.</summary>
|
||||
public CultMeshVerseDiscoveryClientOptions Discovery { get; set; } = new();
|
||||
|
||||
/// <summary>Gets or sets session path and diagnostic policy.</summary>
|
||||
public CultMeshSessionManagerOptions Sessions { get; set; } = new();
|
||||
|
||||
/// <summary>Gets or sets schema connectors. Length-prefixed TCP is used by default.</summary>
|
||||
public IReadOnlyList<ICultMeshTransportConnector>? Connectors { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets streaming content connectors. TCP content delivery is used by default;
|
||||
/// applications may replace it or explicitly add legacy RUDP.
|
||||
/// </summary>
|
||||
public IReadOnlyList<ICultMeshContentTransportConnector>? ContentConnectors { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets realtime state connectors. No connector is installed implicitly;
|
||||
/// promoted runtimes should register QUIC and may explicitly add a legacy fallback.
|
||||
/// </summary>
|
||||
public IReadOnlyList<ICultMeshRealtimeTransportConnector> RealtimeConnectors { get; set; } =
|
||||
Array.Empty<ICultMeshRealtimeTransportConnector>();
|
||||
|
||||
/// <summary>Gets or sets the deadline before an unanswered subscription intent is replayed.</summary>
|
||||
public TimeSpan SubscriptionResponseTimeout { get; set; } = TimeSpan.FromSeconds(2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Owns discovery and reusable sessions for one application lifetime.
|
||||
/// Applications address stable identities; CultMesh owns physical routes and reconnection.
|
||||
/// </summary>
|
||||
public sealed class CultMeshClient : IDisposable
|
||||
{
|
||||
private readonly CultMeshDiscoveryService _discovery;
|
||||
private readonly CultMeshSessionManager _sessions;
|
||||
private readonly TimeSpan _subscriptionResponseTimeout;
|
||||
private readonly ConcurrentDictionary<string, Lazy<Task<object>>> _documents = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, Lazy<Task<object>>> _collections = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentBag<IDisposable> _documentResources = new();
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshClient(CultMeshClientOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
if (options.SubscriptionResponseTimeout <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(options.SubscriptionResponseTimeout));
|
||||
var endpoints = options.RendezvousEndpoints
|
||||
.Where(endpoint => !string.IsNullOrWhiteSpace(endpoint))
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
if (endpoints.Length == 0)
|
||||
throw new ArgumentException("At least one CultMesh rendezvous endpoint is required.", nameof(options));
|
||||
|
||||
var discoveryClient = new CultMeshVerseDiscoveryClient(options.Discovery);
|
||||
_discovery = new CultMeshDiscoveryService(
|
||||
endpoints.Select(endpoint => new RendezvousLookupSource(endpoint, discoveryClient, options.Discovery)),
|
||||
new CultMeshDiscoveryServiceOptions
|
||||
{
|
||||
Clock = options.Discovery.Clock,
|
||||
Diagnostics = options.Discovery.Diagnostics,
|
||||
Store = options.Discovery.DiscoveryStore
|
||||
});
|
||||
_sessions = new CultMeshSessionManager(
|
||||
_discovery,
|
||||
options.Connectors ?? new ICultMeshTransportConnector[]
|
||||
{
|
||||
new CultMeshTcpSchemaTransportConnector(clock: options.Sessions.Clock)
|
||||
},
|
||||
options.ContentConnectors ?? new ICultMeshContentTransportConnector[]
|
||||
{
|
||||
new CultMeshTcpContentTransportConnector()
|
||||
},
|
||||
options.RealtimeConnectors,
|
||||
options.Sessions);
|
||||
_subscriptionResponseTimeout = options.SubscriptionResponseTimeout;
|
||||
}
|
||||
|
||||
/// <summary>Connects to a stable endpoint identity using one application protocol.</summary>
|
||||
public Task<CultMeshSession> ConnectAsync(
|
||||
string endpointId,
|
||||
CultMeshProtocolId protocol,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return _sessions.ConnectAsync(CultMeshEndpointId.Parse(endpointId), protocol, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Connects the reusable realtime state plane by stable endpoint identity.</summary>
|
||||
public Task<CultMeshRealtimeSession> ConnectRealtimeAsync(
|
||||
string endpointId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return _sessions.ConnectRealtimeAsync(CultMeshEndpointId.Parse(endpointId), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Connects to a stable endpoint identity using one application protocol.</summary>
|
||||
public Task<CultMeshSession> ConnectAsync(
|
||||
CultMeshEndpointId endpointId,
|
||||
CultMeshProtocolId protocol,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return _sessions.ConnectAsync(endpointId, protocol, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Creates a verified-transfer provider over this client's reusable content session owner.</summary>
|
||||
public CultMeshSessionContentProvider ContentProvider(
|
||||
string providerId,
|
||||
string endpointId)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return new CultMeshSessionContentProvider(
|
||||
providerId,
|
||||
_sessions,
|
||||
CultMeshEndpointId.Parse(endpointId));
|
||||
}
|
||||
|
||||
/// <summary>Creates a direct body provider over this client's reusable negotiated session owner.</summary>
|
||||
public CultMeshSessionBodyProvider BodyProvider(
|
||||
string providerId,
|
||||
string endpointId,
|
||||
CultMeshSessionBodyProviderOptions? options = null)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return new CultMeshSessionBodyProvider(
|
||||
providerId,
|
||||
_sessions,
|
||||
CultMeshEndpointId.Parse(endpointId),
|
||||
options);
|
||||
}
|
||||
|
||||
/// <summary>Opens one live typed document by stable provider identity and record key.</summary>
|
||||
public async Task<CultMeshDocumentHandle<TDocument>> DocumentAsync<TDocument>(
|
||||
string endpointId,
|
||||
string recordKey,
|
||||
CancellationToken cancellationToken = default)
|
||||
where TDocument : class
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId));
|
||||
if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Record key is required.", nameof(recordKey));
|
||||
var key = endpointId.Trim() + "\u001f" + typeof(TDocument).AssemblyQualifiedName + "\u001f" + recordKey.Trim();
|
||||
var lazy = _documents.GetOrAdd(key, _ => new Lazy<Task<object>>(
|
||||
async () => await OpenDocumentAsync<TDocument>(endpointId.Trim(), recordKey.Trim()).ConfigureAwait(false),
|
||||
LazyThreadSafetyMode.ExecutionAndPublication));
|
||||
try
|
||||
{
|
||||
var binding = (RemoteDocumentBinding<TDocument>)await AwaitForCallerAsync(lazy.Value, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return binding.Handle;
|
||||
}
|
||||
catch
|
||||
{
|
||||
_documents.TryRemove(key, out _);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Opens a live collection of one typed schema by stable provider identity.</summary>
|
||||
public Task<CultMeshCollectionHandle<TDocument>> CollectionAsync<TDocument>(
|
||||
string endpointId,
|
||||
CancellationToken cancellationToken)
|
||||
where TDocument : class =>
|
||||
CollectionAsync<TDocument>(endpointId, includeInitialSnapshot: true, cancellationToken);
|
||||
|
||||
/// <summary>Opens a live collection and optionally skips replaying its initial snapshot.</summary>
|
||||
public async Task<CultMeshCollectionHandle<TDocument>> CollectionAsync<TDocument>(
|
||||
string endpointId,
|
||||
bool includeInitialSnapshot = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
where TDocument : class
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId));
|
||||
var identity = endpointId.Trim();
|
||||
var key = identity + "\u001f" + typeof(TDocument).AssemblyQualifiedName + "\u001f" + includeInitialSnapshot;
|
||||
var lazy = _collections.GetOrAdd(key, _ => new Lazy<Task<object>>(
|
||||
async () => await OpenCollectionAsync<TDocument>(identity, includeInitialSnapshot).ConfigureAwait(false),
|
||||
LazyThreadSafetyMode.ExecutionAndPublication));
|
||||
try
|
||||
{
|
||||
var binding = (RemoteCollectionBinding<TDocument>)await AwaitForCallerAsync(lazy.Value, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return binding.Handle;
|
||||
}
|
||||
catch
|
||||
{
|
||||
_collections.TryRemove(key, out _);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads one typed record once through the reusable document session.</summary>
|
||||
public async Task<TDocument> ReadAsync<TDocument>(
|
||||
string endpointId,
|
||||
string recordKey,
|
||||
CancellationToken cancellationToken = default)
|
||||
where TDocument : class
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId));
|
||||
if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Record key is required.", nameof(recordKey));
|
||||
var documents = await ReadManyAsync<TDocument>(endpointId, new[] { recordKey }, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return documents.FirstOrDefault()
|
||||
?? throw new InvalidOperationException(
|
||||
$"CultMesh endpoint '{endpointId}' did not publish {typeof(TDocument).FullName} record '{recordKey}'.");
|
||||
}
|
||||
|
||||
/// <summary>Reads one typed record once with an explicit response deadline.</summary>
|
||||
public async Task<TDocument> ReadAsync<TDocument>(
|
||||
string endpointId,
|
||||
string recordKey,
|
||||
TimeSpan responseTimeout,
|
||||
CancellationToken cancellationToken = default)
|
||||
where TDocument : class
|
||||
{
|
||||
var documents = await ReadManyCoreAsync<TDocument>(
|
||||
endpointId,
|
||||
new[] { recordKey },
|
||||
responseTimeout,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return documents.FirstOrDefault()
|
||||
?? throw new InvalidOperationException(
|
||||
$"CultMesh endpoint '{endpointId}' did not publish {typeof(TDocument).FullName} record '{recordKey}'.");
|
||||
}
|
||||
|
||||
/// <summary>Reads typed records once in one request through the reusable document session.</summary>
|
||||
public async Task<IReadOnlyList<TDocument>> ReadManyAsync<TDocument>(
|
||||
string endpointId,
|
||||
IReadOnlyList<string> recordKeys,
|
||||
CancellationToken cancellationToken = default)
|
||||
where TDocument : class
|
||||
=> await ReadManyCoreAsync<TDocument>(
|
||||
endpointId,
|
||||
recordKeys,
|
||||
TimeSpan.FromSeconds(10),
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
private async Task<IReadOnlyList<TDocument>> ReadManyCoreAsync<TDocument>(
|
||||
string endpointId,
|
||||
IReadOnlyList<string> recordKeys,
|
||||
TimeSpan responseTimeout,
|
||||
CancellationToken cancellationToken)
|
||||
where TDocument : class
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId));
|
||||
if (recordKeys == null || recordKeys.Count == 0 || recordKeys.Any(string.IsNullOrWhiteSpace))
|
||||
throw new ArgumentException("At least one non-empty record key is required.", nameof(recordKeys));
|
||||
var cacheRegistry = CultMesh.CreateCultCacheDocumentRegistry(typeof(TDocument));
|
||||
var networkRegistry = CultMesh.CreateCultNetDocumentRegistry(new[] { typeof(TDocument) }, cacheRegistry);
|
||||
using var snapshot = await CultMeshSnapshotSession.ConnectAsync(
|
||||
_sessions,
|
||||
CultMeshEndpointId.Parse(endpointId),
|
||||
CultMeshProtocols.Content,
|
||||
new CultMeshSnapshotRequestOptions
|
||||
{
|
||||
ConnectTimeout = TimeSpan.FromSeconds(5),
|
||||
ResponseTimeout = responseTimeout,
|
||||
MessageIdPrefix = "cultmesh-client-read"
|
||||
},
|
||||
networkRegistry,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return await snapshot.FetchDocumentsAsync<TDocument>(
|
||||
recordKeys: recordKeys,
|
||||
schemaIds: new[] { cacheRegistry.GetRequired<TDocument>().SchemaId })
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
foreach (var resource in _documentResources) resource.Dispose();
|
||||
_documents.Clear();
|
||||
_collections.Clear();
|
||||
_sessions.Dispose();
|
||||
_discovery.Dispose();
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshClient));
|
||||
}
|
||||
|
||||
private async Task<object> OpenDocumentAsync<TDocument>(string endpointId, string recordKey)
|
||||
where TDocument : class
|
||||
{
|
||||
var session = await ConnectAsync(endpointId, CultMeshProtocols.Documents).ConfigureAwait(false);
|
||||
var binding = new RemoteDocumentBinding<TDocument>(session, endpointId, recordKey, _subscriptionResponseTimeout);
|
||||
_documentResources.Add(binding);
|
||||
try
|
||||
{
|
||||
await binding.StartAsync().ConfigureAwait(false);
|
||||
return binding;
|
||||
}
|
||||
catch
|
||||
{
|
||||
binding.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<object> OpenCollectionAsync<TDocument>(string endpointId, bool includeInitialSnapshot)
|
||||
where TDocument : class
|
||||
{
|
||||
var session = await ConnectAsync(endpointId, CultMeshProtocols.Documents).ConfigureAwait(false);
|
||||
var binding = new RemoteCollectionBinding<TDocument>(session, endpointId, includeInitialSnapshot, _subscriptionResponseTimeout);
|
||||
_documentResources.Add(binding);
|
||||
try
|
||||
{
|
||||
await binding.StartAsync().ConfigureAwait(false);
|
||||
return binding;
|
||||
}
|
||||
catch
|
||||
{
|
||||
binding.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<T> AwaitForCallerAsync<T>(Task<T> shared, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!cancellationToken.CanBeCanceled) return await shared.ConfigureAwait(false);
|
||||
var cancelled = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using (cancellationToken.Register(() => cancelled.TrySetResult(true)))
|
||||
{
|
||||
if (await Task.WhenAny(shared, cancelled.Task).ConfigureAwait(false) != shared)
|
||||
throw new OperationCanceledException(cancellationToken);
|
||||
}
|
||||
return await shared.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private sealed class RemoteDocumentBinding<TDocument> : IDisposable where TDocument : class
|
||||
{
|
||||
private readonly CultMeshSession _session;
|
||||
private readonly string _recordKey;
|
||||
private readonly string _subscriptionId;
|
||||
private readonly CultCache _cache;
|
||||
private readonly CultNetDatabaseSubscriptionClient _subscription;
|
||||
private readonly TimeSpan _responseTimeout;
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly TaskCompletionSource<bool> _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly object _subscribeLock = new();
|
||||
private Task? _subscribeTask;
|
||||
private long _subscribedGeneration = -1;
|
||||
private IDisposable? _stateWatch;
|
||||
private bool _disposed;
|
||||
|
||||
public RemoteDocumentBinding(
|
||||
CultMeshSession session,
|
||||
string endpointId,
|
||||
string recordKey,
|
||||
TimeSpan responseTimeout)
|
||||
{
|
||||
_session = session;
|
||||
_responseTimeout = responseTimeout;
|
||||
_recordKey = recordKey;
|
||||
_subscriptionId = "cultmesh-document:" + endpointId + ":" + recordKey;
|
||||
var cacheRegistry = CultMesh.CreateCultCacheDocumentRegistry(typeof(TDocument));
|
||||
var networkRegistry = CultMesh.CreateCultNetDocumentRegistry(new[] { typeof(TDocument) }, cacheRegistry);
|
||||
_cache = new CultCache(cacheRegistry);
|
||||
_subscription = new CultNetDatabaseSubscriptionClient(session.OpenSchemaClient(), _cache, networkRegistry);
|
||||
Handle = CultMesh.Document<TDocument>(
|
||||
_cache,
|
||||
new CultRecordKey(recordKey),
|
||||
CultMesh.Verse(endpointId, "cultmesh-client").Context,
|
||||
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, endpointId));
|
||||
}
|
||||
|
||||
public CultMeshDocumentHandle<TDocument> Handle { get; }
|
||||
|
||||
public async Task StartAsync()
|
||||
{
|
||||
_stateWatch = _session.WatchState()
|
||||
.Where(state => state.Status == CultMeshSessionStatus.Online)
|
||||
.Subscribe(state => { _ = EnsureSubscribedAsync(); });
|
||||
_ = EnsureSubscribedAsync();
|
||||
await _ready.Task.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private Task EnsureSubscribedAsync()
|
||||
{
|
||||
lock (_subscribeLock)
|
||||
{
|
||||
var generation = _session.PhysicalGeneration;
|
||||
if (_subscribedGeneration == generation && _subscribeTask != null) return _subscribeTask;
|
||||
_subscribedGeneration = generation;
|
||||
return _subscribeTask = SubscribeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SubscribeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!_disposed)
|
||||
{
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
|
||||
deadline.CancelAfter(_responseTimeout);
|
||||
try
|
||||
{
|
||||
await _subscription.SubscribeAsync(
|
||||
_subscriptionId,
|
||||
recordKeys: new[] { _recordKey },
|
||||
schemaIds: new[] { CultDocumentRegistry.Shared.GetRequired<TDocument>().SchemaId },
|
||||
cancellationToken: deadline.Token)
|
||||
.ConfigureAwait(false);
|
||||
_ready.TrySetResult(true);
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException) when (!_lifetime.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (ObjectDisposedException) when (_disposed)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_lifetime.Cancel();
|
||||
_stateWatch?.Dispose();
|
||||
_subscription.Dispose();
|
||||
_ready.TrySetException(new ObjectDisposedException(GetType().FullName));
|
||||
_cache.Dispose();
|
||||
_lifetime.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RemoteCollectionBinding<TDocument> : IDisposable where TDocument : class
|
||||
{
|
||||
private readonly CultMeshSession _session;
|
||||
private readonly string _subscriptionId;
|
||||
private readonly CultCache _cache;
|
||||
private readonly CultNetDatabaseSubscriptionClient _subscription;
|
||||
private readonly TimeSpan _responseTimeout;
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly bool _includeInitialSnapshot;
|
||||
private readonly TaskCompletionSource<bool> _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly object _subscribeLock = new();
|
||||
private Task? _subscribeTask;
|
||||
private long _subscribedGeneration = -1;
|
||||
private IDisposable? _stateWatch;
|
||||
private bool _disposed;
|
||||
|
||||
public RemoteCollectionBinding(
|
||||
CultMeshSession session,
|
||||
string endpointId,
|
||||
bool includeInitialSnapshot,
|
||||
TimeSpan responseTimeout)
|
||||
{
|
||||
_session = session;
|
||||
_responseTimeout = responseTimeout;
|
||||
_subscriptionId = "cultmesh-collection:" + endpointId + ":" + typeof(TDocument).FullName;
|
||||
_includeInitialSnapshot = includeInitialSnapshot;
|
||||
var cacheRegistry = CultMesh.CreateCultCacheDocumentRegistry(typeof(TDocument));
|
||||
var networkRegistry = CultMesh.CreateCultNetDocumentRegistry(new[] { typeof(TDocument) }, cacheRegistry);
|
||||
_cache = new CultCache(cacheRegistry);
|
||||
_subscription = new CultNetDatabaseSubscriptionClient(session.OpenSchemaClient(), _cache, networkRegistry);
|
||||
Handle = CultMesh.Collection<TDocument>(
|
||||
_cache,
|
||||
routeHint: new CultMeshRouteHint(CultMeshLocalityKind.Network, endpointId));
|
||||
}
|
||||
|
||||
public CultMeshCollectionHandle<TDocument> Handle { get; }
|
||||
|
||||
public async Task StartAsync()
|
||||
{
|
||||
_stateWatch = _session.WatchState()
|
||||
.Where(state => state.Status == CultMeshSessionStatus.Online)
|
||||
.Subscribe(state => { _ = EnsureSubscribedAsync(); });
|
||||
_ = EnsureSubscribedAsync();
|
||||
await _ready.Task.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private Task EnsureSubscribedAsync()
|
||||
{
|
||||
lock (_subscribeLock)
|
||||
{
|
||||
var generation = _session.PhysicalGeneration;
|
||||
if (_subscribedGeneration == generation && _subscribeTask != null) return _subscribeTask;
|
||||
_subscribedGeneration = generation;
|
||||
return _subscribeTask = SubscribeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SubscribeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!_disposed)
|
||||
{
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
|
||||
deadline.CancelAfter(_responseTimeout);
|
||||
try
|
||||
{
|
||||
await _subscription.SubscribeAsync(
|
||||
_subscriptionId,
|
||||
schemaIds: new[] { CultDocumentRegistry.Shared.GetRequired<TDocument>().SchemaId },
|
||||
includeSnapshot: _includeInitialSnapshot,
|
||||
cancellationToken: deadline.Token)
|
||||
.ConfigureAwait(false);
|
||||
_ready.TrySetResult(true);
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException) when (!_lifetime.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (ObjectDisposedException) when (_disposed)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_lifetime.Cancel();
|
||||
_stateWatch?.Dispose();
|
||||
_subscription.Dispose();
|
||||
_ready.TrySetException(new ObjectDisposedException(GetType().FullName));
|
||||
_cache.Dispose();
|
||||
_lifetime.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RendezvousLookupSource : ICultMeshLookupSource
|
||||
{
|
||||
private readonly string _endpoint;
|
||||
private readonly CultMeshVerseDiscoveryClient _client;
|
||||
private readonly CultMeshVerseDiscoveryClientOptions _options;
|
||||
|
||||
public RendezvousLookupSource(
|
||||
string endpoint,
|
||||
CultMeshVerseDiscoveryClient client,
|
||||
CultMeshVerseDiscoveryClientOptions options)
|
||||
{
|
||||
_endpoint = endpoint;
|
||||
_client = client;
|
||||
_options = options;
|
||||
}
|
||||
|
||||
public string SourceId => "rendezvous:" + _endpoint;
|
||||
|
||||
public async Task<IReadOnlyList<CultMeshDiscoveryObservation>> LookupAsync(
|
||||
CultMeshDiscoveryQuery query,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var response = await _client.FetchAsync(
|
||||
_endpoint,
|
||||
new CultMeshVerseCatalogRequestMessage
|
||||
{
|
||||
VerseIds = query.VerseIds.Count == 0 ? null : query.VerseIds.ToArray(),
|
||||
TransportVersion = "cultmesh.v0"
|
||||
}).ConfigureAwait(false);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var observedAt = _options.Clock.UtcNow;
|
||||
return response.Verses.Select(message => new CultMeshDiscoveryObservation(
|
||||
message.ToVerseDescriptor(),
|
||||
SourceId,
|
||||
observedAt,
|
||||
observedAt + _options.ObservationTtl,
|
||||
CultMeshDiscoveryTrust.Unsigned,
|
||||
response.SchemaVersion)).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
242
src/GameCult.Mesh/CultMeshContentSessions.cs
Normal file
242
src/GameCult.Mesh/CultMeshContentSessions.cs
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Networking;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Serves bounded, content-addressed CDN chunks over the CultMesh content protocol.
|
||||
/// Manifests and descriptors remain typed document state; payload bytes do not.
|
||||
/// </summary>
|
||||
public sealed class CultMeshLegacyRudpContentServer : IDisposable
|
||||
{
|
||||
private readonly ICultNetSchemaServer _server;
|
||||
private readonly CultCache _content;
|
||||
private readonly Func<string, bool> _canServeHash;
|
||||
private readonly Func<CultMeshContentChunkRequestMessage, ICultNetSchemaServerPeer, Task> _handler;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Attaches content serving to an existing schema host and provider cache.</summary>
|
||||
public CultMeshLegacyRudpContentServer(
|
||||
ICultNetSchemaServer server,
|
||||
CultCache content,
|
||||
Func<string, bool>? canServeHash = null)
|
||||
{
|
||||
_server = server ?? throw new ArgumentNullException(nameof(server));
|
||||
_content = content ?? throw new ArgumentNullException(nameof(content));
|
||||
_canServeHash = canServeHash ?? (_ => true);
|
||||
_handler = HandleAsync;
|
||||
_server.OnCultNet(_handler);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_server.RemoveCultNetMessageListener<CultMeshContentChunkRequestMessage>(_handler);
|
||||
}
|
||||
|
||||
private Task HandleAsync(
|
||||
CultMeshContentChunkRequestMessage request,
|
||||
ICultNetSchemaServerPeer peer)
|
||||
{
|
||||
var response = new CultMeshContentChunkResponseMessage
|
||||
{
|
||||
MessageId = request?.MessageId ?? string.Empty,
|
||||
ChunkHash = request?.ChunkHash ?? string.Empty
|
||||
};
|
||||
try
|
||||
{
|
||||
if (request == null || string.IsNullOrWhiteSpace(request.MessageId))
|
||||
throw new InvalidDataException("Content chunk request requires a message identity.");
|
||||
var hash = CultMeshCdn.NormalizeHash(request.ChunkHash, nameof(request.ChunkHash));
|
||||
if (!_canServeHash(hash))
|
||||
throw new UnauthorizedAccessException("Content access policy rejected the requested hash.");
|
||||
var canonicalKey = CultMeshCdnArtifactChunk.CreateRecordKey(hash);
|
||||
if (!string.IsNullOrWhiteSpace(request.RecordKey) &&
|
||||
!string.Equals(request.RecordKey, canonicalKey.Value, StringComparison.Ordinal))
|
||||
throw new InvalidDataException("Content chunk record key disagrees with its content hash.");
|
||||
var chunk = _content.Get<CultMeshCdnArtifactChunk>(canonicalKey)
|
||||
?? throw new FileNotFoundException("Content chunk is not available.", canonicalKey.Value);
|
||||
var reference = new CultMeshCdnChunkRef
|
||||
{
|
||||
ChunkHash = hash,
|
||||
RecordKey = canonicalKey.Value,
|
||||
SizeBytes = request.ExpectedSizeBytes
|
||||
};
|
||||
CultMeshCdn.ValidateChunkPayload(reference, chunk);
|
||||
response.Found = true;
|
||||
response.ChunkHash = hash;
|
||||
response.SizeBytes = chunk.SizeBytes;
|
||||
response.Payload = chunk.Payload;
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
response.Found = false;
|
||||
response.Error = error.GetType().Name + ": " + error.Message;
|
||||
response.Payload = Array.Empty<byte>();
|
||||
}
|
||||
peer.SendCultNet(response);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Configures the explicit compatibility path for content over schema-message RUDP.</summary>
|
||||
public sealed class CultMeshLegacyRudpContentTransportOptions
|
||||
{
|
||||
/// <summary>Gets or sets the injected reliability clock.</summary>
|
||||
public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance;
|
||||
/// <summary>Gets or sets the maximum time to wait for one chunk response.</summary>
|
||||
public TimeSpan ResponseTimeout { get; set; } = TimeSpan.FromSeconds(10);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Explicit low-priority compatibility connector for the retired content-over-RUDP path.
|
||||
/// It is never installed by default.
|
||||
/// </summary>
|
||||
public sealed class CultMeshLegacyRudpContentTransportConnector : ICultMeshContentTransportConnector
|
||||
{
|
||||
public const int LegacyPriority = 10_000;
|
||||
private readonly CultMeshSchemaTransportConnector _schemaConnector;
|
||||
private readonly CultMeshLegacyRudpContentTransportOptions _options;
|
||||
|
||||
public CultMeshLegacyRudpContentTransportConnector(
|
||||
CultMeshLegacyRudpContentTransportOptions? options = null,
|
||||
Func<string, ICultNetSchemaClient>? createClient = null)
|
||||
{
|
||||
_options = options ?? new CultMeshLegacyRudpContentTransportOptions();
|
||||
if (_options.ResponseTimeout <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(options), "Content response timeout must be positive.");
|
||||
_schemaConnector = new CultMeshSchemaTransportConnector(createClient, _options.Clock, _options.ResponseTimeout);
|
||||
}
|
||||
|
||||
public string ConnectorId => "legacy-rudp-content";
|
||||
public int Priority => LegacyPriority;
|
||||
public bool CanConnect(CultMeshTransportCandidate candidate) =>
|
||||
Uri.TryCreate(candidate.Endpoint, UriKind.Absolute, out var uri) &&
|
||||
string.Equals(uri.Scheme, "rudp", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public async Task<ICultMeshContentTransport> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshEndpointId endpointId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!CanConnect(candidate))
|
||||
throw new NotSupportedException($"Legacy RUDP content connector does not support '{candidate.Endpoint}'.");
|
||||
var client = await _schemaConnector.ConnectAsync(candidate, CultMeshProtocols.Content, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return new LegacyRudpContentTransport(candidate.Endpoint, client, _options);
|
||||
}
|
||||
|
||||
private sealed class LegacyRudpContentTransport : ICultMeshContentTransport
|
||||
{
|
||||
private readonly ICultNetSchemaClient _client;
|
||||
private readonly CultMeshLegacyRudpContentTransportOptions _options;
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, TaskCompletionSource<CultMeshContentChunkResponseMessage>> _pending = new(StringComparer.Ordinal);
|
||||
private bool _disposed;
|
||||
|
||||
public LegacyRudpContentTransport(
|
||||
string endpoint,
|
||||
ICultNetSchemaClient client,
|
||||
CultMeshLegacyRudpContentTransportOptions options)
|
||||
{
|
||||
Endpoint = endpoint;
|
||||
_client = client;
|
||||
_options = options;
|
||||
_client.OnCultNet<CultMeshContentChunkResponseMessage>(OnResponse);
|
||||
_client.OnCultNet<CultNetErrorMessage>(OnError);
|
||||
}
|
||||
|
||||
public string TransportId => "legacy-rudp-content";
|
||||
public string Endpoint { get; }
|
||||
|
||||
public async Task CopyChunkToAsync(
|
||||
CultMeshCdnChunkRef chunk,
|
||||
Stream destination,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(LegacyRudpContentTransport));
|
||||
if (chunk == null) throw new ArgumentNullException(nameof(chunk));
|
||||
if (destination == null) throw new ArgumentNullException(nameof(destination));
|
||||
var hash = CultMeshCdn.NormalizeHash(chunk.ChunkHash, nameof(chunk.ChunkHash));
|
||||
var messageId = Guid.NewGuid().ToString("N");
|
||||
var completion = new TaskCompletionSource<CultMeshContentChunkResponseMessage>(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
if (!_pending.TryAdd(messageId, completion))
|
||||
throw new InvalidOperationException("Duplicate legacy content request identity.");
|
||||
try
|
||||
{
|
||||
_client.SendCultNet(new CultMeshContentChunkRequestMessage
|
||||
{
|
||||
MessageId = messageId,
|
||||
ChunkHash = hash,
|
||||
RecordKey = string.IsNullOrWhiteSpace(chunk.RecordKey)
|
||||
? CultMeshCdnArtifactChunk.CreateRecordKey(hash).Value
|
||||
: chunk.RecordKey,
|
||||
ExpectedSizeBytes = chunk.SizeBytes
|
||||
});
|
||||
var response = await WaitForResponseAsync(completion.Task, cancellationToken).ConfigureAwait(false);
|
||||
if (!response.Found)
|
||||
throw new FileNotFoundException(
|
||||
"Legacy RUDP content provider rejected chunk '" + hash + "': " + response.Error,
|
||||
chunk.RecordKey);
|
||||
var resolved = new CultMeshCdnArtifactChunk
|
||||
{
|
||||
ChunkHash = response.ChunkHash,
|
||||
SizeBytes = response.SizeBytes,
|
||||
Payload = response.Payload ?? Array.Empty<byte>()
|
||||
};
|
||||
CultMeshCdn.ValidateChunkPayload(chunk, resolved);
|
||||
await destination.WriteAsync(resolved.Payload, 0, resolved.Payload.Length, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pending.TryRemove(messageId, out _);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
foreach (var completion in _pending.Values)
|
||||
completion.TrySetException(new ObjectDisposedException(nameof(LegacyRudpContentTransport)));
|
||||
_pending.Clear();
|
||||
_client.Dispose();
|
||||
}
|
||||
|
||||
private void OnResponse(CultMeshContentChunkResponseMessage response)
|
||||
{
|
||||
if (_pending.TryGetValue(response.MessageId ?? string.Empty, out var completion))
|
||||
completion.TrySetResult(response);
|
||||
}
|
||||
|
||||
private void OnError(CultNetErrorMessage error)
|
||||
{
|
||||
var exception = new IOException(error.Error);
|
||||
foreach (var completion in _pending.Values) completion.TrySetException(exception);
|
||||
}
|
||||
|
||||
private async Task<CultMeshContentChunkResponseMessage> WaitForResponseAsync(
|
||||
Task<CultMeshContentChunkResponseMessage> response,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using var deadlineCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
var deadline = _options.Clock.DelayAsync(_options.ResponseTimeout, deadlineCancellation.Token);
|
||||
var completed = await Task.WhenAny(response, deadline).ConfigureAwait(false);
|
||||
if (completed == response)
|
||||
{
|
||||
deadlineCancellation.Cancel();
|
||||
return await response.ConfigureAwait(false);
|
||||
}
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
throw new TimeoutException("Timed out fetching content through the legacy RUDP connector.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
518
src/GameCult.Mesh/CultMeshContentTransfer.cs
Normal file
518
src/GameCult.Mesh/CultMeshContentTransfer.cs
Normal file
|
|
@ -0,0 +1,518 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Networking;
|
||||
using MessagePack;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
public static class CultMeshContentTransferSchemaVersions
|
||||
{
|
||||
public const string State = "gamecult.mesh.content_transfer_state.v1";
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[CultDocument("gamecult.mesh.content_transfer_state", CultMeshContentTransferSchemaVersions.State)]
|
||||
public sealed class CultMeshContentTransferStateDocument
|
||||
{
|
||||
[Key(0), CultName] public string ContentHash { get; set; } = string.Empty;
|
||||
[Key(1)] public string ManifestFingerprint { get; set; } = string.Empty;
|
||||
[Key(2)] public long SizeBytes { get; set; }
|
||||
[Key(3)] public int[] VerifiedChunkIndexes { get; set; } = Array.Empty<int>();
|
||||
[Key(4)] public string UpdatedAtUtc { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public interface ICultMeshContentProvider
|
||||
{
|
||||
string ProviderId { get; }
|
||||
Task CopyChunkToAsync(
|
||||
CultMeshCdnChunkRef chunk,
|
||||
Stream destination,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class CultMeshDatabaseContentProvider : ICultMeshContentProvider
|
||||
{
|
||||
private readonly CultNetDatabase _database;
|
||||
|
||||
public CultMeshDatabaseContentProvider(string providerId, CultNetDatabase database)
|
||||
{
|
||||
ProviderId = string.IsNullOrWhiteSpace(providerId) ? throw new ArgumentException("Provider id must be non-empty.", nameof(providerId)) : providerId;
|
||||
_database = database ?? throw new ArgumentNullException(nameof(database));
|
||||
}
|
||||
|
||||
public string ProviderId { get; }
|
||||
|
||||
public async Task CopyChunkToAsync(
|
||||
CultMeshCdnChunkRef chunk,
|
||||
Stream destination,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (chunk == null) throw new ArgumentNullException(nameof(chunk));
|
||||
if (destination == null) throw new ArgumentNullException(nameof(destination));
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var key = string.IsNullOrWhiteSpace(chunk.RecordKey)
|
||||
? CultMeshCdnArtifactChunk.CreateRecordKey(chunk.ChunkHash)
|
||||
: new CultRecordKey(chunk.RecordKey);
|
||||
var result = await _database.GetAsync<CultMeshCdnArtifactChunk>(key).ConfigureAwait(false);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (result == null)
|
||||
throw new FileNotFoundException("CDN artifact chunk is missing from the provider.", key.Value);
|
||||
CultMeshCdn.ValidateChunkPayload(chunk, result);
|
||||
await destination.WriteAsync(result.Payload, 0, result.Payload.Length, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshContentTransferOptions
|
||||
{
|
||||
public const int DefaultMaxConcurrentChunkRequests = 4;
|
||||
public const int MaximumConcurrentChunkRequests = 32;
|
||||
|
||||
public CultMeshContentTransferOptions(string cacheDirectory)
|
||||
{
|
||||
CacheDirectory = string.IsNullOrWhiteSpace(cacheDirectory)
|
||||
? throw new ArgumentException("Cache directory must be non-empty.", nameof(cacheDirectory))
|
||||
: Path.GetFullPath(cacheDirectory);
|
||||
}
|
||||
|
||||
public string CacheDirectory { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the bounded number of chunk requests that may be in flight per
|
||||
/// content hash while the transfer owner writes and checkpoints in manifest order.
|
||||
/// </summary>
|
||||
public int MaxConcurrentChunkRequests { get; set; } = DefaultMaxConcurrentChunkRequests;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binds the transfer owner's atomically committed file to an ephemeral read-only
|
||||
/// mapped-body descriptor for the same logical generation.
|
||||
/// </summary>
|
||||
public sealed class CultMeshMappedContent
|
||||
{
|
||||
internal CultMeshMappedContent(string verifiedPath, CultMeshBodyDescriptor descriptor)
|
||||
{
|
||||
VerifiedPath = string.IsNullOrWhiteSpace(verifiedPath)
|
||||
? throw new ArgumentException("Verified content path is required.", nameof(verifiedPath))
|
||||
: Path.GetFullPath(verifiedPath);
|
||||
Descriptor = descriptor ?? throw new ArgumentNullException(nameof(descriptor));
|
||||
}
|
||||
|
||||
/// <summary>Gets the immutable file promoted by the content transfer owner.</summary>
|
||||
public string VerifiedPath { get; }
|
||||
|
||||
/// <summary>Gets the opaque mapped-body capability for the same verified file.</summary>
|
||||
public CultMeshBodyDescriptor Descriptor { get; }
|
||||
}
|
||||
|
||||
public sealed class CultMeshContentTransferService
|
||||
{
|
||||
private readonly CultCache _stateCache;
|
||||
private readonly ICultMeshContentProvider[] _providers;
|
||||
private readonly string _cacheDirectory;
|
||||
private readonly int _maxConcurrentChunkRequests;
|
||||
private readonly CultMeshVerifiedBodyMappingBroker? _mappedBodies;
|
||||
private readonly ConcurrentDictionary<string, SemaphoreSlim> _contentLocks = new(StringComparer.Ordinal);
|
||||
|
||||
public CultMeshContentTransferService(
|
||||
CultCache stateCache,
|
||||
IEnumerable<ICultMeshContentProvider> providers,
|
||||
CultMeshContentTransferOptions options,
|
||||
CultMeshVerifiedBodyMappingBroker? mappedBodies = null)
|
||||
{
|
||||
_stateCache = stateCache ?? throw new ArgumentNullException(nameof(stateCache));
|
||||
_providers = providers?.ToArray() ?? throw new ArgumentNullException(nameof(providers));
|
||||
if (_providers.Length == 0) throw new ArgumentException("At least one content provider is required.", nameof(providers));
|
||||
if (_providers.Any(provider => provider == null)) throw new ArgumentException("Content providers cannot contain null entries.", nameof(providers));
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
if (options.MaxConcurrentChunkRequests <= 0 ||
|
||||
options.MaxConcurrentChunkRequests > CultMeshContentTransferOptions.MaximumConcurrentChunkRequests)
|
||||
throw new ArgumentOutOfRangeException(nameof(options),
|
||||
$"Concurrent chunk request bound must be between 1 and {CultMeshContentTransferOptions.MaximumConcurrentChunkRequests}.");
|
||||
_cacheDirectory = options.CacheDirectory;
|
||||
_maxConcurrentChunkRequests = options.MaxConcurrentChunkRequests;
|
||||
_mappedBodies = mappedBodies;
|
||||
}
|
||||
|
||||
public async Task<CultMeshBodyDescriptor> FetchMappedBodyAsync(
|
||||
CultMeshCdnArtifactManifest manifest,
|
||||
CultMeshBodyDescriptor networkDescriptor,
|
||||
DateTimeOffset nowUtc,
|
||||
TimeSpan leaseDuration,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var mapped = await FetchMappedContentAsync(
|
||||
manifest,
|
||||
networkDescriptor,
|
||||
nowUtc,
|
||||
leaseDuration,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return mapped.Descriptor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetches and atomically verifies one artifact, then grants a mapped read-only
|
||||
/// representation without making the consumer infer the transfer cache path.
|
||||
/// </summary>
|
||||
public async Task<CultMeshMappedContent> FetchMappedContentAsync(
|
||||
CultMeshCdnArtifactManifest manifest,
|
||||
CultMeshBodyDescriptor networkDescriptor,
|
||||
DateTimeOffset nowUtc,
|
||||
TimeSpan leaseDuration,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_mappedBodies == null)
|
||||
throw new InvalidOperationException("Verified body mapping is not configured for this transfer service.");
|
||||
if (networkDescriptor == null) throw new ArgumentNullException(nameof(networkDescriptor));
|
||||
if (networkDescriptor.TransportKind != CultMeshBodyTransportKind.Network)
|
||||
throw new ArgumentException("The fallback descriptor must use the network body transport.", nameof(networkDescriptor));
|
||||
if (leaseDuration <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(leaseDuration));
|
||||
CultMeshCdn.ValidateManifest(manifest);
|
||||
if (networkDescriptor.ByteSize != manifest.SizeBytes)
|
||||
throw new InvalidDataException("CDN manifest size does not match its network body descriptor.");
|
||||
|
||||
var path = await FetchAsync(manifest, cancellationToken).ConfigureAwait(false);
|
||||
var contentHash = CultMeshCdn.NormalizeHash(manifest.ContentHash, nameof(manifest.ContentHash));
|
||||
var requestedExpiry = nowUtc.Add(leaseDuration);
|
||||
var networkExpiry = DateTimeOffset.FromUnixTimeMilliseconds(networkDescriptor.LeaseExpiresAtUnixMs);
|
||||
var expiry = requestedExpiry <= networkExpiry ? requestedExpiry : networkExpiry;
|
||||
if (expiry <= nowUtc) throw new InvalidOperationException("Network body lease has expired.");
|
||||
var descriptor = _mappedBodies.GrantVerified(contentHash, path, networkDescriptor, expiry);
|
||||
return new CultMeshMappedContent(path, descriptor);
|
||||
}
|
||||
|
||||
public async Task<string> FetchAsync(
|
||||
CultMeshCdnArtifactManifest manifest,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (manifest == null) throw new ArgumentNullException(nameof(manifest));
|
||||
CultMeshCdn.ValidateManifest(manifest);
|
||||
|
||||
var contentHash = CultMeshCdn.NormalizeHash(manifest.ContentHash, nameof(manifest.ContentHash));
|
||||
var contentLock = _contentLocks.GetOrAdd(contentHash, _ => new SemaphoreSlim(1, 1));
|
||||
await contentLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return await FetchOwnedAsync(manifest, contentHash, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
contentLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string> FetchOwnedAsync(
|
||||
CultMeshCdnArtifactManifest manifest,
|
||||
string contentHash,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Directory.CreateDirectory(_cacheDirectory);
|
||||
var finalPath = Path.Combine(_cacheDirectory, contentHash + ".body");
|
||||
var partialPath = Path.Combine(_cacheDirectory, "." + contentHash + ".partial");
|
||||
var stateKey = StateKey(contentHash);
|
||||
|
||||
if (File.Exists(finalPath))
|
||||
{
|
||||
if (await HashFileAsync(finalPath, cancellationToken).ConfigureAwait(false) == contentHash)
|
||||
return finalPath;
|
||||
File.Delete(finalPath);
|
||||
}
|
||||
|
||||
var fingerprint = ManifestFingerprint(manifest);
|
||||
var state = _stateCache.Get<CultMeshContentTransferStateDocument>(stateKey);
|
||||
var verified = RestoreVerifiedState(state, manifest, fingerprint, partialPath);
|
||||
|
||||
using (var stream = new FileStream(
|
||||
partialPath,
|
||||
FileMode.OpenOrCreate,
|
||||
FileAccess.ReadWrite,
|
||||
FileShare.ReadWrite,
|
||||
81920,
|
||||
FileOptions.Asynchronous))
|
||||
{
|
||||
stream.SetLength(manifest.SizeBytes);
|
||||
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var ordered = manifest.Chunks
|
||||
.Select((chunk, index) => new { Chunk = chunk, Index = index })
|
||||
.OrderBy(item => item.Chunk.Offset)
|
||||
.ToArray();
|
||||
var remaining = ordered.Where(item => !verified.Contains(item.Index)).ToArray();
|
||||
for (var windowStart = 0; windowStart < remaining.Length; windowStart += _maxConcurrentChunkRequests)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var window = remaining
|
||||
.Skip(windowStart)
|
||||
.Take(_maxConcurrentChunkRequests)
|
||||
.Select(item => (Item: item, Copy: CopyVerifiedChunkToPartialAsync(
|
||||
item.Chunk,
|
||||
partialPath,
|
||||
cancellationToken)))
|
||||
.ToArray();
|
||||
try
|
||||
{
|
||||
foreach (var pending in window)
|
||||
{
|
||||
await pending.Copy.ConfigureAwait(false);
|
||||
verified.Add(pending.Item.Index);
|
||||
await SaveStateAsync(
|
||||
contentHash,
|
||||
fingerprint,
|
||||
manifest.SizeBytes,
|
||||
verified,
|
||||
stateKey,
|
||||
flush: false).ConfigureAwait(false);
|
||||
}
|
||||
await _stateCache.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
foreach (var pending in window)
|
||||
{
|
||||
try
|
||||
{
|
||||
await pending.Copy.ConfigureAwait(false);
|
||||
if (verified.Add(pending.Item.Index))
|
||||
{
|
||||
await SaveStateAsync(
|
||||
contentHash,
|
||||
fingerprint,
|
||||
manifest.SizeBytes,
|
||||
verified,
|
||||
stateKey,
|
||||
flush: false).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
await _stateCache.FlushAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var actualHash = await HashFileAsync(partialPath, cancellationToken).ConfigureAwait(false);
|
||||
if (!string.Equals(actualHash, contentHash, StringComparison.Ordinal))
|
||||
{
|
||||
File.Delete(partialPath);
|
||||
_stateCache.Remove(stateKey);
|
||||
await _stateCache.FlushAsync().ConfigureAwait(false);
|
||||
throw new InvalidDataException("CDN artifact content hash does not match its manifest.");
|
||||
}
|
||||
|
||||
PromoteAtomically(partialPath, finalPath);
|
||||
_stateCache.Remove(stateKey);
|
||||
await _stateCache.FlushAsync().ConfigureAwait(false);
|
||||
return finalPath;
|
||||
}
|
||||
|
||||
private HashSet<int> RestoreVerifiedState(
|
||||
CultMeshContentTransferStateDocument? state,
|
||||
CultMeshCdnArtifactManifest manifest,
|
||||
string fingerprint,
|
||||
string partialPath)
|
||||
{
|
||||
if (state == null || !File.Exists(partialPath) ||
|
||||
state.SizeBytes != manifest.SizeBytes ||
|
||||
!string.Equals(state.ManifestFingerprint, fingerprint, StringComparison.Ordinal) ||
|
||||
new FileInfo(partialPath).Length != manifest.SizeBytes)
|
||||
{
|
||||
if (File.Exists(partialPath)) File.Delete(partialPath);
|
||||
return new HashSet<int>();
|
||||
}
|
||||
|
||||
var verified = new HashSet<int>();
|
||||
using var stream = new FileStream(partialPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
foreach (var index in state.VerifiedChunkIndexes.Distinct().Where(index => index >= 0 && index < manifest.Chunks.Length))
|
||||
{
|
||||
var reference = manifest.Chunks[index];
|
||||
var bytes = new byte[reference.SizeBytes];
|
||||
stream.Position = reference.Offset;
|
||||
if (stream.Read(bytes, 0, bytes.Length) == bytes.Length &&
|
||||
string.Equals(CultMeshCdn.HashBytes(bytes), CultMeshCdn.NormalizeHash(reference.ChunkHash, nameof(reference.ChunkHash)), StringComparison.Ordinal))
|
||||
{
|
||||
verified.Add(index);
|
||||
}
|
||||
}
|
||||
|
||||
return verified;
|
||||
}
|
||||
|
||||
private async Task CopyVerifiedChunkToPartialAsync(
|
||||
CultMeshCdnChunkRef reference,
|
||||
string partialPath,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var failures = new List<Exception>();
|
||||
foreach (var provider in _providers)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
using var partial = new FileStream(
|
||||
partialPath,
|
||||
FileMode.Open,
|
||||
FileAccess.Write,
|
||||
FileShare.ReadWrite,
|
||||
81920,
|
||||
FileOptions.Asynchronous | FileOptions.RandomAccess);
|
||||
partial.Position = reference.Offset;
|
||||
using var destination = new BoundedHashingWriteStream(partial, reference.SizeBytes);
|
||||
await provider.CopyChunkToAsync(reference, destination, cancellationToken).ConfigureAwait(false);
|
||||
await destination.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
var actualHash = destination.CompleteHash();
|
||||
var expectedHash = CultMeshCdn.NormalizeHash(reference.ChunkHash, nameof(reference.ChunkHash));
|
||||
if (!string.Equals(actualHash, expectedHash, StringComparison.Ordinal))
|
||||
throw new InvalidDataException("CDN artifact chunk hash does not match its manifest.");
|
||||
return;
|
||||
}
|
||||
catch (Exception error) when (!(error is OperationCanceledException && cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
failures.Add(new InvalidDataException("Content provider '" + provider.ProviderId + "' could not supply a valid chunk.", error));
|
||||
}
|
||||
}
|
||||
|
||||
throw new AggregateException("No content provider supplied a valid CDN chunk.", failures);
|
||||
}
|
||||
|
||||
private sealed class BoundedHashingWriteStream : Stream
|
||||
{
|
||||
private readonly Stream _destination;
|
||||
private readonly long _expectedBytes;
|
||||
private readonly SHA256 _sha = SHA256.Create();
|
||||
private long _written;
|
||||
private bool _completed;
|
||||
|
||||
public BoundedHashingWriteStream(Stream destination, long expectedBytes)
|
||||
{
|
||||
_destination = destination ?? throw new ArgumentNullException(nameof(destination));
|
||||
if (!destination.CanWrite) throw new ArgumentException("Content destination must be writable.", nameof(destination));
|
||||
if (expectedBytes < 0) throw new ArgumentOutOfRangeException(nameof(expectedBytes));
|
||||
_expectedBytes = expectedBytes;
|
||||
}
|
||||
|
||||
public override bool CanRead => false;
|
||||
public override bool CanSeek => false;
|
||||
public override bool CanWrite => true;
|
||||
public override long Length => throw new NotSupportedException();
|
||||
public override long Position
|
||||
{
|
||||
get => _written;
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Flush() => _destination.Flush();
|
||||
public override Task FlushAsync(CancellationToken cancellationToken) =>
|
||||
_destination.FlushAsync(cancellationToken);
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
ValidateWrite(buffer, offset, count);
|
||||
_destination.Write(buffer, offset, count);
|
||||
_sha.TransformBlock(buffer, offset, count, null, 0);
|
||||
_written += count;
|
||||
}
|
||||
|
||||
public override async Task WriteAsync(
|
||||
byte[] buffer,
|
||||
int offset,
|
||||
int count,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ValidateWrite(buffer, offset, count);
|
||||
await _destination.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
|
||||
_sha.TransformBlock(buffer, offset, count, null, 0);
|
||||
_written += count;
|
||||
}
|
||||
|
||||
public string CompleteHash()
|
||||
{
|
||||
if (_completed) throw new InvalidOperationException("Content destination hash is already complete.");
|
||||
if (_written != _expectedBytes)
|
||||
throw new EndOfStreamException(
|
||||
$"Content transport wrote {_written} bytes; expected {_expectedBytes} bytes.");
|
||||
_sha.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
|
||||
_completed = true;
|
||||
return string.Concat(_sha.Hash!.Select(value => value.ToString("x2", CultureInfo.InvariantCulture)));
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing) _sha.Dispose();
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
|
||||
private void ValidateWrite(byte[] buffer, int offset, int count)
|
||||
{
|
||||
if (_completed) throw new InvalidOperationException("Content destination is already complete.");
|
||||
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
|
||||
if (offset < 0 || count < 0 || offset > buffer.Length - count)
|
||||
throw new ArgumentOutOfRangeException(nameof(offset));
|
||||
if (_written + count > _expectedBytes)
|
||||
throw new InvalidDataException(
|
||||
$"Content transport exceeded its advertised {_expectedBytes}-byte chunk boundary.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveStateAsync(
|
||||
string contentHash,
|
||||
string fingerprint,
|
||||
long sizeBytes,
|
||||
HashSet<int> verified,
|
||||
CultRecordKey stateKey,
|
||||
bool flush)
|
||||
{
|
||||
var state = new CultMeshContentTransferStateDocument
|
||||
{
|
||||
ContentHash = contentHash,
|
||||
ManifestFingerprint = fingerprint,
|
||||
SizeBytes = sizeBytes,
|
||||
VerifiedChunkIndexes = verified.OrderBy(value => value).ToArray(),
|
||||
UpdatedAtUtc = DateTimeOffset.UtcNow.ToString("O", CultureInfo.InvariantCulture)
|
||||
};
|
||||
await _stateCache.UpsertAsync(typeof(CultMeshContentTransferStateDocument), state, stateKey).ConfigureAwait(false);
|
||||
if (flush) await _stateCache.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static CultRecordKey StateKey(string contentHash) => new CultRecordKey("mesh:content-transfer:" + contentHash);
|
||||
|
||||
private static string ManifestFingerprint(CultMeshCdnArtifactManifest manifest)
|
||||
{
|
||||
var shape = string.Join("|", manifest.Chunks.Select(chunk =>
|
||||
chunk.Offset.ToString(CultureInfo.InvariantCulture) + ":" +
|
||||
chunk.SizeBytes.ToString(CultureInfo.InvariantCulture) + ":" +
|
||||
CultMeshCdn.NormalizeHash(chunk.ChunkHash, nameof(chunk.ChunkHash))));
|
||||
return CultMeshCdn.HashBytes(System.Text.Encoding.UTF8.GetBytes(manifest.SizeBytes.ToString(CultureInfo.InvariantCulture) + "|" + shape));
|
||||
}
|
||||
|
||||
private static async Task<string> HashFileAsync(string path, CancellationToken cancellationToken)
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
using var sha = SHA256.Create();
|
||||
var buffer = new byte[81920];
|
||||
int read;
|
||||
while ((read = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0)
|
||||
sha.TransformBlock(buffer, 0, read, null, 0);
|
||||
sha.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
|
||||
return string.Concat(sha.Hash!.Select(value => value.ToString("x2", CultureInfo.InvariantCulture)));
|
||||
}
|
||||
|
||||
private static void PromoteAtomically(string partialPath, string finalPath)
|
||||
{
|
||||
if (File.Exists(finalPath)) File.Replace(partialPath, finalPath, null);
|
||||
else File.Move(partialPath, finalPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
166
src/GameCult.Mesh/CultMeshContentTransports.cs
Normal file
166
src/GameCult.Mesh/CultMeshContentTransports.cs
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Moves immutable content bytes for one selected physical path. Content identity,
|
||||
/// verification, checkpoints, and promotion remain owned by
|
||||
/// <see cref="CultMeshContentTransferService"/>.
|
||||
/// </summary>
|
||||
public interface ICultMeshContentTransport : IDisposable
|
||||
{
|
||||
string TransportId { get; }
|
||||
string Endpoint { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Writes exactly one advertised chunk into the caller-owned destination.
|
||||
/// The transport must honor destination backpressure and must not close it.
|
||||
/// </summary>
|
||||
Task CopyChunkToAsync(
|
||||
CultMeshCdnChunkRef chunk,
|
||||
Stream destination,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates physical content transports. Lower priority values are attempted first;
|
||||
/// a fallback tier is not raced against a preferred tier.
|
||||
/// </summary>
|
||||
public interface ICultMeshContentTransportConnector
|
||||
{
|
||||
string ConnectorId { get; }
|
||||
int Priority { get; }
|
||||
bool CanConnect(CultMeshTransportCandidate candidate);
|
||||
Task<ICultMeshContentTransport> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshEndpointId endpointId,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reusable identity-bound content session selected and owned by
|
||||
/// <see cref="CultMeshSessionManager"/>.
|
||||
/// </summary>
|
||||
public sealed class CultMeshContentSession : IDisposable
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly Action<CultMeshContentSession> _onTransportFailure;
|
||||
private ICultMeshContentTransport _transport;
|
||||
private bool _disposed;
|
||||
|
||||
internal CultMeshContentSession(
|
||||
CultMeshEndpointId endpointId,
|
||||
ICultMeshContentTransport transport,
|
||||
CultMeshSessionState state,
|
||||
Action<CultMeshContentSession> onTransportFailure)
|
||||
{
|
||||
EndpointId = endpointId ?? throw new ArgumentNullException(nameof(endpointId));
|
||||
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
||||
State = state ?? throw new ArgumentNullException(nameof(state));
|
||||
_onTransportFailure = onTransportFailure ?? throw new ArgumentNullException(nameof(onTransportFailure));
|
||||
}
|
||||
|
||||
public CultMeshEndpointId EndpointId { get; }
|
||||
public CultMeshSessionState State { get; private set; }
|
||||
public string TransportId { get { lock (_gate) return _transport.TransportId; } }
|
||||
|
||||
public async Task CopyChunkToAsync(
|
||||
CultMeshCdnChunkRef chunk,
|
||||
Stream destination,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (chunk == null) throw new ArgumentNullException(nameof(chunk));
|
||||
if (destination == null) throw new ArgumentNullException(nameof(destination));
|
||||
ICultMeshContentTransport transport;
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
transport = _transport;
|
||||
}
|
||||
try
|
||||
{
|
||||
await transport.CopyChunkToAsync(chunk, destination, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_onTransportFailure(this);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
internal void Replace(ICultMeshContentTransport transport, CultMeshSessionState state)
|
||||
{
|
||||
if (transport == null) throw new ArgumentNullException(nameof(transport));
|
||||
ICultMeshContentTransport previous;
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
previous = _transport;
|
||||
_transport = transport;
|
||||
State = state;
|
||||
}
|
||||
previous.Dispose();
|
||||
}
|
||||
|
||||
internal void MarkOffline(CultMeshSessionState state)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
State = state;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
ICultMeshContentTransport transport;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
transport = _transport;
|
||||
}
|
||||
transport.Dispose();
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshContentSession));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adapts a selected streaming transport to the verified content-transfer source port.
|
||||
/// </summary>
|
||||
public sealed class CultMeshSessionContentProvider : ICultMeshContentProvider
|
||||
{
|
||||
private readonly CultMeshSessionManager _sessions;
|
||||
private readonly CultMeshEndpointId _endpointId;
|
||||
|
||||
public CultMeshSessionContentProvider(
|
||||
string providerId,
|
||||
CultMeshSessionManager sessions,
|
||||
CultMeshEndpointId endpointId)
|
||||
{
|
||||
ProviderId = string.IsNullOrWhiteSpace(providerId)
|
||||
? throw new ArgumentException("Provider identity is required.", nameof(providerId))
|
||||
: providerId;
|
||||
_sessions = sessions ?? throw new ArgumentNullException(nameof(sessions));
|
||||
_endpointId = endpointId ?? throw new ArgumentNullException(nameof(endpointId));
|
||||
}
|
||||
|
||||
public string ProviderId { get; }
|
||||
|
||||
public async Task CopyChunkToAsync(
|
||||
CultMeshCdnChunkRef chunk,
|
||||
Stream destination,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var session = await _sessions.ConnectContentAsync(_endpointId, cancellationToken).ConfigureAwait(false);
|
||||
await session.CopyChunkToAsync(chunk, destination, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
461
src/GameCult.Mesh/CultMeshDiscoveryService.cs
Normal file
461
src/GameCult.Mesh/CultMeshDiscoveryService.cs
Normal file
|
|
@ -0,0 +1,461 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Networking;
|
||||
using MessagePack;
|
||||
using R3;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
public static class CultMeshDiscoverySchemaVersions
|
||||
{
|
||||
public const string State = "gamecult.mesh.discovery_state.v1";
|
||||
}
|
||||
|
||||
public enum CultMeshDiscoveryFreshness
|
||||
{
|
||||
Fresh,
|
||||
Degraded,
|
||||
Stale,
|
||||
Unavailable
|
||||
}
|
||||
|
||||
public enum CultMeshDiscoveryTrust
|
||||
{
|
||||
Rejected,
|
||||
Unsigned,
|
||||
Signed
|
||||
}
|
||||
|
||||
public sealed class CultMeshDiscoveryQuery
|
||||
{
|
||||
public CultMeshDiscoveryQuery(string endpointId, IEnumerable<string>? verseIds = null)
|
||||
{
|
||||
EndpointId = Require(endpointId, nameof(endpointId));
|
||||
VerseIds = verseIds?.Where(value => !string.IsNullOrWhiteSpace(value))
|
||||
.Distinct(StringComparer.Ordinal).OrderBy(value => value, StringComparer.Ordinal).ToArray()
|
||||
?? Array.Empty<string>();
|
||||
}
|
||||
|
||||
public string EndpointId { get; }
|
||||
public IReadOnlyList<string> VerseIds { get; }
|
||||
|
||||
private static string Require(string value, string name) =>
|
||||
string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Value must be non-empty.", name) : value;
|
||||
}
|
||||
|
||||
public sealed class CultMeshDiscoveryObservation
|
||||
{
|
||||
public CultMeshDiscoveryObservation(
|
||||
CultMeshVerseDescriptor candidate,
|
||||
string sourceId,
|
||||
DateTimeOffset observedAtUtc,
|
||||
DateTimeOffset expiresAtUtc,
|
||||
CultMeshDiscoveryTrust trust = CultMeshDiscoveryTrust.Unsigned,
|
||||
string evidence = "")
|
||||
{
|
||||
Candidate = candidate ?? throw new ArgumentNullException(nameof(candidate));
|
||||
SourceId = string.IsNullOrWhiteSpace(sourceId)
|
||||
? throw new ArgumentException("Value must be non-empty.", nameof(sourceId))
|
||||
: sourceId;
|
||||
if (expiresAtUtc < observedAtUtc) throw new ArgumentOutOfRangeException(nameof(expiresAtUtc));
|
||||
ObservedAtUtc = observedAtUtc;
|
||||
ExpiresAtUtc = expiresAtUtc;
|
||||
Trust = trust;
|
||||
Evidence = evidence ?? "";
|
||||
}
|
||||
|
||||
public CultMeshVerseDescriptor Candidate { get; }
|
||||
public string SourceId { get; }
|
||||
public DateTimeOffset ObservedAtUtc { get; }
|
||||
public DateTimeOffset ExpiresAtUtc { get; }
|
||||
public CultMeshDiscoveryTrust Trust { get; }
|
||||
public string Evidence { get; }
|
||||
}
|
||||
|
||||
public interface ICultMeshLookupSource
|
||||
{
|
||||
string SourceId { get; }
|
||||
|
||||
Task<IReadOnlyList<CultMeshDiscoveryObservation>> LookupAsync(
|
||||
CultMeshDiscoveryQuery query,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public interface ICultMeshDiscoveryStore
|
||||
{
|
||||
Task<CultMeshDiscoveryState?> LoadAsync(string endpointId, CancellationToken cancellationToken = default);
|
||||
|
||||
Task SaveAsync(CultMeshDiscoveryState state, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class CultMeshDiscoveryCandidate
|
||||
{
|
||||
public CultMeshDiscoveryCandidate(
|
||||
CultMeshVerseDescriptor descriptor,
|
||||
string sourceId,
|
||||
DateTimeOffset observedAtUtc,
|
||||
DateTimeOffset expiresAtUtc,
|
||||
CultMeshDiscoveryTrust trust)
|
||||
{
|
||||
Descriptor = descriptor ?? throw new ArgumentNullException(nameof(descriptor));
|
||||
SourceId = sourceId ?? "";
|
||||
ObservedAtUtc = observedAtUtc;
|
||||
ExpiresAtUtc = expiresAtUtc;
|
||||
Trust = trust;
|
||||
}
|
||||
|
||||
public CultMeshVerseDescriptor Descriptor { get; }
|
||||
public string SourceId { get; }
|
||||
public DateTimeOffset ObservedAtUtc { get; }
|
||||
public DateTimeOffset ExpiresAtUtc { get; }
|
||||
public CultMeshDiscoveryTrust Trust { get; }
|
||||
}
|
||||
|
||||
public sealed class CultMeshDiscoveryState
|
||||
{
|
||||
public CultMeshDiscoveryState(
|
||||
string endpointId,
|
||||
CultMeshDiscoveryFreshness freshness,
|
||||
IEnumerable<CultMeshDiscoveryCandidate>? candidates,
|
||||
DateTimeOffset evaluatedAtUtc,
|
||||
DateTimeOffset? retryAfterUtc = null,
|
||||
IEnumerable<string>? failedSourceIds = null,
|
||||
string? queryKey = null)
|
||||
{
|
||||
EndpointId = endpointId ?? "";
|
||||
Freshness = freshness;
|
||||
Candidates = candidates?.OrderBy(candidate => candidate.Descriptor.VerseId, StringComparer.Ordinal).ToArray()
|
||||
?? Array.Empty<CultMeshDiscoveryCandidate>();
|
||||
EvaluatedAtUtc = evaluatedAtUtc;
|
||||
RetryAfterUtc = retryAfterUtc;
|
||||
FailedSourceIds = failedSourceIds?.Distinct(StringComparer.Ordinal).OrderBy(value => value, StringComparer.Ordinal).ToArray()
|
||||
?? Array.Empty<string>();
|
||||
QueryKey = string.IsNullOrWhiteSpace(queryKey) ? EndpointId : queryKey;
|
||||
}
|
||||
|
||||
public string EndpointId { get; }
|
||||
public CultMeshDiscoveryFreshness Freshness { get; }
|
||||
public IReadOnlyList<CultMeshDiscoveryCandidate> Candidates { get; }
|
||||
public DateTimeOffset EvaluatedAtUtc { get; }
|
||||
public DateTimeOffset? RetryAfterUtc { get; }
|
||||
public IReadOnlyList<string> FailedSourceIds { get; }
|
||||
public string QueryKey { get; }
|
||||
}
|
||||
|
||||
public sealed class CultMeshDiscoveryServiceOptions
|
||||
{
|
||||
public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance;
|
||||
public ICultMeshDiagnosticSink Diagnostics { get; set; } = CultMeshNullDiagnosticSink.Instance;
|
||||
public ICultMeshDiscoveryStore? Store { get; set; }
|
||||
public TimeSpan NegativeTtl { get; set; } = TimeSpan.FromSeconds(30);
|
||||
}
|
||||
|
||||
public sealed class CultMeshDiscoveryService : IDisposable
|
||||
{
|
||||
private readonly ICultMeshLookupSource[] _sources;
|
||||
private readonly CultMeshDiscoveryServiceOptions _options;
|
||||
private readonly ConcurrentDictionary<string, Lazy<Task<CultMeshDiscoveryState>>> _inFlight = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, CultMeshDiscoveryState> _states = new(StringComparer.Ordinal);
|
||||
private readonly Subject<CultMeshDiscoveryState> _updates = new();
|
||||
private long _diagnosticSequence;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshDiscoveryService(
|
||||
IEnumerable<ICultMeshLookupSource> sources,
|
||||
CultMeshDiscoveryServiceOptions? options = null)
|
||||
{
|
||||
_sources = sources?.ToArray() ?? throw new ArgumentNullException(nameof(sources));
|
||||
if (_sources.Any(source => source == null)) throw new ArgumentException("Lookup sources cannot contain null.", nameof(sources));
|
||||
_options = options ?? new CultMeshDiscoveryServiceOptions();
|
||||
if (_options.NegativeTtl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(options));
|
||||
}
|
||||
|
||||
public Observable<CultMeshDiscoveryState> Watch() => _updates;
|
||||
|
||||
public CultMeshDiscoveryState? Current(string endpointId)
|
||||
{
|
||||
_states.TryGetValue(endpointId, out var state);
|
||||
return state == null ? null : EvaluateAt(state, _options.Clock.UtcNow);
|
||||
}
|
||||
|
||||
public async Task<CultMeshDiscoveryState> ResolveAsync(
|
||||
CultMeshDiscoveryQuery query,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (query == null) throw new ArgumentNullException(nameof(query));
|
||||
ThrowIfDisposed();
|
||||
var lookupKey = QueryKey(query);
|
||||
var lazy = _inFlight.GetOrAdd(
|
||||
lookupKey,
|
||||
_ => new Lazy<Task<CultMeshDiscoveryState>>(
|
||||
() => ResolveOwnedAsync(query, CancellationToken.None),
|
||||
LazyThreadSafetyMode.ExecutionAndPublication));
|
||||
var shared = lazy.Value;
|
||||
_ = shared.ContinueWith(
|
||||
completed => _inFlight.TryRemove(lookupKey, out _),
|
||||
CancellationToken.None,
|
||||
TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default);
|
||||
return await AwaitForCallerAsync(shared, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static string QueryKey(CultMeshDiscoveryQuery query) =>
|
||||
query.VerseIds.Count == 0
|
||||
? query.EndpointId
|
||||
: query.EndpointId + "\u001f" + string.Join("\u001f", query.VerseIds);
|
||||
|
||||
private static async Task<T> AwaitForCallerAsync<T>(Task<T> shared, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!cancellationToken.CanBeCanceled)
|
||||
return await shared.ConfigureAwait(false);
|
||||
var cancelled = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using (cancellationToken.Register(() => cancelled.TrySetResult(true)))
|
||||
{
|
||||
if (await Task.WhenAny(shared, cancelled.Task).ConfigureAwait(false) != shared)
|
||||
throw new OperationCanceledException(cancellationToken);
|
||||
}
|
||||
return await shared.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<CultMeshDiscoveryState> ResolveOwnedAsync(
|
||||
CultMeshDiscoveryQuery query,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var queryKey = QueryKey(query);
|
||||
var previous = await LoadPreviousAsync(queryKey, cancellationToken).ConfigureAwait(false);
|
||||
var now = _options.Clock.UtcNow;
|
||||
if (previous != null &&
|
||||
((previous.Freshness == CultMeshDiscoveryFreshness.Fresh &&
|
||||
previous.Candidates.Count > 0 && previous.Candidates.All(candidate => candidate.ExpiresAtUtc > now)) ||
|
||||
(previous.Freshness == CultMeshDiscoveryFreshness.Unavailable && previous.RetryAfterUtc > now)))
|
||||
{
|
||||
return previous;
|
||||
}
|
||||
var lookups = _sources.Select(source => ObserveSourceAsync(source, query, cancellationToken)).ToArray();
|
||||
var results = await Task.WhenAll(lookups).ConfigureAwait(false);
|
||||
var failures = results.Where(result => result.Error != null).Select(result => result.SourceId).ToArray();
|
||||
var observations = results.SelectMany(result => result.Observations)
|
||||
.Where(observation => query.VerseIds.Count == 0 || query.VerseIds.Contains(observation.Candidate.VerseId, StringComparer.Ordinal))
|
||||
.ToArray();
|
||||
|
||||
foreach (var rejected in observations.Where(observation => observation.Trust == CultMeshDiscoveryTrust.Rejected))
|
||||
{
|
||||
Emit(CultMeshDiagnosticKind.CandidateRejected, query.EndpointId, rejected.Candidate.VerseId,
|
||||
"rejected", "trust_rejected", rejected.SourceId);
|
||||
}
|
||||
|
||||
var accepted = observations.Where(observation => observation.Trust != CultMeshDiscoveryTrust.Rejected)
|
||||
.GroupBy(observation => observation.Candidate.VerseId, StringComparer.Ordinal)
|
||||
.Select(group => group
|
||||
.OrderByDescending(observation => observation.Trust)
|
||||
.ThenByDescending(observation => observation.ObservedAtUtc)
|
||||
.First())
|
||||
.Select(observation => new CultMeshDiscoveryCandidate(
|
||||
observation.Candidate,
|
||||
observation.SourceId,
|
||||
observation.ObservedAtUtc,
|
||||
observation.ExpiresAtUtc,
|
||||
observation.Trust))
|
||||
.ToArray();
|
||||
|
||||
IReadOnlyList<CultMeshDiscoveryCandidate> candidates = accepted.Length > 0
|
||||
? accepted
|
||||
: previous?.Candidates ?? Array.Empty<CultMeshDiscoveryCandidate>();
|
||||
var freshCount = candidates.Count(candidate => candidate.ExpiresAtUtc > now);
|
||||
CultMeshDiscoveryFreshness freshness;
|
||||
if (accepted.Length > 0)
|
||||
freshness = freshCount == 0
|
||||
? CultMeshDiscoveryFreshness.Stale
|
||||
: failures.Length > 0 || freshCount < candidates.Count
|
||||
? CultMeshDiscoveryFreshness.Degraded
|
||||
: CultMeshDiscoveryFreshness.Fresh;
|
||||
else if (candidates.Count > 0)
|
||||
freshness = freshCount > 0 ? CultMeshDiscoveryFreshness.Degraded : CultMeshDiscoveryFreshness.Stale;
|
||||
else
|
||||
freshness = CultMeshDiscoveryFreshness.Unavailable;
|
||||
|
||||
var state = new CultMeshDiscoveryState(
|
||||
query.EndpointId,
|
||||
freshness,
|
||||
candidates,
|
||||
now,
|
||||
freshness == CultMeshDiscoveryFreshness.Fresh ? null : now + _options.NegativeTtl,
|
||||
failures,
|
||||
queryKey);
|
||||
_states[queryKey] = state;
|
||||
if (_options.Store != null) await _options.Store.SaveAsync(state, cancellationToken).ConfigureAwait(false);
|
||||
_updates.OnNext(state);
|
||||
Emit(CultMeshDiagnosticKind.DiscoveryObservation, query.EndpointId, query.EndpointId,
|
||||
freshness.ToString().ToLowerInvariant(), failures.Length == 0 ? "" : "source_failure", "discovery-service");
|
||||
return state;
|
||||
}
|
||||
|
||||
private static CultMeshDiscoveryState EvaluateAt(CultMeshDiscoveryState state, DateTimeOffset now)
|
||||
{
|
||||
if (state.Candidates.Count == 0 || state.Freshness == CultMeshDiscoveryFreshness.Unavailable)
|
||||
return state;
|
||||
var freshCount = state.Candidates.Count(candidate => candidate.ExpiresAtUtc > now);
|
||||
var freshness = freshCount == 0
|
||||
? CultMeshDiscoveryFreshness.Stale
|
||||
: freshCount < state.Candidates.Count || state.FailedSourceIds.Count > 0
|
||||
? CultMeshDiscoveryFreshness.Degraded
|
||||
: CultMeshDiscoveryFreshness.Fresh;
|
||||
return freshness == state.Freshness
|
||||
? state
|
||||
: new CultMeshDiscoveryState(
|
||||
state.EndpointId, freshness, state.Candidates, now,
|
||||
state.RetryAfterUtc, state.FailedSourceIds, state.QueryKey);
|
||||
}
|
||||
|
||||
private async Task<CultMeshDiscoveryState?> LoadPreviousAsync(string queryKey, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_states.TryGetValue(queryKey, out var current)) return current;
|
||||
if (_options.Store == null) return null;
|
||||
var stored = await _options.Store.LoadAsync(queryKey, cancellationToken).ConfigureAwait(false);
|
||||
if (stored != null) _states[queryKey] = stored;
|
||||
return stored;
|
||||
}
|
||||
|
||||
private static async Task<LookupResult> ObserveSourceAsync(
|
||||
ICultMeshLookupSource source,
|
||||
CultMeshDiscoveryQuery query,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var observations = await source.LookupAsync(query, cancellationToken).ConfigureAwait(false);
|
||||
return new LookupResult(source.SourceId, observations ?? Array.Empty<CultMeshDiscoveryObservation>(), null);
|
||||
}
|
||||
catch (Exception error) when (!(error is OperationCanceledException && cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
return new LookupResult(source.SourceId, Array.Empty<CultMeshDiscoveryObservation>(), error);
|
||||
}
|
||||
}
|
||||
|
||||
private void Emit(CultMeshDiagnosticKind kind, string operationId, string subjectId, string state, string reason, string source)
|
||||
{
|
||||
_options.Diagnostics.Emit(new CultMeshDiagnosticEvent(
|
||||
Interlocked.Increment(ref _diagnosticSequence), _options.Clock.UtcNow,
|
||||
CultMeshReliabilityOrgan.Discovery, kind, operationId, subjectId, state,
|
||||
reason, source, subjectId, CultMeshDiscoverySchemaVersions.State));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_updates.Dispose();
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshDiscoveryService));
|
||||
}
|
||||
|
||||
private sealed class LookupResult
|
||||
{
|
||||
public LookupResult(string sourceId, IReadOnlyList<CultMeshDiscoveryObservation> observations, Exception? error)
|
||||
{
|
||||
SourceId = sourceId;
|
||||
Observations = observations;
|
||||
Error = error;
|
||||
}
|
||||
|
||||
public string SourceId { get; }
|
||||
public IReadOnlyList<CultMeshDiscoveryObservation> Observations { get; }
|
||||
public Exception? Error { get; }
|
||||
}
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
[CultDocument("gamecult.mesh.discovery_state", CultMeshDiscoverySchemaVersions.State)]
|
||||
public sealed class CultMeshDiscoveryStateDocument
|
||||
{
|
||||
[Key(0), CultName] public string EndpointId { get; set; } = "";
|
||||
[Key(1)] public CultMeshDiscoveryFreshness Freshness { get; set; }
|
||||
[Key(2)] public string EvaluatedAtUtc { get; set; } = "";
|
||||
[Key(3)] public string? RetryAfterUtc { get; set; }
|
||||
[Key(4)] public string[] FailedSourceIds { get; set; } = Array.Empty<string>();
|
||||
[Key(5)] public CultMeshDiscoveryCandidateDocument[] Candidates { get; set; } = Array.Empty<CultMeshDiscoveryCandidateDocument>();
|
||||
[Key(6)] public string QueryKey { get; set; } = "";
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshDiscoveryCandidateDocument
|
||||
{
|
||||
[Key(0)] public CultMeshVerseDescriptorMessage Descriptor { get; set; } = new CultMeshVerseDescriptorMessage();
|
||||
[Key(1)] public string SourceId { get; set; } = "";
|
||||
[Key(2)] public string ObservedAtUtc { get; set; } = "";
|
||||
[Key(3)] public string ExpiresAtUtc { get; set; } = "";
|
||||
[Key(4)] public CultMeshDiscoveryTrust Trust { get; set; }
|
||||
}
|
||||
|
||||
public sealed class CultMeshCultCacheDiscoveryStore : ICultMeshDiscoveryStore
|
||||
{
|
||||
private readonly CultCache _cache;
|
||||
|
||||
public CultMeshCultCacheDiscoveryStore(CultCache cache)
|
||||
{
|
||||
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
|
||||
}
|
||||
|
||||
public Task<CultMeshDiscoveryState?> LoadAsync(string endpointId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var document = _cache.Get<CultMeshDiscoveryStateDocument>(Key(endpointId));
|
||||
return Task.FromResult(document == null ? null : FromDocument(document));
|
||||
}
|
||||
|
||||
public async Task SaveAsync(CultMeshDiscoveryState state, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await _cache.UpsertAsync(typeof(CultMeshDiscoveryStateDocument), ToDocument(state), Key(state.QueryKey)).ConfigureAwait(false);
|
||||
await _cache.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static CultRecordKey Key(string endpointId) => new CultRecordKey("mesh:discovery:" + StableToken(endpointId));
|
||||
|
||||
private static string StableToken(string value)
|
||||
{
|
||||
using var sha = System.Security.Cryptography.SHA256.Create();
|
||||
return string.Concat(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(value ?? "")).Select(item => item.ToString("x2")));
|
||||
}
|
||||
|
||||
private static CultMeshDiscoveryStateDocument ToDocument(CultMeshDiscoveryState state) => new CultMeshDiscoveryStateDocument
|
||||
{
|
||||
EndpointId = state.EndpointId,
|
||||
Freshness = state.Freshness,
|
||||
EvaluatedAtUtc = state.EvaluatedAtUtc.ToString("O"),
|
||||
RetryAfterUtc = state.RetryAfterUtc?.ToString("O"),
|
||||
FailedSourceIds = state.FailedSourceIds.ToArray(),
|
||||
QueryKey = state.QueryKey,
|
||||
Candidates = state.Candidates.Select(candidate => new CultMeshDiscoveryCandidateDocument
|
||||
{
|
||||
Descriptor = candidate.Descriptor.ToMessage(),
|
||||
SourceId = candidate.SourceId,
|
||||
ObservedAtUtc = candidate.ObservedAtUtc.ToString("O"),
|
||||
ExpiresAtUtc = candidate.ExpiresAtUtc.ToString("O"),
|
||||
Trust = candidate.Trust
|
||||
}).ToArray()
|
||||
};
|
||||
|
||||
private static CultMeshDiscoveryState FromDocument(CultMeshDiscoveryStateDocument document) => new CultMeshDiscoveryState(
|
||||
document.EndpointId,
|
||||
document.Freshness,
|
||||
document.Candidates.Select(candidate => new CultMeshDiscoveryCandidate(
|
||||
candidate.Descriptor.ToVerseDescriptor(),
|
||||
candidate.SourceId,
|
||||
DateTimeOffset.Parse(candidate.ObservedAtUtc, null, System.Globalization.DateTimeStyles.RoundtripKind),
|
||||
DateTimeOffset.Parse(candidate.ExpiresAtUtc, null, System.Globalization.DateTimeStyles.RoundtripKind),
|
||||
candidate.Trust)),
|
||||
DateTimeOffset.Parse(document.EvaluatedAtUtc, null, System.Globalization.DateTimeStyles.RoundtripKind),
|
||||
string.IsNullOrWhiteSpace(document.RetryAfterUtc) ? null : DateTimeOffset.Parse(document.RetryAfterUtc, null, System.Globalization.DateTimeStyles.RoundtripKind),
|
||||
document.FailedSourceIds,
|
||||
string.IsNullOrWhiteSpace(document.QueryKey) ? document.EndpointId : document.QueryKey);
|
||||
}
|
||||
}
|
||||
|
|
@ -26,13 +26,7 @@ namespace GameCult.Mesh
|
|||
throw new ArgumentNullException(nameof(documentTypes));
|
||||
}
|
||||
|
||||
var registry = new CultDocumentRegistry();
|
||||
foreach (var documentType in DistinctDocumentTypes(documentTypes))
|
||||
{
|
||||
registry.GetRequired(documentType);
|
||||
}
|
||||
|
||||
return registry;
|
||||
return CultDocumentRegistry.ForTypes(DistinctDocumentTypes(documentTypes));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
912
src/GameCult.Mesh/CultMeshFrameBodies.cs
Normal file
912
src/GameCult.Mesh/CultMeshFrameBodies.cs
Normal file
|
|
@ -0,0 +1,912 @@
|
|||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.MemoryMappedFiles;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
#nullable enable
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
// Owner: this publisher owns mapping lifetime, logical generation, and slot commit.
|
||||
// Consumers own only read leases; mappings, capabilities, and slot selection remain CultMesh state.
|
||||
public sealed class CultMeshFrameBodyPublisher : IDisposable
|
||||
{
|
||||
internal const string CapabilityPrefix = "frame-v2-";
|
||||
internal const int HeaderSize = 512;
|
||||
internal const int SequenceOffset = 8;
|
||||
internal const int ReaderCountOffset = 32;
|
||||
internal const int WriterCountOffset = 48;
|
||||
internal const int ContractHashOffset = 64;
|
||||
internal const int ByteLengthOffset = 128;
|
||||
internal const int LeaseExpiresAtOffset = 144;
|
||||
internal const int SemanticHashOffset = 192;
|
||||
internal const int SemanticHashStride = 64;
|
||||
private readonly object _gate = new();
|
||||
private readonly MemoryMappedFile _mapping;
|
||||
private readonly MemoryMappedViewAccessor _control;
|
||||
private readonly Mutex _mutex;
|
||||
private readonly TimeSpan _leaseDuration;
|
||||
private readonly string _token;
|
||||
private int _cursor;
|
||||
private long _nextSequence;
|
||||
private CultMeshFrameBodyWriteLease? _activeWrite;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshFrameBodyPublisher(
|
||||
string bodyId,
|
||||
string schemaId,
|
||||
int layoutVersion,
|
||||
int capacity,
|
||||
long producerEpoch,
|
||||
int slotByteLength,
|
||||
TimeSpan? leaseDuration = null)
|
||||
{
|
||||
BodyId = Require(bodyId, nameof(bodyId));
|
||||
SchemaId = Require(schemaId, nameof(schemaId));
|
||||
if (layoutVersion < 0) throw new ArgumentOutOfRangeException(nameof(layoutVersion));
|
||||
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
|
||||
if (producerEpoch < 0) throw new ArgumentOutOfRangeException(nameof(producerEpoch));
|
||||
if (slotByteLength <= 0) throw new ArgumentOutOfRangeException(nameof(slotByteLength));
|
||||
LayoutVersion = layoutVersion;
|
||||
Capacity = capacity;
|
||||
ProducerEpoch = producerEpoch;
|
||||
SlotByteLength = slotByteLength;
|
||||
_leaseDuration = leaseDuration ?? TimeSpan.FromSeconds(5);
|
||||
if (_leaseDuration <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(leaseDuration));
|
||||
_token = CapabilityPrefix + RandomToken();
|
||||
_mapping = MemoryMappedFile.CreateNew(MappingName(_token), checked(HeaderSize + CultMeshFrameRegion.SlotCount * slotByteLength));
|
||||
_control = _mapping.CreateViewAccessor(0, HeaderSize, MemoryMappedFileAccess.ReadWrite);
|
||||
_control.Write(0, slotByteLength);
|
||||
_control.Write(4, CultMeshFrameRegion.SlotCount);
|
||||
for (var slot = 0; slot < CultMeshFrameRegion.SlotCount; slot++)
|
||||
_control.Write(SequenceOffset + slot * sizeof(long), -1L);
|
||||
var contractHash = Encoding.ASCII.GetBytes(ContractHash(BodyId, SchemaId, LayoutVersion, Capacity, ProducerEpoch, SlotByteLength));
|
||||
_control.WriteArray(ContractHashOffset, contractHash, 0, contractHash.Length);
|
||||
_mutex = new Mutex(false, MutexName(_token));
|
||||
}
|
||||
|
||||
public string BodyId { get; }
|
||||
public string SchemaId { get; }
|
||||
public int LayoutVersion { get; }
|
||||
public int Capacity { get; }
|
||||
public long ProducerEpoch { get; }
|
||||
public int SlotByteLength { get; }
|
||||
|
||||
public bool TryPublish(ReadOnlySpan<byte> body, DateTimeOffset nowUtc, out CultMeshBodyDescriptor descriptor)
|
||||
{
|
||||
if (body.Length > SlotByteLength) throw new ArgumentOutOfRangeException(nameof(body));
|
||||
if (!TryAcquireWrite(out var write))
|
||||
{
|
||||
descriptor = null!;
|
||||
return false;
|
||||
}
|
||||
using (write)
|
||||
{
|
||||
body.CopyTo(write.Span);
|
||||
descriptor = write.Commit(body.Length, nowUtc);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reserves one producer-owned shared-memory slot for direct writes. The caller must commit or dispose the lease.
|
||||
/// </summary>
|
||||
public bool TryAcquireWrite(out CultMeshFrameBodyWriteLease lease)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (_activeWrite != null)
|
||||
{
|
||||
lease = null!;
|
||||
return false;
|
||||
}
|
||||
|
||||
var slot = -1;
|
||||
WithMutex(() =>
|
||||
{
|
||||
for (var attempt = 0; attempt < CultMeshFrameRegion.SlotCount; attempt++)
|
||||
{
|
||||
var candidate = (_cursor + attempt) % CultMeshFrameRegion.SlotCount;
|
||||
if (_control.ReadInt32(ReaderCountOffset + candidate * sizeof(int)) != 0 ||
|
||||
_control.ReadInt32(WriterCountOffset + candidate * sizeof(int)) != 0)
|
||||
continue;
|
||||
_control.Write(WriterCountOffset + candidate * sizeof(int), 1);
|
||||
slot = candidate;
|
||||
_cursor = (candidate + 1) % CultMeshFrameRegion.SlotCount;
|
||||
return;
|
||||
}
|
||||
});
|
||||
if (slot < 0)
|
||||
{
|
||||
lease = null!;
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var view = _mapping.CreateViewAccessor(
|
||||
SlotOffset(slot, SlotByteLength),
|
||||
SlotByteLength,
|
||||
MemoryMappedFileAccess.ReadWrite);
|
||||
lease = new CultMeshFrameBodyWriteLease(this, view, slot, _nextSequence, SlotByteLength);
|
||||
_activeWrite = lease;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
WithMutex(() => _control.Write(WriterCountOffset + slot * sizeof(int), 0));
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal CultMeshBodyDescriptor Commit(
|
||||
CultMeshFrameBodyWriteLease lease,
|
||||
int byteLength,
|
||||
DateTimeOffset nowUtc)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (!ReferenceEquals(_activeWrite, lease) || lease.Sequence != _nextSequence)
|
||||
throw new InvalidOperationException("The CultMesh frame write lease is stale or is not owned by this publisher.");
|
||||
if (byteLength < 0 || byteLength > SlotByteLength)
|
||||
throw new ArgumentOutOfRangeException(nameof(byteLength));
|
||||
var semanticHash = CultMeshBodyDescriptorValidator.ComputeSemanticHash(lease.Span[..byteLength]);
|
||||
WithMutex(() =>
|
||||
{
|
||||
var writerOffset = WriterCountOffset + lease.SlotIndex * sizeof(int);
|
||||
if (_control.ReadInt32(writerOffset) != 1 ||
|
||||
_control.ReadInt32(ReaderCountOffset + lease.SlotIndex * sizeof(int)) != 0)
|
||||
throw new InvalidOperationException("The CultMesh frame write reservation was lost before commit.");
|
||||
_control.Write(SequenceOffset + lease.SlotIndex * sizeof(long), lease.Sequence);
|
||||
_control.Write(ByteLengthOffset + lease.SlotIndex * sizeof(int), byteLength);
|
||||
_control.Write(LeaseExpiresAtOffset + lease.SlotIndex * sizeof(long), nowUtc.Add(_leaseDuration).ToUnixTimeMilliseconds());
|
||||
var hashBytes = Encoding.ASCII.GetBytes(semanticHash);
|
||||
_control.WriteArray(SemanticHashOffset + lease.SlotIndex * SemanticHashStride, hashBytes, 0, hashBytes.Length);
|
||||
_control.Write(writerOffset, 0);
|
||||
});
|
||||
var descriptor = Descriptor(lease.SlotIndex, byteLength, lease.Sequence, semanticHash, nowUtc);
|
||||
_nextSequence++;
|
||||
_activeWrite = null;
|
||||
lease.Complete();
|
||||
return descriptor;
|
||||
}
|
||||
}
|
||||
|
||||
internal void Abandon(CultMeshFrameBodyWriteLease lease)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!ReferenceEquals(_activeWrite, lease)) return;
|
||||
if (!_disposed)
|
||||
{
|
||||
WithMutex(() =>
|
||||
_control.Write(WriterCountOffset + lease.SlotIndex * sizeof(int), 0));
|
||||
}
|
||||
_activeWrite = null;
|
||||
}
|
||||
}
|
||||
|
||||
private CultMeshBodyDescriptor Descriptor(
|
||||
int slot,
|
||||
int byteLength,
|
||||
long sequence,
|
||||
string semanticHash,
|
||||
DateTimeOffset nowUtc) => new()
|
||||
{
|
||||
BodyId = BodyId, SchemaId = SchemaId, LayoutVersion = LayoutVersion, ByteSize = byteLength,
|
||||
Capacity = Capacity, ProducerEpoch = ProducerEpoch, Sequence = sequence,
|
||||
AccessMode = CultMeshBodyAccessMode.ReadOnly, Synchronization = CultMeshBodySynchronization.TripleBuffer,
|
||||
LeaseExpiresAtUnixMs = nowUtc.Add(_leaseDuration).ToUnixTimeMilliseconds(),
|
||||
TransportKind = CultMeshBodyTransportKind.SharedMemory,
|
||||
CapabilityToken = _token + "." + slot,
|
||||
SemanticHash = semanticHash
|
||||
};
|
||||
|
||||
internal static bool IsFrameCapability(string capability) => capability.StartsWith(CapabilityPrefix, StringComparison.Ordinal);
|
||||
|
||||
internal static ICultMeshBodyReadLease OpenReadOnly(CultMeshBodyDescriptor descriptor)
|
||||
{
|
||||
ParseCapability(descriptor.CapabilityToken, out var token, out var slot);
|
||||
MemoryMappedFile mapping;
|
||||
Mutex mutex;
|
||||
try
|
||||
{
|
||||
mapping = MemoryMappedFile.OpenExisting(MappingName(token), MemoryMappedFileRights.ReadWrite);
|
||||
mutex = Mutex.OpenExisting(MutexName(token));
|
||||
}
|
||||
catch (Exception error) when (error is FileNotFoundException || error is WaitHandleCannotBeOpenedException)
|
||||
{
|
||||
throw new InvalidDataException("CultMesh frame capability is unavailable or revoked.", error);
|
||||
}
|
||||
try
|
||||
{
|
||||
int slotByteLength = 0;
|
||||
WithMutex(mutex, () =>
|
||||
{
|
||||
using var control = mapping.CreateViewAccessor(0, HeaderSize, MemoryMappedFileAccess.ReadWrite);
|
||||
slotByteLength = control.ReadInt32(0);
|
||||
if (slot < 0 || slot >= control.ReadInt32(4) || descriptor.ByteSize > slotByteLength)
|
||||
throw new InvalidDataException("CultMesh frame capability does not match its mapping layout.");
|
||||
var contractHash = new byte[64];
|
||||
control.ReadArray(ContractHashOffset, contractHash, 0, contractHash.Length);
|
||||
var expectedContract = ContractHash(
|
||||
descriptor.BodyId, descriptor.SchemaId, descriptor.LayoutVersion,
|
||||
descriptor.Capacity, descriptor.ProducerEpoch, slotByteLength);
|
||||
if (!string.Equals(Encoding.ASCII.GetString(contractHash), expectedContract, StringComparison.Ordinal) ||
|
||||
control.ReadInt64(SequenceOffset + slot * sizeof(long)) != descriptor.Sequence)
|
||||
throw new InvalidOperationException("CultMesh frame generation is stale or belongs to a different body contract.");
|
||||
var offset = ReaderCountOffset + slot * sizeof(int);
|
||||
control.Write(offset, checked(control.ReadInt32(offset) + 1));
|
||||
});
|
||||
return new CultMeshMappedBodyLease(
|
||||
descriptor, mapping, SlotOffset(slot, slotByteLength),
|
||||
() => ReleaseReader(token, slot));
|
||||
}
|
||||
catch
|
||||
{
|
||||
mapping.Dispose();
|
||||
mutex.Dispose();
|
||||
throw;
|
||||
}
|
||||
finally { mutex.Dispose(); }
|
||||
}
|
||||
|
||||
internal static void ReleaseReader(string token, int slot)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var mapping = MemoryMappedFile.OpenExisting(MappingName(token), MemoryMappedFileRights.ReadWrite);
|
||||
using var mutex = Mutex.OpenExisting(MutexName(token));
|
||||
WithMutex(mutex, () =>
|
||||
{
|
||||
using var control = mapping.CreateViewAccessor(0, HeaderSize, MemoryMappedFileAccess.ReadWrite);
|
||||
var offset = ReaderCountOffset + slot * sizeof(int);
|
||||
var readers = control.ReadInt32(offset);
|
||||
if (readers > 0) control.Write(offset, readers - 1);
|
||||
});
|
||||
}
|
||||
catch (Exception error) when (error is FileNotFoundException || error is WaitHandleCannotBeOpenedException) { }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_activeWrite?.Invalidate();
|
||||
_activeWrite = null;
|
||||
_control.Dispose();
|
||||
_mapping.Dispose();
|
||||
_mutex.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void WithMutex(Action action) => WithMutex(_mutex, action);
|
||||
internal static void WithMutex(Mutex mutex, Action action)
|
||||
{
|
||||
mutex.WaitOne();
|
||||
try { action(); }
|
||||
finally { mutex.ReleaseMutex(); }
|
||||
}
|
||||
internal static long SlotOffset(int slot, int slotByteLength) => HeaderSize + (long)slot * slotByteLength;
|
||||
internal static string MappingName(string token) => "cultmesh-map-" + token;
|
||||
internal static string MutexName(string token) => "cultmesh-lock-" + token;
|
||||
internal static void ParseCapability(string capability, out string token, out int slot)
|
||||
{
|
||||
var separator = capability.LastIndexOf('.');
|
||||
if (separator <= CapabilityPrefix.Length || !int.TryParse(capability.Substring(separator + 1), out slot))
|
||||
throw new UnauthorizedAccessException("Invalid CultMesh frame capability.");
|
||||
token = capability.Substring(0, separator);
|
||||
}
|
||||
private static string RandomToken()
|
||||
{
|
||||
var bytes = new byte[24];
|
||||
using (var random = RandomNumberGenerator.Create()) random.GetBytes(bytes);
|
||||
return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant();
|
||||
}
|
||||
internal static string ContractHash(string bodyId, string schemaId, int layoutVersion, int capacity, long epoch, int slotByteLength) =>
|
||||
CultMeshBodyDescriptorValidator.ComputeSemanticHash(
|
||||
Encoding.UTF8.GetBytes($"{bodyId}\n{schemaId}\n{layoutVersion}\n{capacity}\n{epoch}\n{slotByteLength}"));
|
||||
private void ThrowIfDisposed() { if (_disposed) throw new ObjectDisposedException(nameof(CultMeshFrameBodyPublisher)); }
|
||||
private static string Require(string value, string name) => string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Value is required.", name) : value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retains one verified shared-memory frame mapping and leases only newer committed generations.
|
||||
/// The control plane is needed for bootstrap and layout changes, not for every frame.
|
||||
/// </summary>
|
||||
public sealed class CultMeshMappedFrameBodyCursor : IDisposable
|
||||
{
|
||||
private readonly CultMeshBodyDescriptor _contract;
|
||||
private readonly string _token;
|
||||
private readonly MemoryMappedFile _mapping;
|
||||
private readonly MemoryMappedViewAccessor _control;
|
||||
private readonly Mutex _mutex;
|
||||
private readonly int _slotByteLength;
|
||||
private long _lastSequence = -1;
|
||||
private bool _disposed;
|
||||
|
||||
public static bool CanOpen(CultMeshBodyDescriptor descriptor) =>
|
||||
descriptor != null &&
|
||||
descriptor.TransportKind == CultMeshBodyTransportKind.SharedMemory &&
|
||||
descriptor.Synchronization == CultMeshBodySynchronization.TripleBuffer &&
|
||||
CultMeshFrameBodyPublisher.IsFrameCapability(descriptor.CapabilityToken);
|
||||
|
||||
public CultMeshMappedFrameBodyCursor(CultMeshBodyDescriptor descriptor)
|
||||
{
|
||||
_contract = descriptor ?? throw new ArgumentNullException(nameof(descriptor));
|
||||
if (!CanOpen(descriptor))
|
||||
throw new ArgumentException("Descriptor is not a mapped CultMesh frame capability.", nameof(descriptor));
|
||||
CultMeshFrameBodyPublisher.ParseCapability(descriptor.CapabilityToken, out _token, out _);
|
||||
try
|
||||
{
|
||||
_mapping = MemoryMappedFile.OpenExisting(
|
||||
CultMeshFrameBodyPublisher.MappingName(_token),
|
||||
MemoryMappedFileRights.ReadWrite);
|
||||
_mutex = Mutex.OpenExisting(CultMeshFrameBodyPublisher.MutexName(_token));
|
||||
}
|
||||
catch (Exception error) when (error is FileNotFoundException || error is WaitHandleCannotBeOpenedException)
|
||||
{
|
||||
throw new InvalidDataException("CultMesh frame capability is unavailable or revoked.", error);
|
||||
}
|
||||
try
|
||||
{
|
||||
_control = _mapping.CreateViewAccessor(
|
||||
0,
|
||||
CultMeshFrameBodyPublisher.HeaderSize,
|
||||
MemoryMappedFileAccess.ReadWrite);
|
||||
_slotByteLength = _control.ReadInt32(0);
|
||||
var contractHash = new byte[64];
|
||||
_control.ReadArray(CultMeshFrameBodyPublisher.ContractHashOffset, contractHash, 0, contractHash.Length);
|
||||
var expected = CultMeshFrameBodyPublisher.ContractHash(
|
||||
descriptor.BodyId,
|
||||
descriptor.SchemaId,
|
||||
descriptor.LayoutVersion,
|
||||
descriptor.Capacity,
|
||||
descriptor.ProducerEpoch,
|
||||
_slotByteLength);
|
||||
if (!string.Equals(Encoding.ASCII.GetString(contractHash), expected, StringComparison.Ordinal))
|
||||
throw new InvalidDataException("CultMesh frame cursor contract does not match its mapping.");
|
||||
}
|
||||
catch
|
||||
{
|
||||
_mapping.Dispose();
|
||||
_mutex.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public long LastSequence => _lastSequence;
|
||||
|
||||
public bool TryAcquireLatest(out ICultMeshBodyReadLease lease) =>
|
||||
TryAcquireLatest(DateTimeOffset.UtcNow, out lease);
|
||||
|
||||
public bool TryAcquireLatest(DateTimeOffset nowUtc, out ICultMeshBodyReadLease lease)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshMappedFrameBodyCursor));
|
||||
var slot = -1;
|
||||
var sequence = -1L;
|
||||
var byteLength = 0;
|
||||
var leaseExpiresAt = 0L;
|
||||
var semanticHash = "";
|
||||
CultMeshFrameBodyPublisher.WithMutex(_mutex, () =>
|
||||
{
|
||||
var slotCount = _control.ReadInt32(4);
|
||||
for (var candidate = 0; candidate < slotCount; candidate++)
|
||||
{
|
||||
if (_control.ReadInt32(CultMeshFrameBodyPublisher.WriterCountOffset + candidate * sizeof(int)) != 0)
|
||||
continue;
|
||||
var candidateSequence = _control.ReadInt64(
|
||||
CultMeshFrameBodyPublisher.SequenceOffset + candidate * sizeof(long));
|
||||
if (candidateSequence <= _lastSequence || candidateSequence <= sequence)
|
||||
continue;
|
||||
var candidateExpiry = _control.ReadInt64(
|
||||
CultMeshFrameBodyPublisher.LeaseExpiresAtOffset + candidate * sizeof(long));
|
||||
var candidateLength = _control.ReadInt32(
|
||||
CultMeshFrameBodyPublisher.ByteLengthOffset + candidate * sizeof(int));
|
||||
// A byte-length change means the control-plane layout contract changed.
|
||||
// Do not expose that generation through a cursor bootstrapped against
|
||||
// the previous layout; its new descriptor must arrive first.
|
||||
if (candidateExpiry <= nowUtc.ToUnixTimeMilliseconds() ||
|
||||
candidateLength != _contract.ByteSize || candidateLength > _slotByteLength)
|
||||
continue;
|
||||
slot = candidate;
|
||||
sequence = candidateSequence;
|
||||
leaseExpiresAt = candidateExpiry;
|
||||
byteLength = candidateLength;
|
||||
}
|
||||
if (slot < 0) return;
|
||||
var hashBytes = new byte[CultMeshFrameBodyPublisher.SemanticHashStride];
|
||||
_control.ReadArray(
|
||||
CultMeshFrameBodyPublisher.SemanticHashOffset + slot * CultMeshFrameBodyPublisher.SemanticHashStride,
|
||||
hashBytes,
|
||||
0,
|
||||
hashBytes.Length);
|
||||
semanticHash = Encoding.ASCII.GetString(hashBytes);
|
||||
var readerOffset = CultMeshFrameBodyPublisher.ReaderCountOffset + slot * sizeof(int);
|
||||
_control.Write(readerOffset, checked(_control.ReadInt32(readerOffset) + 1));
|
||||
});
|
||||
if (slot < 0)
|
||||
{
|
||||
lease = null!;
|
||||
return false;
|
||||
}
|
||||
|
||||
var descriptor = new CultMeshBodyDescriptor
|
||||
{
|
||||
BodyId = _contract.BodyId,
|
||||
SchemaId = _contract.SchemaId,
|
||||
LayoutVersion = _contract.LayoutVersion,
|
||||
ByteSize = byteLength,
|
||||
Capacity = _contract.Capacity,
|
||||
ProducerEpoch = _contract.ProducerEpoch,
|
||||
Sequence = sequence,
|
||||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
Synchronization = CultMeshBodySynchronization.TripleBuffer,
|
||||
LeaseExpiresAtUnixMs = leaseExpiresAt,
|
||||
TransportKind = CultMeshBodyTransportKind.SharedMemory,
|
||||
CapabilityToken = _token + "." + slot,
|
||||
SemanticHash = semanticHash
|
||||
};
|
||||
try
|
||||
{
|
||||
var mapping = MemoryMappedFile.OpenExisting(
|
||||
CultMeshFrameBodyPublisher.MappingName(_token),
|
||||
MemoryMappedFileRights.ReadWrite);
|
||||
lease = new CultMeshMappedBodyLease(
|
||||
descriptor,
|
||||
mapping,
|
||||
CultMeshFrameBodyPublisher.SlotOffset(slot, _slotByteLength),
|
||||
() => CultMeshFrameBodyPublisher.ReleaseReader(_token, slot));
|
||||
_lastSequence = sequence;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
CultMeshFrameBodyPublisher.ReleaseReader(_token, slot);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_control.Dispose();
|
||||
_mapping.Dispose();
|
||||
_mutex.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A bounded producer lease over one directly writable shared-memory frame slot.</summary>
|
||||
public sealed unsafe class CultMeshFrameBodyWriteLease : IDisposable
|
||||
{
|
||||
private CultMeshFrameBodyPublisher? _owner;
|
||||
private readonly MemoryMappedViewAccessor _view;
|
||||
private readonly CultMeshMappedMemoryManager _memory;
|
||||
private bool _completed;
|
||||
|
||||
internal CultMeshFrameBodyWriteLease(
|
||||
CultMeshFrameBodyPublisher owner,
|
||||
MemoryMappedViewAccessor view,
|
||||
int slotIndex,
|
||||
long sequence,
|
||||
int byteLength)
|
||||
{
|
||||
_owner = owner;
|
||||
_view = view;
|
||||
_memory = new CultMeshMappedMemoryManager(view, byteLength);
|
||||
SlotIndex = slotIndex;
|
||||
Sequence = sequence;
|
||||
}
|
||||
|
||||
public int SlotIndex { get; }
|
||||
public long Sequence { get; }
|
||||
public Memory<byte> Memory => _memory.Memory;
|
||||
public Span<byte> Span => Memory.Span;
|
||||
|
||||
public CultMeshBodyDescriptor Commit(int byteLength, DateTimeOffset nowUtc) =>
|
||||
(_owner ?? throw new ObjectDisposedException(nameof(CultMeshFrameBodyWriteLease)))
|
||||
.Commit(this, byteLength, nowUtc);
|
||||
|
||||
internal void Complete()
|
||||
{
|
||||
_completed = true;
|
||||
ReleaseResources();
|
||||
}
|
||||
|
||||
internal void Invalidate()
|
||||
{
|
||||
_owner = null;
|
||||
ReleaseResources();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
var owner = Interlocked.Exchange(ref _owner, null);
|
||||
if (!_completed) owner?.Abandon(this);
|
||||
ReleaseResources();
|
||||
}
|
||||
|
||||
private void ReleaseResources()
|
||||
{
|
||||
((IDisposable)_memory).Dispose();
|
||||
_view.Dispose();
|
||||
_owner = null;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed unsafe class CultMeshMappedMemoryManager : MemoryManager<byte>
|
||||
{
|
||||
private SafeMemoryMappedViewHandle? _handle;
|
||||
private byte* _pointer;
|
||||
private readonly int _length;
|
||||
|
||||
public CultMeshMappedMemoryManager(MemoryMappedViewAccessor view, int length)
|
||||
{
|
||||
_handle = view.SafeMemoryMappedViewHandle;
|
||||
_length = length;
|
||||
byte* pointer = null;
|
||||
_handle.AcquirePointer(ref pointer);
|
||||
_pointer = pointer + view.PointerOffset;
|
||||
}
|
||||
|
||||
public override Span<byte> GetSpan() =>
|
||||
_handle == null ? throw new ObjectDisposedException(nameof(CultMeshMappedMemoryManager)) : new Span<byte>(_pointer, _length);
|
||||
|
||||
public override MemoryHandle Pin(int elementIndex = 0)
|
||||
{
|
||||
if ((uint)elementIndex > (uint)_length) throw new ArgumentOutOfRangeException(nameof(elementIndex));
|
||||
if (_handle == null) throw new ObjectDisposedException(nameof(CultMeshMappedMemoryManager));
|
||||
return new MemoryHandle(_pointer + elementIndex);
|
||||
}
|
||||
|
||||
public override void Unpin() { }
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
var handle = Interlocked.Exchange(ref _handle, null);
|
||||
if (handle == null) return;
|
||||
handle.ReleasePointer();
|
||||
_pointer = null;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshFrameGeneration
|
||||
{
|
||||
internal CultMeshFrameGeneration(
|
||||
int slotIndex,
|
||||
CultMeshBodyDescriptor descriptor,
|
||||
long timestampNs,
|
||||
long durationNs,
|
||||
int unavoidableCopyCount,
|
||||
IReadOnlyDictionary<string, string>? metadata)
|
||||
{
|
||||
SlotIndex = slotIndex;
|
||||
Descriptor = descriptor;
|
||||
TimestampNs = timestampNs;
|
||||
DurationNs = durationNs;
|
||||
UnavoidableCopyCount = unavoidableCopyCount;
|
||||
Metadata = metadata == null
|
||||
? new Dictionary<string, string>()
|
||||
: new Dictionary<string, string>(metadata);
|
||||
}
|
||||
|
||||
public int SlotIndex { get; }
|
||||
public CultMeshBodyDescriptor Descriptor { get; }
|
||||
public long TimestampNs { get; }
|
||||
public long DurationNs { get; }
|
||||
public int UnavoidableCopyCount { get; }
|
||||
public IReadOnlyDictionary<string, string> Metadata { get; }
|
||||
}
|
||||
|
||||
public readonly struct CultMeshFrameRegionWriteLease
|
||||
{
|
||||
private readonly CultMeshFrameRegion? _owner;
|
||||
private readonly object? _reservation;
|
||||
|
||||
internal CultMeshFrameRegionWriteLease(
|
||||
CultMeshFrameRegion owner,
|
||||
object reservation,
|
||||
int slotIndex,
|
||||
long sequence,
|
||||
Memory<byte> memory)
|
||||
{
|
||||
_owner = owner;
|
||||
_reservation = reservation;
|
||||
SlotIndex = slotIndex;
|
||||
Sequence = sequence;
|
||||
Memory = memory;
|
||||
}
|
||||
|
||||
public int SlotIndex { get; }
|
||||
public long Sequence { get; }
|
||||
public Memory<byte> Memory { get; }
|
||||
public Span<byte> Span => Memory.Span;
|
||||
|
||||
internal CultMeshFrameGeneration Commit(
|
||||
int byteLength,
|
||||
long timestampNs,
|
||||
long durationNs,
|
||||
int unavoidableCopyCount,
|
||||
IReadOnlyDictionary<string, string>? metadata) =>
|
||||
_owner?.Commit(this, _reservation!, byteLength, timestampNs, durationNs, unavoidableCopyCount, metadata)
|
||||
?? throw new InvalidOperationException("The frame-region write lease is not valid.");
|
||||
}
|
||||
|
||||
public sealed class CultMeshFrameRegionReadLease : IDisposable
|
||||
{
|
||||
private CultMeshFrameRegion? _owner;
|
||||
|
||||
internal CultMeshFrameRegionReadLease(
|
||||
CultMeshFrameRegion owner,
|
||||
CultMeshFrameGeneration generation,
|
||||
ReadOnlyMemory<byte> memory)
|
||||
{
|
||||
_owner = owner;
|
||||
Generation = generation;
|
||||
Memory = memory;
|
||||
}
|
||||
|
||||
public CultMeshFrameGeneration Generation { get; }
|
||||
public ReadOnlyMemory<byte> Memory { get; }
|
||||
public ReadOnlySpan<byte> Span => Memory.Span;
|
||||
|
||||
public void Dispose() => Interlocked.Exchange(ref _owner, null)?.ReleaseRead(Generation.SlotIndex);
|
||||
}
|
||||
|
||||
public sealed class CultMeshFrameRegionStats
|
||||
{
|
||||
internal CultMeshFrameRegionStats(
|
||||
ulong publishedFrames,
|
||||
ulong droppedFrames,
|
||||
ulong blockedWrites,
|
||||
long latestSequence,
|
||||
ulong unavoidableCopyCount)
|
||||
{
|
||||
PublishedFrames = publishedFrames;
|
||||
DroppedFrames = droppedFrames;
|
||||
BlockedWrites = blockedWrites;
|
||||
LatestSequence = latestSequence;
|
||||
UnavoidableCopyCount = unavoidableCopyCount;
|
||||
}
|
||||
|
||||
public ulong PublishedFrames { get; }
|
||||
public ulong DroppedFrames { get; }
|
||||
public ulong BlockedWrites { get; }
|
||||
public long LatestSequence { get; }
|
||||
public ulong UnavoidableCopyCount { get; }
|
||||
}
|
||||
|
||||
public sealed class CultMeshFrameRegion : IDisposable
|
||||
{
|
||||
public const int SlotCount = 3;
|
||||
|
||||
private readonly object _gate = new();
|
||||
private readonly byte[] _storage;
|
||||
private readonly int[] _readerCounts = new int[SlotCount];
|
||||
private readonly object?[] _writeReservations = new object?[SlotCount];
|
||||
private readonly CultMeshFrameGeneration?[] _generations = new CultMeshFrameGeneration?[SlotCount];
|
||||
private object? _activeWriteReservation;
|
||||
private int _writeCursor;
|
||||
private int _latestSlot = -1;
|
||||
private bool _disposed;
|
||||
private long _nextSequence;
|
||||
private ulong _publishedFrames;
|
||||
private ulong _droppedFrames;
|
||||
private ulong _blockedWrites;
|
||||
private ulong _unavoidableCopyCount;
|
||||
|
||||
public CultMeshFrameRegion(
|
||||
string bodyId,
|
||||
string schemaId,
|
||||
int layoutVersion,
|
||||
int capacity,
|
||||
long producerEpoch,
|
||||
int slotByteLength)
|
||||
{
|
||||
BodyId = Require(bodyId, nameof(bodyId));
|
||||
SchemaId = Require(schemaId, nameof(schemaId));
|
||||
if (layoutVersion < 0) throw new ArgumentOutOfRangeException(nameof(layoutVersion));
|
||||
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
|
||||
if (producerEpoch < 0) throw new ArgumentOutOfRangeException(nameof(producerEpoch));
|
||||
if (slotByteLength <= 0) throw new ArgumentOutOfRangeException(nameof(slotByteLength));
|
||||
LayoutVersion = layoutVersion;
|
||||
Capacity = capacity;
|
||||
ProducerEpoch = producerEpoch;
|
||||
SlotByteLength = slotByteLength;
|
||||
_storage = new byte[checked(SlotCount * slotByteLength)];
|
||||
}
|
||||
|
||||
public string BodyId { get; }
|
||||
public string SchemaId { get; }
|
||||
public int LayoutVersion { get; }
|
||||
public int Capacity { get; }
|
||||
public long ProducerEpoch { get; }
|
||||
public int SlotByteLength { get; }
|
||||
|
||||
public bool TryAcquireWrite(out CultMeshFrameRegionWriteLease lease)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (_activeWriteReservation != null)
|
||||
{
|
||||
_blockedWrites++;
|
||||
lease = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var attempt = 0; attempt < SlotCount; attempt++)
|
||||
{
|
||||
var slotIndex = (_writeCursor + attempt) % SlotCount;
|
||||
if (_readerCounts[slotIndex] != 0 || _writeReservations[slotIndex] != null)
|
||||
continue;
|
||||
|
||||
if (_generations[slotIndex] != null)
|
||||
_droppedFrames++;
|
||||
|
||||
var reservation = new object();
|
||||
_writeReservations[slotIndex] = reservation;
|
||||
_activeWriteReservation = reservation;
|
||||
_writeCursor = (slotIndex + 1) % SlotCount;
|
||||
lease = new CultMeshFrameRegionWriteLease(
|
||||
this,
|
||||
reservation,
|
||||
slotIndex,
|
||||
_nextSequence,
|
||||
new Memory<byte>(_storage, slotIndex * SlotByteLength, SlotByteLength));
|
||||
return true;
|
||||
}
|
||||
|
||||
_blockedWrites++;
|
||||
lease = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public CultMeshFrameGeneration Commit(
|
||||
CultMeshFrameRegionWriteLease lease,
|
||||
int byteLength,
|
||||
long timestampNs,
|
||||
long durationNs = 0,
|
||||
int unavoidableCopyCount = 0,
|
||||
IReadOnlyDictionary<string, string>? metadata = null) =>
|
||||
lease.Commit(byteLength, timestampNs, durationNs, unavoidableCopyCount, metadata);
|
||||
|
||||
internal CultMeshFrameGeneration Commit(
|
||||
CultMeshFrameRegionWriteLease lease,
|
||||
object reservation,
|
||||
int byteLength,
|
||||
long timestampNs,
|
||||
long durationNs,
|
||||
int unavoidableCopyCount,
|
||||
IReadOnlyDictionary<string, string>? metadata)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
RequireSlot(lease.SlotIndex);
|
||||
if (!ReferenceEquals(_activeWriteReservation, reservation) ||
|
||||
!ReferenceEquals(_writeReservations[lease.SlotIndex], reservation) ||
|
||||
lease.Sequence != _nextSequence)
|
||||
throw new InvalidOperationException("The frame-region write lease is stale or was already committed.");
|
||||
if (byteLength < 0 || byteLength > SlotByteLength)
|
||||
throw new ArgumentOutOfRangeException(nameof(byteLength));
|
||||
|
||||
var descriptor = new CultMeshBodyDescriptor
|
||||
{
|
||||
BodyId = BodyId,
|
||||
SchemaId = SchemaId,
|
||||
LayoutVersion = LayoutVersion,
|
||||
ByteSize = byteLength,
|
||||
Capacity = Capacity,
|
||||
ProducerEpoch = ProducerEpoch,
|
||||
Sequence = _nextSequence,
|
||||
AccessMode = CultMeshBodyAccessMode.ReadOnly,
|
||||
Synchronization = CultMeshBodySynchronization.TripleBuffer,
|
||||
LeaseExpiresAtUnixMs = long.MaxValue,
|
||||
TransportKind = CultMeshBodyTransportKind.SharedMemory,
|
||||
SemanticHash = CultMeshBodyDescriptorValidator.ComputeSemanticHash(
|
||||
lease.Span[..byteLength])
|
||||
};
|
||||
var generation = new CultMeshFrameGeneration(
|
||||
lease.SlotIndex, descriptor, timestampNs, durationNs, unavoidableCopyCount, metadata);
|
||||
|
||||
_generations[lease.SlotIndex] = generation;
|
||||
_writeReservations[lease.SlotIndex] = null;
|
||||
_activeWriteReservation = null;
|
||||
_latestSlot = lease.SlotIndex;
|
||||
_nextSequence++;
|
||||
_publishedFrames++;
|
||||
_unavoidableCopyCount += (ulong)Math.Max(0, unavoidableCopyCount);
|
||||
return generation;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryAcquireLatestRead(
|
||||
CultMeshBodyValidationRequest request,
|
||||
out CultMeshFrameRegionReadLease lease)
|
||||
{
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (_latestSlot < 0 || _generations[_latestSlot] == null)
|
||||
{
|
||||
lease = null!;
|
||||
return false;
|
||||
}
|
||||
|
||||
var generation = _generations[_latestSlot]!;
|
||||
CultMeshBodyDescriptorValidator.Validate(generation.Descriptor, request);
|
||||
_readerCounts[_latestSlot]++;
|
||||
lease = new CultMeshFrameRegionReadLease(
|
||||
this,
|
||||
generation,
|
||||
new ReadOnlyMemory<byte>(
|
||||
_storage,
|
||||
_latestSlot * SlotByteLength,
|
||||
checked((int)generation.Descriptor.ByteSize)));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public CultMeshFrameRegionStats Stats()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return new CultMeshFrameRegionStats(
|
||||
_publishedFrames,
|
||||
_droppedFrames,
|
||||
_blockedWrites,
|
||||
_latestSlot < 0 ? 0 : _generations[_latestSlot]!.Descriptor.Sequence,
|
||||
_unavoidableCopyCount);
|
||||
}
|
||||
}
|
||||
|
||||
internal void ReleaseRead(int slotIndex)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
RequireSlot(slotIndex);
|
||||
if (_readerCounts[slotIndex] <= 0)
|
||||
throw new InvalidOperationException("The frame-region reader lease was released more than once.");
|
||||
_readerCounts[slotIndex]--;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshFrameRegion));
|
||||
}
|
||||
|
||||
private static string Require(string value, string parameterName) =>
|
||||
string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Value is required.", parameterName) : value;
|
||||
|
||||
private static void RequireSlot(int slotIndex)
|
||||
{
|
||||
if (slotIndex < 0 || slotIndex >= SlotCount) throw new ArgumentOutOfRangeException(nameof(slotIndex));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -28,6 +28,12 @@ namespace GameCult.Mesh
|
|||
/// </summary>
|
||||
public CultMeshAuthorityLeaseCatalog? AuthorityLeases { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the sole authority resolver used by the session. When omitted, the
|
||||
/// session installs a deny-by-default resolver over <see cref="AuthorityLeases"/>.
|
||||
/// </summary>
|
||||
public CultMeshAuthorityResolver? AuthorityResolver { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets simulation consensus options.
|
||||
/// </summary>
|
||||
|
|
@ -68,6 +74,7 @@ namespace GameCult.Mesh
|
|||
VerseCatalog = options.VerseCatalog ?? new CultMeshVerseCatalog();
|
||||
PeerCatalog = options.PeerCatalog ?? new CultMeshPeerCatalog();
|
||||
AuthorityLeases = options.AuthorityLeases ?? new CultMeshAuthorityLeaseCatalog();
|
||||
AuthorityResolver = options.AuthorityResolver ?? CultMeshAuthorityResolver.CreateDenyByDefault(AuthorityLeases);
|
||||
ObservationHub = new CultNetSimulationObservationHub(options.ConsensusOptions);
|
||||
FactCommitter = new CultMeshSimulationFactCommitter(Node.Database);
|
||||
|
||||
|
|
@ -117,6 +124,9 @@ namespace GameCult.Mesh
|
|||
/// </summary>
|
||||
public CultMeshAuthorityLeaseCatalog AuthorityLeases { get; }
|
||||
|
||||
/// <summary>Gets the session authority decision owner.</summary>
|
||||
public CultMeshAuthorityResolver AuthorityResolver { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the session simulation observation hub.
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,79 @@
|
|||
using System;
|
||||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
|
||||
#nullable enable
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads the current structured invocation record and the legacy operation-id string.
|
||||
/// </summary>
|
||||
public sealed class CultMeshOperationInvocationRecordFormatter :
|
||||
IMessagePackFormatter<CultMeshOperationInvocationRecord?>
|
||||
{
|
||||
private const int FieldCount = 5;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Serialize(
|
||||
ref MessagePackWriter writer,
|
||||
CultMeshOperationInvocationRecord? value,
|
||||
MessagePackSerializerOptions options)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
writer.WriteNil();
|
||||
return;
|
||||
}
|
||||
|
||||
writer.WriteArrayHeader(FieldCount);
|
||||
writer.Write(value.OperationId);
|
||||
writer.Write(value.SchemaId);
|
||||
writer.Write(value.RouteKind);
|
||||
writer.Write(value.RouteDescription);
|
||||
writer.Write(value.IdempotencyKey);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public CultMeshOperationInvocationRecord? Deserialize(
|
||||
ref MessagePackReader reader,
|
||||
MessagePackSerializerOptions options)
|
||||
{
|
||||
if (reader.TryReadNil())
|
||||
return new CultMeshOperationInvocationRecord();
|
||||
|
||||
if (reader.NextMessagePackType == MessagePackType.String)
|
||||
return new CultMeshOperationInvocationRecord(reader.ReadString());
|
||||
|
||||
if (reader.NextMessagePackType != MessagePackType.Array)
|
||||
throw new MessagePackSerializationException(
|
||||
$"CultMesh operation invocation must be a string or array, not {reader.NextMessagePackType}.");
|
||||
|
||||
options.Security.DepthStep(ref reader);
|
||||
try
|
||||
{
|
||||
var fields = reader.ReadArrayHeader();
|
||||
var operationId = ReadString(ref reader, fields, 0);
|
||||
var schemaId = ReadString(ref reader, fields, 1);
|
||||
var routeKind = ReadString(ref reader, fields, 2);
|
||||
var routeDescription = ReadString(ref reader, fields, 3);
|
||||
var idempotencyKey = ReadString(ref reader, fields, 4);
|
||||
for (var index = FieldCount; index < fields; index++)
|
||||
reader.Skip();
|
||||
return new CultMeshOperationInvocationRecord(
|
||||
operationId,
|
||||
schemaId,
|
||||
routeKind,
|
||||
routeDescription,
|
||||
idempotencyKey);
|
||||
}
|
||||
finally
|
||||
{
|
||||
reader.Depth--;
|
||||
}
|
||||
}
|
||||
|
||||
private static string ReadString(ref MessagePackReader reader, int fields, int index) =>
|
||||
index < fields ? reader.ReadString() ?? "" : "";
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Networking;
|
||||
using R3;
|
||||
|
|
@ -191,23 +192,40 @@ namespace GameCult.Mesh
|
|||
}
|
||||
|
||||
/// <summary>Finds peers that advertise a Verse role and are authorized by the supplied lease catalog.</summary>
|
||||
[Obsolete("Supply CultMeshAuthorityResolver and an explicit authority epoch. This compatibility path denies unverifiable leases.")]
|
||||
public IReadOnlyList<CultMeshPeerCard> FindAuthorized(
|
||||
string verseId,
|
||||
string role,
|
||||
CultMeshAuthorityLeaseCatalog leases,
|
||||
string? shardId = null,
|
||||
DateTimeOffset? at = null)
|
||||
{
|
||||
if (leases == null) throw new ArgumentNullException(nameof(leases));
|
||||
var resolver = CultMeshAuthorityResolver.CreateDenyByDefault(leases,
|
||||
at.HasValue ? new PeerCatalogFixedClock(at.Value) : null);
|
||||
return FindAuthorized(verseId, role, resolver, 0, shardId);
|
||||
}
|
||||
|
||||
/// <summary>Finds contact candidates accepted by the authority resolver.</summary>
|
||||
public IReadOnlyList<CultMeshPeerCard> FindAuthorized(
|
||||
string verseId,
|
||||
string role,
|
||||
CultMeshAuthorityResolver resolver,
|
||||
long authorityEpoch,
|
||||
string? shardId = null,
|
||||
string? resourceScope = null)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (string.IsNullOrWhiteSpace(verseId)) throw new ArgumentException("Value must be non-empty.", nameof(verseId));
|
||||
if (string.IsNullOrWhiteSpace(role)) throw new ArgumentException("Value must be non-empty.", nameof(role));
|
||||
if (leases == null) throw new ArgumentNullException(nameof(leases));
|
||||
if (resolver == null) throw new ArgumentNullException(nameof(resolver));
|
||||
return Find(verseId, role)
|
||||
.Where(peer => leases.IsAuthorized(peer, role, shardId, at))
|
||||
.Where(peer => resolver.Resolve(new CultMeshAuthorityRequest(peer, role, shardId, authorityEpoch, resourceScope)).IsAuthorized)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Returns the first peer that advertises a Verse role and is authorized by the supplied lease catalog.</summary>
|
||||
[Obsolete("Supply CultMeshAuthorityResolver and an explicit authority epoch. This compatibility path denies unverifiable leases.")]
|
||||
public CultMeshPeerCard? FirstAuthorized(
|
||||
string verseId,
|
||||
string role,
|
||||
|
|
@ -218,6 +236,18 @@ namespace GameCult.Mesh
|
|||
return FindAuthorized(verseId, role, leases, shardId, at).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>Returns the first contact candidate accepted by the authority resolver.</summary>
|
||||
public CultMeshPeerCard? FirstAuthorized(
|
||||
string verseId,
|
||||
string role,
|
||||
CultMeshAuthorityResolver resolver,
|
||||
long authorityEpoch,
|
||||
string? shardId = null,
|
||||
string? resourceScope = null)
|
||||
{
|
||||
return FindAuthorized(verseId, role, resolver, authorityEpoch, shardId, resourceScope).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
|
|
@ -238,6 +268,13 @@ namespace GameCult.Mesh
|
|||
throw new ObjectDisposedException(nameof(CultMeshPeerCatalog));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class PeerCatalogFixedClock : ICultMeshClock
|
||||
{
|
||||
public PeerCatalogFixedClock(DateTimeOffset utcNow) => UtcNow = utcNow;
|
||||
public DateTimeOffset UtcNow { get; }
|
||||
public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken = default) => Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -343,6 +380,12 @@ namespace GameCult.Mesh
|
|||
/// Defaults to endpoint selection: rudp:// uses RUDP and cultnet:// uses LiteNetLib.
|
||||
/// </summary>
|
||||
public Func<ICultNetSchemaClient>? CreateClient { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the shared CultMesh session owner.</summary>
|
||||
public CultMeshSessionManager? Sessions { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the clock used by managed response deadlines.</summary>
|
||||
public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -401,6 +444,36 @@ namespace GameCult.Mesh
|
|||
return await WaitForResponseAsync(completion.Task, endpoint).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Fetches peer cards through the shared session owner.</summary>
|
||||
public async Task<CultMeshPeerExchangeResponseMessage> FetchAsync(
|
||||
CultMeshEndpointId endpointId,
|
||||
CultMeshPeerExchangeRequestMessage request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
if (string.IsNullOrWhiteSpace(request.VerseId)) throw new ArgumentException("Peer exchange requires a verseId.", nameof(request));
|
||||
var sessions = _options.Sessions ?? throw new InvalidOperationException("Managed peer exchange requires a CultMeshSessionManager.");
|
||||
var session = await sessions.ConnectAsync(endpointId, CultMeshProtocols.PeerExchange, cancellationToken).ConfigureAwait(false);
|
||||
var messageId = Guid.NewGuid().ToString("N");
|
||||
var completion = new TaskCompletionSource<CultMeshPeerExchangeResponseMessage>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var responseSubscription = session.OnCultNet<CultMeshPeerExchangeResponseMessage>(response =>
|
||||
{
|
||||
if (string.Equals(response.MessageId, messageId, StringComparison.Ordinal)) completion.TrySetResult(response);
|
||||
});
|
||||
using var errorSubscription = session.OnCultNet<CultNetErrorMessage>(error =>
|
||||
completion.TrySetException(new InvalidOperationException(error.Error)));
|
||||
session.SendCultNet(new CultMeshPeerExchangeRequestMessage
|
||||
{
|
||||
MessageId = messageId,
|
||||
VerseId = request.VerseId,
|
||||
Roles = request.Roles,
|
||||
KnownPeerIds = request.KnownPeerIds,
|
||||
Limit = request.Limit
|
||||
});
|
||||
return await WaitForManagedResponseAsync(completion.Task, endpointId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetches peer cards from endpoints and upserts every response into a local peer catalog.
|
||||
/// </summary>
|
||||
|
|
@ -465,5 +538,20 @@ namespace GameCult.Mesh
|
|||
|
||||
return await responseTask.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<CultMeshPeerExchangeResponseMessage> WaitForManagedResponseAsync(
|
||||
Task<CultMeshPeerExchangeResponseMessage> responseTask,
|
||||
CultMeshEndpointId endpointId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var timeout = _options.Clock.DelayAsync(_options.ResponseTimeout, cancellationToken);
|
||||
var completed = await Task.WhenAny(responseTask, timeout).ConfigureAwait(false);
|
||||
if (completed != responseTask)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
throw new TimeoutException($"Timed out waiting for peer exchange response from {endpointId}.");
|
||||
}
|
||||
return await responseTask.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using System.Collections;
|
|||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
|
@ -58,6 +59,7 @@ namespace GameCult.Mesh
|
|||
/// Flat, transport-friendly fields for a CultMesh route hint.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
[MessagePackFormatter(typeof(CultMeshRouteRecordFormatter))]
|
||||
public sealed class CultMeshRouteRecord
|
||||
{
|
||||
/// <summary>Creates flat route fields.</summary>
|
||||
|
|
@ -1001,6 +1003,27 @@ namespace GameCult.Mesh
|
|||
return Watch().Subscribe(onNext);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Projects one typed document field into a stable reactive state pointer. The expression is
|
||||
/// structural metadata: only member access and constant collection indices are accepted.
|
||||
/// </summary>
|
||||
public CultMeshStatePointer<TValue> Field<TValue>(Expression<Func<TDocument, TValue>> field)
|
||||
{
|
||||
if (field == null) throw new ArgumentNullException(nameof(field));
|
||||
var path = CultMeshFieldPath.Parse(field.Body, field.Parameters[0]);
|
||||
var read = field.Compile();
|
||||
return new CultMeshStatePointer<TValue>(
|
||||
DocumentId + "#" + path,
|
||||
async context => read(await Feed
|
||||
.SnapshotAsync(CultMeshDocumentQueryParameters.Empty, context)
|
||||
.ConfigureAwait(false)),
|
||||
context => Feed
|
||||
.Watch(CultMeshDocumentQueryParameters.Empty, context)
|
||||
.Select(read),
|
||||
RouteHint,
|
||||
Sources);
|
||||
}
|
||||
|
||||
/// <summary>Replaces the underlying document when this handle is backed by mutable state.</summary>
|
||||
public Task ReplaceAsync(TDocument value)
|
||||
{
|
||||
|
|
@ -1121,6 +1144,62 @@ namespace GameCult.Mesh
|
|||
payload);
|
||||
}
|
||||
|
||||
private static class CultMeshFieldPath
|
||||
{
|
||||
public static string Parse(Expression expression, ParameterExpression root)
|
||||
{
|
||||
var segments = new Stack<string>();
|
||||
while (expression != root)
|
||||
{
|
||||
if (expression is MemberExpression member)
|
||||
{
|
||||
segments.Push(member.Member.Name);
|
||||
expression = member.Expression
|
||||
?? throw Invalid();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (expression is MethodCallExpression call &&
|
||||
call.Method.Name == "get_Item" &&
|
||||
call.Object != null &&
|
||||
call.Arguments.Count == 1)
|
||||
{
|
||||
segments.Push("[" + ConstantIndex(call.Arguments[0]) + "]");
|
||||
expression = call.Object;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (expression is BinaryExpression binary && binary.NodeType == ExpressionType.ArrayIndex)
|
||||
{
|
||||
segments.Push("[" + ConstantIndex(binary.Right) + "]");
|
||||
expression = binary.Left;
|
||||
continue;
|
||||
}
|
||||
|
||||
throw Invalid();
|
||||
}
|
||||
|
||||
if (segments.Count == 0) throw Invalid();
|
||||
var path = string.Empty;
|
||||
foreach (var segment in segments)
|
||||
path += segment.StartsWith("[", StringComparison.Ordinal) || path.Length == 0
|
||||
? segment
|
||||
: "." + segment;
|
||||
return path;
|
||||
}
|
||||
|
||||
private static string ConstantIndex(Expression expression)
|
||||
{
|
||||
if (expression is ConstantExpression constant && constant.Value != null)
|
||||
return Convert.ToString(constant.Value, CultureInfo.InvariantCulture)!;
|
||||
throw Invalid();
|
||||
}
|
||||
|
||||
private static ArgumentException Invalid() => new(
|
||||
"CultMesh field selectors may contain only member access and constant collection indices.",
|
||||
"field");
|
||||
}
|
||||
|
||||
internal static TTarget ConvertDocument<TSource, TTarget>(TSource document)
|
||||
where TSource : class
|
||||
where TTarget : class
|
||||
|
|
@ -3439,6 +3518,7 @@ namespace GameCult.Mesh
|
|||
/// Flat, transport-friendly fields for a concrete CultMesh operation invocation.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
[MessagePackFormatter(typeof(CultMeshOperationInvocationRecordFormatter))]
|
||||
public sealed class CultMeshOperationInvocationRecord
|
||||
{
|
||||
/// <summary>Creates flat operation invocation fields.</summary>
|
||||
|
|
|
|||
522
src/GameCult.Mesh/CultMeshProviderSessionWire.cs
Normal file
522
src/GameCult.Mesh/CultMeshProviderSessionWire.cs
Normal file
|
|
@ -0,0 +1,522 @@
|
|||
using System;
|
||||
using System.Globalization;
|
||||
using GameCult.Networking;
|
||||
using MessagePack;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Canonical CultNet service, operation, payload-schema, and status identifiers for
|
||||
/// the CultMesh provider-session control plane.
|
||||
/// </summary>
|
||||
public static class CultMeshProviderSessionWireContract
|
||||
{
|
||||
/// <summary>The CultNet service id.</summary>
|
||||
public const string ServiceId = "gamecult.mesh.provider_session";
|
||||
|
||||
/// <summary>The registration operation.</summary>
|
||||
public const string RegisterOperation = "provider.register";
|
||||
/// <summary>The lease-renewal operation.</summary>
|
||||
public const string RenewOperation = "provider.renew";
|
||||
/// <summary>The publication-put operation.</summary>
|
||||
public const string PublicationPutOperation = "provider.publication.put";
|
||||
/// <summary>The publication-delete operation.</summary>
|
||||
public const string PublicationDeleteOperation = "provider.publication.delete";
|
||||
/// <summary>The command-receipt-put operation.</summary>
|
||||
public const string ReceiptPutOperation = "provider.receipt.put";
|
||||
/// <summary>The provider-withdrawal operation.</summary>
|
||||
public const string WithdrawOperation = "provider.withdraw";
|
||||
|
||||
/// <summary>The registration payload schema.</summary>
|
||||
public const string RegistrationSchema = "gamecult.mesh.provider_registration.v1";
|
||||
/// <summary>The provider-lease payload schema.</summary>
|
||||
public const string LeaseSchema = "gamecult.mesh.provider_lease.v1";
|
||||
/// <summary>The lease-renewal payload schema.</summary>
|
||||
public const string LeaseRenewalSchema = "gamecult.mesh.provider_lease_renewal.v1";
|
||||
/// <summary>The publication-put payload schema.</summary>
|
||||
public const string PublicationPutSchema = "gamecult.mesh.provider_publication_put.v1";
|
||||
/// <summary>The publication-delete payload schema.</summary>
|
||||
public const string PublicationDeleteSchema = "gamecult.mesh.provider_publication_delete.v1";
|
||||
/// <summary>The broker-to-provider command document schema.</summary>
|
||||
public const string CommandSchema = "gamecult.mesh.provider_command.v1";
|
||||
/// <summary>The command-receipt-put payload schema.</summary>
|
||||
public const string ReceiptPutSchema = "gamecult.mesh.provider_receipt_put.v1";
|
||||
/// <summary>The provider-withdrawal payload schema.</summary>
|
||||
public const string WithdrawalSchema = "gamecult.mesh.provider_withdrawal.v1";
|
||||
/// <summary>The accepted-mutation response payload schema.</summary>
|
||||
public const string MutationAcceptanceSchema = "gamecult.mesh.provider_mutation_acceptance.v1";
|
||||
|
||||
/// <summary>The successful application status.</summary>
|
||||
public const string OkStatus = "ok";
|
||||
/// <summary>The identity or generation conflict status.</summary>
|
||||
public const string ConflictStatus = "conflict";
|
||||
/// <summary>The expired-lease status.</summary>
|
||||
public const string ExpiredStatus = "expired";
|
||||
/// <summary>The authority-denied status.</summary>
|
||||
public const string DeniedStatus = "denied";
|
||||
/// <summary>The invalid-request status.</summary>
|
||||
public const string InvalidStatus = "invalid";
|
||||
/// <summary>The CultNet inner-payload encoding.</summary>
|
||||
public const string PayloadEncoding = "messagepack-base64";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Carries provider authorization evidence and a transport-owned connection
|
||||
/// generation in an RUDP Connect packet. The token is not a session id.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderConnectEvidenceWire
|
||||
{
|
||||
/// <summary>Gets or sets the fresh id minted for this physical connection.</summary>
|
||||
[Key("clientSessionId")] public string ClientSessionId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the optional signed provider authorization token.</summary>
|
||||
[Key("sessionToken")] public string? SessionToken { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Requests a fenced provider lease from the provider-session broker.</summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderRegistrationWire
|
||||
{
|
||||
/// <summary>Gets or sets the stable provider identity.</summary>
|
||||
[Key("providerId")] public string ProviderId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the provider process generation.</summary>
|
||||
[Key("serviceInstanceId")] public string ServiceInstanceId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the advertised endpoint identity.</summary>
|
||||
[Key("endpointId")] public string EndpointId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the Verse identity.</summary>
|
||||
[Key("verseId")] public string VerseId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the requested lease duration in milliseconds.</summary>
|
||||
[Key("requestedLeaseDurationMs")] public int RequestedLeaseDurationMs { get; set; }
|
||||
/// <summary>Gets or sets the optional authority lease authorizing registration.</summary>
|
||||
[Key("authorityLeaseId")] public string? AuthorityLeaseId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Identifies the provider generation authorized by a broker lease.</summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderLeaseWire
|
||||
{
|
||||
/// <summary>Gets or sets the stable provider identity.</summary>
|
||||
[Key("providerId")] public string ProviderId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the authorized provider process generation.</summary>
|
||||
[Key("serviceInstanceId")] public string ServiceInstanceId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the authorized endpoint identity.</summary>
|
||||
[Key("endpointId")] public string EndpointId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the authorized Verse identity.</summary>
|
||||
[Key("verseId")] public string VerseId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the unique fencing lease id.</summary>
|
||||
[Key("leaseId")] public string LeaseId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the RFC3339 lease validity start.</summary>
|
||||
[Key("validFromUtc")] public string ValidFromUtc { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the RFC3339 lease expiry.</summary>
|
||||
[Key("expiresAtUtc")] public string ExpiresAtUtc { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Requests replacement of an active provider lease.</summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderLeaseRenewalWire
|
||||
{
|
||||
/// <summary>Gets or sets the lease being replaced.</summary>
|
||||
[Key("leaseId")] public string LeaseId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the requested replacement duration in milliseconds.</summary>
|
||||
[Key("requestedLeaseDurationMs")] public int RequestedLeaseDurationMs { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Publishes one typed document under an active provider lease.</summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderPublicationPutWire
|
||||
{
|
||||
/// <summary>Gets or sets the active provider lease.</summary>
|
||||
[Key("leaseId")] public string LeaseId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the provider-owned publication identity.</summary>
|
||||
[Key("publicationId")] public string PublicationId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the exact typed CultNet document.</summary>
|
||||
[Key("document")] public CultNetRawDocumentRecord Document { get; set; } = new CultNetRawDocumentRecord();
|
||||
}
|
||||
|
||||
/// <summary>Deletes one exact provider-owned publication tuple.</summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderPublicationDeleteWire
|
||||
{
|
||||
/// <summary>Gets or sets the active provider lease.</summary>
|
||||
[Key("leaseId")] public string LeaseId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the provider-owned publication identity.</summary>
|
||||
[Key("publicationId")] public string PublicationId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the exact published schema id.</summary>
|
||||
[Key("schemaId")] public string SchemaId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the exact published record key.</summary>
|
||||
[Key("recordKey")] public string RecordKey { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>A retained command routed from the broker to one provider generation.</summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderCommandWire
|
||||
{
|
||||
/// <summary>Gets or sets the stable command identity.</summary>
|
||||
[Key("commandId")] public string CommandId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the provider-defined command kind.</summary>
|
||||
[Key("commandKind")] public string CommandKind { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the target provider identity.</summary>
|
||||
[Key("providerId")] public string ProviderId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the target provider process generation.</summary>
|
||||
[Key("serviceInstanceId")] public string ServiceInstanceId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the typed command payload value.</summary>
|
||||
[Key("payload")] public object? Payload { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The exactly-once outcome of one provider command.</summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderCommandReceiptWire
|
||||
{
|
||||
/// <summary>Gets or sets the stable receipt identity.</summary>
|
||||
[Key("receiptId")] public string ReceiptId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the completed command identity.</summary>
|
||||
[Key("commandId")] public string CommandId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the completed command kind.</summary>
|
||||
[Key("commandKind")] public string CommandKind { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the provider identity.</summary>
|
||||
[Key("providerId")] public string ProviderId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the provider process generation.</summary>
|
||||
[Key("serviceInstanceId")] public string ServiceInstanceId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets applied, rejected, or failed.</summary>
|
||||
[Key("state")] public string State { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the RFC3339 completion time.</summary>
|
||||
[Key("completedAtUtc")] public string CompletedAtUtc { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the optional typed result value.</summary>
|
||||
[Key("result")] public object? Result { get; set; }
|
||||
/// <summary>Gets or sets the optional bounded failure detail.</summary>
|
||||
[Key("error")] public string? Error { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Submits a durable command receipt under an active provider lease.</summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderReceiptPutWire
|
||||
{
|
||||
/// <summary>Gets or sets the active provider lease.</summary>
|
||||
[Key("leaseId")] public string LeaseId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the durable command receipt.</summary>
|
||||
[Key("receipt")] public CultMeshProviderCommandReceiptWire Receipt { get; set; } = new CultMeshProviderCommandReceiptWire();
|
||||
}
|
||||
|
||||
/// <summary>Withdraws the provider generation identified by a lease.</summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderWithdrawalWire
|
||||
{
|
||||
/// <summary>Gets or sets the lease whose owned publications must be withdrawn.</summary>
|
||||
[Key("leaseId")] public string LeaseId { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Confirms broker acceptance of one provider-session mutation.</summary>
|
||||
[MessagePackObject]
|
||||
public sealed class CultMeshProviderMutationAcceptanceWire
|
||||
{
|
||||
/// <summary>Gets or sets the RFC3339 broker acceptance time.</summary>
|
||||
[Key("acceptedAtUtc")] public string AcceptedAtUtc { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the accepted lease identity, when applicable.</summary>
|
||||
[Key("leaseId")] public string? LeaseId { get; set; }
|
||||
/// <summary>Gets or sets the accepted publication identity, when applicable.</summary>
|
||||
[Key("publicationId")] public string? PublicationId { get; set; }
|
||||
/// <summary>Gets or sets the accepted command identity, when applicable.</summary>
|
||||
[Key("commandId")] public string? CommandId { get; set; }
|
||||
/// <summary>Gets or sets the accepted receipt identity, when applicable.</summary>
|
||||
[Key("receiptId")] public string? ReceiptId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Encodes provider-session payloads inside the existing CultNet operation envelope.
|
||||
/// Transport acknowledgement is deliberately not treated as application acceptance.
|
||||
/// </summary>
|
||||
public static class CultMeshProviderSessionWire
|
||||
{
|
||||
private static readonly MessagePackSerializerOptions Options =
|
||||
MessagePackSerializerOptions.Standard.WithSecurity(MessagePackSecurity.UntrustedData);
|
||||
|
||||
/// <summary>Encodes one validated provider-session value as MessagePack base64.</summary>
|
||||
public static string EncodePayload<T>(T value)
|
||||
{
|
||||
if (value == null) throw new ArgumentNullException(nameof(value));
|
||||
Validate(value);
|
||||
return Convert.ToBase64String(MessagePackSerializer.Serialize(value, Options));
|
||||
}
|
||||
|
||||
/// <summary>Decodes and validates one MessagePack-base64 provider-session value.</summary>
|
||||
public static T DecodePayload<T>(string payload)
|
||||
{
|
||||
RequireText(payload, nameof(payload));
|
||||
byte[] bytes;
|
||||
try
|
||||
{
|
||||
bytes = Convert.FromBase64String(payload);
|
||||
}
|
||||
catch (FormatException exception)
|
||||
{
|
||||
throw new ArgumentException("Provider-session payload must be MessagePack base64.", nameof(payload), exception);
|
||||
}
|
||||
|
||||
var value = MessagePackSerializer.Deserialize<T>(bytes, Options);
|
||||
if (value == null) throw new MessagePackSerializationException("Provider-session payload decoded to null.");
|
||||
Validate(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>Encodes provider RUDP Connect evidence as a named MessagePack map.</summary>
|
||||
public static byte[] EncodeConnectEvidence(CultMeshProviderConnectEvidenceWire evidence)
|
||||
{
|
||||
if (evidence == null) throw new ArgumentNullException(nameof(evidence));
|
||||
Validate(evidence);
|
||||
return MessagePackSerializer.Serialize(evidence, Options);
|
||||
}
|
||||
|
||||
/// <summary>Decodes and validates provider RUDP Connect evidence.</summary>
|
||||
public static CultMeshProviderConnectEvidenceWire DecodeConnectEvidence(byte[] payload)
|
||||
{
|
||||
if (payload == null) throw new ArgumentNullException(nameof(payload));
|
||||
var evidence = MessagePackSerializer.Deserialize<CultMeshProviderConnectEvidenceWire>(payload, Options);
|
||||
if (evidence == null) throw new MessagePackSerializationException("Provider Connect evidence decoded to null.");
|
||||
Validate(evidence);
|
||||
return evidence;
|
||||
}
|
||||
|
||||
/// <summary>Decodes a retained provider command carried as a raw CultNet document.</summary>
|
||||
public static CultMeshProviderCommandWire DecodeCommandDocument(CultNetRawDocumentRecord document)
|
||||
{
|
||||
if (document == null) throw new ArgumentNullException(nameof(document));
|
||||
if (!string.Equals(document.SchemaId, CultMeshProviderSessionWireContract.CommandSchema, StringComparison.Ordinal))
|
||||
throw new ArgumentException($"Expected provider command schema '{CultMeshProviderSessionWireContract.CommandSchema}'.", nameof(document));
|
||||
if (!string.Equals(document.PayloadEncoding, "messagepack", StringComparison.Ordinal))
|
||||
throw new ArgumentException("Provider command document must use MessagePack.", nameof(document));
|
||||
var command = MessagePackSerializer.Deserialize<CultMeshProviderCommandWire>(document.Payload, Options);
|
||||
if (command == null) throw new MessagePackSerializationException("Provider command decoded to null.");
|
||||
Validate(command);
|
||||
return command;
|
||||
}
|
||||
|
||||
/// <summary>Creates a canonical provider-session CultNet operation request.</summary>
|
||||
public static CultNetOperationRequestMessage CreateRequest<T>(
|
||||
string messageId,
|
||||
string operation,
|
||||
string payloadSchema,
|
||||
T payload,
|
||||
string? sourceRuntimeId = null,
|
||||
string? targetRuntimeId = null)
|
||||
{
|
||||
RequireText(messageId, nameof(messageId));
|
||||
ValidateOperation(operation, payloadSchema);
|
||||
return new CultNetOperationRequestMessage
|
||||
{
|
||||
MessageId = messageId,
|
||||
ServiceId = CultMeshProviderSessionWireContract.ServiceId,
|
||||
Operation = operation,
|
||||
PayloadSchema = payloadSchema,
|
||||
PayloadEncoding = CultMeshProviderSessionWireContract.PayloadEncoding,
|
||||
Payload = EncodePayload(payload),
|
||||
SourceRuntimeId = sourceRuntimeId,
|
||||
TargetRuntimeId = targetRuntimeId
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Validates an operation request envelope and decodes its typed payload.</summary>
|
||||
public static T DecodeRequest<T>(
|
||||
CultNetOperationRequestMessage request,
|
||||
string expectedOperation,
|
||||
string expectedPayloadSchema)
|
||||
{
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
RequireEnvelope(request.ServiceId, request.Operation, request.PayloadSchema, request.PayloadEncoding,
|
||||
expectedOperation, expectedPayloadSchema);
|
||||
return DecodePayload<T>(request.Payload);
|
||||
}
|
||||
|
||||
/// <summary>Creates a correlated application-level operation response.</summary>
|
||||
public static CultNetOperationResponseMessage CreateResponse<T>(
|
||||
CultNetOperationRequestMessage request,
|
||||
string status,
|
||||
string payloadSchema,
|
||||
T payload,
|
||||
string? sourceRuntimeId = null)
|
||||
{
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
ValidateStatus(status);
|
||||
return new CultNetOperationResponseMessage
|
||||
{
|
||||
MessageId = RequireText(request.MessageId, nameof(request.MessageId)),
|
||||
ServiceId = CultMeshProviderSessionWireContract.ServiceId,
|
||||
Operation = RequireText(request.Operation, nameof(request.Operation)),
|
||||
Status = status,
|
||||
PayloadSchema = RequireText(payloadSchema, nameof(payloadSchema)),
|
||||
PayloadEncoding = CultMeshProviderSessionWireContract.PayloadEncoding,
|
||||
Payload = EncodePayload(payload),
|
||||
SourceRuntimeId = sourceRuntimeId
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Validates an operation response envelope and decodes its typed payload.</summary>
|
||||
public static T DecodeResponse<T>(
|
||||
CultNetOperationResponseMessage response,
|
||||
string expectedOperation,
|
||||
string expectedPayloadSchema)
|
||||
{
|
||||
if (response == null) throw new ArgumentNullException(nameof(response));
|
||||
ValidateStatus(response.Status);
|
||||
RequireEnvelope(response.ServiceId, response.Operation, response.PayloadSchema, response.PayloadEncoding,
|
||||
expectedOperation, expectedPayloadSchema);
|
||||
return DecodePayload<T>(response.Payload);
|
||||
}
|
||||
|
||||
/// <summary>Validates the invariants of a known provider-session wire value.</summary>
|
||||
public static void Validate<T>(T value)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case CultMeshProviderConnectEvidenceWire evidence:
|
||||
RequireText(evidence.ClientSessionId, nameof(evidence.ClientSessionId));
|
||||
RequireOptionalText(evidence.SessionToken, nameof(evidence.SessionToken));
|
||||
break;
|
||||
case CultMeshProviderRegistrationWire registration:
|
||||
RequireIdentity(registration.ProviderId, registration.ServiceInstanceId, registration.EndpointId, registration.VerseId);
|
||||
RequirePositive(registration.RequestedLeaseDurationMs, nameof(registration.RequestedLeaseDurationMs));
|
||||
RequireOptionalText(registration.AuthorityLeaseId, nameof(registration.AuthorityLeaseId));
|
||||
break;
|
||||
case CultMeshProviderLeaseWire lease:
|
||||
RequireIdentity(lease.ProviderId, lease.ServiceInstanceId, lease.EndpointId, lease.VerseId);
|
||||
RequireText(lease.LeaseId, nameof(lease.LeaseId));
|
||||
var validFrom = RequireTimestamp(lease.ValidFromUtc, nameof(lease.ValidFromUtc));
|
||||
var expiresAt = RequireTimestamp(lease.ExpiresAtUtc, nameof(lease.ExpiresAtUtc));
|
||||
if (expiresAt <= validFrom) throw new ArgumentException("Provider lease must expire after validFromUtc.");
|
||||
break;
|
||||
case CultMeshProviderLeaseRenewalWire renewal:
|
||||
RequireText(renewal.LeaseId, nameof(renewal.LeaseId));
|
||||
RequirePositive(renewal.RequestedLeaseDurationMs, nameof(renewal.RequestedLeaseDurationMs));
|
||||
break;
|
||||
case CultMeshProviderPublicationPutWire publication:
|
||||
RequireText(publication.LeaseId, nameof(publication.LeaseId));
|
||||
RequireText(publication.PublicationId, nameof(publication.PublicationId));
|
||||
if (publication.Document == null) throw new ArgumentException("Provider publication document is required.");
|
||||
RequireText(publication.Document.SchemaId, nameof(publication.Document.SchemaId));
|
||||
RequireText(publication.Document.RecordKey, nameof(publication.Document.RecordKey));
|
||||
if (!string.Equals(publication.Document.PayloadEncoding, "messagepack", StringComparison.Ordinal))
|
||||
throw new ArgumentException("Provider publication document must use MessagePack.");
|
||||
break;
|
||||
case CultMeshProviderPublicationDeleteWire deletion:
|
||||
RequireText(deletion.LeaseId, nameof(deletion.LeaseId));
|
||||
RequireText(deletion.PublicationId, nameof(deletion.PublicationId));
|
||||
RequireText(deletion.SchemaId, nameof(deletion.SchemaId));
|
||||
RequireText(deletion.RecordKey, nameof(deletion.RecordKey));
|
||||
break;
|
||||
case CultMeshProviderCommandWire command:
|
||||
RequireText(command.CommandId, nameof(command.CommandId));
|
||||
RequireText(command.CommandKind, nameof(command.CommandKind));
|
||||
RequireText(command.ProviderId, nameof(command.ProviderId));
|
||||
RequireText(command.ServiceInstanceId, nameof(command.ServiceInstanceId));
|
||||
break;
|
||||
case CultMeshProviderCommandReceiptWire receipt:
|
||||
RequireText(receipt.ReceiptId, nameof(receipt.ReceiptId));
|
||||
RequireText(receipt.CommandId, nameof(receipt.CommandId));
|
||||
RequireText(receipt.CommandKind, nameof(receipt.CommandKind));
|
||||
RequireText(receipt.ProviderId, nameof(receipt.ProviderId));
|
||||
RequireText(receipt.ServiceInstanceId, nameof(receipt.ServiceInstanceId));
|
||||
ValidateReceiptState(receipt.State);
|
||||
RequireTimestamp(receipt.CompletedAtUtc, nameof(receipt.CompletedAtUtc));
|
||||
RequireOptionalText(receipt.Error, nameof(receipt.Error));
|
||||
break;
|
||||
case CultMeshProviderReceiptPutWire receiptPut:
|
||||
RequireText(receiptPut.LeaseId, nameof(receiptPut.LeaseId));
|
||||
if (receiptPut.Receipt == null) throw new ArgumentException("Provider receipt is required.");
|
||||
Validate(receiptPut.Receipt);
|
||||
break;
|
||||
case CultMeshProviderWithdrawalWire withdrawal:
|
||||
RequireText(withdrawal.LeaseId, nameof(withdrawal.LeaseId));
|
||||
break;
|
||||
case CultMeshProviderMutationAcceptanceWire acceptance:
|
||||
RequireTimestamp(acceptance.AcceptedAtUtc, nameof(acceptance.AcceptedAtUtc));
|
||||
RequireOptionalText(acceptance.LeaseId, nameof(acceptance.LeaseId));
|
||||
RequireOptionalText(acceptance.PublicationId, nameof(acceptance.PublicationId));
|
||||
RequireOptionalText(acceptance.CommandId, nameof(acceptance.CommandId));
|
||||
RequireOptionalText(acceptance.ReceiptId, nameof(acceptance.ReceiptId));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void RequireEnvelope(
|
||||
string serviceId,
|
||||
string operation,
|
||||
string payloadSchema,
|
||||
string payloadEncoding,
|
||||
string expectedOperation,
|
||||
string expectedPayloadSchema)
|
||||
{
|
||||
if (!string.Equals(serviceId, CultMeshProviderSessionWireContract.ServiceId, StringComparison.Ordinal))
|
||||
throw new ArgumentException($"Expected provider-session service '{CultMeshProviderSessionWireContract.ServiceId}'.");
|
||||
if (!string.Equals(operation, expectedOperation, StringComparison.Ordinal))
|
||||
throw new ArgumentException($"Expected provider-session operation '{expectedOperation}'.");
|
||||
if (!string.Equals(payloadSchema, expectedPayloadSchema, StringComparison.Ordinal))
|
||||
throw new ArgumentException($"Expected provider-session payload schema '{expectedPayloadSchema}'.");
|
||||
if (!string.Equals(payloadEncoding, CultMeshProviderSessionWireContract.PayloadEncoding, StringComparison.Ordinal))
|
||||
throw new ArgumentException("Provider-session operation payload must use MessagePack base64.");
|
||||
}
|
||||
|
||||
private static void ValidateOperation(string operation, string payloadSchema)
|
||||
{
|
||||
var expectedSchema = operation switch
|
||||
{
|
||||
CultMeshProviderSessionWireContract.RegisterOperation => CultMeshProviderSessionWireContract.RegistrationSchema,
|
||||
CultMeshProviderSessionWireContract.RenewOperation => CultMeshProviderSessionWireContract.LeaseRenewalSchema,
|
||||
CultMeshProviderSessionWireContract.PublicationPutOperation => CultMeshProviderSessionWireContract.PublicationPutSchema,
|
||||
CultMeshProviderSessionWireContract.PublicationDeleteOperation => CultMeshProviderSessionWireContract.PublicationDeleteSchema,
|
||||
CultMeshProviderSessionWireContract.ReceiptPutOperation => CultMeshProviderSessionWireContract.ReceiptPutSchema,
|
||||
CultMeshProviderSessionWireContract.WithdrawOperation => CultMeshProviderSessionWireContract.WithdrawalSchema,
|
||||
_ => throw new ArgumentException($"Unsupported provider-session operation '{operation}'.", nameof(operation))
|
||||
};
|
||||
if (!string.Equals(payloadSchema, expectedSchema, StringComparison.Ordinal))
|
||||
throw new ArgumentException($"Operation '{operation}' requires payload schema '{expectedSchema}'.", nameof(payloadSchema));
|
||||
}
|
||||
|
||||
private static void ValidateStatus(string status)
|
||||
{
|
||||
if (status != CultMeshProviderSessionWireContract.OkStatus &&
|
||||
status != CultMeshProviderSessionWireContract.ConflictStatus &&
|
||||
status != CultMeshProviderSessionWireContract.ExpiredStatus &&
|
||||
status != CultMeshProviderSessionWireContract.DeniedStatus &&
|
||||
status != CultMeshProviderSessionWireContract.InvalidStatus)
|
||||
throw new ArgumentException($"Unsupported provider-session status '{status}'.", nameof(status));
|
||||
}
|
||||
|
||||
private static void ValidateReceiptState(string state)
|
||||
{
|
||||
if (state != "applied" && state != "rejected" && state != "failed")
|
||||
throw new ArgumentException($"Unsupported provider receipt state '{state}'.", nameof(state));
|
||||
}
|
||||
|
||||
private static void RequireIdentity(string providerId, string serviceInstanceId, string endpointId, string verseId)
|
||||
{
|
||||
RequireText(providerId, nameof(providerId));
|
||||
RequireText(serviceInstanceId, nameof(serviceInstanceId));
|
||||
RequireText(endpointId, nameof(endpointId));
|
||||
RequireText(verseId, nameof(verseId));
|
||||
}
|
||||
|
||||
private static string RequireText(string value, string name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Value must be non-empty.", name);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void RequireOptionalText(string? value, string name)
|
||||
{
|
||||
if (value != null && string.IsNullOrWhiteSpace(value))
|
||||
throw new ArgumentException("Optional value must be null or non-empty.", name);
|
||||
}
|
||||
|
||||
private static void RequirePositive(int value, string name)
|
||||
{
|
||||
if (value <= 0) throw new ArgumentOutOfRangeException(name, "Value must be positive.");
|
||||
}
|
||||
|
||||
private static DateTimeOffset RequireTimestamp(string value, string name)
|
||||
{
|
||||
RequireText(value, name);
|
||||
if (!DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var timestamp))
|
||||
throw new ArgumentException("Value must be an RFC3339 timestamp.", name);
|
||||
return timestamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
154
src/GameCult.Mesh/CultMeshRealtimeTransports.cs
Normal file
154
src/GameCult.Mesh/CultMeshRealtimeTransports.cs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>Delivery semantics requested from a realtime state transport.</summary>
|
||||
public enum CultMeshRealtimeDelivery
|
||||
{
|
||||
ReliableOrdered,
|
||||
LatestOnly,
|
||||
Unreliable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Transport-neutral realtime state frame. Schema identity and logical generation
|
||||
/// remain stable when the physical connector changes.
|
||||
/// </summary>
|
||||
public sealed class CultMeshRealtimeFrame
|
||||
{
|
||||
public string ChannelId { get; set; } = string.Empty;
|
||||
public string SchemaId { get; set; } = string.Empty;
|
||||
public string BodyId { get; set; } = string.Empty;
|
||||
public long ProducerEpoch { get; set; }
|
||||
public long Sequence { get; set; }
|
||||
public CultMeshRealtimeDelivery Delivery { get; set; }
|
||||
public ReadOnlyMemory<byte> Payload { get; set; }
|
||||
|
||||
internal void Validate()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(ChannelId))
|
||||
throw new InvalidOperationException("Realtime channel identity is required.");
|
||||
if (string.IsNullOrWhiteSpace(SchemaId))
|
||||
throw new InvalidOperationException("Realtime schema identity is required.");
|
||||
if (string.IsNullOrWhiteSpace(BodyId))
|
||||
throw new InvalidOperationException("Realtime body identity is required.");
|
||||
if (ProducerEpoch < 0 || Sequence < 0)
|
||||
throw new InvalidOperationException("Realtime epoch and sequence must be non-negative.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bidirectional realtime state plane. Commands, receipts, manifests, and other
|
||||
/// registered schema documents do not travel through this port.
|
||||
/// </summary>
|
||||
public interface ICultMeshRealtimeTransport : IDisposable
|
||||
{
|
||||
string TransportId { get; }
|
||||
string Endpoint { get; }
|
||||
Task SendAsync(CultMeshRealtimeFrame frame, CancellationToken cancellationToken = default);
|
||||
Task<CultMeshRealtimeFrame> ReceiveAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>Creates a realtime state transport, normally QUIC streams/datagrams.</summary>
|
||||
public interface ICultMeshRealtimeTransportConnector
|
||||
{
|
||||
string ConnectorId { get; }
|
||||
int Priority { get; }
|
||||
bool CanConnect(CultMeshTransportCandidate candidate);
|
||||
Task<ICultMeshRealtimeTransport> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshEndpointId endpointId,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>Reusable identity-bound realtime state session.</summary>
|
||||
public sealed class CultMeshRealtimeSession : IDisposable
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly Action<CultMeshRealtimeSession> _onTransportFailure;
|
||||
private ICultMeshRealtimeTransport _transport;
|
||||
private bool _disposed;
|
||||
|
||||
internal CultMeshRealtimeSession(
|
||||
CultMeshEndpointId endpointId,
|
||||
ICultMeshRealtimeTransport transport,
|
||||
CultMeshSessionState state,
|
||||
Action<CultMeshRealtimeSession> onTransportFailure)
|
||||
{
|
||||
EndpointId = endpointId ?? throw new ArgumentNullException(nameof(endpointId));
|
||||
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
||||
State = state ?? throw new ArgumentNullException(nameof(state));
|
||||
_onTransportFailure = onTransportFailure ?? throw new ArgumentNullException(nameof(onTransportFailure));
|
||||
}
|
||||
|
||||
public CultMeshEndpointId EndpointId { get; }
|
||||
public CultMeshSessionState State { get; private set; }
|
||||
public string TransportId { get { lock (_gate) return _transport.TransportId; } }
|
||||
|
||||
public async Task SendAsync(
|
||||
CultMeshRealtimeFrame frame,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (frame == null) throw new ArgumentNullException(nameof(frame));
|
||||
frame.Validate();
|
||||
var transport = GetTransport();
|
||||
try
|
||||
{
|
||||
await transport.SendAsync(frame, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_onTransportFailure(this);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<CultMeshRealtimeFrame> ReceiveAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var transport = GetTransport();
|
||||
try
|
||||
{
|
||||
var frame = await transport.ReceiveAsync(cancellationToken).ConfigureAwait(false);
|
||||
frame.Validate();
|
||||
return frame;
|
||||
}
|
||||
catch (Exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_onTransportFailure(this);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
internal void MarkOffline(CultMeshSessionState state)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
State = state;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
ICultMeshRealtimeTransport transport;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
transport = _transport;
|
||||
}
|
||||
transport.Dispose();
|
||||
}
|
||||
|
||||
private ICultMeshRealtimeTransport GetTransport()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshRealtimeSession));
|
||||
return _transport;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
93
src/GameCult.Mesh/CultMeshRealtimeWireProtocol.cs
Normal file
93
src/GameCult.Mesh/CultMeshRealtimeWireProtocol.cs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Stable CultMesh realtime frame encoding shared by managed and native QUIC connectors.
|
||||
/// QUIC stream framing remains transport-owned; this codec owns only typed frame bytes.
|
||||
/// </summary>
|
||||
public static class CultMeshRealtimeWireProtocol
|
||||
{
|
||||
public const string ApplicationProtocolName = "cultmesh-state-v1";
|
||||
public const long ConnectionCloseCode = 0x43554c54;
|
||||
public const long StreamAbortCode = 0x53544154;
|
||||
public const byte ReliableStream = 1;
|
||||
public const byte LatestOnlyStream = 2;
|
||||
public const int MaximumFrameBytes = 64 * 1024 * 1024;
|
||||
public const int MaximumEncodedFrameBytes = MaximumFrameBytes + 37 + (3 * ushort.MaxValue);
|
||||
|
||||
private const uint Magic = 0x31545343;
|
||||
private const int FixedHeaderBytes = 37;
|
||||
|
||||
public static byte[] EncodeFrame(CultMeshRealtimeFrame frame)
|
||||
{
|
||||
if (frame == null) throw new ArgumentNullException(nameof(frame));
|
||||
frame.Validate();
|
||||
var channel = Encoding.UTF8.GetBytes(frame.ChannelId);
|
||||
var schema = Encoding.UTF8.GetBytes(frame.SchemaId);
|
||||
var body = Encoding.UTF8.GetBytes(frame.BodyId);
|
||||
if (channel.Length > ushort.MaxValue || schema.Length > ushort.MaxValue || body.Length > ushort.MaxValue)
|
||||
throw new InvalidDataException("Realtime frame identity exceeds the QUIC wire limit.");
|
||||
if (frame.Payload.Length > MaximumFrameBytes)
|
||||
throw new InvalidDataException("Realtime frame payload exceeds the QUIC wire limit.");
|
||||
|
||||
var result = new byte[checked(FixedHeaderBytes + channel.Length + schema.Length + body.Length + frame.Payload.Length)];
|
||||
var span = result.AsSpan();
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(span, Magic);
|
||||
span[4] = (byte)frame.Delivery;
|
||||
BinaryPrimitives.WriteInt64LittleEndian(span.Slice(5), frame.ProducerEpoch);
|
||||
BinaryPrimitives.WriteInt64LittleEndian(span.Slice(13), frame.Sequence);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(21), (ushort)channel.Length);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(23), (ushort)schema.Length);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(25), (ushort)body.Length);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(27), frame.Payload.Length);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(31), FixedHeaderBytes);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(35), 1);
|
||||
var offset = FixedHeaderBytes;
|
||||
channel.CopyTo(span.Slice(offset)); offset += channel.Length;
|
||||
schema.CopyTo(span.Slice(offset)); offset += schema.Length;
|
||||
body.CopyTo(span.Slice(offset)); offset += body.Length;
|
||||
frame.Payload.Span.CopyTo(span.Slice(offset));
|
||||
return result;
|
||||
}
|
||||
|
||||
public static CultMeshRealtimeFrame DecodeFrame(byte[] bytes)
|
||||
{
|
||||
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
|
||||
if (bytes.Length < FixedHeaderBytes) throw new InvalidDataException("Realtime frame header is truncated.");
|
||||
var span = bytes.AsSpan();
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(span) != Magic)
|
||||
throw new InvalidDataException("Realtime frame magic is invalid.");
|
||||
if (BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(35)) != 1 ||
|
||||
BinaryPrimitives.ReadInt32LittleEndian(span.Slice(31)) != FixedHeaderBytes)
|
||||
throw new InvalidDataException("Realtime frame wire version is unsupported.");
|
||||
var delivery = (CultMeshRealtimeDelivery)span[4];
|
||||
if (delivery < CultMeshRealtimeDelivery.ReliableOrdered || delivery > CultMeshRealtimeDelivery.Unreliable)
|
||||
throw new InvalidDataException("Realtime frame delivery mode is invalid.");
|
||||
var channelLength = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(21));
|
||||
var schemaLength = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(23));
|
||||
var bodyLength = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(25));
|
||||
var payloadLength = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(27));
|
||||
var expected = checked(FixedHeaderBytes + channelLength + schemaLength + bodyLength + payloadLength);
|
||||
if (payloadLength < 0 || expected != bytes.Length)
|
||||
throw new InvalidDataException("Realtime frame length is invalid.");
|
||||
var offset = FixedHeaderBytes;
|
||||
var channel = Encoding.UTF8.GetString(bytes, offset, channelLength); offset += channelLength;
|
||||
var schema = Encoding.UTF8.GetString(bytes, offset, schemaLength); offset += schemaLength;
|
||||
var body = Encoding.UTF8.GetString(bytes, offset, bodyLength); offset += bodyLength;
|
||||
return new CultMeshRealtimeFrame
|
||||
{
|
||||
ChannelId = channel,
|
||||
SchemaId = schema,
|
||||
BodyId = body,
|
||||
ProducerEpoch = BinaryPrimitives.ReadInt64LittleEndian(span.Slice(5)),
|
||||
Sequence = BinaryPrimitives.ReadInt64LittleEndian(span.Slice(13)),
|
||||
Delivery = delivery,
|
||||
Payload = bytes.AsMemory(offset, payloadLength)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
183
src/GameCult.Mesh/CultMeshReliabilityDiagnostics.cs
Normal file
183
src/GameCult.Mesh/CultMeshReliabilityDiagnostics.cs
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Clock used by CultMesh reliability owners.
|
||||
/// </summary>
|
||||
public interface ICultMeshClock
|
||||
{
|
||||
DateTimeOffset UtcNow { get; }
|
||||
|
||||
Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wall clock used outside deterministic tests.
|
||||
/// </summary>
|
||||
public sealed class CultMeshSystemClock : ICultMeshClock
|
||||
{
|
||||
public static CultMeshSystemClock Instance { get; } = new CultMeshSystemClock();
|
||||
|
||||
private CultMeshSystemClock()
|
||||
{
|
||||
}
|
||||
|
||||
public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
|
||||
|
||||
public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return Task.Delay(delay, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
public enum CultMeshReliabilityOrgan
|
||||
{
|
||||
Discovery,
|
||||
Session,
|
||||
Authority,
|
||||
ContentTransfer,
|
||||
Stream
|
||||
}
|
||||
|
||||
public enum CultMeshDiagnosticKind
|
||||
{
|
||||
DiscoveryObservation,
|
||||
CandidateRejected,
|
||||
ConnectionAttempt,
|
||||
PathChanged,
|
||||
RetryDecision,
|
||||
AuthorityDecision,
|
||||
VerifiedRange,
|
||||
StreamGap
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One bounded operational observation emitted by a CultMesh reliability owner.
|
||||
/// </summary>
|
||||
public sealed class CultMeshDiagnosticEvent
|
||||
{
|
||||
public CultMeshDiagnosticEvent(
|
||||
long sequence,
|
||||
DateTimeOffset observedAtUtc,
|
||||
CultMeshReliabilityOrgan organ,
|
||||
CultMeshDiagnosticKind kind,
|
||||
string operationId,
|
||||
string subjectId,
|
||||
string state,
|
||||
string reasonCode = "",
|
||||
string sourceId = "",
|
||||
string endpoint = "",
|
||||
string schemaVersion = "",
|
||||
string libraryVersion = "")
|
||||
{
|
||||
if (sequence < 0) throw new ArgumentOutOfRangeException(nameof(sequence));
|
||||
Sequence = sequence;
|
||||
ObservedAtUtc = observedAtUtc;
|
||||
Organ = organ;
|
||||
Kind = kind;
|
||||
OperationId = operationId ?? "";
|
||||
SubjectId = subjectId ?? "";
|
||||
State = state ?? "";
|
||||
ReasonCode = reasonCode ?? "";
|
||||
SourceId = sourceId ?? "";
|
||||
Endpoint = endpoint ?? "";
|
||||
SchemaVersion = schemaVersion ?? "";
|
||||
LibraryVersion = string.IsNullOrWhiteSpace(libraryVersion)
|
||||
? CultMeshLibraryVersion.Current
|
||||
: libraryVersion;
|
||||
}
|
||||
|
||||
public long Sequence { get; }
|
||||
public DateTimeOffset ObservedAtUtc { get; }
|
||||
public CultMeshReliabilityOrgan Organ { get; }
|
||||
public CultMeshDiagnosticKind Kind { get; }
|
||||
public string OperationId { get; }
|
||||
public string SubjectId { get; }
|
||||
public string State { get; }
|
||||
public string ReasonCode { get; }
|
||||
public string SourceId { get; }
|
||||
public string Endpoint { get; }
|
||||
public string SchemaVersion { get; }
|
||||
public string LibraryVersion { get; }
|
||||
}
|
||||
|
||||
public interface ICultMeshDiagnosticSink
|
||||
{
|
||||
void Emit(CultMeshDiagnosticEvent diagnostic);
|
||||
}
|
||||
|
||||
public sealed class CultMeshNullDiagnosticSink : ICultMeshDiagnosticSink
|
||||
{
|
||||
public static CultMeshNullDiagnosticSink Instance { get; } = new CultMeshNullDiagnosticSink();
|
||||
|
||||
private CultMeshNullDiagnosticSink()
|
||||
{
|
||||
}
|
||||
|
||||
public void Emit(CultMeshDiagnosticEvent diagnostic)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bounded diagnostic projection suitable for inspection and tests.
|
||||
/// </summary>
|
||||
public sealed class CultMeshDiagnosticBuffer : ICultMeshDiagnosticSink
|
||||
{
|
||||
private readonly object _gate = new object();
|
||||
private readonly Queue<CultMeshDiagnosticEvent> _events;
|
||||
|
||||
public CultMeshDiagnosticBuffer(int capacity = 256)
|
||||
{
|
||||
if (capacity <= 0) throw new ArgumentOutOfRangeException(nameof(capacity));
|
||||
Capacity = capacity;
|
||||
_events = new Queue<CultMeshDiagnosticEvent>(capacity);
|
||||
}
|
||||
|
||||
public int Capacity { get; }
|
||||
|
||||
public IReadOnlyList<CultMeshDiagnosticEvent> Snapshot()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _events.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public void Emit(CultMeshDiagnosticEvent diagnostic)
|
||||
{
|
||||
if (diagnostic == null) throw new ArgumentNullException(nameof(diagnostic));
|
||||
lock (_gate)
|
||||
{
|
||||
while (_events.Count >= Capacity)
|
||||
{
|
||||
_events.Dequeue();
|
||||
}
|
||||
_events.Enqueue(diagnostic);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class CultMeshLibraryVersion
|
||||
{
|
||||
public static string Current { get; } = Resolve();
|
||||
|
||||
private static string Resolve()
|
||||
{
|
||||
var assembly = typeof(CultMeshLibraryVersion).Assembly;
|
||||
var informational = assembly
|
||||
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
|
||||
.OfType<AssemblyInformationalVersionAttribute>()
|
||||
.FirstOrDefault()?.InformationalVersion;
|
||||
return string.IsNullOrWhiteSpace(informational)
|
||||
? assembly.GetName().Version?.ToString() ?? "unknown"
|
||||
: informational;
|
||||
}
|
||||
}
|
||||
}
|
||||
54
src/GameCult.Mesh/CultMeshRouteRecordFormatter.cs
Normal file
54
src/GameCult.Mesh/CultMeshRouteRecordFormatter.cs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
|
||||
#nullable enable
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads current structured route records and legacy locality strings.
|
||||
/// </summary>
|
||||
public sealed class CultMeshRouteRecordFormatter : IMessagePackFormatter<CultMeshRouteRecord?>
|
||||
{
|
||||
private const int FieldCount = 2;
|
||||
|
||||
public void Serialize(ref MessagePackWriter writer, CultMeshRouteRecord? value, MessagePackSerializerOptions options)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
writer.WriteNil();
|
||||
return;
|
||||
}
|
||||
|
||||
writer.WriteArrayHeader(FieldCount);
|
||||
writer.Write(value.Kind);
|
||||
writer.Write(value.Description);
|
||||
}
|
||||
|
||||
public CultMeshRouteRecord? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
|
||||
{
|
||||
if (reader.TryReadNil())
|
||||
return new CultMeshRouteRecord();
|
||||
if (reader.NextMessagePackType == MessagePackType.String)
|
||||
return new CultMeshRouteRecord(reader.ReadString(), "");
|
||||
if (reader.NextMessagePackType != MessagePackType.Array)
|
||||
throw new MessagePackSerializationException(
|
||||
$"CultMesh route must be a string or array, not {reader.NextMessagePackType}.");
|
||||
|
||||
options.Security.DepthStep(ref reader);
|
||||
try
|
||||
{
|
||||
var fields = reader.ReadArrayHeader();
|
||||
var kind = fields > 0 ? reader.ReadString() ?? "" : "";
|
||||
var description = fields > 1 ? reader.ReadString() ?? "" : "";
|
||||
for (var index = FieldCount; index < fields; index++)
|
||||
reader.Skip();
|
||||
return new CultMeshRouteRecord(kind, description);
|
||||
}
|
||||
finally
|
||||
{
|
||||
reader.Depth--;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
946
src/GameCult.Mesh/CultMeshSessions.cs
Normal file
946
src/GameCult.Mesh/CultMeshSessions.cs
Normal file
|
|
@ -0,0 +1,946 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Networking;
|
||||
using R3;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
public sealed class CultMeshEndpointId : IEquatable<CultMeshEndpointId>
|
||||
{
|
||||
private CultMeshEndpointId(string value) { Value = value; }
|
||||
public string Value { get; }
|
||||
public static CultMeshEndpointId Parse(string value) => new CultMeshEndpointId(
|
||||
string.IsNullOrWhiteSpace(value) ? throw new FormatException("CultMesh endpoint identity must be non-empty.") : value.Trim());
|
||||
public bool Equals(CultMeshEndpointId? other) => other != null && string.Equals(Value, other.Value, StringComparison.Ordinal);
|
||||
public override bool Equals(object? obj) => Equals(obj as CultMeshEndpointId);
|
||||
public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value);
|
||||
public override string ToString() => Value;
|
||||
}
|
||||
|
||||
public sealed class CultMeshProtocolId : IEquatable<CultMeshProtocolId>
|
||||
{
|
||||
public CultMeshProtocolId(string value) { Value = string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Protocol identity is required.", nameof(value)) : value; }
|
||||
public string Value { get; }
|
||||
public bool Equals(CultMeshProtocolId? other) => other != null && string.Equals(Value, other.Value, StringComparison.Ordinal);
|
||||
public override bool Equals(object? obj) => Equals(obj as CultMeshProtocolId);
|
||||
public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Value);
|
||||
public override string ToString() => Value;
|
||||
}
|
||||
|
||||
public static class CultMeshProtocols
|
||||
{
|
||||
public static CultMeshProtocolId Documents { get; } = new CultMeshProtocolId("cultmesh.documents.v1");
|
||||
public static CultMeshProtocolId Content { get; } = new CultMeshProtocolId("cultmesh.content.v1");
|
||||
public static CultMeshProtocolId Bodies { get; } = new CultMeshProtocolId("cultmesh.bodies.v1");
|
||||
public static CultMeshProtocolId Discovery { get; } = new CultMeshProtocolId("cultmesh.discovery.v1");
|
||||
public static CultMeshProtocolId PeerExchange { get; } = new CultMeshProtocolId("cultmesh.peer_exchange.v1");
|
||||
public static CultMeshProtocolId Subscriptions { get; } = new CultMeshProtocolId("cultmesh.subscriptions.v1");
|
||||
public static CultMeshProtocolId RealtimeState { get; } = new CultMeshProtocolId("cultmesh.realtime_state.v1");
|
||||
}
|
||||
|
||||
public enum CultMeshTransportPathKind { Direct, Relay, Tunnel }
|
||||
|
||||
public sealed class CultMeshTransportCandidate
|
||||
{
|
||||
public CultMeshTransportCandidate(string endpoint, CultMeshTransportPathKind pathKind = CultMeshTransportPathKind.Direct, int priority = 0)
|
||||
{
|
||||
Endpoint = string.IsNullOrWhiteSpace(endpoint) ? throw new ArgumentException("Physical endpoint is required.", nameof(endpoint)) : endpoint;
|
||||
PathKind = pathKind;
|
||||
Priority = priority;
|
||||
}
|
||||
public string Endpoint { get; }
|
||||
public CultMeshTransportPathKind PathKind { get; }
|
||||
public int Priority { get; }
|
||||
}
|
||||
|
||||
public enum CultMeshSessionStatus { Connecting, Online, Degraded, Reconnecting, Offline }
|
||||
public enum CultMeshSessionFailureReason { Resolution, Authentication, Transport, Protocol, Timeout, Cancellation, Authority, UnsupportedPath }
|
||||
|
||||
public sealed class CultMeshSessionFailure
|
||||
{
|
||||
public CultMeshSessionFailure(CultMeshSessionFailureReason reason, string message, string endpoint = "")
|
||||
{
|
||||
Reason = reason;
|
||||
Message = message ?? "";
|
||||
Endpoint = endpoint ?? "";
|
||||
}
|
||||
public CultMeshSessionFailureReason Reason { get; }
|
||||
public string Message { get; }
|
||||
public string Endpoint { get; }
|
||||
}
|
||||
|
||||
public sealed class CultMeshSessionState
|
||||
{
|
||||
public CultMeshSessionState(
|
||||
CultMeshSessionStatus status,
|
||||
DateTimeOffset observedAtUtc,
|
||||
CultMeshTransportCandidate? path = null,
|
||||
CultMeshSessionFailure? failure = null)
|
||||
{
|
||||
Status = status;
|
||||
ObservedAtUtc = observedAtUtc;
|
||||
Path = path;
|
||||
Failure = failure;
|
||||
}
|
||||
public CultMeshSessionStatus Status { get; }
|
||||
public DateTimeOffset ObservedAtUtc { get; }
|
||||
public CultMeshTransportCandidate? Path { get; }
|
||||
public CultMeshSessionFailure? Failure { get; }
|
||||
}
|
||||
|
||||
public sealed class CultMeshSessionException : Exception
|
||||
{
|
||||
public CultMeshSessionException(CultMeshSessionFailure failure, Exception? inner = null)
|
||||
: base(failure?.Message, inner) { Failure = failure ?? throw new ArgumentNullException(nameof(failure)); }
|
||||
public CultMeshSessionFailure Failure { get; }
|
||||
}
|
||||
|
||||
public interface ICultMeshTransportConnector
|
||||
{
|
||||
string ConnectorId { get; }
|
||||
int Priority { get; }
|
||||
bool CanConnect(CultMeshTransportCandidate candidate);
|
||||
Task<ICultNetSchemaClient> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshProtocolId protocol,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Explicit compatibility connector for the previous RUDP/LiteNetLib schema lanes.
|
||||
/// Prefer <see cref="CultMeshTcpSchemaTransportConnector"/> for registered schemas.
|
||||
/// </summary>
|
||||
public sealed class CultMeshSchemaTransportConnector : ICultMeshTransportConnector
|
||||
{
|
||||
private readonly Func<string, ICultNetSchemaClient> _createClient;
|
||||
private readonly ICultMeshClock _clock;
|
||||
private readonly TimeSpan _connectTimeout;
|
||||
|
||||
public CultMeshSchemaTransportConnector(
|
||||
Func<string, ICultNetSchemaClient>? createClient = null,
|
||||
ICultMeshClock? clock = null,
|
||||
TimeSpan? connectTimeout = null)
|
||||
{
|
||||
_createClient = createClient ?? (endpoint => CultNetSchemaClients.CreateForEndpoint(endpoint));
|
||||
_clock = clock ?? CultMeshSystemClock.Instance;
|
||||
_connectTimeout = connectTimeout ?? TimeSpan.FromSeconds(5);
|
||||
}
|
||||
|
||||
public string ConnectorId => "legacy-datagram-schema";
|
||||
public int Priority => 10_000;
|
||||
public bool CanConnect(CultMeshTransportCandidate candidate) =>
|
||||
Uri.TryCreate(candidate.Endpoint, UriKind.Absolute, out var uri) &&
|
||||
(string.Equals(uri.Scheme, "rudp", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(uri.Scheme, "cultnet", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public async Task<ICultNetSchemaClient> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshProtocolId protocol,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!CanConnect(candidate)) throw new NotSupportedException($"Unsupported CultNet endpoint '{candidate.Endpoint}'.");
|
||||
var client = _createClient(candidate.Endpoint);
|
||||
try
|
||||
{
|
||||
var (host, port) = CultNetSchemaWriteForwarder.ParseEndpoint(candidate.Endpoint);
|
||||
client.Connect(host, port);
|
||||
var deadline = _clock.UtcNow + _connectTimeout;
|
||||
while (!client.Connected)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (_clock.UtcNow >= deadline)
|
||||
throw new TimeoutException($"Timed out connecting to '{candidate.Endpoint}'.");
|
||||
await _clock.DelayAsync(TimeSpan.FromMilliseconds(25), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return client;
|
||||
}
|
||||
catch
|
||||
{
|
||||
client.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Preferred connector for registered schema, command, receipt, and manifest traffic.</summary>
|
||||
public sealed class CultMeshTcpSchemaTransportConnector : ICultMeshTransportConnector
|
||||
{
|
||||
private readonly Func<string, ICultNetSchemaClient> _createClient;
|
||||
private readonly ICultMeshClock _clock;
|
||||
private readonly TimeSpan _connectTimeout;
|
||||
|
||||
public CultMeshTcpSchemaTransportConnector(
|
||||
Func<string, ICultNetSchemaClient>? createClient = null,
|
||||
ICultMeshClock? clock = null,
|
||||
TimeSpan? connectTimeout = null)
|
||||
{
|
||||
_createClient = createClient ?? (_ => CultNetSchemaClients.CreateTcpFramed());
|
||||
_clock = clock ?? CultMeshSystemClock.Instance;
|
||||
_connectTimeout = connectTimeout ?? TimeSpan.FromSeconds(5);
|
||||
}
|
||||
|
||||
public string ConnectorId => "tcp-schema";
|
||||
public int Priority => 0;
|
||||
public bool CanConnect(CultMeshTransportCandidate candidate) =>
|
||||
Uri.TryCreate(candidate.Endpoint, UriKind.Absolute, out var uri) &&
|
||||
string.Equals(uri.Scheme, "cultnet+tcp", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public async Task<ICultNetSchemaClient> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshProtocolId protocol,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!CanConnect(candidate))
|
||||
throw new NotSupportedException($"TCP schema connector does not support '{candidate.Endpoint}'.");
|
||||
var client = _createClient(candidate.Endpoint);
|
||||
try
|
||||
{
|
||||
var (host, port) = CultNetSchemaWriteForwarder.ParseEndpoint(candidate.Endpoint);
|
||||
client.Connect(host, port);
|
||||
var deadline = _clock.UtcNow + _connectTimeout;
|
||||
while (!client.Connected)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (_clock.UtcNow >= deadline)
|
||||
throw new TimeoutException($"Timed out connecting to '{candidate.Endpoint}'.");
|
||||
await _clock.DelayAsync(TimeSpan.FromMilliseconds(25), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return client;
|
||||
}
|
||||
catch
|
||||
{
|
||||
client.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshSession : IDisposable
|
||||
{
|
||||
private readonly Subject<CultMeshSessionState> _states = new();
|
||||
private readonly ConcurrentBag<IDisposable> _subscriptions = new();
|
||||
private readonly ManagedSchemaChannel _channel;
|
||||
private long _physicalGeneration;
|
||||
private bool _disposed;
|
||||
internal CultMeshSession(CultMeshEndpointId endpointId, CultMeshProtocolId protocol, ICultNetSchemaClient channel, CultMeshSessionState state)
|
||||
{
|
||||
EndpointId = endpointId;
|
||||
Protocol = protocol;
|
||||
_channel = new ManagedSchemaChannel(channel);
|
||||
State = state;
|
||||
}
|
||||
public CultMeshEndpointId EndpointId { get; }
|
||||
public CultMeshProtocolId Protocol { get; }
|
||||
internal ICultNetSchemaClient Channel => _channel;
|
||||
public CultMeshSessionState State { get; private set; }
|
||||
internal long PhysicalGeneration => Interlocked.Read(ref _physicalGeneration);
|
||||
public Observable<CultMeshSessionState> WatchState() => _states;
|
||||
public ICultNetSchemaClient OpenSchemaClient() => new SessionSchemaClient(this);
|
||||
public void SendCultNet<T>(T message) where T : ICultNetSchemaMessage => Channel.SendCultNet(message);
|
||||
public IDisposable OnCultNet<T>(Action<T> callback) where T : ICultNetSchemaMessage
|
||||
{
|
||||
if (callback == null) throw new ArgumentNullException(nameof(callback));
|
||||
var subscription = new SessionSubscription<T>(callback);
|
||||
Channel.OnCultNet<T>(subscription.Invoke);
|
||||
_subscriptions.Add(subscription);
|
||||
return subscription;
|
||||
}
|
||||
internal void Transition(CultMeshSessionState state) { State = state; _states.OnNext(state); }
|
||||
internal void ReplacePhysicalChannel(ICultNetSchemaClient channel)
|
||||
{
|
||||
_channel.Replace(channel);
|
||||
Interlocked.Increment(ref _physicalGeneration);
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
foreach (var subscription in _subscriptions) subscription.Dispose();
|
||||
_channel.Dispose();
|
||||
_states.Dispose();
|
||||
}
|
||||
|
||||
private sealed class ManagedSchemaChannel : ICultNetSchemaClient
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly List<IChannelRegistration> _registrations = new();
|
||||
private ICultNetSchemaClient _physical;
|
||||
private bool _disposed;
|
||||
|
||||
public ManagedSchemaChannel(ICultNetSchemaClient physical) =>
|
||||
_physical = physical ?? throw new ArgumentNullException(nameof(physical));
|
||||
|
||||
public bool Connected { get { lock (_gate) return !_disposed && _physical.Connected; } }
|
||||
public void Connect(string host, int port)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
_physical.Connect(host, port);
|
||||
}
|
||||
}
|
||||
public void SendCultNet<T>(T message) where T : ICultNetSchemaMessage
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
_physical.SendCultNet(message);
|
||||
}
|
||||
}
|
||||
public void OnCultNet<T>(Action<T> callback) where T : ICultNetSchemaMessage
|
||||
{
|
||||
if (callback == null) throw new ArgumentNullException(nameof(callback));
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var registration = new ChannelRegistration<T>(callback);
|
||||
registration.Attach(_physical);
|
||||
_registrations.Add(registration);
|
||||
}
|
||||
}
|
||||
public void Replace(ICultNetSchemaClient physical)
|
||||
{
|
||||
if (physical == null) throw new ArgumentNullException(nameof(physical));
|
||||
ICultNetSchemaClient previous;
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
previous = _physical;
|
||||
foreach (var registration in _registrations) registration.Attach(physical);
|
||||
_physical = physical;
|
||||
}
|
||||
previous.Dispose();
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
ICultNetSchemaClient physical;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
physical = _physical;
|
||||
_registrations.Clear();
|
||||
}
|
||||
physical.Dispose();
|
||||
}
|
||||
private void ThrowIfDisposed() { if (_disposed) throw new ObjectDisposedException(nameof(ManagedSchemaChannel)); }
|
||||
|
||||
private interface IChannelRegistration { void Attach(ICultNetSchemaClient physical); }
|
||||
private sealed class ChannelRegistration<T> : IChannelRegistration where T : ICultNetSchemaMessage
|
||||
{
|
||||
private readonly Action<T> _callback;
|
||||
public ChannelRegistration(Action<T> callback) => _callback = callback;
|
||||
public void Attach(ICultNetSchemaClient physical) => physical.OnCultNet(_callback);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SessionSubscription<T> : IDisposable where T : ICultNetSchemaMessage
|
||||
{
|
||||
private Action<T>? _callback;
|
||||
public SessionSubscription(Action<T> callback) { _callback = callback; }
|
||||
public void Invoke(T message) => Volatile.Read(ref _callback)?.Invoke(message);
|
||||
public void Dispose() => Interlocked.Exchange(ref _callback, null);
|
||||
}
|
||||
|
||||
private sealed class SessionSchemaClient : ICultNetSchemaClient
|
||||
{
|
||||
private readonly CultMeshSession _session;
|
||||
private readonly ConcurrentBag<IDisposable> _registrations = new();
|
||||
private bool _disposed;
|
||||
public SessionSchemaClient(CultMeshSession session) { _session = session; }
|
||||
public bool Connected => !_disposed && _session.State.Status == CultMeshSessionStatus.Online;
|
||||
public void Connect(string host, int port)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(SessionSchemaClient));
|
||||
if (!Connected) throw new InvalidOperationException("The managed CultMesh session is not online.");
|
||||
}
|
||||
public void SendCultNet<T>(T message) where T : ICultNetSchemaMessage
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(SessionSchemaClient));
|
||||
_session.SendCultNet(message);
|
||||
}
|
||||
public void OnCultNet<T>(Action<T> callback) where T : ICultNetSchemaMessage
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(SessionSchemaClient));
|
||||
_registrations.Add(_session.OnCultNet(callback));
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
foreach (var registration in _registrations) registration.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CultMeshSessionManagerOptions
|
||||
{
|
||||
public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance;
|
||||
public ICultMeshDiagnosticSink Diagnostics { get; set; } = CultMeshNullDiagnosticSink.Instance;
|
||||
public int MaxRacedCandidates { get; set; } = 2;
|
||||
}
|
||||
|
||||
public sealed class CultMeshSessionManager : IDisposable
|
||||
{
|
||||
private readonly CultMeshDiscoveryService _discovery;
|
||||
private readonly ICultMeshTransportConnector[] _connectors;
|
||||
private readonly ICultMeshContentTransportConnector[] _contentConnectors;
|
||||
private readonly ICultMeshRealtimeTransportConnector[] _realtimeConnectors;
|
||||
private readonly CultMeshSessionManagerOptions _options;
|
||||
private readonly ConcurrentDictionary<string, Lazy<Task<CultMeshSession>>> _sessions = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, Lazy<Task<CultMeshContentSession>>> _contentSessions = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, Lazy<Task<CultMeshRealtimeSession>>> _realtimeSessions = new(StringComparer.Ordinal);
|
||||
private long _diagnosticSequence;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshSessionManager(
|
||||
CultMeshDiscoveryService discovery,
|
||||
IEnumerable<ICultMeshTransportConnector> connectors,
|
||||
CultMeshSessionManagerOptions? options = null)
|
||||
: this(
|
||||
discovery,
|
||||
connectors,
|
||||
Array.Empty<ICultMeshContentTransportConnector>(),
|
||||
Array.Empty<ICultMeshRealtimeTransportConnector>(),
|
||||
options)
|
||||
{
|
||||
}
|
||||
|
||||
public CultMeshSessionManager(
|
||||
CultMeshDiscoveryService discovery,
|
||||
IEnumerable<ICultMeshTransportConnector> connectors,
|
||||
IEnumerable<ICultMeshContentTransportConnector> contentConnectors,
|
||||
CultMeshSessionManagerOptions? options = null)
|
||||
: this(
|
||||
discovery,
|
||||
connectors,
|
||||
contentConnectors,
|
||||
Array.Empty<ICultMeshRealtimeTransportConnector>(),
|
||||
options)
|
||||
{
|
||||
}
|
||||
|
||||
public CultMeshSessionManager(
|
||||
CultMeshDiscoveryService discovery,
|
||||
IEnumerable<ICultMeshTransportConnector> connectors,
|
||||
IEnumerable<ICultMeshContentTransportConnector> contentConnectors,
|
||||
IEnumerable<ICultMeshRealtimeTransportConnector> realtimeConnectors,
|
||||
CultMeshSessionManagerOptions? options = null)
|
||||
{
|
||||
_discovery = discovery ?? throw new ArgumentNullException(nameof(discovery));
|
||||
_connectors = connectors?.ToArray() ?? throw new ArgumentNullException(nameof(connectors));
|
||||
_contentConnectors = contentConnectors?.ToArray() ?? throw new ArgumentNullException(nameof(contentConnectors));
|
||||
_realtimeConnectors = realtimeConnectors?.ToArray() ?? throw new ArgumentNullException(nameof(realtimeConnectors));
|
||||
if (_contentConnectors.Any(connector => connector == null))
|
||||
throw new ArgumentException("Content transport connectors cannot contain null entries.", nameof(contentConnectors));
|
||||
if (_realtimeConnectors.Any(connector => connector == null))
|
||||
throw new ArgumentException("Realtime transport connectors cannot contain null entries.", nameof(realtimeConnectors));
|
||||
_options = options ?? new CultMeshSessionManagerOptions();
|
||||
if (_options.MaxRacedCandidates <= 0) throw new ArgumentOutOfRangeException(nameof(options));
|
||||
}
|
||||
|
||||
public async Task<CultMeshSession> ConnectAsync(
|
||||
CultMeshEndpointId endpointId,
|
||||
CultMeshProtocolId protocol,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
|
||||
if (protocol == null) throw new ArgumentNullException(nameof(protocol));
|
||||
ThrowIfDisposed();
|
||||
var key = endpointId.Value + "\u001f" + protocol.Value;
|
||||
while (true)
|
||||
{
|
||||
var lazy = _sessions.GetOrAdd(key, _ => new Lazy<Task<CultMeshSession>>(
|
||||
() => ConnectOwnedAsync(key, endpointId, protocol), LazyThreadSafetyMode.ExecutionAndPublication));
|
||||
try
|
||||
{
|
||||
var session = await AwaitForCallerAsync(lazy.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (session.State.Status != CultMeshSessionStatus.Offline) return session;
|
||||
_sessions.TryRemove(key, out _);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_sessions.TryRemove(key, out _);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connects one reusable streaming content plane by stable endpoint identity.
|
||||
/// Preferred connector tiers are exhausted before legacy fallback tiers are attempted.
|
||||
/// </summary>
|
||||
public async Task<CultMeshContentSession> ConnectContentAsync(
|
||||
CultMeshEndpointId endpointId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
|
||||
ThrowIfDisposed();
|
||||
var key = endpointId.Value;
|
||||
while (true)
|
||||
{
|
||||
var lazy = _contentSessions.GetOrAdd(key, _ => new Lazy<Task<CultMeshContentSession>>(
|
||||
() => ConnectContentOwnedAsync(key, endpointId), LazyThreadSafetyMode.ExecutionAndPublication));
|
||||
try
|
||||
{
|
||||
var session = await AwaitForCallerAsync(lazy.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (session.State.Status != CultMeshSessionStatus.Offline) return session;
|
||||
_contentSessions.TryRemove(key, out _);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_contentSessions.TryRemove(key, out _);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<CultMeshContentSession> ConnectContentOwnedAsync(
|
||||
string key,
|
||||
CultMeshEndpointId endpointId)
|
||||
{
|
||||
var result = await ResolveContentPathAsync(endpointId).ConfigureAwait(false);
|
||||
var session = new CultMeshContentSession(
|
||||
endpointId,
|
||||
result.Transport,
|
||||
new CultMeshSessionState(CultMeshSessionStatus.Online, _options.Clock.UtcNow, result.Candidate),
|
||||
failed => InvalidateContentSession(key, failed));
|
||||
Emit(endpointId, CultMeshProtocols.Content, "online", result.Candidate.Endpoint);
|
||||
return session;
|
||||
}
|
||||
|
||||
private async Task<ConnectedContentPath> ResolveContentPathAsync(CultMeshEndpointId endpointId)
|
||||
{
|
||||
if (_contentConnectors.Length == 0)
|
||||
throw Failure(
|
||||
CultMeshSessionFailureReason.UnsupportedPath,
|
||||
"No streaming content connectors are configured. Register the TCP content connector or the explicit legacy RUDP connector.");
|
||||
|
||||
var discovery = await _discovery.ResolveAsync(new CultMeshDiscoveryQuery(endpointId.Value)).ConfigureAwait(false);
|
||||
var candidates = discovery.Candidates
|
||||
.SelectMany(candidate => candidate.Descriptor.DiscoveryEndpoints)
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.Select(endpoint => new CultMeshTransportCandidate(endpoint))
|
||||
.ToArray();
|
||||
var routes = candidates
|
||||
.SelectMany(candidate => _contentConnectors
|
||||
.Where(connector => connector.CanConnect(candidate))
|
||||
.Select(connector => new ContentRoute(candidate, connector)))
|
||||
.OrderBy(route => route.Connector.Priority)
|
||||
.ThenBy(route => route.Candidate.Priority)
|
||||
.ToArray();
|
||||
if (routes.Length == 0)
|
||||
throw Failure(
|
||||
CultMeshSessionFailureReason.UnsupportedPath,
|
||||
$"No streaming content connector supports an advertised route for '{endpointId}'.");
|
||||
|
||||
var failures = new List<Exception>();
|
||||
foreach (var tier in routes.GroupBy(route => route.Connector.Priority).OrderBy(group => group.Key))
|
||||
{
|
||||
var attempts = tier.Take(_options.MaxRacedCandidates)
|
||||
.Select(route => ConnectContentCandidateAsync(endpointId, route))
|
||||
.ToList();
|
||||
while (attempts.Count > 0)
|
||||
{
|
||||
var completed = await Task.WhenAny(attempts).ConfigureAwait(false);
|
||||
attempts.Remove(completed);
|
||||
try
|
||||
{
|
||||
var result = await completed.ConfigureAwait(false);
|
||||
foreach (var loser in attempts)
|
||||
_ = loser.ContinueWith(task =>
|
||||
{
|
||||
if (task.Status == TaskStatus.RanToCompletion) task.Result.Transport.Dispose();
|
||||
}, TaskScheduler.Default);
|
||||
return result;
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
failures.Add(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var last = failures.LastOrDefault();
|
||||
throw Failure(
|
||||
last is TimeoutException ? CultMeshSessionFailureReason.Timeout : CultMeshSessionFailureReason.Transport,
|
||||
$"No streaming content path connected for '{endpointId}'.",
|
||||
last);
|
||||
}
|
||||
|
||||
private static async Task<ConnectedContentPath> ConnectContentCandidateAsync(
|
||||
CultMeshEndpointId endpointId,
|
||||
ContentRoute route)
|
||||
{
|
||||
var transport = await route.Connector.ConnectAsync(route.Candidate, endpointId).ConfigureAwait(false);
|
||||
return new ConnectedContentPath(route.Candidate, transport);
|
||||
}
|
||||
|
||||
private void InvalidateContentSession(string key, CultMeshContentSession session)
|
||||
{
|
||||
session.MarkOffline(new CultMeshSessionState(
|
||||
CultMeshSessionStatus.Offline,
|
||||
_options.Clock.UtcNow,
|
||||
session.State.Path,
|
||||
new CultMeshSessionFailure(
|
||||
CultMeshSessionFailureReason.Transport,
|
||||
"The selected streaming content transport failed.",
|
||||
session.State.Path?.Endpoint ?? string.Empty)));
|
||||
if (_contentSessions.TryRemove(key, out var removed) &&
|
||||
removed.IsValueCreated && removed.Value.Status == TaskStatus.RanToCompletion)
|
||||
removed.Value.Result.Dispose();
|
||||
Emit(session.EndpointId, CultMeshProtocols.Content, "offline", session.State.Path?.Endpoint ?? string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connects the realtime state plane. No connector is implied: promoted runtimes
|
||||
/// register QUIC explicitly, while RUDP compatibility remains opt-in.
|
||||
/// </summary>
|
||||
public async Task<CultMeshRealtimeSession> ConnectRealtimeAsync(
|
||||
CultMeshEndpointId endpointId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
|
||||
ThrowIfDisposed();
|
||||
var key = endpointId.Value;
|
||||
while (true)
|
||||
{
|
||||
var lazy = _realtimeSessions.GetOrAdd(key, _ => new Lazy<Task<CultMeshRealtimeSession>>(
|
||||
() => ConnectRealtimeOwnedAsync(key, endpointId), LazyThreadSafetyMode.ExecutionAndPublication));
|
||||
try
|
||||
{
|
||||
var session = await AwaitForCallerAsync(lazy.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (session.State.Status != CultMeshSessionStatus.Offline) return session;
|
||||
_realtimeSessions.TryRemove(key, out _);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_realtimeSessions.TryRemove(key, out _);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<CultMeshRealtimeSession> ConnectRealtimeOwnedAsync(
|
||||
string key,
|
||||
CultMeshEndpointId endpointId)
|
||||
{
|
||||
var result = await ResolveRealtimePathAsync(endpointId).ConfigureAwait(false);
|
||||
var session = new CultMeshRealtimeSession(
|
||||
endpointId,
|
||||
result.Transport,
|
||||
new CultMeshSessionState(CultMeshSessionStatus.Online, _options.Clock.UtcNow, result.Candidate),
|
||||
failed => InvalidateRealtimeSession(key, failed));
|
||||
Emit(endpointId, CultMeshProtocols.RealtimeState, "online", result.Candidate.Endpoint);
|
||||
return session;
|
||||
}
|
||||
|
||||
private async Task<ConnectedRealtimePath> ResolveRealtimePathAsync(CultMeshEndpointId endpointId)
|
||||
{
|
||||
if (_realtimeConnectors.Length == 0)
|
||||
throw Failure(
|
||||
CultMeshSessionFailureReason.UnsupportedPath,
|
||||
"No realtime state connectors are configured. Register a QUIC connector explicitly.");
|
||||
|
||||
var discovery = await _discovery.ResolveAsync(new CultMeshDiscoveryQuery(endpointId.Value)).ConfigureAwait(false);
|
||||
var routes = discovery.Candidates
|
||||
.SelectMany(candidate => candidate.Descriptor.DiscoveryEndpoints)
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.Select(endpoint => new CultMeshTransportCandidate(endpoint))
|
||||
.SelectMany(candidate => _realtimeConnectors
|
||||
.Where(connector => connector.CanConnect(candidate))
|
||||
.Select(connector => new RealtimeRoute(candidate, connector)))
|
||||
.OrderBy(route => route.Connector.Priority)
|
||||
.ThenBy(route => route.Candidate.Priority)
|
||||
.ToArray();
|
||||
if (routes.Length == 0)
|
||||
throw Failure(
|
||||
CultMeshSessionFailureReason.UnsupportedPath,
|
||||
$"No realtime connector supports an advertised route for '{endpointId}'.");
|
||||
|
||||
var failures = new List<Exception>();
|
||||
foreach (var tier in routes.GroupBy(route => route.Connector.Priority).OrderBy(group => group.Key))
|
||||
{
|
||||
var attempts = tier.Take(_options.MaxRacedCandidates)
|
||||
.Select(route => ConnectRealtimeCandidateAsync(endpointId, route))
|
||||
.ToList();
|
||||
while (attempts.Count > 0)
|
||||
{
|
||||
var completed = await Task.WhenAny(attempts).ConfigureAwait(false);
|
||||
attempts.Remove(completed);
|
||||
try
|
||||
{
|
||||
var result = await completed.ConfigureAwait(false);
|
||||
foreach (var loser in attempts)
|
||||
_ = loser.ContinueWith(task =>
|
||||
{
|
||||
if (task.Status == TaskStatus.RanToCompletion) task.Result.Transport.Dispose();
|
||||
}, TaskScheduler.Default);
|
||||
return result;
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
failures.Add(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var last = failures.LastOrDefault();
|
||||
throw Failure(
|
||||
last is TimeoutException ? CultMeshSessionFailureReason.Timeout : CultMeshSessionFailureReason.Transport,
|
||||
$"No realtime state path connected for '{endpointId}'.",
|
||||
last);
|
||||
}
|
||||
|
||||
private static async Task<ConnectedRealtimePath> ConnectRealtimeCandidateAsync(
|
||||
CultMeshEndpointId endpointId,
|
||||
RealtimeRoute route)
|
||||
{
|
||||
var transport = await route.Connector.ConnectAsync(route.Candidate, endpointId).ConfigureAwait(false);
|
||||
return new ConnectedRealtimePath(route.Candidate, transport);
|
||||
}
|
||||
|
||||
private void InvalidateRealtimeSession(string key, CultMeshRealtimeSession session)
|
||||
{
|
||||
var endpoint = session.State.Path?.Endpoint ?? string.Empty;
|
||||
session.MarkOffline(new CultMeshSessionState(
|
||||
CultMeshSessionStatus.Offline,
|
||||
_options.Clock.UtcNow,
|
||||
session.State.Path,
|
||||
new CultMeshSessionFailure(
|
||||
CultMeshSessionFailureReason.Transport,
|
||||
"The selected realtime state transport failed.",
|
||||
endpoint)));
|
||||
if (_realtimeSessions.TryRemove(key, out var removed) &&
|
||||
removed.IsValueCreated && removed.Value.Status == TaskStatus.RanToCompletion)
|
||||
removed.Value.Result.Dispose();
|
||||
Emit(session.EndpointId, CultMeshProtocols.RealtimeState, "offline", endpoint);
|
||||
}
|
||||
|
||||
private async Task<CultMeshSession> ConnectOwnedAsync(string key, CultMeshEndpointId endpointId, CultMeshProtocolId protocol)
|
||||
{
|
||||
var result = await ResolveConnectedPathAsync(endpointId, protocol).ConfigureAwait(false);
|
||||
var session = new CultMeshSession(endpointId, protocol, result.Client,
|
||||
new CultMeshSessionState(CultMeshSessionStatus.Online, _options.Clock.UtcNow, result.Candidate));
|
||||
ObservePhysicalFailure(key, session, result);
|
||||
Emit(endpointId, protocol, "online", result.Candidate.Endpoint);
|
||||
return session;
|
||||
}
|
||||
|
||||
private async Task<ConnectedPath> ResolveConnectedPathAsync(CultMeshEndpointId endpointId, CultMeshProtocolId protocol)
|
||||
{
|
||||
var discovery = await _discovery.ResolveAsync(new CultMeshDiscoveryQuery(endpointId.Value)).ConfigureAwait(false);
|
||||
var candidates = discovery.Candidates.SelectMany(candidate => candidate.Descriptor.DiscoveryEndpoints)
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.Select(endpoint => new CultMeshTransportCandidate(endpoint))
|
||||
.ToArray();
|
||||
var routes = candidates
|
||||
.SelectMany(candidate => _connectors
|
||||
.Where(connector => connector.CanConnect(candidate))
|
||||
.Select(connector => new SchemaRoute(candidate, connector)))
|
||||
.OrderBy(route => route.Connector.Priority)
|
||||
.ThenBy(route => route.Candidate.Priority)
|
||||
.ToArray();
|
||||
if (candidates.Length == 0)
|
||||
throw Failure(CultMeshSessionFailureReason.Resolution, $"No route candidates for '{endpointId}'.");
|
||||
if (routes.Length == 0)
|
||||
throw Failure(
|
||||
CultMeshSessionFailureReason.Transport,
|
||||
$"No transport path connected for '{endpointId}' and protocol '{protocol}'.",
|
||||
Failure(
|
||||
CultMeshSessionFailureReason.UnsupportedPath,
|
||||
$"No registered connector supports an advertised route for '{endpointId}'."));
|
||||
|
||||
var failures = new List<Exception>();
|
||||
foreach (var tier in routes.GroupBy(route => route.Connector.Priority).OrderBy(group => group.Key))
|
||||
{
|
||||
var attempts = tier.Take(_options.MaxRacedCandidates)
|
||||
.Select(route => ConnectCandidateAsync(route, protocol))
|
||||
.ToList();
|
||||
while (attempts.Count > 0)
|
||||
{
|
||||
var completed = await Task.WhenAny(attempts).ConfigureAwait(false);
|
||||
attempts.Remove(completed);
|
||||
try
|
||||
{
|
||||
var result = await completed.ConfigureAwait(false);
|
||||
foreach (var loser in attempts)
|
||||
_ = loser.ContinueWith(task => { if (task.Status == TaskStatus.RanToCompletion) task.Result.Client.Dispose(); }, TaskScheduler.Default);
|
||||
return result;
|
||||
}
|
||||
catch (Exception error) { failures.Add(error); }
|
||||
}
|
||||
}
|
||||
var last = failures.LastOrDefault();
|
||||
throw Failure(last is TimeoutException ? CultMeshSessionFailureReason.Timeout : CultMeshSessionFailureReason.Transport,
|
||||
$"No transport path connected for '{endpointId}' and protocol '{protocol}'.", last);
|
||||
}
|
||||
|
||||
private void ObservePhysicalFailure(string key, CultMeshSession session, ConnectedPath path)
|
||||
{
|
||||
if (path.Client is not ICultNetSchemaClientHealth health) return;
|
||||
_ = health.BackgroundFailure.ContinueWith(
|
||||
task => ReconnectOwnedAsync(key, session, path, task),
|
||||
CancellationToken.None,
|
||||
TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default).Unwrap();
|
||||
}
|
||||
|
||||
private async Task ReconnectOwnedAsync(
|
||||
string key,
|
||||
CultMeshSession session,
|
||||
ConnectedPath failedPath,
|
||||
Task<Exception> failureTask)
|
||||
{
|
||||
if (_disposed || session.State.Status == CultMeshSessionStatus.Offline) return;
|
||||
var error = failureTask.Status == TaskStatus.RanToCompletion ? failureTask.Result : failureTask.Exception;
|
||||
var failure = new CultMeshSessionFailure(
|
||||
CultMeshSessionFailureReason.Transport,
|
||||
error?.Message ?? "Transport background loop stopped.",
|
||||
failedPath.Candidate.Endpoint);
|
||||
session.Transition(new CultMeshSessionState(
|
||||
CultMeshSessionStatus.Reconnecting,
|
||||
_options.Clock.UtcNow,
|
||||
failedPath.Candidate,
|
||||
failure));
|
||||
Emit(session.EndpointId, session.Protocol, "reconnecting", failedPath.Candidate.Endpoint);
|
||||
try
|
||||
{
|
||||
var replacement = await ResolveConnectedPathAsync(session.EndpointId, session.Protocol).ConfigureAwait(false);
|
||||
session.ReplacePhysicalChannel(replacement.Client);
|
||||
session.Transition(new CultMeshSessionState(
|
||||
CultMeshSessionStatus.Online,
|
||||
_options.Clock.UtcNow,
|
||||
replacement.Candidate));
|
||||
ObservePhysicalFailure(key, session, replacement);
|
||||
Emit(session.EndpointId, session.Protocol, "online", replacement.Candidate.Endpoint);
|
||||
}
|
||||
catch (Exception reconnectError)
|
||||
{
|
||||
session.Transition(new CultMeshSessionState(
|
||||
CultMeshSessionStatus.Offline,
|
||||
_options.Clock.UtcNow,
|
||||
failedPath.Candidate,
|
||||
new CultMeshSessionFailure(
|
||||
reconnectError is CultMeshSessionException typed ? typed.Failure.Reason : CultMeshSessionFailureReason.Transport,
|
||||
reconnectError.Message,
|
||||
failedPath.Candidate.Endpoint)));
|
||||
_sessions.TryRemove(key, out _);
|
||||
Emit(session.EndpointId, session.Protocol, "offline", failedPath.Candidate.Endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<ConnectedPath> ConnectCandidateAsync(SchemaRoute route, CultMeshProtocolId protocol)
|
||||
{
|
||||
var client = await route.Connector.ConnectAsync(route.Candidate, protocol).ConfigureAwait(false);
|
||||
return new ConnectedPath(route.Candidate, client);
|
||||
}
|
||||
|
||||
private static async Task<T> AwaitForCallerAsync<T>(Task<T> shared, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!cancellationToken.CanBeCanceled) return await shared.ConfigureAwait(false);
|
||||
var cancelled = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using (cancellationToken.Register(() => cancelled.TrySetResult(true)))
|
||||
{
|
||||
if (await Task.WhenAny(shared, cancelled.Task).ConfigureAwait(false) != shared)
|
||||
throw new OperationCanceledException(cancellationToken);
|
||||
}
|
||||
return await shared.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private CultMeshSessionException Failure(CultMeshSessionFailureReason reason, string message, Exception? inner = null) =>
|
||||
new CultMeshSessionException(new CultMeshSessionFailure(reason, message), inner);
|
||||
|
||||
private void Emit(CultMeshEndpointId endpoint, CultMeshProtocolId protocol, string state, string path)
|
||||
{
|
||||
_options.Diagnostics.Emit(new CultMeshDiagnosticEvent(
|
||||
Interlocked.Increment(ref _diagnosticSequence), _options.Clock.UtcNow,
|
||||
CultMeshReliabilityOrgan.Session, CultMeshDiagnosticKind.PathChanged,
|
||||
endpoint.Value + ":" + protocol.Value, endpoint.Value, state,
|
||||
sourceId: "session-manager", endpoint: path));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
foreach (var lazy in _sessions.Values)
|
||||
if (lazy.IsValueCreated && lazy.Value.Status == TaskStatus.RanToCompletion) lazy.Value.Result.Dispose();
|
||||
_sessions.Clear();
|
||||
foreach (var lazy in _contentSessions.Values)
|
||||
if (lazy.IsValueCreated && lazy.Value.Status == TaskStatus.RanToCompletion) lazy.Value.Result.Dispose();
|
||||
_contentSessions.Clear();
|
||||
foreach (var lazy in _realtimeSessions.Values)
|
||||
if (lazy.IsValueCreated && lazy.Value.Status == TaskStatus.RanToCompletion) lazy.Value.Result.Dispose();
|
||||
_realtimeSessions.Clear();
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed() { if (_disposed) throw new ObjectDisposedException(nameof(CultMeshSessionManager)); }
|
||||
|
||||
private sealed class ConnectedPath
|
||||
{
|
||||
public ConnectedPath(CultMeshTransportCandidate candidate, ICultNetSchemaClient client) { Candidate = candidate; Client = client; }
|
||||
public CultMeshTransportCandidate Candidate { get; }
|
||||
public ICultNetSchemaClient Client { get; }
|
||||
}
|
||||
|
||||
private sealed class ConnectedContentPath
|
||||
{
|
||||
public ConnectedContentPath(CultMeshTransportCandidate candidate, ICultMeshContentTransport transport)
|
||||
{
|
||||
Candidate = candidate;
|
||||
Transport = transport;
|
||||
}
|
||||
public CultMeshTransportCandidate Candidate { get; }
|
||||
public ICultMeshContentTransport Transport { get; }
|
||||
}
|
||||
|
||||
private sealed class SchemaRoute
|
||||
{
|
||||
public SchemaRoute(CultMeshTransportCandidate candidate, ICultMeshTransportConnector connector)
|
||||
{
|
||||
Candidate = candidate;
|
||||
Connector = connector;
|
||||
}
|
||||
public CultMeshTransportCandidate Candidate { get; }
|
||||
public ICultMeshTransportConnector Connector { get; }
|
||||
}
|
||||
|
||||
private sealed class ContentRoute
|
||||
{
|
||||
public ContentRoute(CultMeshTransportCandidate candidate, ICultMeshContentTransportConnector connector)
|
||||
{
|
||||
Candidate = candidate;
|
||||
Connector = connector;
|
||||
}
|
||||
public CultMeshTransportCandidate Candidate { get; }
|
||||
public ICultMeshContentTransportConnector Connector { get; }
|
||||
}
|
||||
|
||||
private sealed class ConnectedRealtimePath
|
||||
{
|
||||
public ConnectedRealtimePath(CultMeshTransportCandidate candidate, ICultMeshRealtimeTransport transport)
|
||||
{
|
||||
Candidate = candidate;
|
||||
Transport = transport;
|
||||
}
|
||||
public CultMeshTransportCandidate Candidate { get; }
|
||||
public ICultMeshRealtimeTransport Transport { get; }
|
||||
}
|
||||
|
||||
private sealed class RealtimeRoute
|
||||
{
|
||||
public RealtimeRoute(CultMeshTransportCandidate candidate, ICultMeshRealtimeTransportConnector connector)
|
||||
{
|
||||
Candidate = candidate;
|
||||
Connector = connector;
|
||||
}
|
||||
public CultMeshTransportCandidate Candidate { get; }
|
||||
public ICultMeshRealtimeTransportConnector Connector { get; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -69,6 +69,9 @@ namespace GameCult.Mesh
|
|||
private readonly string _endpoint;
|
||||
private readonly CultMeshSnapshotRequestOptions _defaults;
|
||||
private readonly ICultNetSchemaClient _client;
|
||||
private readonly CultMeshSession? _sharedSession;
|
||||
private readonly IDisposable? _responseSubscription;
|
||||
private readonly IDisposable? _errorSubscription;
|
||||
private readonly CultNetDocumentRegistry _registry;
|
||||
private readonly SemaphoreSlim _requests = new(1, 1);
|
||||
private readonly object _completionLock = new();
|
||||
|
|
@ -93,6 +96,45 @@ namespace GameCult.Mesh
|
|||
_client.Connect(host, port);
|
||||
}
|
||||
|
||||
private CultMeshSnapshotSession(
|
||||
CultMeshSession session,
|
||||
CultMeshSnapshotRequestOptions options,
|
||||
CultNetDocumentRegistry? registry)
|
||||
{
|
||||
_sharedSession = session ?? throw new ArgumentNullException(nameof(session));
|
||||
_endpoint = session.State.Path?.Endpoint ?? session.EndpointId.Value;
|
||||
_defaults = CultMesh.CloneSnapshotRequestOptions(options);
|
||||
_registry = registry ?? new CultNetDocumentRegistry();
|
||||
_client = session.Channel;
|
||||
_responseSubscription = session.OnCultNet<CultNetSnapshotResponseRawMessage>(OnResponse);
|
||||
_errorSubscription = session.OnCultNet<CultNetErrorMessage>(OnError);
|
||||
}
|
||||
|
||||
public static async Task<CultMeshSnapshotSession> ConnectAsync(
|
||||
CultMeshSessionManager sessions,
|
||||
CultMeshEndpointId endpointId,
|
||||
CultMeshSnapshotRequestOptions options,
|
||||
CultNetDocumentRegistry? registry = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (sessions == null) throw new ArgumentNullException(nameof(sessions));
|
||||
var session = await sessions.ConnectAsync(endpointId, CultMeshProtocols.Documents, cancellationToken).ConfigureAwait(false);
|
||||
return new CultMeshSnapshotSession(session, options ?? new CultMeshSnapshotRequestOptions(), registry);
|
||||
}
|
||||
|
||||
public static async Task<CultMeshSnapshotSession> ConnectAsync(
|
||||
CultMeshSessionManager sessions,
|
||||
CultMeshEndpointId endpointId,
|
||||
CultMeshProtocolId protocol,
|
||||
CultMeshSnapshotRequestOptions options,
|
||||
CultNetDocumentRegistry? registry = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (sessions == null) throw new ArgumentNullException(nameof(sessions));
|
||||
var session = await sessions.ConnectAsync(endpointId, protocol, cancellationToken).ConfigureAwait(false);
|
||||
return new CultMeshSnapshotSession(session, options ?? new CultMeshSnapshotRequestOptions(), registry);
|
||||
}
|
||||
|
||||
/// <summary>Fetches one raw snapshot while retaining the underlying endpoint connection.</summary>
|
||||
public async Task<CultNetSnapshotResponseRawMessage> FetchSnapshotAsync(
|
||||
IReadOnlyList<string>? schemaIds = null,
|
||||
|
|
@ -165,7 +207,9 @@ namespace GameCult.Mesh
|
|||
_disposed = true;
|
||||
lock (_completionLock)
|
||||
_completion?.TrySetException(new ObjectDisposedException(nameof(CultMeshSnapshotSession)));
|
||||
_client.Dispose();
|
||||
_responseSubscription?.Dispose();
|
||||
_errorSubscription?.Dispose();
|
||||
if (_sharedSession == null) _client.Dispose();
|
||||
_requests.Dispose();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
|
@ -264,43 +263,43 @@ namespace GameCult.Mesh
|
|||
|
||||
public readonly struct CultMeshFrameWriteLease
|
||||
{
|
||||
internal CultMeshFrameWriteLease(int slotIndex, ulong sequence, Memory<byte> memory)
|
||||
private readonly CultMeshFrameRegionWriteLease _lease;
|
||||
|
||||
internal CultMeshFrameWriteLease(CultMeshFrameRegionWriteLease lease)
|
||||
{
|
||||
SlotIndex = slotIndex;
|
||||
Sequence = sequence;
|
||||
Memory = memory;
|
||||
_lease = lease;
|
||||
}
|
||||
|
||||
public int SlotIndex { get; }
|
||||
public ulong Sequence { get; }
|
||||
public Memory<byte> Memory { get; }
|
||||
public int SlotIndex => _lease.SlotIndex;
|
||||
public ulong Sequence => checked((ulong)_lease.Sequence);
|
||||
public Memory<byte> Memory => _lease.Memory;
|
||||
public Span<byte> Span => Memory.Span;
|
||||
|
||||
internal CultMeshFrameRegionWriteLease RegionLease => _lease;
|
||||
}
|
||||
|
||||
public readonly struct CultMeshFrameReadLease : IDisposable
|
||||
{
|
||||
private readonly CultMeshSharedMemoryFrameRing? _owner;
|
||||
private readonly CultMeshFrameRegionReadLease? _lease;
|
||||
|
||||
internal CultMeshFrameReadLease(
|
||||
CultMeshSharedMemoryFrameRing owner,
|
||||
int slotIndex,
|
||||
CultMeshFrameRegionReadLease lease,
|
||||
CultMeshStreamFrameHandle handle,
|
||||
ReadOnlyMemory<byte> memory)
|
||||
int slotIndex)
|
||||
{
|
||||
_owner = owner;
|
||||
_lease = lease;
|
||||
SlotIndex = slotIndex;
|
||||
Handle = handle;
|
||||
Memory = memory;
|
||||
}
|
||||
|
||||
public int SlotIndex { get; }
|
||||
public CultMeshStreamFrameHandle Handle { get; }
|
||||
public ReadOnlyMemory<byte> Memory { get; }
|
||||
public ReadOnlyMemory<byte> Memory => _lease?.Memory ?? ReadOnlyMemory<byte>.Empty;
|
||||
public ReadOnlySpan<byte> Span => Memory.Span;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_owner?.ReleaseRead(SlotIndex);
|
||||
_lease?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -338,59 +337,33 @@ namespace GameCult.Mesh
|
|||
|
||||
public sealed class CultMeshSharedMemoryFrameRing : IDisposable
|
||||
{
|
||||
private readonly byte[] _storage;
|
||||
private readonly int[] _readerCounts;
|
||||
private readonly CultMeshStreamFrameHandle?[] _handles;
|
||||
private int _writeCursor;
|
||||
private int _latestSlot = -1;
|
||||
private int _disposed;
|
||||
private ulong _nextSequence;
|
||||
private ulong _publishedFrames;
|
||||
private ulong _droppedFrames;
|
||||
private ulong _blockedWrites;
|
||||
private ulong _unavoidableCopyCount;
|
||||
private readonly CultMeshFrameRegion _region;
|
||||
|
||||
public CultMeshSharedMemoryFrameRing(string streamId, int slotCount, int slotByteLength)
|
||||
{
|
||||
StreamId = RequireNonEmpty(streamId, nameof(streamId));
|
||||
if (slotCount <= 0) throw new ArgumentOutOfRangeException(nameof(slotCount));
|
||||
if (slotByteLength <= 0) throw new ArgumentOutOfRangeException(nameof(slotByteLength));
|
||||
SlotByteLength = slotByteLength;
|
||||
_storage = ArrayPool<byte>.Shared.Rent(checked(slotCount * slotByteLength));
|
||||
_readerCounts = new int[slotCount];
|
||||
_handles = new CultMeshStreamFrameHandle?[slotCount];
|
||||
if (slotCount != CultMeshFrameRegion.SlotCount)
|
||||
throw new ArgumentOutOfRangeException(nameof(slotCount), "CultMesh frame regions use exactly three slots.");
|
||||
_region = new CultMeshFrameRegion(
|
||||
streamId,
|
||||
$"{streamId}.frame",
|
||||
layoutVersion: 1,
|
||||
capacity: slotByteLength,
|
||||
producerEpoch: 0,
|
||||
slotByteLength);
|
||||
}
|
||||
|
||||
public string StreamId { get; }
|
||||
public int SlotCount => _handles.Length;
|
||||
public int SlotByteLength { get; }
|
||||
public int SlotCount => CultMeshFrameRegion.SlotCount;
|
||||
public int SlotByteLength => _region.SlotByteLength;
|
||||
|
||||
public bool TryAcquireWriteSlot(out CultMeshFrameWriteLease lease)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
for (var attempt = 0; attempt < SlotCount; attempt++)
|
||||
if (_region.TryAcquireWrite(out var regionLease))
|
||||
{
|
||||
var slotIndex = (_writeCursor + attempt) % SlotCount;
|
||||
if (Volatile.Read(ref _readerCounts[slotIndex]) != 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (_handles[slotIndex] != null)
|
||||
{
|
||||
_droppedFrames++;
|
||||
}
|
||||
|
||||
_writeCursor = (slotIndex + 1) % SlotCount;
|
||||
lease = new CultMeshFrameWriteLease(
|
||||
slotIndex,
|
||||
_nextSequence,
|
||||
new Memory<byte>(_storage, slotIndex * SlotByteLength, SlotByteLength));
|
||||
lease = new CultMeshFrameWriteLease(regionLease);
|
||||
return true;
|
||||
}
|
||||
|
||||
_blockedWrites++;
|
||||
lease = default;
|
||||
return false;
|
||||
}
|
||||
|
|
@ -403,29 +376,9 @@ namespace GameCult.Mesh
|
|||
int unavoidableCopyCount = 0,
|
||||
IReadOnlyDictionary<string, string>? metadata = null)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
RequireSlot(lease.SlotIndex);
|
||||
if (byteLength < 0 || byteLength > SlotByteLength)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(byteLength));
|
||||
}
|
||||
|
||||
_unavoidableCopyCount += (ulong)Math.Max(0, unavoidableCopyCount);
|
||||
var handle = new CultMeshStreamFrameHandle(
|
||||
StreamId,
|
||||
lease.Sequence,
|
||||
timestampNs,
|
||||
CultMeshStreamBodyTransport.SharedMemory,
|
||||
durationNs,
|
||||
byteLength,
|
||||
resourceKey: $"{StreamId}:slot:{lease.SlotIndex}",
|
||||
unavoidableCopyCount: unavoidableCopyCount,
|
||||
metadata: metadata);
|
||||
_handles[lease.SlotIndex] = handle;
|
||||
_latestSlot = lease.SlotIndex;
|
||||
_nextSequence = lease.Sequence + 1;
|
||||
_publishedFrames++;
|
||||
return handle;
|
||||
var generation = _region.Commit(
|
||||
lease.RegionLease, byteLength, timestampNs, durationNs, unavoidableCopyCount, metadata);
|
||||
return ToHandle(generation);
|
||||
}
|
||||
|
||||
public bool TryPublishCopy(
|
||||
|
|
@ -434,7 +387,6 @@ namespace GameCult.Mesh
|
|||
long durationNs,
|
||||
out CultMeshStreamFrameHandle handle)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (bytes.Length > SlotByteLength)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(bytes));
|
||||
|
|
@ -453,79 +405,51 @@ namespace GameCult.Mesh
|
|||
|
||||
public bool TryAcquireLatestRead(out CultMeshFrameReadLease lease)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var slotIndex = Volatile.Read(ref _latestSlot);
|
||||
if (slotIndex < 0)
|
||||
var request = new CultMeshBodyValidationRequest
|
||||
{
|
||||
BodyId = _region.BodyId,
|
||||
SchemaId = _region.SchemaId,
|
||||
LayoutVersion = _region.LayoutVersion,
|
||||
ProducerEpoch = _region.ProducerEpoch,
|
||||
Capacity = _region.Capacity,
|
||||
AccessMode = CultMeshBodyAccessMode.ReadOnly
|
||||
};
|
||||
if (!_region.TryAcquireLatestRead(request, out var regionLease))
|
||||
{
|
||||
lease = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
var handle = _handles[slotIndex];
|
||||
if (handle == null)
|
||||
{
|
||||
lease = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
Interlocked.Increment(ref _readerCounts[slotIndex]);
|
||||
lease = new CultMeshFrameReadLease(
|
||||
this,
|
||||
slotIndex,
|
||||
handle,
|
||||
new ReadOnlyMemory<byte>(_storage, slotIndex * SlotByteLength, handle.ByteLength));
|
||||
var generation = regionLease.Generation;
|
||||
lease = new CultMeshFrameReadLease(regionLease, ToHandle(generation), generation.SlotIndex);
|
||||
return true;
|
||||
}
|
||||
|
||||
public CultMeshSharedMemoryFrameRingStats Stats()
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var latest = _latestSlot < 0 ? 0 : _handles[_latestSlot]?.Sequence ?? 0;
|
||||
var stats = _region.Stats();
|
||||
return new CultMeshSharedMemoryFrameRingStats(
|
||||
StreamId,
|
||||
SlotCount,
|
||||
SlotByteLength,
|
||||
_publishedFrames,
|
||||
_droppedFrames,
|
||||
_blockedWrites,
|
||||
latest,
|
||||
_unavoidableCopyCount);
|
||||
stats.PublishedFrames,
|
||||
stats.DroppedFrames,
|
||||
stats.BlockedWrites,
|
||||
checked((ulong)stats.LatestSequence),
|
||||
stats.UnavoidableCopyCount);
|
||||
}
|
||||
|
||||
internal void ReleaseRead(int slotIndex)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
public void Dispose() => _region.Dispose();
|
||||
|
||||
RequireSlot(slotIndex);
|
||||
Interlocked.Decrement(ref _readerCounts[slotIndex]);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 0)
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(_storage);
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
{
|
||||
throw new ObjectDisposedException(nameof(CultMeshSharedMemoryFrameRing));
|
||||
}
|
||||
}
|
||||
|
||||
private void RequireSlot(int slotIndex)
|
||||
{
|
||||
if (slotIndex < 0 || slotIndex >= SlotCount)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(slotIndex));
|
||||
}
|
||||
}
|
||||
private CultMeshStreamFrameHandle ToHandle(CultMeshFrameGeneration generation) => new(
|
||||
StreamId,
|
||||
checked((ulong)generation.Descriptor.Sequence),
|
||||
generation.TimestampNs,
|
||||
CultMeshStreamBodyTransport.SharedMemory,
|
||||
generation.DurationNs,
|
||||
checked((int)generation.Descriptor.ByteSize),
|
||||
resourceKey: $"{StreamId}:slot:{generation.SlotIndex}",
|
||||
unavoidableCopyCount: generation.UnavoidableCopyCount,
|
||||
metadata: generation.Metadata);
|
||||
}
|
||||
|
||||
public sealed class CultMeshStreamCatalog
|
||||
|
|
|
|||
440
src/GameCult.Mesh/CultMeshTcpContentTransport.cs
Normal file
440
src/GameCult.Mesh/CultMeshTcpContentTransport.cs
Normal file
|
|
@ -0,0 +1,440 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Networking;
|
||||
|
||||
namespace GameCult.Mesh
|
||||
{
|
||||
/// <summary>Creates dedicated TCP streams for immutable CultMesh content.</summary>
|
||||
public sealed class CultMeshTcpContentTransportConnector : ICultMeshContentTransportConnector
|
||||
{
|
||||
public const string Scheme = "cultmesh-content+tcp";
|
||||
private readonly TimeSpan _connectTimeout;
|
||||
private int _connectCount;
|
||||
|
||||
public CultMeshTcpContentTransportConnector(TimeSpan? connectTimeout = null)
|
||||
{
|
||||
_connectTimeout = connectTimeout ?? TimeSpan.FromSeconds(5);
|
||||
if (_connectTimeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(connectTimeout));
|
||||
}
|
||||
|
||||
public string ConnectorId => "tcp-content";
|
||||
public int Priority => 0;
|
||||
public int ConnectCount => Volatile.Read(ref _connectCount);
|
||||
|
||||
public bool CanConnect(CultMeshTransportCandidate candidate) =>
|
||||
TryParseEndpoint(candidate?.Endpoint, out _, out _);
|
||||
|
||||
public async Task<ICultMeshContentTransport> ConnectAsync(
|
||||
CultMeshTransportCandidate candidate,
|
||||
CultMeshEndpointId endpointId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
|
||||
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
|
||||
if (!TryParseEndpoint(candidate.Endpoint, out var host, out var port))
|
||||
throw new NotSupportedException($"TCP content connector does not support '{candidate.Endpoint}'.");
|
||||
|
||||
var client = new TcpClient();
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(_connectTimeout);
|
||||
try
|
||||
{
|
||||
await CultMeshTcpContentWire.AwaitAsync(client.ConnectAsync(host, port), timeout.Token)
|
||||
.ConfigureAwait(false);
|
||||
Interlocked.Increment(ref _connectCount);
|
||||
return new CultMeshTcpContentTransport(candidate.Endpoint, client);
|
||||
}
|
||||
catch
|
||||
{
|
||||
client.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool TryParseEndpoint(string? endpoint, out string host, out int port)
|
||||
{
|
||||
host = string.Empty;
|
||||
port = 0;
|
||||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
|
||||
!string.Equals(uri.Scheme, Scheme, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.IsNullOrWhiteSpace(uri.Host) || uri.Port <= 0)
|
||||
return false;
|
||||
host = uri.Host;
|
||||
port = uri.Port;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class CultMeshTcpContentTransport : ICultMeshContentTransport
|
||||
{
|
||||
private readonly TcpClient _client;
|
||||
private readonly NetworkStream _stream;
|
||||
private readonly SemaphoreSlim _sendLock = new(1, 1);
|
||||
private readonly ConcurrentDictionary<string, PendingCopy> _pending = new(StringComparer.Ordinal);
|
||||
private readonly CancellationTokenSource _shutdown = new();
|
||||
private readonly Task _receiveLoop;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshTcpContentTransport(string endpoint, TcpClient client)
|
||||
{
|
||||
Endpoint = endpoint;
|
||||
_client = client ?? throw new ArgumentNullException(nameof(client));
|
||||
_stream = client.GetStream();
|
||||
_receiveLoop = ReceiveLoopAsync(_shutdown.Token);
|
||||
}
|
||||
|
||||
public string TransportId => "tcp-content";
|
||||
public string Endpoint { get; }
|
||||
|
||||
public async Task CopyChunkToAsync(
|
||||
CultMeshCdnChunkRef chunk,
|
||||
Stream destination,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshTcpContentTransport));
|
||||
if (chunk == null) throw new ArgumentNullException(nameof(chunk));
|
||||
if (destination == null) throw new ArgumentNullException(nameof(destination));
|
||||
if (!destination.CanWrite) throw new ArgumentException("Content destination must be writable.", nameof(destination));
|
||||
|
||||
var messageId = Guid.NewGuid().ToString("N");
|
||||
var completion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var pending = new PendingCopy(destination, completion, cancellationToken);
|
||||
if (!_pending.TryAdd(messageId, pending))
|
||||
throw new InvalidOperationException("Duplicate TCP content request identity.");
|
||||
try
|
||||
{
|
||||
var request = new CultMeshContentChunkRequestMessage
|
||||
{
|
||||
MessageId = messageId,
|
||||
ChunkHash = CultMeshCdn.NormalizeHash(chunk.ChunkHash, nameof(chunk.ChunkHash)),
|
||||
RecordKey = string.IsNullOrWhiteSpace(chunk.RecordKey)
|
||||
? CultMeshCdnArtifactChunk.CreateRecordKey(chunk.ChunkHash).Value
|
||||
: chunk.RecordKey,
|
||||
ExpectedSizeBytes = chunk.SizeBytes
|
||||
};
|
||||
var payload = CultNetSchemaMessageSerialization.Serialize(request);
|
||||
await _sendLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await CultMeshTcpContentWire.WriteFrameAsync(_stream, payload, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_sendLock.Release();
|
||||
}
|
||||
await CultMeshTcpContentWire.AwaitAsync(completion.Task, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pending.TryRemove(messageId, out _);
|
||||
pending.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_shutdown.Cancel();
|
||||
_client.Dispose();
|
||||
var error = new ObjectDisposedException(nameof(CultMeshTcpContentTransport));
|
||||
foreach (var pending in _pending.Values) pending.Completion.TrySetException(error);
|
||||
_pending.Clear();
|
||||
_sendLock.Dispose();
|
||||
_shutdown.Dispose();
|
||||
}
|
||||
|
||||
private async Task ReceiveLoopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var headerBytes = await CultMeshTcpContentWire.ReadFrameAsync(_stream, cancellationToken).ConfigureAwait(false);
|
||||
var response = CultNetSchemaMessageSerialization.Deserialize(headerBytes) as CultMeshContentChunkResponseMessage
|
||||
?? throw new InvalidDataException("TCP content response used an unexpected schema.");
|
||||
if (!_pending.TryGetValue(response.MessageId ?? string.Empty, out var pending))
|
||||
throw new InvalidDataException("TCP content response did not match an active request.");
|
||||
if (!response.Found)
|
||||
{
|
||||
pending.Completion.TrySetException(new FileNotFoundException(response.Error, response.ChunkHash));
|
||||
continue;
|
||||
}
|
||||
await CultMeshTcpContentWire.CopyExactlyAsync(
|
||||
_stream,
|
||||
pending.Destination,
|
||||
response.SizeBytes,
|
||||
pending.CancellationToken).ConfigureAwait(false);
|
||||
pending.Completion.TrySetResult(true);
|
||||
}
|
||||
}
|
||||
catch (Exception error) when (!_disposed)
|
||||
{
|
||||
foreach (var pending in _pending.Values) pending.Completion.TrySetException(error);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class PendingCopy : IDisposable
|
||||
{
|
||||
private readonly CancellationTokenRegistration _registration;
|
||||
|
||||
public PendingCopy(
|
||||
Stream destination,
|
||||
TaskCompletionSource<bool> completion,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Destination = destination;
|
||||
Completion = completion;
|
||||
CancellationToken = cancellationToken;
|
||||
_registration = cancellationToken.Register(() => completion.TrySetCanceled(cancellationToken));
|
||||
}
|
||||
|
||||
public Stream Destination { get; }
|
||||
public TaskCompletionSource<bool> Completion { get; }
|
||||
public CancellationToken CancellationToken { get; }
|
||||
public void Dispose() => _registration.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serves content-addressed chunks over a dedicated TCP byte stream. Typed headers
|
||||
/// remain CultNet schema messages; chunk bytes are streamed outside those messages.
|
||||
/// </summary>
|
||||
public sealed class CultMeshTcpContentServer : IDisposable
|
||||
{
|
||||
private readonly TcpListener _listener;
|
||||
private readonly Func<string, CultMeshCdnArtifactChunk?> _resolveChunk;
|
||||
private readonly Func<string, bool> _canServeHash;
|
||||
private readonly CancellationTokenSource _shutdown = new();
|
||||
private readonly ConcurrentDictionary<TcpClient, byte> _clients = new();
|
||||
private readonly Task _acceptLoop;
|
||||
private long _chunkRequestsServed;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshTcpContentServer(
|
||||
TcpListener listener,
|
||||
CultCache content,
|
||||
Func<string, bool>? canServeHash = null)
|
||||
: this(listener, CreateCacheResolver(content), canServeHash)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts a dedicated TCP content server over provider-owned immutable chunks.
|
||||
/// The resolver receives a normalized SHA-256 hash and may return <see langword="null"/>
|
||||
/// when that chunk is unavailable.
|
||||
/// </summary>
|
||||
public CultMeshTcpContentServer(
|
||||
TcpListener listener,
|
||||
Func<string, CultMeshCdnArtifactChunk?> resolveChunk,
|
||||
Func<string, bool>? canServeHash = null)
|
||||
{
|
||||
_listener = listener ?? throw new ArgumentNullException(nameof(listener));
|
||||
_resolveChunk = resolveChunk ?? throw new ArgumentNullException(nameof(resolveChunk));
|
||||
_canServeHash = canServeHash ?? (_ => true);
|
||||
_listener.Start();
|
||||
_acceptLoop = AcceptLoopAsync(_shutdown.Token);
|
||||
}
|
||||
|
||||
public IPEndPoint LocalEndPoint => (IPEndPoint)_listener.LocalEndpoint;
|
||||
public long ChunkRequestsServed => Interlocked.Read(ref _chunkRequestsServed);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_shutdown.Cancel();
|
||||
_listener.Stop();
|
||||
foreach (var client in _clients.Keys) client.Dispose();
|
||||
_clients.Clear();
|
||||
_shutdown.Dispose();
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false);
|
||||
_clients.TryAdd(client, 0);
|
||||
_ = ServeClientAsync(client, cancellationToken);
|
||||
}
|
||||
}
|
||||
catch (Exception) when (_disposed || cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ServeClientAsync(TcpClient client, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var stream = client.GetStream();
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var requestBytes = await CultMeshTcpContentWire.ReadFrameAsync(stream, cancellationToken).ConfigureAwait(false);
|
||||
var request = CultNetSchemaMessageSerialization.Deserialize(requestBytes) as CultMeshContentChunkRequestMessage
|
||||
?? throw new InvalidDataException("TCP content request used an unexpected schema.");
|
||||
await SendChunkAsync(stream, request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception) when (_disposed || cancellationToken.IsCancellationRequested || !client.Connected)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
_clients.TryRemove(client, out _);
|
||||
client.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendChunkAsync(
|
||||
Stream stream,
|
||||
CultMeshContentChunkRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var response = new CultMeshContentChunkResponseMessage
|
||||
{
|
||||
MessageId = request.MessageId,
|
||||
ChunkHash = request.ChunkHash,
|
||||
Payload = Array.Empty<byte>()
|
||||
};
|
||||
CultMeshCdnArtifactChunk? chunk = null;
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.MessageId))
|
||||
throw new InvalidDataException("Content chunk request requires a message identity.");
|
||||
var hash = CultMeshCdn.NormalizeHash(request.ChunkHash, nameof(request.ChunkHash));
|
||||
if (!_canServeHash(hash))
|
||||
throw new UnauthorizedAccessException("Content access policy rejected the requested hash.");
|
||||
var key = CultMeshCdnArtifactChunk.CreateRecordKey(hash);
|
||||
if (!string.IsNullOrWhiteSpace(request.RecordKey) &&
|
||||
!string.Equals(request.RecordKey, key.Value, StringComparison.Ordinal))
|
||||
throw new InvalidDataException("Content chunk record key disagrees with its content hash.");
|
||||
chunk = _resolveChunk(hash)
|
||||
?? throw new FileNotFoundException("Content chunk is not available.", key.Value);
|
||||
CultMeshCdn.ValidateChunkPayload(new CultMeshCdnChunkRef
|
||||
{
|
||||
ChunkHash = hash,
|
||||
RecordKey = key.Value,
|
||||
SizeBytes = request.ExpectedSizeBytes
|
||||
}, chunk);
|
||||
response.Found = true;
|
||||
response.ChunkHash = hash;
|
||||
response.SizeBytes = chunk.SizeBytes;
|
||||
Interlocked.Increment(ref _chunkRequestsServed);
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
response.Found = false;
|
||||
response.Error = error.GetType().Name + ": " + error.Message;
|
||||
}
|
||||
|
||||
await CultMeshTcpContentWire.WriteFrameAsync(
|
||||
stream,
|
||||
CultNetSchemaMessageSerialization.Serialize(response),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
if (chunk != null)
|
||||
{
|
||||
await stream.WriteAsync(chunk.Payload, 0, chunk.Payload.Length, cancellationToken).ConfigureAwait(false);
|
||||
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static Func<string, CultMeshCdnArtifactChunk?> CreateCacheResolver(CultCache content)
|
||||
{
|
||||
if (content == null) throw new ArgumentNullException(nameof(content));
|
||||
return hash => content.Get<CultMeshCdnArtifactChunk>(CultMeshCdnArtifactChunk.CreateRecordKey(hash));
|
||||
}
|
||||
}
|
||||
|
||||
internal static class CultMeshTcpContentWire
|
||||
{
|
||||
private const int HeaderBytes = 4;
|
||||
private const int MaximumHeaderBytes = 1024 * 1024;
|
||||
|
||||
public static async Task AwaitAsync(Task task, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!cancellationToken.CanBeCanceled)
|
||||
{
|
||||
await task.ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
var cancelled = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using (cancellationToken.Register(() => cancelled.TrySetResult(true)))
|
||||
{
|
||||
if (await Task.WhenAny(task, cancelled.Task).ConfigureAwait(false) != task)
|
||||
throw new OperationCanceledException(cancellationToken);
|
||||
}
|
||||
await task.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public static async Task WriteFrameAsync(
|
||||
Stream stream,
|
||||
byte[] payload,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (payload.Length > MaximumHeaderBytes)
|
||||
throw new InvalidDataException("TCP content control frame exceeds its size bound.");
|
||||
var header = new byte[HeaderBytes];
|
||||
BinaryPrimitives.WriteUInt32BigEndian(header, checked((uint)payload.Length));
|
||||
await stream.WriteAsync(header, 0, header.Length, cancellationToken).ConfigureAwait(false);
|
||||
await stream.WriteAsync(payload, 0, payload.Length, cancellationToken).ConfigureAwait(false);
|
||||
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public static async Task<byte[]> ReadFrameAsync(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var header = new byte[HeaderBytes];
|
||||
await ReadExactlyAsync(stream, header, cancellationToken).ConfigureAwait(false);
|
||||
var size = checked((int)BinaryPrimitives.ReadUInt32BigEndian(header));
|
||||
if (size <= 0 || size > MaximumHeaderBytes)
|
||||
throw new InvalidDataException("TCP content control frame has an invalid size.");
|
||||
var payload = new byte[size];
|
||||
await ReadExactlyAsync(stream, payload, cancellationToken).ConfigureAwait(false);
|
||||
return payload;
|
||||
}
|
||||
|
||||
public static async Task CopyExactlyAsync(
|
||||
Stream source,
|
||||
Stream destination,
|
||||
long bytes,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (bytes < 0) throw new InvalidDataException("TCP content body size cannot be negative.");
|
||||
var buffer = new byte[81920];
|
||||
var remaining = bytes;
|
||||
while (remaining > 0)
|
||||
{
|
||||
var requested = (int)Math.Min(buffer.Length, remaining);
|
||||
var read = await source.ReadAsync(buffer, 0, requested, cancellationToken).ConfigureAwait(false);
|
||||
if (read == 0) throw new EndOfStreamException();
|
||||
await destination.WriteAsync(buffer, 0, read, cancellationToken).ConfigureAwait(false);
|
||||
remaining -= read;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ReadExactlyAsync(
|
||||
Stream stream,
|
||||
byte[] buffer,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var offset = 0;
|
||||
while (offset < buffer.Length)
|
||||
{
|
||||
var read = await stream.ReadAsync(buffer, offset, buffer.Length - offset, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (read == 0) throw new EndOfStreamException();
|
||||
offset += read;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Networking;
|
||||
|
||||
|
|
@ -161,6 +162,21 @@ namespace GameCult.Mesh
|
|||
/// Defaults to endpoint selection: rudp:// uses RUDP and cultnet:// uses LiteNetLib.
|
||||
/// </summary>
|
||||
public Func<ICultNetSchemaClient>? CreateClient { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the clock that owns discovery deadlines.</summary>
|
||||
public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance;
|
||||
|
||||
/// <summary>Gets or sets the bounded operational diagnostic sink.</summary>
|
||||
public ICultMeshDiagnosticSink Diagnostics { get; set; } = CultMeshNullDiagnosticSink.Instance;
|
||||
|
||||
/// <summary>Gets or sets the identity of this bootstrap lookup source.</summary>
|
||||
public string SourceId { get; set; } = "configured-bootstrap";
|
||||
|
||||
/// <summary>Gets or sets how long a successful compatibility observation remains fresh.</summary>
|
||||
public TimeSpan ObservationTtl { get; set; } = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>Gets or sets the persistent last-known-good discovery store.</summary>
|
||||
public ICultMeshDiscoveryStore? DiscoveryStore { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -169,6 +185,7 @@ namespace GameCult.Mesh
|
|||
public sealed class CultMeshVerseDiscoveryClient
|
||||
{
|
||||
private readonly CultMeshVerseDiscoveryClientOptions _options;
|
||||
private long _diagnosticSequence;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Verse discovery client.
|
||||
|
|
@ -176,6 +193,8 @@ namespace GameCult.Mesh
|
|||
public CultMeshVerseDiscoveryClient(CultMeshVerseDiscoveryClientOptions? options = null)
|
||||
{
|
||||
_options = options ?? new CultMeshVerseDiscoveryClientOptions();
|
||||
if (_options.ObservationTtl <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(options), "Discovery observation TTL must be greater than zero.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -202,17 +221,38 @@ namespace GameCult.Mesh
|
|||
client.OnCultNet<CultNetErrorMessage>(error =>
|
||||
completion.TrySetException(new InvalidOperationException(error.Error)));
|
||||
|
||||
client.Connect(host, port);
|
||||
var backgroundFailure = (client as ICultNetSchemaClientHealth)?.BackgroundFailure;
|
||||
await WaitForConnectionAsync(client, endpoint, backgroundFailure).ConfigureAwait(false);
|
||||
client.SendCultNet(new CultMeshVerseCatalogRequestMessage
|
||||
Emit(CultMeshDiagnosticKind.ConnectionAttempt, messageId, endpoint, "connecting");
|
||||
try
|
||||
{
|
||||
MessageId = messageId,
|
||||
TransportVersion = request?.TransportVersion,
|
||||
VerseIds = request?.VerseIds
|
||||
});
|
||||
client.Connect(host, port);
|
||||
var backgroundFailure = (client as ICultNetSchemaClientHealth)?.BackgroundFailure;
|
||||
await WaitForConnectionAsync(client, endpoint, backgroundFailure).ConfigureAwait(false);
|
||||
client.SendCultNet(new CultMeshVerseCatalogRequestMessage
|
||||
{
|
||||
MessageId = messageId,
|
||||
TransportVersion = request?.TransportVersion,
|
||||
VerseIds = request?.VerseIds
|
||||
});
|
||||
|
||||
return await WaitForResponseAsync(completion.Task, endpoint, backgroundFailure).ConfigureAwait(false);
|
||||
var response = await WaitForResponseAsync(completion.Task, endpoint, backgroundFailure).ConfigureAwait(false);
|
||||
Emit(
|
||||
CultMeshDiagnosticKind.DiscoveryObservation,
|
||||
messageId,
|
||||
endpoint,
|
||||
"fresh",
|
||||
schemaVersion: response.SchemaVersion);
|
||||
return response;
|
||||
}
|
||||
catch (Exception error) when (!(error is OperationCanceledException))
|
||||
{
|
||||
Emit(
|
||||
CultMeshDiagnosticKind.CandidateRejected,
|
||||
messageId,
|
||||
endpoint,
|
||||
"unavailable",
|
||||
ReasonCode(error));
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -226,18 +266,25 @@ namespace GameCult.Mesh
|
|||
if (catalog == null) throw new ArgumentNullException(nameof(catalog));
|
||||
if (endpoints == null) throw new ArgumentNullException(nameof(endpoints));
|
||||
|
||||
var count = 0;
|
||||
foreach (var endpoint in endpoints.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
var response = await FetchAsync(endpoint, new CultMeshVerseCatalogRequestMessage
|
||||
var eligible = endpoints.Where(value => !string.IsNullOrWhiteSpace(value))
|
||||
.Distinct(StringComparer.Ordinal).OrderBy(value => value, StringComparer.Ordinal).ToArray();
|
||||
if (eligible.Length == 0) return 0;
|
||||
var identity = "compatibility:" + (transportVersion ?? "any") + ":" + string.Join("|", eligible);
|
||||
using var service = new CultMeshDiscoveryService(
|
||||
eligible.Select(endpoint => new CompatibilityLookupSource(this, endpoint, transportVersion)),
|
||||
new CultMeshDiscoveryServiceOptions
|
||||
{
|
||||
TransportVersion = transportVersion
|
||||
}).ConfigureAwait(false);
|
||||
catalog.Upsert(response);
|
||||
count += response.Verses.Length;
|
||||
Clock = _options.Clock,
|
||||
Diagnostics = _options.Diagnostics,
|
||||
Store = _options.DiscoveryStore
|
||||
});
|
||||
var state = await service.ResolveAsync(new CultMeshDiscoveryQuery(identity)).ConfigureAwait(false);
|
||||
foreach (var candidate in state.Candidates)
|
||||
{
|
||||
catalog.Upsert(candidate.Descriptor);
|
||||
}
|
||||
|
||||
return count;
|
||||
return state.Candidates.Count;
|
||||
}
|
||||
|
||||
private ICultNetSchemaClient CreateClient(string endpoint)
|
||||
|
|
@ -251,7 +298,7 @@ namespace GameCult.Mesh
|
|||
string endpoint,
|
||||
Task<Exception>? backgroundFailure)
|
||||
{
|
||||
var deadline = DateTimeOffset.UtcNow + _options.ConnectTimeout;
|
||||
var deadline = _options.Clock.UtcNow + _options.ConnectTimeout;
|
||||
while (!client.Connected)
|
||||
{
|
||||
if (backgroundFailure?.IsCompleted == true)
|
||||
|
|
@ -261,12 +308,12 @@ namespace GameCult.Mesh
|
|||
$"Verse discovery client failed while connecting to {endpoint}.",
|
||||
error);
|
||||
}
|
||||
if (DateTimeOffset.UtcNow >= deadline)
|
||||
if (_options.Clock.UtcNow >= deadline)
|
||||
{
|
||||
throw new TimeoutException($"Timed out connecting to Verse discovery endpoint {endpoint}.");
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(25)).ConfigureAwait(false);
|
||||
await _options.Clock.DelayAsync(TimeSpan.FromMilliseconds(25)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -275,7 +322,7 @@ namespace GameCult.Mesh
|
|||
string endpoint,
|
||||
Task<Exception>? backgroundFailure)
|
||||
{
|
||||
var timeoutTask = Task.Delay(_options.ResponseTimeout);
|
||||
var timeoutTask = _options.Clock.DelayAsync(_options.ResponseTimeout);
|
||||
var completed = backgroundFailure == null
|
||||
? await Task.WhenAny(responseTask, timeoutTask).ConfigureAwait(false)
|
||||
: await Task.WhenAny(responseTask, timeoutTask, backgroundFailure).ConfigureAwait(false);
|
||||
|
|
@ -293,5 +340,68 @@ namespace GameCult.Mesh
|
|||
|
||||
return await responseTask.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private void Emit(
|
||||
CultMeshDiagnosticKind kind,
|
||||
string operationId,
|
||||
string endpoint,
|
||||
string state,
|
||||
string reasonCode = "",
|
||||
string schemaVersion = "")
|
||||
{
|
||||
_options.Diagnostics.Emit(new CultMeshDiagnosticEvent(
|
||||
Interlocked.Increment(ref _diagnosticSequence),
|
||||
_options.Clock.UtcNow,
|
||||
CultMeshReliabilityOrgan.Discovery,
|
||||
kind,
|
||||
operationId,
|
||||
endpoint,
|
||||
state,
|
||||
reasonCode,
|
||||
_options.SourceId,
|
||||
endpoint,
|
||||
schemaVersion));
|
||||
}
|
||||
|
||||
private static string ReasonCode(Exception error)
|
||||
{
|
||||
if (error is TimeoutException) return "timeout";
|
||||
if (error is InvalidOperationException) return "transport_failure";
|
||||
return "lookup_failure";
|
||||
}
|
||||
|
||||
private sealed class CompatibilityLookupSource : ICultMeshLookupSource
|
||||
{
|
||||
private readonly CultMeshVerseDiscoveryClient _owner;
|
||||
private readonly string _endpoint;
|
||||
private readonly string? _transportVersion;
|
||||
|
||||
public CompatibilityLookupSource(CultMeshVerseDiscoveryClient owner, string endpoint, string? transportVersion)
|
||||
{
|
||||
_owner = owner;
|
||||
_endpoint = endpoint;
|
||||
_transportVersion = transportVersion;
|
||||
}
|
||||
|
||||
public string SourceId => _endpoint;
|
||||
|
||||
public async Task<IReadOnlyList<CultMeshDiscoveryObservation>> LookupAsync(
|
||||
CultMeshDiscoveryQuery query,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var response = await _owner.FetchAsync(
|
||||
_endpoint,
|
||||
new CultMeshVerseCatalogRequestMessage { TransportVersion = _transportVersion }).ConfigureAwait(false);
|
||||
var observedAt = _owner._options.Clock.UtcNow;
|
||||
return response.Verses.Select(message => new CultMeshDiscoveryObservation(
|
||||
message.ToVerseDescriptor(),
|
||||
SourceId,
|
||||
observedAt,
|
||||
observedAt + _owner._options.ObservationTtl,
|
||||
CultMeshDiscoveryTrust.Unsigned,
|
||||
response.SchemaVersion)).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
<PackageId>GameCult.Mesh</PackageId>
|
||||
<PackageTags>game;distributed;realtime;mesh;database;simulation;consensus</PackageTags>
|
||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -380,6 +380,47 @@ runtime-native storage: shared D3D12 textures, shared memory rings, platform GPU
|
|||
handles, DMA buffers, or paged CultCache fallbacks when a zero-copy transport is
|
||||
not available.
|
||||
|
||||
For entity SoA and other CPU-visible hot state, subscribe to the exact control
|
||||
records and logical bodies the lowerer consumes. The subscription advertises
|
||||
the transports the runtime can import; the provider's demand tracker selects
|
||||
the cheapest mutually usable representation. A same-machine consumer normally
|
||||
receives one shared-memory bootstrap descriptor, then observes later commits
|
||||
through the mapped ring header. Per-frame CultNet documents are neither needed
|
||||
nor desirable.
|
||||
|
||||
```csharp
|
||||
using var entities = await CultMesh.SubscribeLiveBodyAsync(
|
||||
subscriptions,
|
||||
bodyResolver,
|
||||
new CultMeshLiveBodySubscription(
|
||||
"pilot-entities",
|
||||
"eve-unity",
|
||||
"eve:entity-soa:aetheria.daemon:pilot"));
|
||||
|
||||
using var input = await subscriptions.SubscribeLiveValueAsync<EveInputCapabilityDocument>(
|
||||
"pilot-input",
|
||||
"eve:input:aetheria.daemon:pilot");
|
||||
|
||||
// Open after each descriptor change. CultMesh chooses shared memory, shared-file
|
||||
// mapping, or network from observed locality and the resolver's real adapters.
|
||||
if (entities.HasValue && input.HasValue)
|
||||
{
|
||||
using var frame = entities.OpenCurrentReadOnly().Lease;
|
||||
Present(frame, input.Current);
|
||||
}
|
||||
```
|
||||
|
||||
`CultMeshLiveBody` watches only the small latest-publication record and declares
|
||||
the logical body demand. It never routes the body through the subscription
|
||||
snapshot. `CultNetLiveValue<T>` does the corresponding job for exact scalar or
|
||||
small structured state without creating a renderer-owned replica cache. Both
|
||||
subscriptions may begin before the provider's first publication: `HasValue`
|
||||
remains false while the retained demand stays active, then the first typed value
|
||||
arrives through the normal reactive change path.
|
||||
|
||||
Snapshots remain bootstrap and recovery machinery. Reactive document changes
|
||||
carry small control state; mapped or negotiated network bodies carry hot data.
|
||||
|
||||
```csharp
|
||||
using GameCult.Mesh;
|
||||
|
||||
|
|
|
|||
60
src/GameCult.Mesh/docs/content-sessions.md
Normal file
60
src/GameCult.Mesh/docs/content-sessions.md
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
# CultMesh content sessions
|
||||
|
||||
Large immutable artifacts use CultMesh content sessions. Typed snapshots carry
|
||||
manifests, body descriptors, leases, and progress; they do not carry artifact
|
||||
payloads.
|
||||
|
||||
The provider attaches one generic content server to its existing CultNet
|
||||
schema host:
|
||||
|
||||
```csharp
|
||||
using var content = new CultMeshContentServer(schemaServer, providerCache);
|
||||
```
|
||||
|
||||
The consumer creates a provider over its existing identity-first session
|
||||
manager, then gives that provider to the transfer owner:
|
||||
|
||||
```csharp
|
||||
var provider = mesh.ContentProvider(
|
||||
"aetheria.daemon",
|
||||
"service:aetheria.daemon");
|
||||
|
||||
var transfer = new CultMeshContentTransferService(
|
||||
transferStateCache,
|
||||
new[] { provider },
|
||||
new CultMeshContentTransferOptions(cacheDirectory));
|
||||
|
||||
var verifiedBodyPath = await transfer.FetchAsync(manifest, cancellationToken);
|
||||
```
|
||||
|
||||
`CultMeshContentTransferService` remains the only owner of verified partial
|
||||
state and final cache promotion. It validates each chunk, resumes durable work,
|
||||
verifies the complete SHA-256 identity, and atomically publishes
|
||||
`<content-hash>.body`. The session provider owns no cache truth and does not
|
||||
implement a second retry, failover, or promotion policy.
|
||||
|
||||
For local consumers, configure `CultMeshVerifiedBodyMappingBroker` and call
|
||||
`FetchMappedContentAsync`. The result binds the transfer owner's verified path
|
||||
to the mapped descriptor, so consumers do not infer cache filenames. The older
|
||||
`FetchMappedBodyAsync` shape delegates to the same owner when only the
|
||||
descriptor is needed. Mapping failure remains observable and falls back through
|
||||
the equivalent network descriptor without changing logical identity.
|
||||
|
||||
The content protocol uses one bounded response per manifest chunk. A snapshot
|
||||
response containing `gamecult.mesh.cdn_artifact_chunk.v1` payload records is a
|
||||
legacy transport path and must not be used for bulk delivery.
|
||||
|
||||
The transfer owner may keep a bounded window of requests in flight per content
|
||||
hash (four by default, never more than 32). Candidate chunks can arrive out of
|
||||
order, but only the transfer owner writes them, and it flushes and checkpoints
|
||||
them in manifest-offset order. If one request fails, the owner observes the
|
||||
rest of that window before returning; fetched-but-uncommitted bytes never become
|
||||
trusted resume state. Concurrent artifacts have independent windows.
|
||||
|
||||
RUDP schema hosts drain immediately available transport work with
|
||||
`PollAvailableAsync`, and the managed schema client pump applies the same
|
||||
bounded-drain rule. Transport packets, including fragments, ACKs, and connection
|
||||
traffic, count as progress without impersonating an application message or
|
||||
paying one operating-system scheduler delay per packet. Reliable sends are
|
||||
paced in one 32-packet acknowledgement window rather than one fragment at a
|
||||
time.
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
# Distributed CDN Documents
|
||||
|
||||
CultMesh CDN artifacts are typed CultCache documents, not a separate asset
|
||||
transport. The same manifest and chunk records can be written by an asset
|
||||
pipeline daemon, replicated through CultNet raw snapshots or shard logs, and
|
||||
read by Unity, TypeScript, or another runtime that implements the CultCache
|
||||
document contract.
|
||||
CultMesh CDN artifacts use typed CultCache storage and a separate managed
|
||||
content-delivery session. Manifests may travel through snapshots or shard logs;
|
||||
artifact payload chunks remain in provider storage and cross the network through
|
||||
`cultmesh.content.v1`. Unity, TypeScript, and other runtimes consume the same
|
||||
manifest and verification contract without making snapshots a bulk byte lane.
|
||||
|
||||
This is the canonical path for moving Aetheria assets into CultLib. Starbridge
|
||||
Unity and Starbridge Electron should consume the same records so UI textures,
|
||||
|
|
@ -67,11 +67,11 @@ updates.
|
|||
Clients should:
|
||||
|
||||
1. Fetch or receive a manifest by record key, tag, or index.
|
||||
2. Fetch every chunk record referenced by `manifest.Chunks`.
|
||||
3. Verify each chunk hash before copying bytes.
|
||||
4. Reassemble chunks by `Offset`.
|
||||
5. Verify the full `ContentHash`.
|
||||
6. Interpret bytes according to `MimeType` plus domain metadata.
|
||||
2. Give it to `CultMeshContentTransferService` with one or more content providers.
|
||||
3. Let that owner request missing chunks through managed content sessions.
|
||||
4. Use only the atomically promoted `<content-hash>.body` returned after chunk
|
||||
and full-body verification.
|
||||
5. Interpret bytes according to `MimeType` plus domain metadata.
|
||||
|
||||
Single-channel data stays single-channel. For example, a gravity map can use
|
||||
raw bytes with metadata such as `channels=r32` instead of pretending to be an
|
||||
|
|
@ -147,27 +147,20 @@ await CultMesh.PublishCdnArtifactAsync(node.Cache, artifact);
|
|||
For build distribution, use the same API with `Kind = CultMeshCdnArtifactKinds.Build`
|
||||
and metadata such as `platform=windows-x64` or `channel=internal`.
|
||||
|
||||
## CultNet Replication
|
||||
## CultNet Publication And Delivery
|
||||
|
||||
CDN documents use the regular raw document lane:
|
||||
Publish manifests and chunks into the provider cache:
|
||||
|
||||
```csharp
|
||||
var registry = CultMesh.CreateCdnDocumentRegistry(node.Cache.Registry);
|
||||
var request = registry.CreateSnapshotRequest(
|
||||
"cdn-request",
|
||||
schemaIds:
|
||||
[
|
||||
node.Cache.Registry.GetRequired<CultMeshCdnArtifactManifest>().SchemaId,
|
||||
node.Cache.Registry.GetRequired<CultMeshCdnArtifactChunk>().SchemaId
|
||||
],
|
||||
recordKeys: artifact.RecordKeys.Select(key => key.Value));
|
||||
|
||||
var response = registry.CreateRawSnapshotResponse(node.Cache, "cdn-response", request);
|
||||
await CultMesh.PublishCdnArtifactAsync(providerCache, artifact);
|
||||
using var contentServer = new CultMeshContentServer(schemaServer, providerCache);
|
||||
```
|
||||
|
||||
The TypeScript client should mirror the C# schema names, schema versions,
|
||||
record-key rules, chunk hashing, and verification order. C# remains the
|
||||
reference implementation.
|
||||
Snapshots may publish the manifest record, catalog, and body-control documents.
|
||||
They must not publish `CultMeshCdnArtifactChunk` payload records for bulk
|
||||
delivery. Consumers use `CultMeshSessionContentProvider` and
|
||||
`CultMeshContentTransferService`; C# remains the reference implementation for
|
||||
record keys, hashing, resumability, and atomic promotion.
|
||||
|
||||
## Entity Prefabs
|
||||
|
||||
|
|
@ -187,7 +180,8 @@ the same package graph into their native entity/component model.
|
|||
Unity and TypeScript clients should implement the same rules:
|
||||
|
||||
- Fetch prefab packages by record key, tag, or version catalog.
|
||||
- Fetch every referenced artifact manifest and chunk.
|
||||
- Fetch every referenced artifact manifest, then delegate payload transfer to
|
||||
the generic content-transfer owner.
|
||||
- Verify signed manifests before trusting package membership.
|
||||
- Verify chunk hashes and full artifact hashes before import.
|
||||
- Cache artifacts locally by content hash.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,22 @@
|
|||
# 1. Persist Typed Application State
|
||||
|
||||
Start with a typed CultCache document and a durable CultMesh node. The complete
|
||||
sample is [the durable node quickstart](../durable-node-quickstart.md).
|
||||
|
||||
At the end of that guide you should have:
|
||||
|
||||
- a document type with a stable schema id;
|
||||
- a `CultMeshNode` whose database owns the live local document;
|
||||
- a `.cc`/CultCache-backed durable state path;
|
||||
- a restart proof that reads the same typed document.
|
||||
|
||||
Do not create an Eve-shaped copy of this state. The Eve surface published in
|
||||
chapter 3 points at typed records and commands owned by the provider.
|
||||
|
||||
Verification:
|
||||
|
||||
```powershell
|
||||
dotnet test tests/GameCult.Networking.Tests/GameCult.Networking.Tests.csproj --filter FullyQualifiedName~CultMeshNode_CanRoundTrip_DurableTypedDocument_Through_PublicDatabaseSurface
|
||||
```
|
||||
|
||||
Next: [connect a client by stable identity](02-connect-by-identity.md).
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
# 2. Connect A Client By Stable Identity
|
||||
|
||||
Clients address a provider or Verse by stable identity. Discovery owns the
|
||||
current physical candidates and the session manager owns connection reuse,
|
||||
path rotation, and transport failure state.
|
||||
|
||||
```csharp
|
||||
using GameCult.Mesh;
|
||||
|
||||
using var mesh = new CultMeshClient(new CultMeshClientOptions
|
||||
{
|
||||
RendezvousEndpoints = new[] { "rudp://odin.gamecult.net:3076" }
|
||||
});
|
||||
|
||||
var pilotSurface = await mesh.DocumentAsync<EveSurfaceDocument>(
|
||||
"aetheria.daemon",
|
||||
"eve:surface:aetheria.pilot",
|
||||
cancellationToken);
|
||||
|
||||
using var surfaceWatch = pilotSurface.Watch().Subscribe(Render);
|
||||
```
|
||||
|
||||
Keep `mesh` for the application lifetime. The document handle is stable: when
|
||||
Odin advertises a new physical route after a partition, CultMesh migrates the
|
||||
session, restores the server-side subscription, refreshes the typed snapshot,
|
||||
and continues the same watch.
|
||||
|
||||
Open a session directly only when implementing infrastructure that needs
|
||||
protocol-level state or diagnostics:
|
||||
|
||||
```csharp
|
||||
var session = await mesh.ConnectAsync(
|
||||
"aetheria.daemon",
|
||||
CultMeshProtocols.Documents,
|
||||
cancellationToken);
|
||||
|
||||
using var stateWatch = session.WatchState().Subscribe(state =>
|
||||
Console.WriteLine($"{state.Status}: {state.Path?.Endpoint}"));
|
||||
```
|
||||
|
||||
Application code does not reconnect, sleep, rank endpoints, or replace the
|
||||
session. Those decisions belong to CultMesh.
|
||||
|
||||
Verification:
|
||||
|
||||
```powershell
|
||||
dotnet test tests/GameCult.Mesh.Tests/GameCult.Mesh.Tests.csproj --filter FullyQualifiedName~CultMeshSessionManagerTests
|
||||
```
|
||||
|
||||
Advanced hosts may inject lookup sources, connectors, clocks, persistence, and
|
||||
diagnostics through the lower-level discovery and session APIs. Application
|
||||
features should not need them.
|
||||
|
||||
Next: [publish one Eve surface to multiple runtimes](03-publish-an-eve-surface.md).
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
# 3. Publish One Eve Surface To Multiple Runtimes
|
||||
|
||||
An Eve application publishes one provider advertisement and one or more typed
|
||||
surface documents through CultMesh. Browser, Unity, Electron, Flutter, and
|
||||
other clients discover the same advertisement and lower only the capabilities
|
||||
they support.
|
||||
|
||||
The authority split is fixed:
|
||||
|
||||
- provider daemon: live application state, command handling, receipts, assets;
|
||||
- Eve: surface, command, binding, embedding, and plugin contracts;
|
||||
- CultMesh: discovery, sessions, document delivery, and asset transfer;
|
||||
- runtime: native rendering, input sampling, and platform lifecycle.
|
||||
|
||||
A runtime configuration contains identity and selection constraints, not a
|
||||
copy of provider behavior:
|
||||
|
||||
```text
|
||||
rendezvous: odin
|
||||
provider: aetheria.daemon
|
||||
surface kind: interactive-world
|
||||
runtime capabilities: unity-scene + eve-fields
|
||||
```
|
||||
|
||||
EveUnity currently expresses this through
|
||||
`EveUnityCultMeshPlayableWorldProvider.Configure(...)`. Its provider discovery,
|
||||
advertisement snapshot, live snapshots, and subscriptions share one managed
|
||||
CultMesh document session. Other runtime lowerers must preserve the same
|
||||
boundary: they may reject or report unsupported capabilities, but they may not
|
||||
import provider internals.
|
||||
|
||||
## Multi-Runtime Checkpoint
|
||||
|
||||
Run the same provider and connect at least two lowerers. Both must report the
|
||||
same provider id, surface id, surface version, and command receipt ids. Native
|
||||
pixels may differ; provider truth may not.
|
||||
|
||||
Current verification for the Unity consumer:
|
||||
|
||||
```powershell
|
||||
cd E:\Projects\EveUnity
|
||||
powershell -ExecutionPolicy Bypass -File .\scripts\run-release-consumer-tests.ps1
|
||||
```
|
||||
|
||||
The browser/Electron counterpart and a single command-driven two-runtime sample
|
||||
remain required before this chapter can be considered complete. Their absence
|
||||
is tracked as developer-experience debt rather than papered over with bespoke
|
||||
setup instructions.
|
||||
|
||||
|
|
@ -0,0 +1,122 @@
|
|||
# 4. Keep A TypeScript Provider Alive
|
||||
|
||||
A provider process should declare desired typed publications and domain command
|
||||
handlers once. It should not rebuild discovery registration, lease renewal,
|
||||
reconnect, republish, receipt delivery, and withdrawal loops in a renderer or
|
||||
scheduled export script.
|
||||
|
||||
`CultMeshProviderSession` owns that lifecycle. The application still owns its
|
||||
state and command transaction. A transport connector owns the physical CultNet
|
||||
route. Eve advertisements and surfaces are ordinary typed publications; the
|
||||
session does not import Eve or learn provider gameplay.
|
||||
|
||||
```ts
|
||||
import {
|
||||
CultMeshProviderSession,
|
||||
type CultMeshProviderReceiptStore,
|
||||
type CultMeshProviderTransport,
|
||||
} from "cultmesh-ts";
|
||||
|
||||
export async function runProvider(
|
||||
transport: CultMeshProviderTransport,
|
||||
receipts: CultMeshProviderReceiptStore,
|
||||
) {
|
||||
const provider = new CultMeshProviderSession({
|
||||
identity: {
|
||||
providerId: "voidbot.swarm",
|
||||
serviceInstanceId: "voidbot-worker-7",
|
||||
endpointId: "odin:voidbot-worker-7",
|
||||
verseId: "voidbot.local",
|
||||
},
|
||||
transport,
|
||||
receiptStore: receipts,
|
||||
publications: [
|
||||
{
|
||||
publicationId: "voidbot.swarm.advertisement",
|
||||
documentType: "gamecult.eve.provider_advertisement",
|
||||
schemaId: "gamecult.eve.provider_advertisement.v1",
|
||||
recordKey: "voidbot.swarm",
|
||||
value: providerAdvertisement,
|
||||
},
|
||||
{
|
||||
publicationId: "voidbot.swarm.surface",
|
||||
documentType: "gamecult.eve.surface_state",
|
||||
schemaId: "gamecult.eve.surface_state.v1",
|
||||
recordKey: "voidbot.swarm",
|
||||
value: currentSurface,
|
||||
},
|
||||
],
|
||||
commandHandlers: {
|
||||
"swarm.set_heat": async command =>
|
||||
applyHeatCommandTransaction(command.commandId, command.payload),
|
||||
},
|
||||
});
|
||||
|
||||
await provider.start();
|
||||
|
||||
await provider.upsertPublication({
|
||||
publicationId: "voidbot.swarm.surface",
|
||||
documentType: "gamecult.eve.surface_state",
|
||||
schemaId: "gamecult.eve.surface_state.v1",
|
||||
recordKey: "voidbot.swarm",
|
||||
value: nextSurface,
|
||||
});
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
provider.stop().catch(error => {
|
||||
console.error("CultMesh provider shutdown completed with cleanup failures.", error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
The four identities are deliberately distinct:
|
||||
|
||||
- `providerId` names the product capability clients select;
|
||||
- `serviceInstanceId` names the running owner incarnation;
|
||||
- `endpointId` names the stable discovery/session route.
|
||||
- `verseId` names the discovery and state-sharing domain.
|
||||
|
||||
Do not replace any of them with a process id, socket address, body producer id,
|
||||
or renderer id.
|
||||
|
||||
## Receipt Rule
|
||||
|
||||
The receipt store is required and must be durable in a daemon. The in-memory
|
||||
store exported by the package is for tests and disposable tools only. The
|
||||
domain command handler must apply its mutation idempotently using `commandId`;
|
||||
the provider session deduplicates delivery and republishes the stored typed
|
||||
receipt, but it cannot make an unrelated database mutation atomic by wishing
|
||||
at it harder. `commandId` is the idempotency key: later delivery of the same
|
||||
provider, service-instance, and command kind returns the original receipt even
|
||||
if a sender incorrectly changes the payload. Reusing the ID for another kind
|
||||
or identity is rejected as a conflict.
|
||||
|
||||
The store is also the receipt outbox. `put` commits the receipt before any wire
|
||||
publication. `listPending` supplies receipts after startup or reconnect, and
|
||||
`markPublished` removes one only after the active connection accepts it. Scope
|
||||
the store to the provider and service-instance identity. If the store is
|
||||
unavailable, the session enters `degraded` and stops accepting commands until a
|
||||
renewal can drain the outbox again; a store failure is not a transport failure.
|
||||
|
||||
## Verification Checkpoint
|
||||
|
||||
Use an injected scheduler and transport fault double to prove the actual
|
||||
lifecycle:
|
||||
|
||||
1. initial registration publishes every desired document in stable order;
|
||||
2. lease renewal occurs before expiry;
|
||||
3. a failed route produces `reconnecting`, then republishes current desired
|
||||
state on the replacement connection;
|
||||
4. duplicate command delivery runs one handler transaction and republishes the
|
||||
same receipt;
|
||||
5. failed receipt transport reconnects and replays the durable outbox exactly
|
||||
until `markPublished` succeeds;
|
||||
6. shutdown drains command persistence, withdraws the lease and remaining
|
||||
publications, and closes even when cleanup reports failures;
|
||||
7. stopping during registration cannot let the stale connection publish;
|
||||
8. observers and conflicting command IDs cannot become lifecycle authorities.
|
||||
|
||||
The package suite contains this timeline in
|
||||
`packages/cultmesh-ts/test/provider-session.test.ts`.
|
||||
36
src/GameCult.Mesh/docs/getting-started/README.md
Normal file
36
src/GameCult.Mesh/docs/getting-started/README.md
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# CultMesh And Eve Getting Started
|
||||
|
||||
This series builds one typed application state and presents it through multiple
|
||||
Eve runtimes. It is maintained as an API acceptance test: examples use public
|
||||
APIs, name the owner of each decision, and include a verification checkpoint.
|
||||
|
||||
Follow the chapters in order:
|
||||
|
||||
1. [Persist typed application state](01-persist-typed-state.md)
|
||||
2. [Connect a client by stable identity](02-connect-by-identity.md)
|
||||
3. [Publish one Eve surface to multiple runtimes](03-publish-an-eve-surface.md)
|
||||
4. [Keep a TypeScript provider alive](04-keep-a-typescript-provider-alive.md)
|
||||
|
||||
The intended application shape is small:
|
||||
|
||||
```text
|
||||
provider daemon -> typed CultCache documents -> CultMesh advertisement
|
||||
|
|
||||
+------------------------+--------------------+
|
||||
| | |
|
||||
Eve browser EveUnity another lowerer
|
||||
```
|
||||
|
||||
The provider owns live truth. Eve owns the surface contract. Each runtime owns
|
||||
native projection. CultMesh owns discovery and connection continuity.
|
||||
|
||||
## Maintenance Contract
|
||||
|
||||
- A chapter must not tell an application to choose physical endpoints, build a
|
||||
reconnect loop, or duplicate provider state.
|
||||
- Code must compile against the package version named by the release that
|
||||
publishes it.
|
||||
- Every release changing a demonstrated API must update this series in the same
|
||||
pull request.
|
||||
- A setup step that depends on repository internals is an API defect, not
|
||||
acceptable tutorial folklore.
|
||||
609
src/GameCult.Mesh/docs/postmortem-2026-07-cultmesh-bulk-rudp.md
Normal file
609
src/GameCult.Mesh/docs/postmortem-2026-07-cultmesh-bulk-rudp.md
Normal file
|
|
@ -0,0 +1,609 @@
|
|||
# Postmortem: CultMesh bulk content over custom RUDP
|
||||
|
||||
**Incident window:** 2026-07-12 through 2026-07-19
|
||||
|
||||
**Detected:** 2026-07-19 during the released EveUnity/Aetheria cold-cache witness
|
||||
|
||||
**Scope:** CultMesh Phase 4 content delivery and the physical transport assumptions beneath it
|
||||
|
||||
**Status:** architectural cause identified; RUDP tuning stopped; replacement data planes not yet integrated
|
||||
|
||||
## Executive summary
|
||||
|
||||
The CultMesh reliability migration correctly moved discovery, session reuse,
|
||||
authority, content verification, resumable state, and final cache promotion out
|
||||
of applications and renderers. It failed at the boundary between those control
|
||||
planes and physical byte delivery.
|
||||
|
||||
The canonical plan stated that the existing RUDP implementation already
|
||||
covered acknowledgement, resend, ordering, duplicate suppression,
|
||||
fragmentation, timeout, and bounded pending work. It therefore said the first
|
||||
migration target was not a transport rewrite. That sequencing was reasonable
|
||||
while CultMesh lacked identity-first sessions: replacing the wire first would
|
||||
have preserved caller-owned reconnect and topology policy.
|
||||
|
||||
The mistake came later. Once `CultMeshSessionManager` existed, the condition
|
||||
named by the plan for adopting Iroh or QUIC had been satisfied. Instead of
|
||||
benchmarking and attaching a proven content stream at that boundary, Phase 4
|
||||
introduced `CultMeshContentChunkRequestMessage` and
|
||||
`CultMeshContentChunkResponseMessage` over the existing schema session. The
|
||||
response embedded each raw chunk payload and therefore sent bulk bytes through
|
||||
the custom RUDP fragmentation and retransmission engine.
|
||||
|
||||
This preserved schema identity and moved cache authority to the correct owner,
|
||||
but it did not produce the intended data plane. It changed the envelope around
|
||||
the bytes while leaving the physical bottleneck intact.
|
||||
|
||||
The failure was not detected promptly because the gates proved eventual
|
||||
delivery and ownership, not transport fitness:
|
||||
|
||||
- the initial content-session test used an in-memory schema client and server;
|
||||
- the deterministic hostile-network harness tested its own schedule but was
|
||||
not connected to the public content path or a physical connector;
|
||||
- the later real-UDP regression allowed one MiB to take nearly ten seconds;
|
||||
- the released cold witness allowed the artifact to finish under a 300-second
|
||||
deadline;
|
||||
- no test compared goodput, wire amplification, copies, or allocation against
|
||||
TCP, QUIC, Iroh, or a same-machine mapping baseline;
|
||||
- `SharedFileMapping` in witness output described mapping the client cache
|
||||
after the network transfer, not direct access to a provider-owned local body.
|
||||
|
||||
The result was a locally reliable but grossly inefficient bulk path. A
|
||||
56,204,750-byte released Aetheria body caused 105,911,320 daemon transmit bytes
|
||||
in one cold witness. A later controlled parity run emitted 129,241,066 server
|
||||
bytes and delivered only 10.1 MiB/s, while the same body moved and verified at
|
||||
250.7 MiB/s over TCP and 71.1 MiB/s over .NET's MsQuic-backed QUIC stream. An
|
||||
existing mapped file opened in 10.9 ms without transferring the body.
|
||||
|
||||
The ownership migration is not discarded. The physical content connector and
|
||||
its gates must be replaced. CultNet remains the typed schema and dispatch
|
||||
substrate; it must not imply that every payload belongs inside the custom RUDP
|
||||
message plane.
|
||||
|
||||
## Was the branch following the plan?
|
||||
|
||||
Yes, substantially—and that is why this incident cannot be dismissed as one
|
||||
implementation ignoring good documentation.
|
||||
|
||||
| Plan commitment | Branch result | Verdict |
|
||||
| --- | --- | --- |
|
||||
| Stable identity and shared sessions before transport replacement | Discovery and session owners were implemented before content migration | Followed |
|
||||
| Authority independent of contact and transport success | A mandatory resolver and provider/body authorization were added | Followed |
|
||||
| One verified content-transfer owner | Resume state, range verification, failover, hashing, and atomic promotion moved into `CultMeshContentTransferService` | Followed |
|
||||
| Remove renderer-owned chunk and cache authority | EveUnity delegates transfer and only lowers the verified result | Followed |
|
||||
| Bounded adaptive concurrency | A fixed four-request window was added; adaptation was explicitly deferred | Partial |
|
||||
| Caller-provided streaming destinations and backpressure | Not implemented before the managed content session became the released default | Not followed |
|
||||
| Real consumer plus hostile-network proof at phase closure | A real released consumer ran, but the hostile harness did not drive that physical path | Not followed |
|
||||
| Borrow QUIC/Iroh boundaries before dependencies | Connector/session/body boundaries were borrowed | Followed |
|
||||
| Consider Iroh or QUIC after the boundary and harness exist | The prerequisite existed, but no mandatory comparison or adoption decision occurred | Missed transition |
|
||||
| Public surface becomes smaller and more obvious | Application ownership shrank, but the physical RUDP machinery expanded | Mixed |
|
||||
|
||||
The plan also lacked a throughput, amplification, flow-control, copy-budget, or
|
||||
comparative transport gate. Consequently, the branch could follow much of the
|
||||
written plan and still release an unfit bulk path. This is both a plan defect
|
||||
and an execution defect:
|
||||
|
||||
- **Plan defect:** it treated RUDP feature completeness as a sufficient reason
|
||||
to defer physical transport evaluation and did not define the evaluation
|
||||
trigger or fitness budget.
|
||||
- **Execution defect:** once repeated cold failures supplied contrary evidence,
|
||||
the work kept repairing RUDP locally instead of reopening the premise.
|
||||
|
||||
## User-visible impact
|
||||
|
||||
- A same-machine Aetheria daemon and Unity client copied a provider-owned asset
|
||||
bundle through UDP instead of opening an authorized mapped body.
|
||||
- The 0.3.91 released Unity test took 54.803 seconds. File timestamps place the
|
||||
56,204,750-byte body promotion roughly 31 seconds after partial creation.
|
||||
- The 0.3.92/CultLib 1.0.33 witness reduced the Unity test to 36.028 seconds and
|
||||
body transfer to roughly 12 seconds, but daemon transmit volume rose to
|
||||
105,911,320 bytes. The apparent speedup came partly from more aggressive
|
||||
packet emission and retransmission.
|
||||
- Cold startup competed with transient gameplay state and initially allowed a
|
||||
live body publication lease to expire before subscription.
|
||||
- Release and witness effort was repeatedly spent changing drains, sleeps,
|
||||
ACK handling, request windows, and lifecycle ordering rather than selecting
|
||||
the intended data plane.
|
||||
- Remote behavior under real latency, loss, and bandwidth contention remains
|
||||
unproven and is likely worse than loopback evidence.
|
||||
|
||||
Content hashes, incremental chunk verification, final SHA-256 verification,
|
||||
and atomic promotion prevented corrupted or partial bodies from becoming cache
|
||||
truth. The incident is a performance and architecture failure, not known data
|
||||
corruption.
|
||||
|
||||
## Intended architecture
|
||||
|
||||
The reliability plan's durable intent was:
|
||||
|
||||
1. stable endpoint identity rather than application-owned physical endpoints;
|
||||
2. shared long-lived sessions rather than request-scoped clients;
|
||||
3. authority independent of contact and transport success;
|
||||
4. content identity independent of provider and location;
|
||||
5. verified resumable transfer owned outside renderers;
|
||||
6. negotiated local mappings and remote streams behind the same body identity;
|
||||
7. Iroh/QUIC lessons expressed in boundaries before dependencies were adopted.
|
||||
|
||||
The intended phrase “CultNet as the transport substrate” meant that registered
|
||||
schemas, typed envelopes, dispatch, and diagnostics remain portable across
|
||||
transport connectors. It did not require every body byte to be serialized as a
|
||||
schema-message field or fragmented by CultNet's RUDP implementation.
|
||||
|
||||
## What was implemented
|
||||
|
||||
The following pieces match the plan and remain useful:
|
||||
|
||||
- `CultMeshDiscoveryService` owns route observations and freshness.
|
||||
- `CultMeshSessionManager` owns identity-first connection reuse and path state.
|
||||
- `CultMeshAuthorityResolver` separates contact from authorization.
|
||||
- `CultMeshContentTransferService` owns partial files, verified ranges,
|
||||
provider failover, final hashing, and atomic cache promotion.
|
||||
- content hashes remain independent of provider identity and location.
|
||||
- body publications preserve schema, layout, producer epoch, sequence, access,
|
||||
lease, and transport representations.
|
||||
- exact reactive subscriptions and SoA demand avoid broad per-frame snapshots.
|
||||
- verified client cache files can be mapped without allocating another managed
|
||||
body after transfer.
|
||||
|
||||
The incorrect slice was the managed content session:
|
||||
|
||||
```text
|
||||
manifest chunk
|
||||
-> CultMeshContentChunkRequestMessage
|
||||
-> CultMeshContentChunkResponseMessage.Payload
|
||||
-> MessagePack schema frame
|
||||
-> custom RUDP fragmentation
|
||||
-> per-packet ACK/resend/reassembly
|
||||
-> managed byte[] chunk
|
||||
-> verified partial file
|
||||
```
|
||||
|
||||
The desired path is:
|
||||
|
||||
```text
|
||||
typed content request / authorized body capability
|
||||
-> CultMesh session selects an advertised physical plane
|
||||
-> same machine: provider-owned mapped file/shared memory
|
||||
-> remote: proven independent byte stream/range fetch
|
||||
-> existing verified partial/final promotion owner
|
||||
```
|
||||
|
||||
Registered schemas remain the control language. They identify the body, hash,
|
||||
range, lease, stream, progress, cancellation, and receipt. They do not need to
|
||||
contain the body itself.
|
||||
|
||||
## Timeline
|
||||
|
||||
### Before the migration plan
|
||||
|
||||
- **2026-06-14 to 2026-06-17:** commits `8ce89688` through `1c85eabe`
|
||||
introduced the C# transport port, custom RUDP reliability core, socket
|
||||
transport, fragmentation, schema ergonomics, reconnect support, and a
|
||||
multi-peer listener.
|
||||
- **2026-07-10 to 2026-07-12:** snapshot connection reuse and large-snapshot
|
||||
fixes made RUDP the working physical path for the first Aetheria witness.
|
||||
|
||||
### Reliability migration
|
||||
|
||||
- **2026-07-12, `f0b5e103`:** the canonical reliability plan was committed. It
|
||||
explicitly treated low-level RUDP reliability as present and deferred Iroh or
|
||||
QUIC until session ownership and a failure harness existed.
|
||||
- **2026-07-12, `fc65e25f`:** Phase 0 added a deterministic fault scheduler and
|
||||
diagnostics. The harness could replay hostile events, but it was not wired to
|
||||
the public content transfer or actual transport connectors.
|
||||
- **2026-07-13, `b9f17a71`:** `CultMeshContentTransferService` correctly took
|
||||
ownership of resumable verification and atomic promotion.
|
||||
- **2026-07-14, `7d571402`:** the decisive wrong fork. Managed content sessions
|
||||
embedded chunk bytes in typed schema responses over the existing session.
|
||||
The primary test used an in-memory loopback transport and therefore proved
|
||||
ownership and message shape without exercising RUDP.
|
||||
- **2026-07-14, `a311cbe8`:** fixed request concurrency and RUDP polling to
|
||||
improve throughput. The plan explicitly deferred adaptive scheduling and
|
||||
streaming destinations instead of reopening physical-plane selection.
|
||||
- **2026-07-14, `b943fa7e`:** a 13,006,384-byte cold run completing under the
|
||||
unchanged 300-second deadline was recorded as content-session delivery proof.
|
||||
- **2026-07-16, `25231429`:** a physical RUDP content test was finally added.
|
||||
Its one-MiB payload only had to finish within ten seconds. It recorded wire
|
||||
statistics on failure but asserted no goodput or lossless amplification
|
||||
budget.
|
||||
- **2026-07-16, `15bffc6d`:** a 46,412,384-byte released cold witness was
|
||||
recorded as proof while explicitly acknowledging that the managed session
|
||||
still copied and fragmented the body.
|
||||
- **2026-07-17 to 2026-07-19:** ACK synchronization, concurrent session
|
||||
serialization, exact body demand, reactive delivery, and live subscription
|
||||
work made the path more correct under concurrency. None tested whether RUDP
|
||||
deserved to carry bulk bytes.
|
||||
- **2026-07-19, `2afec5c5`:** per-32-packet `Thread.Sleep(1)` calls were replaced
|
||||
by `Thread.Yield`. The cold transfer became faster while wire volume nearly
|
||||
doubled, revealing that the system was flooding loopback rather than
|
||||
controlling flow.
|
||||
- **2026-07-19, `ee0fb235`:** the first dedicated transport parity harness
|
||||
compared the Aetheria-sized public content path with mapped-file, TCP, and
|
||||
MsQuic-backed QUIC baselines. The result rejected further RUDP bulk tuning.
|
||||
|
||||
## Detection
|
||||
|
||||
The incident surfaced only after the released-package witness became fully
|
||||
cold and provider-owned assets grew to 56,204,750 bytes. Earlier warm-cache
|
||||
runs bypassed transfer. Earlier cold runs were framed as timeout/reliability
|
||||
problems rather than fitness problems.
|
||||
|
||||
The decisive signals were:
|
||||
|
||||
1. transfer duration remained many seconds on loopback;
|
||||
2. removing scheduler sleeps reduced duration but drove daemon transmit volume
|
||||
to almost twice the body size in the released witness;
|
||||
3. the dedicated parity harness showed a stable order-of-magnitude gap;
|
||||
4. opening an existing provider body locally required milliseconds and no
|
||||
transfer, proving that the same-machine witness was selecting the wrong
|
||||
plane before RUDP performance even mattered.
|
||||
|
||||
## Root cause
|
||||
|
||||
### Primary cause: capability was mistaken for fitness
|
||||
|
||||
The plan listed ACK, resend, ordering, duplicate suppression, fragmentation,
|
||||
timeout, and bounded pending work and concluded that transport replacement was
|
||||
not the first target. Those properties can establish eventual reliable message
|
||||
delivery. They do not establish congestion control, receiver flow control,
|
||||
packet pacing, batching, stream multiplexing, loss recovery quality, or bulk
|
||||
goodput.
|
||||
|
||||
The custom RUDP path had a 32-packet acknowledgement mask, 1,024-byte fragments,
|
||||
managed per-fragment bookkeeping, and no congestion window tied to receiver
|
||||
progress. A sender could emit multiple 256-KiB chunk responses concurrently.
|
||||
Yielding after 32 sends yielded CPU time; it did not create backpressure or
|
||||
wait for acknowledgement progress.
|
||||
|
||||
### Secondary cause: “CultNet substrate” was underspecified
|
||||
|
||||
The plan did not say plainly enough that CultNet owns typed schema semantics
|
||||
independently of physical transport. Implementers treated “preserve CultNet as
|
||||
the transport substrate” as a reason to carry content through the available
|
||||
RUDP schema channel. This collapsed two distinct claims:
|
||||
|
||||
- CultNet documents and registered schemas remain the portable protocol.
|
||||
- the current CultNet RUDP implementation is suitable for every payload class.
|
||||
|
||||
Only the first claim was required.
|
||||
|
||||
### Secondary cause: the QUIC/Iroh adoption trigger had no gate
|
||||
|
||||
The plan correctly warned against adopting Iroh or QUIC before session and
|
||||
failure boundaries existed. It did not define a mandatory decision point once
|
||||
those boundaries existed. Phase 2 delivered the connector/session seam, but
|
||||
Phase 4 did not require candidate transports to pass a fitness comparison
|
||||
before becoming the content default.
|
||||
|
||||
The deferral therefore became sticky. “Not yet” silently became “continue using
|
||||
RUDP.”
|
||||
|
||||
### Secondary cause: evidence harnesses observed the wrong layer
|
||||
|
||||
Phase 0's deterministic network proved that a fault schedule could replay
|
||||
loss, duplication, delay, reordering, partition, corruption, endpoint rotation,
|
||||
and restart. It did not drive the RUDP socket transport, session manager, or
|
||||
content transfer service. A self-test of the harness was treated as sufficient
|
||||
foundation for later phase proof.
|
||||
|
||||
The first managed-content test used an in-memory schema bridge. It proved that
|
||||
content did not use snapshot records, sessions were reused, hashes matched, and
|
||||
warm cache avoided another request. It could not reveal fragmentation cost,
|
||||
socket flooding, resend amplification, scheduling delays, or contention with
|
||||
other messages.
|
||||
|
||||
The later physical test's ten-second bound for one MiB was a hang detector, not
|
||||
a performance contract. The 300-second released witness deadline was likewise
|
||||
a liveness ceiling, not a native-experience gate.
|
||||
|
||||
### Secondary cause: local failures were repaired locally
|
||||
|
||||
Each symptom had a plausible narrow explanation:
|
||||
|
||||
- snapshot payloads starved peers;
|
||||
- poll loops slept after control packets;
|
||||
- fragment sends slept per packet;
|
||||
- ACKs fell outside the rolling mask;
|
||||
- concurrent publishers mutated one reliability session;
|
||||
- content subscription leases expired during cold loading.
|
||||
|
||||
The fixes were individually defensible and often necessary for small-message
|
||||
correctness. Together they kept attention inside RUDP. No rule required a
|
||||
transport parity check after two transport-level fixes failed to produce an
|
||||
acceptable cold path.
|
||||
|
||||
This is the process failure described by the project's Jenga warning: the
|
||||
machine supplied enough local context to justify each patch while withholding
|
||||
the comparative evidence needed to question the owner.
|
||||
|
||||
### Secondary cause: post-transfer mapping obscured pre-transfer cost
|
||||
|
||||
The witness reported `SharedFileMapping` because EveUnity mapped the verified
|
||||
client cache file before loading the Unity bundle. That was true at the body
|
||||
lease layer, but incomplete at the user-visible layer: the provider-owned file
|
||||
had already crossed RUDP into the client cache.
|
||||
|
||||
The metric did not lie, but it observed the wrong interval. No durable witness
|
||||
fact distinguished:
|
||||
|
||||
- provider-owned same-machine mapping with zero body transfer;
|
||||
- client-cache mapping after remote delivery;
|
||||
- managed network-buffer fallback.
|
||||
|
||||
### Secondary cause: the plan became both specification and evidence ledger
|
||||
|
||||
The plan accumulated phase body maps, implementation notes, witness results,
|
||||
and partial-proof language in the same document that still contained the
|
||||
original `Cut first`, `Build`, and `Gate` contracts. That made useful progress
|
||||
visible, but it blurred the difference between these two statements:
|
||||
|
||||
- a coherent slice of the phase has evidence;
|
||||
- the phase's closure contract has been satisfied.
|
||||
|
||||
In Phase 4, content ownership, verification, and released-consumer delivery had
|
||||
evidence while adaptive scheduling, caller-provided streaming destinations,
|
||||
backpressure, hostile-network coverage of the real physical path, and transport
|
||||
fitness remained open. The document could therefore tell an increasingly
|
||||
convincing success story without forcing the remaining gate failures back to
|
||||
the top of the decision process.
|
||||
|
||||
Evidence belongs beside the plan, but phase status must be derived only from an
|
||||
explicit closure checklist. A partial proof may close a named slice; it cannot
|
||||
silently weaken the parent phase gate.
|
||||
|
||||
## Five whys
|
||||
|
||||
1. **Why was Aetheria cold asset delivery slow?**
|
||||
|
||||
The provider sent a large immutable body as thousands of reliable UDP
|
||||
fragments with heavy retransmission and managed per-packet work.
|
||||
|
||||
2. **Why was bulk content sent through that path?**
|
||||
|
||||
Phase 4 represented chunks as typed request/response schema messages on the
|
||||
existing CultMesh session.
|
||||
|
||||
3. **Why was the existing session assumed suitable?**
|
||||
|
||||
The plan equated implemented reliability features with transport fitness and
|
||||
deferred Iroh/QUIC until the session boundary existed.
|
||||
|
||||
4. **Why was the assumption not revisited after the boundary existed?**
|
||||
|
||||
There was no mandatory transport parity gate, and every test emphasized
|
||||
ownership, eventual completion, or failure recovery rather than comparative
|
||||
goodput and amplification.
|
||||
|
||||
5. **Why did repeated fixes not trigger redesign?**
|
||||
|
||||
The workflow classified each failure as another RUDP correctness defect and
|
||||
rewarded a passing witness under generous timeouts. It lacked an escalation
|
||||
rule that says repeated physical-transport repairs reopen transport
|
||||
selection.
|
||||
|
||||
## What went well
|
||||
|
||||
- Content identity, verification, restart state, provider failover, and atomic
|
||||
promotion were moved to a coherent owner and survived the incident.
|
||||
- The released-package witness eventually exercised a truly cold cache and
|
||||
exposed the problem at the user-visible boundary.
|
||||
- Daemon transport counters made wire amplification observable.
|
||||
- The later parity harness reused the public transfer path instead of comparing
|
||||
only synthetic packet loops.
|
||||
- The unreleased two-chunk/Sleep(0) tuning experiment was reverted rather than
|
||||
released after it showed improved duration with unacceptable wire behavior.
|
||||
- The plan had preserved a transport connector boundary, so replacing the
|
||||
physical plane does not require returning authority to EveUnity or Aetheria.
|
||||
|
||||
## What went poorly
|
||||
|
||||
- Research direction was treated as future inspiration after its adoption
|
||||
prerequisite had already been met.
|
||||
- The deterministic failure harness was not integrated with the systems whose
|
||||
reliability it purported to de-risk.
|
||||
- “Large” tests used 128 KiB, 700 KiB, or one MiB while the consumer used 13 to
|
||||
56 MiB artifacts.
|
||||
- Test thresholds detected hangs but certified them as performance proof.
|
||||
- Lossless wire amplification was not a release gate.
|
||||
- The cold witness separated gameplay from content for valid lifecycle reasons,
|
||||
but that separation also reduced pressure to make cold startup feel native.
|
||||
- Plan updates faithfully described partial slices yet allowed “proven” wording
|
||||
before the full Phase 4 build and gate lists were complete.
|
||||
- The same-machine deployment advertised and selected network delivery before
|
||||
mapping the resulting client cache.
|
||||
|
||||
## Corrective architecture
|
||||
|
||||
### Owner
|
||||
|
||||
`CultMeshSessionManager` owns physical-plane selection for an endpoint identity
|
||||
and application protocol. `CultMeshContentTransferService` owns verification,
|
||||
resume state, and final promotion. A selected transport connector owns byte
|
||||
movement. CultNet schema dispatch owns none of the physical reliability policy.
|
||||
|
||||
### Inputs
|
||||
|
||||
- stable endpoint and provider identity;
|
||||
- authorized content hash, byte size, ranges, and lease;
|
||||
- provider-advertised physical candidates;
|
||||
- consumer-supported candidates;
|
||||
- same-machine evidence;
|
||||
- platform capabilities and measured connector health.
|
||||
|
||||
### Outputs
|
||||
|
||||
- same-machine: an authorized provider-owned mapped file or shared-memory body;
|
||||
- remote: an independent proven stream/range fetch feeding the transfer owner;
|
||||
- typed progress, cancellation, failure, and receipt state over CultNet.
|
||||
|
||||
### Derived state
|
||||
|
||||
Selected plane, endpoint address, stream identifiers, byte progress, path
|
||||
health, and performance telemetry are derived. They do not alter content hash,
|
||||
provider authority, or cache truth.
|
||||
|
||||
### Forbidden writers
|
||||
|
||||
- schema-message helpers cannot embed bulk body payloads;
|
||||
- renderers cannot choose physical endpoints or write final cache entries;
|
||||
- a body adapter cannot confer provider authority;
|
||||
- RUDP retry, chunk-window, or timeout tuning cannot make RUDP the preferred
|
||||
bulk plane;
|
||||
- a client-cache mapping cannot claim same-machine zero-copy provenance.
|
||||
|
||||
### Shared paths
|
||||
|
||||
Every remote connector terminates in the existing verified-range and atomic
|
||||
promotion primitives. Local mapping and remote fallback preserve the same body
|
||||
identity, schema/layout, epoch/sequence, access mode, and lease semantics.
|
||||
|
||||
### Deletion line
|
||||
|
||||
1. Stop adding bulk-performance behavior to custom RUDP.
|
||||
2. Prevent `CultMeshContentChunkResponseMessage.Payload` from being the default
|
||||
content body path.
|
||||
3. Make RUDP an explicit compatibility/control candidate, not the implicit
|
||||
connector for `cultmesh.content.v1`.
|
||||
4. Delete RUDP content serving once every released consumer negotiates local
|
||||
mapping or a dedicated remote stream.
|
||||
5. Retain RUDP only for payload classes whose own fitness gates justify it;
|
||||
eventual cleanup may remove the custom reliability engine entirely.
|
||||
|
||||
## Corrective actions
|
||||
|
||||
### Completed
|
||||
|
||||
- [x] Add `tools/GameCult.TransportParity` using the public CultMesh transfer
|
||||
owner and Aetheria-sized payloads.
|
||||
- [x] Compare mapped-file open, TCP stream, MsQuic-backed QUIC stream, and
|
||||
CultMesh RUDP on the same host.
|
||||
- [x] Record duration, goodput, and RUDP server wire bytes.
|
||||
- [x] Stop and revert the unreleased request-window/pacing experiment.
|
||||
- [x] Amend the reliability plan with the physical body-plane ownership cut.
|
||||
|
||||
### Required before another bulk transport release
|
||||
|
||||
- [ ] Make same-machine evidence select a provider-owned mapped body before any
|
||||
network fetch.
|
||||
- [ ] Attach at least one proven remote stream connector behind
|
||||
`CultMeshSessionManager` and the content protocol identity.
|
||||
- [ ] Keep content request, authorization, range, progress, cancellation, and
|
||||
receipt state typed while moving body bytes out of schema response payloads.
|
||||
- [ ] Integrate the deterministic hostile-network schedule with the actual
|
||||
connector and public content transfer path.
|
||||
- [ ] Exercise Aetheria-sized payloads, not only unit-sized fixtures.
|
||||
- [ ] Add cold and warm released-consumer witnesses that report plane
|
||||
provenance, bytes sent, bytes copied, promotion time, and total lowering time.
|
||||
- [ ] Prove remote cancellation, range resume, provider failover, and corruption
|
||||
recovery over the selected stream.
|
||||
- [ ] Define and enforce platform packaging for Unity, daemon, TypeScript, and
|
||||
other promoted runtimes before making the connector the public default.
|
||||
|
||||
### Required transport fitness gates
|
||||
|
||||
The precise budgets may be tightened as deployment data accumulates, but a
|
||||
candidate cannot become the default without all of these categories:
|
||||
|
||||
- **Comparative goodput:** integrated verified transfer measured against the
|
||||
same connector's raw stream baseline on the same host and route.
|
||||
- **Lossless amplification:** total wire bytes bounded relative to body bytes;
|
||||
success alone is insufficient.
|
||||
- **Small-message latency:** control messages and receipts remain responsive
|
||||
while a body transfers.
|
||||
- **Backpressure:** sender progress follows receiver and destination capacity;
|
||||
thread yields and timeout retries are not accepted as flow control.
|
||||
- **Hostile network:** loss, duplication, reordering, latency, partition,
|
||||
reconnect, and path change drive the actual public path.
|
||||
- **Memory/copy budget:** allocation and copy counts distinguish provider-owned
|
||||
mapping, streamed promotion, client-cache mapping, and managed fallback.
|
||||
- **User-visible cold start:** a released generic client lowers the world within
|
||||
an explicit experience budget; a multi-minute timeout is only a deadlock
|
||||
guard.
|
||||
|
||||
### Escalation rule
|
||||
|
||||
After two fixes in the physical transport layer for the same consumer outcome,
|
||||
work stops and transport selection is reopened against dedicated baselines.
|
||||
Further local transport repair requires evidence that the current connector
|
||||
still satisfies its fitness budget. This is not a ban on fixing bugs; it
|
||||
prevents repeated correctness patches from impersonating architectural proof.
|
||||
|
||||
## Plan amendments
|
||||
|
||||
The reliability plan should now be read with these corrections:
|
||||
|
||||
1. “CultNet as transport substrate” means typed schema identity, framing,
|
||||
dispatch, diagnostics, and connector contracts. It does not bless a single
|
||||
physical transport for all payloads.
|
||||
2. Implemented ACK/resend/fragmentation is evidence of reliable-message
|
||||
capability, not evidence of bulk, realtime, or media fitness.
|
||||
3. Once the session connector boundary exists, physical candidates must pass a
|
||||
workload-specific parity gate before a consumer migration closes.
|
||||
4. Typed control state and body transport are separate. Registered schemas make
|
||||
the control plane smaller; they do not require body bytes to become document
|
||||
fields.
|
||||
5. Same-machine mapping is selected before transfer. Mapping a cache file after
|
||||
transfer is a useful lowering optimization but not zero-copy delivery.
|
||||
6. A phase slice may be recorded as partial evidence, but “proven” and “closed”
|
||||
require the complete build list, gates, real consumer, and performance
|
||||
evidence relevant to that slice.
|
||||
|
||||
## Evidence
|
||||
|
||||
### Source and history
|
||||
|
||||
- Canonical plan: `src/GameCult.Mesh/docs/reliability-migration-plan.md`, commit
|
||||
`f0b5e103`.
|
||||
- Managed content session fork: commit `7d571402`.
|
||||
- Fixed request concurrency and drain work: commit `a311cbe8`.
|
||||
- First physical one-MiB RUDP content regression: commit `25231429`.
|
||||
- Scheduler-yield release: commit `2afec5c5`.
|
||||
- Dedicated parity harness and initial body-plane correction: commit
|
||||
`ee0fb235`.
|
||||
|
||||
### Released witness
|
||||
|
||||
- EveUnity `artifacts/cold-release-0391/results.xml`: 54.803-second Unity test.
|
||||
- EveUnity `artifacts/cold-release-0392/results.xml`: 36.028-second Unity test.
|
||||
- EveUnity `artifacts/cold-release-0392/aetheria-daemon.log`: final daemon
|
||||
counters `rx=3903892 tx=105911320` for the cold run.
|
||||
- Both witness documents report a 56,204,750-byte provider asset and
|
||||
`SharedFileMapping`; the mapping occurred after network promotion into the
|
||||
client cache.
|
||||
|
||||
### Parity harness
|
||||
|
||||
- Payload: 56,204,750 bytes.
|
||||
- Existing mapped file: 10.9 ms to open and touch; no body transfer.
|
||||
- TCP plus file write and SHA-256 verification: 213.8 ms, 250.7 MiB/s.
|
||||
- MsQuic-backed QUIC plus file write and SHA-256 verification: 753.4 ms,
|
||||
71.1 MiB/s; repeated runs reached 87.0 to 107.4 MiB/s.
|
||||
- CultMesh RUDP public content transfer: 5,322.9 ms, 10.1 MiB/s,
|
||||
129,241,066 server bytes; repeated runs reached 10.1 to 13.0 MiB/s.
|
||||
|
||||
## Accountability
|
||||
|
||||
Git author identity does not distinguish human-authored work from agent work in
|
||||
this repository, so this postmortem does not infer personal authorship from the
|
||||
commit metadata. The failure belongs to the engineering process and especially
|
||||
to the agent execution that kept accepting narrow transport repairs as progress
|
||||
toward the user's native-experience requirement.
|
||||
|
||||
The user explicitly warned that cold asset delivery was not healthy enough to
|
||||
claim, that larger timeouts must not conceal it, and that the daemon architecture
|
||||
could not cost game performance. The eventual switch from “times out” to
|
||||
“finishes before the deadline” did not satisfy those constraints. The agent
|
||||
should have introduced comparative transport evidence at the first Phase 4
|
||||
physical failure, not after several releases and witness iterations.
|
||||
|
||||
## Closing statement
|
||||
|
||||
The reliability migration did not fail because it learned from Iroh and QUIC.
|
||||
It failed because it stopped at their control-plane lessons after building the
|
||||
seam where their transport machinery was meant to attach.
|
||||
|
||||
The repair is not to discard the new discovery, session, authority, transfer,
|
||||
or body ownership. It is to finish the architecture: keep registered schemas as
|
||||
the small typed language of CultNet, attach proven physical transports beneath
|
||||
the session boundary, and make every promoted plane prove that it deserves the
|
||||
workload before a released consumer depends on it.
|
||||
|
|
@ -520,6 +520,23 @@ explicitly forwarded. Stale epochs fail loudly.
|
|||
|
||||
Consumers subscribe to typed document changes through `CultNetDatabase` watch
|
||||
methods. Subscriptions receive domain changes rather than storage envelopes.
|
||||
Exact remote values use `SubscribeLiveValueAsync<T>(...)`; they remain ephemeral
|
||||
and own their unsubscribe lifetime. Hot body state uses
|
||||
`CultMesh.SubscribeLiveBodyAsync(...)`: the reactive value is only the current
|
||||
body descriptor, while `OpenCurrentReadOnly()` negotiates shared memory,
|
||||
shared-file mapping, or network from observed locality and available adapters.
|
||||
Same-machine bodies are opened from the mapped producer slab. Remote live bodies
|
||||
are capability-bound and read through one reusable `cultmesh.bodies.v1` session;
|
||||
they are not packed into CultCache or CDN records. `CultMeshClient.BodyProvider(...)`
|
||||
creates that verified network adapter without exposing session machinery to the
|
||||
consumer. Body bytes never become subscription snapshot payload. Either subscription may
|
||||
legitimately start with `HasValue == false`; it remains active until the provider
|
||||
publishes the exact record, avoiding a startup retry loop or broad snapshot.
|
||||
`CultNetDatabaseSubscriptionServer.DemandChanged` exposes the exact requested
|
||||
record and schema set as well as optional body negotiation. A provider can
|
||||
therefore materialize a computed record only while it has consumers. The watch
|
||||
is installed before demand is announced, so the first publication travels as a
|
||||
normal live change and does not require a bootstrap snapshot.
|
||||
|
||||
### Client Prediction
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
# CultMesh Reliability Migration Plan
|
||||
|
||||
Incident record: [CultMesh bulk content over custom RUDP, July 2026](postmortem-2026-07-cultmesh-bulk-rudp.md).
|
||||
|
||||
Physical-plane authority: [CultMesh transport planes](transport-planes.md).
|
||||
|
||||
## Objective
|
||||
|
||||
CultMesh should give an application one typed, watchable route to a Verse,
|
||||
|
|
@ -9,13 +13,14 @@ transfer recovery.
|
|||
|
||||
The migration preserves CultCache as the typed persistence substrate and
|
||||
CultNet as the transport substrate. It moves reliability policy out of callers
|
||||
and the broad `CultMesh` convenience facade into five explicit organs:
|
||||
and the broad `CultMesh` convenience facade into six explicit organs:
|
||||
|
||||
1. discovery control plane
|
||||
2. connection and session manager
|
||||
3. authority resolver
|
||||
4. content transfer scheduler
|
||||
5. stream control plane
|
||||
6. negotiated body transport
|
||||
|
||||
This is an ownership migration, not a new layer wrapped around the existing
|
||||
caller-driven machinery. Each phase cuts an obsolete decision path before its
|
||||
|
|
@ -42,6 +47,34 @@ usable while endpoints fail or move.
|
|||
|
||||
## Target Authority Map
|
||||
|
||||
### Local persistence hydration
|
||||
|
||||
**Owner:** the attached CultCache backing store owns durable record discovery;
|
||||
the consuming service owns its working-set selector.
|
||||
|
||||
**Inputs:** an indexed manifest containing record key, schema identity, and
|
||||
commit time; an explicit metadata predicate supplied at open or at a later
|
||||
subscription boundary.
|
||||
|
||||
**Outputs:** only selected typed documents enter the live cache. Record payload
|
||||
pages outside the working set remain durable and unopened. Indexed stores may
|
||||
hydrate an additional selection without replaying or evicting the existing hot
|
||||
set; non-indexed stores retain the correct full-pull fallback.
|
||||
|
||||
**Derived state:** hydrated keys, dirty keys, and migration reports are local
|
||||
backing-store state. The manifest index remains the durable catalog even when a
|
||||
consumer has only a narrow working set in memory.
|
||||
|
||||
**Forbidden writers:** service boot code must not scan page directories or
|
||||
deserialize broad snapshots to discover keys. A filtered flush must not delete
|
||||
unsubscribed records, and implicit global assembly discovery must not expand an
|
||||
explicit service registry.
|
||||
|
||||
**Cut line:** directory manifests now carry metadata-only record indexes;
|
||||
explicit registries contain exactly the requested document types; selective
|
||||
pulls use the same indexed authority instead of reopening the store through a
|
||||
second compatibility path.
|
||||
|
||||
### Discovery control plane
|
||||
|
||||
**Owner:** `CultMeshDiscoveryService`.
|
||||
|
|
@ -103,6 +136,45 @@ must never confer authority.
|
|||
**Demotion:** an advertised peer card is only contact evidence. It is never an
|
||||
authorization result.
|
||||
|
||||
#### Phase 3 body map
|
||||
|
||||
**Owner:** `CultMeshAuthorityResolver` is the only component that decides
|
||||
whether a peer may act. Decisions are evaluated on demand and are never cached
|
||||
as grants.
|
||||
|
||||
**Inputs:** `CultMeshAuthorityRequest`, an `ICultMeshAuthorityLeaseSource`, an
|
||||
`ICultMeshAuthoritySignatureVerifier`, an
|
||||
`ICultMeshAuthorityRevocationSource`, the current authority epoch, and an
|
||||
injected `ICultMeshClock`.
|
||||
|
||||
**Outputs:** `CultMeshAuthorityDecision`, carrying either the accepted lease
|
||||
evidence identifiers or one typed denial reason. Authority diagnostics carry
|
||||
lease, peer, and issuer identifiers but never signature material.
|
||||
|
||||
**Derived state:** peer selection is a projection over contact candidates and
|
||||
fresh resolver decisions. The lease catalog is only a mutable evidence source;
|
||||
the peer catalog is only a contact source.
|
||||
|
||||
**Forbidden writers:** lease replacement, peer-card publication, successful
|
||||
transport connection, cached presence, and wall-clock defaults cannot grant or
|
||||
restore authority. Revocation and epoch policy remain outside both catalogs.
|
||||
|
||||
**Shared paths:** gameplay sessions expose their resolver; peer selection and
|
||||
both privileged RUDP creation paths call that resolver. Compatibility overloads
|
||||
delegate to the same resolver with deny-by-default signature policy.
|
||||
|
||||
**Cut line:** `CultMeshAuthorityLease.Covers`,
|
||||
`CultMeshAuthorityLeaseCatalog.IsAuthorized`, and catalog-owned
|
||||
`FindAuthorized`/`FirstAuthorized` no longer contain authorization logic.
|
||||
Version-zero or unsigned leases are not reinterpreted as trusted epoch-zero
|
||||
leases. Callers must supply a version-one lease, explicit epoch, signature
|
||||
verifier, and revocation source.
|
||||
|
||||
**Compatibility inventory:** the old lease/catalog peer-selection and RUDP
|
||||
overloads remain source-compatible for migration, but cannot authorize because
|
||||
they have no signature-verification authority. They delegate to a
|
||||
deny-by-default resolver and should be replaced by resolver-taking overloads.
|
||||
|
||||
### Content transfer scheduler
|
||||
|
||||
**Owner:** `CultMeshContentTransferService`.
|
||||
|
|
@ -144,6 +216,33 @@ latest-frame cache must not own stream identity or publisher liveness.
|
|||
**Demotion:** the current in-process stream catalog becomes a local projection
|
||||
and body adapter. It is not the distributed stream registry.
|
||||
|
||||
### Negotiated body transport
|
||||
|
||||
**Owner:** `CultMeshBodyTransportService` owns representation negotiation and
|
||||
the lifetime of transport-specific body access. It does not own body identity,
|
||||
publisher authority, content integrity, or application semantics.
|
||||
|
||||
**Inputs:** a typed body descriptor, authorized producer lease, consumer
|
||||
capabilities, locality evidence, schema/layout support, transport adapters,
|
||||
clock, and access policy.
|
||||
|
||||
**Outputs:** a read-only body lease by default, bound to one logical body
|
||||
identity, schema/layout version, producer epoch, sequence, and negotiated
|
||||
transport. Local peers may receive an OS-handle capability token; remote peers
|
||||
receive the same typed body through the network representation.
|
||||
|
||||
**Derived state:** transport preference, local/remote eligibility, mapped
|
||||
region or file-handle lifetime, slot availability, and lease expiry.
|
||||
|
||||
**Forbidden writers:** process IDs, virtual addresses, mapping names, OS
|
||||
handles, and transport endpoints cannot become logical identity. A successful
|
||||
mapping cannot authorize a producer, extend a lease, bless content, or permit a
|
||||
consumer to mutate the body.
|
||||
|
||||
**Demotion:** shared-memory regions and file mappings are body adapters. They
|
||||
do not become a local message bus, alternate discovery plane, or source of
|
||||
authority.
|
||||
|
||||
## Shared Public Shape
|
||||
|
||||
The target API is identity-first and watchable:
|
||||
|
|
@ -202,6 +301,36 @@ failure.
|
|||
counters.
|
||||
- Diagnostics have bounded cost and can be disabled or sampled on hot paths.
|
||||
|
||||
### Phase 0 Body Map
|
||||
|
||||
**Owner:** reliability organs own their clocks and emit typed observations;
|
||||
`CultMeshDiagnosticBuffer` owns only a bounded inspection projection.
|
||||
|
||||
**Inputs:** injected `ICultMeshClock`, organ state transitions, endpoint and
|
||||
source identity, reason code, and served schema/library version.
|
||||
|
||||
**Outputs:** ordered `CultMeshDiagnosticEvent` observations. The deterministic
|
||||
test network emits scheduled packet deliveries under loss, duplication,
|
||||
reordering, latency, partition, endpoint rotation, corruption, and restart.
|
||||
|
||||
**Derived state:** diagnostic sequence and the bounded recent-event window.
|
||||
Neither confers reachability, authority, or retry policy.
|
||||
|
||||
**Forbidden writers:** diagnostic sinks and fault harnesses cannot choose a
|
||||
route, mutate discovery candidates, authorize a peer, or repair a session.
|
||||
|
||||
**Shared paths:** the existing Verse discovery client now uses the injected
|
||||
clock for connection and response deadlines and emits the same typed timeline
|
||||
for success, timeout, and transport failure.
|
||||
|
||||
**Cut line:** wall-clock reads and unobservable timeout delays have been removed
|
||||
from Verse discovery. Caller-owned catalog mutation and endpoint sequencing
|
||||
remain compatibility authority until Phase 1 replaces and demotes them.
|
||||
|
||||
**Verification layer:** tests observe the emitted discovery timeline and served
|
||||
version, while the deterministic network harness proves exact replay of every
|
||||
required hostile-network action.
|
||||
|
||||
## Phase Closure Contract
|
||||
|
||||
Every implementation phase must close with all of the following:
|
||||
|
|
@ -265,6 +394,55 @@ retain an independent endpoint loop or catalog opinion.
|
|||
- A poisoned or unsigned observation cannot override an accepted signed
|
||||
candidate.
|
||||
|
||||
### Phase 1 Body Map
|
||||
|
||||
**Owner:** `CultMeshDiscoveryService` owns current candidate observations,
|
||||
freshness, source failures, positive/negative expiry, and shared in-flight
|
||||
lookup work for a stable identity plus constraints.
|
||||
|
||||
**Inputs:** `ICultMeshLookupSource` observations, injected clock, optional
|
||||
`ICultMeshDiscoveryStore`, query identity/Verse constraints, and caller-local
|
||||
cancellation.
|
||||
|
||||
**Outputs:** watchable `CultMeshDiscoveryState` projections with fresh,
|
||||
degraded, stale, or unavailable status; persisted
|
||||
`gamecult.mesh.discovery_state.v1` last-known-good documents; typed diagnostic
|
||||
events.
|
||||
|
||||
**Derived state:** failed-source lists, retry-after time, candidate ordering,
|
||||
and legacy `CultMeshVerseCatalog` contents. The catalog is no longer a lookup
|
||||
writer.
|
||||
|
||||
**Forbidden writers:** lookup sources cannot replace the candidate set, caller
|
||||
cancellation cannot cancel shared lookup work, and rejected observations cannot
|
||||
override accepted candidates.
|
||||
|
||||
**Shared paths:** direct service callers and compatibility `DiscoverAsync`
|
||||
both use concurrent source lookup and the same freshness merge. Compatibility
|
||||
projects the service result into the old catalog only after resolution.
|
||||
|
||||
**Cut line:** sequential fail-fast endpoint lookup and per-response catalog
|
||||
mutation have been removed from Verse discovery. Physical endpoint lookup
|
||||
remains available only as a compatibility source observation.
|
||||
|
||||
**State transition:** restart loads the typed CultCache discovery document.
|
||||
Expired candidates remain inspectable as stale; unavailable results retain a
|
||||
bounded negative expiry before sources are queried again.
|
||||
|
||||
**Compatibility inventory:** `AetheriaRuntimeVerseDiscovery` remains the only
|
||||
known caller of `DiscoverAsync(catalog, endpoints)`. It receives the service
|
||||
projection now and should migrate to watching `CultMeshDiscoveryState` during
|
||||
the Phase 2 Aetheria session migration.
|
||||
|
||||
**Rollback:** revert the service, store document, and compatibility delegation
|
||||
as one unit. Do not run sequential catalog mutation alongside service-owned
|
||||
resolution.
|
||||
|
||||
**Proof:** Mesh tests cover concurrent good/dead sources, shared in-flight work,
|
||||
caller-local cancellation, negative expiry, signed precedence, stale-on-error,
|
||||
public state watches, and CultCache restart reconstruction. Networking tests
|
||||
prove the compatibility method retains a good concurrent source.
|
||||
|
||||
## Phase 2: Long-Lived Sessions
|
||||
|
||||
### Cut first
|
||||
|
|
@ -303,6 +481,101 @@ transient outage, or hand-assemble snapshot options from physical topology.
|
|||
unsupported-path result.
|
||||
- The legacy request path cannot open a second competing session.
|
||||
|
||||
### Phase 2 Body Map
|
||||
|
||||
**Owner:** `CultMeshSessionManager` owns physical path selection, replacement,
|
||||
and reconnect. A live document or collection binding owns only its logical
|
||||
subscription intent and readiness promise.
|
||||
|
||||
**Inputs:** stable endpoint and protocol identity, discovery candidates,
|
||||
connector results, session state transitions, typed schema and record filters,
|
||||
and client disposal.
|
||||
|
||||
**Outputs:** one reusable logical session, subscription replay on each new
|
||||
online physical incarnation, cache-backed typed handles, and readiness after
|
||||
the first successful snapshot from any incarnation.
|
||||
|
||||
**Derived state:** physical client identity and generation, attempt count,
|
||||
cached snapshots, and online/reconnecting/offline projections. The session
|
||||
increments the generation only after replacing its physical channel. A binding
|
||||
may coalesce duplicate subscription attempts within that generation, but a
|
||||
pending request from an older generation cannot suppress replay. No individual
|
||||
request owns the logical handle. Within one healthy generation, an unanswered
|
||||
subscribe request expires on the client policy deadline and the binding
|
||||
replays the same idempotent subscription intent; the caller does not own this
|
||||
retry loop.
|
||||
|
||||
**Forbidden writers:** bindings and schema clients cannot choose endpoints,
|
||||
replace channels, reconnect, or declare session state. An abandoned initial
|
||||
subscribe request cannot block a replacement request from satisfying logical
|
||||
readiness.
|
||||
|
||||
**Shared paths:** initial open and reconnect both use session-manager path
|
||||
resolution. Document and collection activation both replay the same binding
|
||||
intent once per physical generation when the logical session returns online.
|
||||
|
||||
**Cut line:** the initial subscribe no longer runs before reconnect observation,
|
||||
and a per-binding semaphore no longer lets an unanswered physical request hold
|
||||
all later replay attempts. Bindings become client-owned resources before
|
||||
waiting for readiness, so disposal terminates pending opens.
|
||||
|
||||
**Verification layer:** Mesh tests lose the first document and collection
|
||||
snapshot, fail the physical client, and prove the replacement snapshot opens
|
||||
the same logical handle exactly once. A disposal test proves a pending open
|
||||
cannot survive its owning client. Another test drops a subscription response
|
||||
without dropping the physical path and proves the same binding becomes ready
|
||||
after bounded replay. The Aetheria/EveUnity witness proves provider
|
||||
discovery, live SoA state, commands, receipts, and assets through the migrated
|
||||
session path.
|
||||
|
||||
### Phase 2 TypeScript provider-lifecycle slice
|
||||
|
||||
**Owner:** `CultMeshProviderSession` owns one TypeScript provider's discovery
|
||||
registration, lease renewal, physical reconnect, desired typed publication
|
||||
replay, command dispatch, receipt publication, and explicit withdrawal. It is
|
||||
keyed by provider, service-instance, endpoint, and Verse identity; those
|
||||
identities are never collapsed.
|
||||
|
||||
**Inputs:** an injected `CultMeshProviderTransport`, stable provider identity,
|
||||
lease/reconnect policy, desired typed publications, domain command handlers, a
|
||||
required durable receipt store, and an injected scheduler.
|
||||
|
||||
**Outputs:** watchable connecting/active/reconnecting/withdrawing/stopped
|
||||
state, current lease evidence, ordered document publication, a durable typed
|
||||
receipt outbox, and withdrawal of the lease plus remaining publications.
|
||||
|
||||
**Derived state:** reconnect attempt, backoff, current physical connection, and
|
||||
the in-flight duplicate-command set. Pending receipt delivery is derived from
|
||||
the durable receipt store, not volatile session memory. Provider state, Eve surface semantics,
|
||||
command effects, endpoint discovery evidence, and body-producer identity are
|
||||
not derived by the session.
|
||||
|
||||
**Forbidden writers:** renderers, HTML exporters, and scheduled projection
|
||||
scripts may not register providers, renew leases, reconnect, publish receipts,
|
||||
or withdraw provider state. A transport connection cannot mutate provider
|
||||
domain state or treat successful delivery as authorization.
|
||||
|
||||
**Shared paths:** initial connect and reconnect both register, subscribe, and
|
||||
replay the same desired publication set. Live publication updates use one
|
||||
serialized lane, so an older update cannot arrive after a newer one. Duplicate
|
||||
command deliveries share one in-flight transaction and later deliveries reuse
|
||||
the durable receipt. A receipt is stored before publication and marked only
|
||||
after acceptance; reconnect drains pending receipts before command intake.
|
||||
|
||||
**Cut line:** TypeScript one-shot RUDP publication helpers remain low-level
|
||||
compatibility surfaces, not provider lifecycle owners. VoidBot's swarm renderer
|
||||
is the first identified obsolete owner; its provider catalog mutation,
|
||||
publication, reconnect, and receipt paths must be deleted when it adopts this
|
||||
session. That consumer migration is still open and must not run both owners.
|
||||
|
||||
**Verification layer:** deterministic TypeScript tests prove initial
|
||||
registration, renewal, stable publication order, reconnect and replay,
|
||||
duplicate receipt reuse, explicit withdrawal, and the negative stop-during-
|
||||
registration timeline, durable receipt replay, observer isolation, conflicting
|
||||
command IDs, and exception-safe shutdown. The empty-consumer tarball smoke proves the session is
|
||||
present in the installable `cultmesh-ts` package. A live Odin transport adapter
|
||||
and the VoidBot migration remain required for the production proof.
|
||||
|
||||
## Phase 3: Authority as a Mandatory Boundary
|
||||
|
||||
### Cut first
|
||||
|
|
@ -328,6 +601,197 @@ transient outage, or hand-assemble snapshot options from physical topology.
|
|||
|
||||
## Phase 4: Verified Content Transfer
|
||||
|
||||
### Phase 4 first-slice body map
|
||||
|
||||
**Owner:** `CultMeshContentTransferService` owns verified partial state and the
|
||||
only promotion path into the completed content cache. Work is serialized and
|
||||
shared by normalized content hash; provider identity is never part of content
|
||||
identity or the destination name.
|
||||
|
||||
**Inputs:** a validated CDN manifest, ordered `ICultMeshContentProvider`
|
||||
observations, a typed CultCache checkpoint store, a canonical cache directory,
|
||||
and caller cancellation.
|
||||
|
||||
**Outputs:** a complete read-only-by-convention body path named by SHA-256, or
|
||||
a failure with no completed body. `gamecult.mesh.content_transfer_state.v1`
|
||||
records verified chunk indexes keyed by content hash.
|
||||
|
||||
**Derived state:** missing chunks, provider failover order, deterministic
|
||||
partial-file path, manifest fingerprint, and completed cache path. A provider
|
||||
success is evidence only for the returned chunk; it does not confer publisher
|
||||
authority.
|
||||
|
||||
**Forbidden writers:** callers, renderers, providers, manifests, and the legacy
|
||||
async CDN reader cannot publish a final body or mark a range verified. CultCache
|
||||
checkpoint claims are rehashed against the partial body before reuse.
|
||||
|
||||
**Shared paths:** direct transfers and the legacy distributed-database reader
|
||||
both pass through the same chunk verification, full-hash verification, and
|
||||
atomic promotion primitive. Concurrent requests for one hash share the same
|
||||
per-content transfer lock and verified work.
|
||||
|
||||
**Cut line:** the legacy distributed reader no longer owns a sequential chunk
|
||||
loop or whole-artifact allocation. The transfer owner now opens a bounded
|
||||
per-content request window while preserving one ordered writer/checkpointer.
|
||||
Adaptive scheduling, quotas, pinning, signer policy, arbitrary streaming
|
||||
destinations, and cleanup scheduling remain later Phase 4 work.
|
||||
|
||||
**State transition:** each verified chunk flushes a typed checkpoint. Restart
|
||||
rehydrates that record, rehashes every claimed range, and fetches corrupt or
|
||||
unclaimed chunks again. Completion verifies the entire partial file, atomically
|
||||
promotes it, and removes the checkpoint. Cancellation leaves only re-verifiable
|
||||
partial state.
|
||||
|
||||
**Verification layer:** focused tests cover durable cancellation/restart,
|
||||
provider corruption and failover, forged checkpoint rejection, final-hash
|
||||
failure, atomic visibility, concurrent request coalescing, bounded concurrent
|
||||
fetch, ordered checkpointing under out-of-order completion, and observation of
|
||||
the whole request window after an early failure. Existing CDN tests cover the
|
||||
compatibility reader.
|
||||
|
||||
### Phase 4 managed content-session slice
|
||||
|
||||
**Owner:** `CultMeshContentTransferService` still owns verification, resumable
|
||||
state, provider failover, and atomic promotion. `CultMeshSessionContentProvider`
|
||||
owns only one bounded request/response projection over a reusable
|
||||
`cultmesh.content.v1` session; `CultMeshContentServer` owns only serving
|
||||
canonical content-addressed chunks from provider storage.
|
||||
|
||||
**Inputs:** stable provider endpoint identity, the shared session manager, a
|
||||
validated manifest chunk reference, provider CultCache content, response
|
||||
deadline, and caller cancellation.
|
||||
|
||||
**Outputs:** one manifest-bound chunk response to the transfer service. The
|
||||
session manager retains connection/reconnect/path authority, and the transfer
|
||||
service decides whether the response becomes verified partial state.
|
||||
|
||||
**Derived state:** request correlation identities and content-session physical
|
||||
channels. Neither is content identity, authority evidence, or cache truth.
|
||||
|
||||
**Forbidden writers:** snapshot servers cannot embed artifact payloads in raw
|
||||
document responses; the session provider cannot write partial/final files,
|
||||
mark ranges verified, choose a replacement endpoint, or authorize a producer.
|
||||
|
||||
**Shared paths:** every cold network chunk enters the same incremental and
|
||||
final verification path used by database and test providers. Concurrent chunks
|
||||
borrow the same logical content session.
|
||||
|
||||
**Cut line:** bulk CDN bytes no longer require
|
||||
`CultNetSnapshotResponseRawMessage` records. Snapshots retain manifests and
|
||||
descriptors; the managed content protocol carries bounded payload responses.
|
||||
|
||||
**Verification layer:** Mesh tests transfer a multi-chunk body through one
|
||||
managed session, assert zero snapshot requests, assert warm committed reuse
|
||||
without another network request, and round-trip both wire messages through the
|
||||
schema dispatcher. RUDP schema hosts and managed clients distinguish transport
|
||||
progress from dispatched messages and drain bounded available work without
|
||||
idle sleeps. Wire sends cooperatively yield after each 32-packet acknowledgement
|
||||
window without sleeping for a Windows scheduler quantum; a real UDP
|
||||
content-session test transfers a four-chunk, one-megabyte request window through
|
||||
the public transfer owner within its ten-second regression bound.
|
||||
The released EveUnity/Aetheria `cold-start-lowering` run now promotes the
|
||||
46,412,384-byte bundle to its exact SHA-256 `.body` under the unchanged
|
||||
300-second deadline with no partial left behind. It starts with zero bodies,
|
||||
lowers the provider-owned world after promotion, and proves pilot/map camera
|
||||
separation. The separate `full-session-gameplay` profile starts a fresh warm
|
||||
daemon session and proves combat, destruction-created canonical loot, Ymir
|
||||
contact collection, and exactly-once cargo mutation. This split is deliberate:
|
||||
cold download latency does not own the lifetime of transient gameplay objects.
|
||||
Content-session delivery and product lifecycle are proven without claiming a
|
||||
mapped/zero-copy transfer; the managed session still copies and fragments the
|
||||
body in process.
|
||||
|
||||
### Phase 4 transport parity and body-plane cut
|
||||
|
||||
**Owner:** CultMesh negotiation selects a body transport from provider-owned
|
||||
capabilities and consumer demand. The selected transport owns byte movement;
|
||||
`CultMeshContentTransferService` continues to own content identity, resumable
|
||||
verification, and atomic cache promotion. TCP owns remote immutable content;
|
||||
CultNet RUDP does not own bulk-body performance.
|
||||
|
||||
**Inputs:** content hash and size, provider-advertised transport candidates,
|
||||
consumer-supported transports, same-machine evidence, and platform support.
|
||||
|
||||
**Outputs:** an authorized mapped body for same-machine deployments, or a
|
||||
dedicated TCP byte stream feeding the existing verification/promotion owner.
|
||||
Schemas, commands, receipts, and manifests use framed TCP CultNet messages.
|
||||
Realtime state uses a separately negotiated QUIC stream or datagram and is not
|
||||
smuggled through either snapshots or the immutable-content stream.
|
||||
|
||||
**Derived state:** selected plane, physical endpoint, mapped-file descriptor,
|
||||
stream progress, and transport telemetry. None can change content identity,
|
||||
provider authority, or the final verified cache record.
|
||||
|
||||
**Forbidden writers:** applications and renderers cannot choose an unadvertised
|
||||
path or turn a local filesystem path into authority. Snapshot and schema-message
|
||||
helpers cannot regain ownership of immutable body bytes. A remote stream cannot
|
||||
publish a completed body without the transfer owner's hash verification and
|
||||
atomic promotion.
|
||||
|
||||
**Shared paths:** every remote plane terminates in the same partial-file,
|
||||
checkpoint, final-hash, and promotion primitives. Same-machine mapping uses the
|
||||
same advertised content hash and provider authorization but does not copy the
|
||||
body merely to prove that two processes inhabit one machine.
|
||||
|
||||
**Cut line:** request-window and scheduler-yield tuning is not the bulk-content
|
||||
roadmap. RUDP remains a compatibility fallback while dedicated stream and local
|
||||
mapping planes are integrated. The old fallback stays unable to become the
|
||||
preferred same-machine or remote bulk plane through timing tweaks.
|
||||
|
||||
**Parity evidence:** `tools/GameCult.TransportParity` measures the public
|
||||
CultMesh RUDP content path against file mapping, TCP, and .NET's MsQuic-backed
|
||||
QUIC stream with the Aetheria 56,204,750-byte body size. On the 2026-07-19
|
||||
Windows development host, a representative released-source run opened the
|
||||
existing mapped body in 10.9 ms, moved and verified it over TCP in 213.8 ms
|
||||
(250.7 MiB/s), moved and verified it over QUIC in 753.4 ms (71.1 MiB/s), and
|
||||
moved it through CultMesh RUDP in 5,322.9 ms (10.1 MiB/s) while emitting
|
||||
129,241,066 server bytes. Repeated QUIC runs reached 87.0-107.4 MiB/s; repeated
|
||||
RUDP runs reached 10.1-13.0 MiB/s. This is a plane-selection result, not a case
|
||||
for a more elaborate home-grown congestion controller.
|
||||
|
||||
**Dedicated references:** .NET's stable `System.Net.Quic` API delegates to
|
||||
MsQuic on supported platforms:
|
||||
https://learn.microsoft.com/dotnet/fundamentals/networking/quic/quic-overview.
|
||||
MsQuic publishes its performance methodology and dashboard at
|
||||
https://microsoft.github.io/msquic/. Valve GameNetworkingSockets remains a
|
||||
candidate for the cross-platform realtime message plane because it provides
|
||||
reliable/unreliable messages, acknowledgement vectors, fragmentation,
|
||||
congestion behavior, encryption, and priority lanes:
|
||||
https://github.com/ValveSoftware/GameNetworkingSockets.
|
||||
|
||||
### Phase 5 verified CDN mapped-body slice
|
||||
|
||||
**Owner:** `CultMeshContentTransferService` remains the sole writer and promoter
|
||||
of completed CDN bodies. `CultMeshVerifiedBodyMappingBroker` owns only ephemeral,
|
||||
opaque capability-to-file grants for those completed bodies. Body negotiation
|
||||
and producer authorization remain owned by `CultMeshBodyTransportService`.
|
||||
|
||||
**Inputs:** the atomically committed `<sha256>.body` path returned by transfer,
|
||||
the equivalent network body descriptor, and a bounded lease.
|
||||
|
||||
**Outputs:** a read-only file-mapping descriptor for the same logical generation.
|
||||
Multiple consumers map the same completed cache file and therefore share the OS
|
||||
page cache; no process-sized byte array or republished body file is created.
|
||||
`CultMeshMappedContent` binds that descriptor to the exact final path returned
|
||||
by the transfer owner, so runtime lowerers never reconstruct cache layout.
|
||||
|
||||
**Derived state:** opaque capability tokens and their expiry. Tokens are neither
|
||||
content hashes nor paths and do not confer producer authority or content trust.
|
||||
|
||||
**Forbidden writers:** the mapping broker and adapter cannot create, promote,
|
||||
rename, repair, or map partial/checkpoint files. `CultMeshMappedBodyPublisher`
|
||||
is not used for verified CDN content.
|
||||
|
||||
**Shared paths:** local and network descriptors preserve body identity,
|
||||
schema/layout, capacity, producer epoch, sequence, and byte size. Local open
|
||||
failure is observed by body negotiation and falls back to that network
|
||||
representation.
|
||||
|
||||
**Cut line:** there is no second CDN publication path. Mapping is granted only
|
||||
after the transfer owner returns its verified final file. The compatibility
|
||||
descriptor-only method delegates to the path-and-descriptor result rather than
|
||||
repeating transfer or cache-path policy.
|
||||
|
||||
### Cut first
|
||||
|
||||
- Delete the first consumer-owned CDN chunk loop and partial-file convention.
|
||||
|
|
@ -356,7 +820,331 @@ transient outage, or hand-assemble snapshot options from physical topology.
|
|||
state.
|
||||
- The old renderer-owned downloader can no longer write the final cache entry.
|
||||
|
||||
## Phase 5: Distributed Stream Control
|
||||
## Phase 5: Negotiated Zero-Copy Data Plane
|
||||
|
||||
CultNet/CultMesh remains the control plane for identity, discovery, schemas,
|
||||
capabilities, leases, epochs, liveness, receipts, and body-transport
|
||||
negotiation. The existing network representation remains the remote path and
|
||||
the fallback whenever local negotiation, handle transfer, schema validation,
|
||||
or lease validation fails.
|
||||
|
||||
### Cut first
|
||||
|
||||
- Stop embedding process-local mapping names, process IDs, virtual addresses,
|
||||
or native handles in logical body identity.
|
||||
- Stop local body adapters from interpreting transport access as producer
|
||||
authority or content validity.
|
||||
- Do not create a general shared-memory message bus for reactive documents,
|
||||
commands, advertisements, or receipts.
|
||||
|
||||
### Body contract
|
||||
|
||||
Define one typed shared-body descriptor containing:
|
||||
|
||||
- logical body identity
|
||||
- schema identity and layout version
|
||||
- byte size and logical capacity
|
||||
- producer epoch and body sequence
|
||||
- access mode
|
||||
- synchronization method
|
||||
- lease expiry
|
||||
- transport kind
|
||||
- an opaque OS-handle capability token when negotiated locally
|
||||
|
||||
The capability token is scoped, expiring transport material. It is never
|
||||
serialized as durable identity. The same descriptor semantics must bind a
|
||||
local shared-memory body and its remote network representation.
|
||||
|
||||
### Build order
|
||||
|
||||
1. Define the transport-neutral typed body descriptor, lease, adapter ports,
|
||||
and validation rules.
|
||||
2. Negotiate shared-memory capability and exchange OS handles through an
|
||||
authenticated platform adapter; retain network fallback.
|
||||
3. Map immutable CultMesh CDN artifacts as content-addressed, file-backed,
|
||||
read-only bodies keyed by verified hash so processes share OS page cache.
|
||||
4. Map fixed-capacity, schema-versioned SoA frame regions using triple
|
||||
buffering or an epoch/sequence protocol. Consumers receive read-only views,
|
||||
detect stale epochs, and never receive raw pointers.
|
||||
5. Add local/remote equivalence, fallback, reconnect, crash, corruption, and
|
||||
conformance tests.
|
||||
6. Profile copy volume, latency, memory pressure, page-cache reuse, frame
|
||||
drops, and lease contention under real EveUnity/Aetheria workloads.
|
||||
7. Decide from measurements whether ordinary local control traffic merits a
|
||||
separate shared-memory lane. Do not build that lane as part of this phase.
|
||||
|
||||
### Frame-region authority
|
||||
|
||||
**Owner:** `CultMeshFrameRegion` is the sole owner of one fixed-capacity,
|
||||
schema/layout-versioned, producer-epoch-bound triple buffer. It owns slot
|
||||
storage, write reservations, reader protection, publication metadata, latest
|
||||
generation selection, sequence advancement, and contention statistics.
|
||||
|
||||
**Inputs:** logical body identity, schema identity, layout version, logical
|
||||
capacity, producer epoch, slot byte length, frame bytes, and commit metadata.
|
||||
The bounded producer contract permits at most one outstanding write reservation
|
||||
for the region, so sequence assignment and slot reservation cannot diverge.
|
||||
|
||||
**Outputs:** bounded write leases, immutable generation descriptors, read-only
|
||||
consumer leases, and owner-derived statistics. Publication installs bytes and
|
||||
metadata as one locked commit and advances sequence exactly once.
|
||||
|
||||
**Derived state:** `CultMeshSharedMemoryFrameRing` handles and statistics are
|
||||
compatibility projections of region generations. Capability tokens remain
|
||||
transport material and do not participate in frame identity or generation
|
||||
validation.
|
||||
|
||||
**Forbidden writers:** the compatibility ring has no slot buffers, cursors,
|
||||
reader counts, latest-slot state, frame-handle catalog, sequence counter, or
|
||||
independent commit path.
|
||||
|
||||
**Shared paths:** direct SoA writes, compatibility zero-copy writes, and
|
||||
compatibility copy publication all reserve and commit through
|
||||
`CultMeshFrameRegion`. Direct and compatibility reads acquire the same owner
|
||||
lease and release the same reader count.
|
||||
|
||||
**Cut line:** the former ring-owned arrays and counters are removed. A frame
|
||||
region always has exactly three slots; construction with another slot count is
|
||||
rejected rather than creating a second buffering model.
|
||||
|
||||
### Required invariants
|
||||
|
||||
- Only an explicitly authorized producer may publish or advance a body.
|
||||
- Consumers are read-only unless a distinct contract explicitly grants write
|
||||
authority.
|
||||
- Producer or broker death invalidates leases without requiring cooperative
|
||||
cleanup from the dead process.
|
||||
- A producer cannot overwrite a slot while any valid consumer lease protects
|
||||
it.
|
||||
- Schema/layout, producer epoch, and sequence mismatches are rejected before
|
||||
bytes are interpreted.
|
||||
- Reconnect creates a new validated lease and cannot reinterpret stale mapped
|
||||
memory from an earlier producer epoch.
|
||||
- Content hash integrity remains distinct from publisher identity and
|
||||
authority.
|
||||
- Negotiation failure is observable and falls back to the network body without
|
||||
changing logical body identity.
|
||||
|
||||
### Phase 5 local/remote conformance slice
|
||||
|
||||
**Owner:** `CultMeshBodyTransportService` owns representation selection for one
|
||||
validated logical generation. Each transport adapter owns only acquisition and
|
||||
pre-interpretation validation of its representation. Producer authorization is
|
||||
an independent input to negotiation; a valid digest never grants authority.
|
||||
|
||||
**Inputs:** equivalent local and network descriptors, the consumer's expected
|
||||
body identity/schema/layout/capacity/epoch/sequence, an authorized-producer
|
||||
decision, registered transport adapters, and network bytes carrying the
|
||||
descriptor-bound semantic digest.
|
||||
|
||||
**Outputs:** one read-only lease for the selected representation plus a typed
|
||||
negotiation result that records the selected transport and any rejected local
|
||||
attempt. Local and network leases expose the same logical descriptor fields and
|
||||
semantic bytes.
|
||||
|
||||
**Derived state:** local preference, adapter availability, and fallback reason
|
||||
are negotiation state only. Capability tokens and network fetch details remain
|
||||
transport material and cannot alter logical body identity.
|
||||
|
||||
**Invariants:** both descriptors must agree on body identity, schema, layout,
|
||||
byte size, capacity, producer epoch, sequence, synchronization, access mode,
|
||||
and semantic digest before either representation is opened. Lease expiry is
|
||||
representation lifetime, validated independently for each descriptor; it is
|
||||
not logical generation identity because a local broker may issue a shorter
|
||||
capability lease than the network representation.
|
||||
Expected schema, layout, capacity, epoch, and sequence are validated before a
|
||||
network fetch. Fetched network bytes are digest-verified before a lease is
|
||||
created or any typed read is possible. Digest integrity does not authorize the
|
||||
publisher.
|
||||
|
||||
**Forbidden writers:** adapters, fallback handling, capability material,
|
||||
network payloads, and integrity checks cannot rewrite logical identity or grant
|
||||
producer authority. A failed local adapter cannot repair, mutate, or reinterpret
|
||||
the network descriptor.
|
||||
|
||||
**Shared paths:** successful local open and network fallback use the same
|
||||
logical-generation equivalence check and consumer validation request. Direct
|
||||
network consumption uses the same pre-interpretation descriptor and digest
|
||||
validation as fallback consumption.
|
||||
|
||||
**Cut line:** replace exception-only fallback reporting with a typed negotiation
|
||||
result while retaining the existing overload as a delegating compatibility
|
||||
surface. Add only descriptor-bound semantic integrity; do not add a shared-memory
|
||||
control bus, content-authority inference, reconnect policy, or profiling hooks.
|
||||
|
||||
**Verification layer:** conformance tests compare descriptor semantics and full
|
||||
bytes across file mapping, shared memory where supported, direct network, and
|
||||
network fallback. Negative tests prove stale schema/epoch/sequence are rejected
|
||||
before fetch, corrupt network bytes never produce a lease, local failure is
|
||||
reported, fallback preserves identity, and authorization is evaluated separately
|
||||
from content integrity.
|
||||
|
||||
### Phase 5 exact-demand body map
|
||||
|
||||
**Owner:** `CultMeshBodyDemandTracker` owns the live derivation from retained,
|
||||
exact database subscriptions to the transport representations a producer must
|
||||
publish. The provider owns body contents. A body adapter owns only access to
|
||||
one representation. A renderer owns none of those decisions.
|
||||
|
||||
**Inputs:** consumer runtime identity, exact logical body IDs, advertised
|
||||
consumer transport capabilities, and server-observed peer locality. A
|
||||
same-machine claim selects shared memory only when the transport peer is
|
||||
actually loopback and the consumer explicitly supports shared memory. When
|
||||
named shared memory is unavailable but the consumer can map files, the same
|
||||
locality proof selects shared-file mapping before network.
|
||||
|
||||
**Outputs:** a per-body plan requiring shared memory, network, both, or no
|
||||
publication. Producers use that plan before allocating, copying, hashing, or
|
||||
packaging a representation.
|
||||
|
||||
**Derived state:** transport preference and publication work are notification
|
||||
state derived from active subscriptions. Heavy database snapshots remain
|
||||
bootstrap/recovery state. They are not a frame delivery mechanism.
|
||||
|
||||
**Forbidden writers:** providers cannot infer demand from renderer identity;
|
||||
renderers cannot choose a provider-specific plane; CDN publication cannot run
|
||||
unconditionally beside a local mapped write; body descriptors cannot create
|
||||
stream demand merely by existing.
|
||||
|
||||
**Shared paths:** subscribe, resubscribe, replacement, explicit unsubscribe,
|
||||
and server disposal all update the same typed demand projection. Stable peer
|
||||
identity, not per-message wrapper identity, keys subscription lifetime.
|
||||
|
||||
Exact reactive document demand carries the requested record and schema set even
|
||||
when no hot body is involved. Providers may use that demand to materialize
|
||||
computed documents lazily; the subscription watch exists before activation is
|
||||
reported, so frame zero is delivered on the live path. Dynamic state is not
|
||||
forced back through a broad snapshot merely because the record did not exist at
|
||||
subscribe time.
|
||||
|
||||
The client installs the declared delivery mode before sending the subscription.
|
||||
A provider may publish synchronously from demand activation, so a live change
|
||||
can correctly precede the empty bootstrap acknowledgement without briefly
|
||||
becoming durable replica state.
|
||||
|
||||
`CultMesh.SubscribeLiveBodyAsync(...)` is the narrow public construction path.
|
||||
Its `CultMeshLiveBodySubscription` names only the logical body, consumer, and
|
||||
subscription lifetime. `CultMeshLiveBody` owns the ephemeral latest-publication
|
||||
value and opens the current generation through the fastest valid representation
|
||||
the resolver can actually import. Layout and other small state are independent
|
||||
exact reactive values, so changing one variable does not redeliver an unrelated
|
||||
view document or body. A subscription may predate frame zero: absence is an
|
||||
uninitialized live value, not a failed subscription, and demand remains active
|
||||
until the first descriptor arrives.
|
||||
|
||||
`CultMesh.SubscribeHotBodyAsync(...)` remains the grouped compatibility path. Its
|
||||
`CultMeshHotBodySubscription` keeps the exact view record, the body's stable
|
||||
latest-publication record, consumer identity, and logical body demand in one
|
||||
contract. The local `CultMeshBodyTransportService` contributes only adapters it
|
||||
can actually open, ordered shared-memory first; the server combines those
|
||||
capabilities with observed peer locality. Applications do not hand-assemble
|
||||
transport-name arrays or request one snapshot per frame. Hot-body subscriptions
|
||||
default to `Live`: their exact initial metadata is decoded for bootstrap, then
|
||||
subsequent layout/publication changes remain ephemeral notifications. Durable
|
||||
cache replication is an explicit opt-in for consumers that actually own a
|
||||
replica requirement.
|
||||
|
||||
### Reactive document delivery body map
|
||||
|
||||
**Owner:** the subscription declaration owns whether a selected typed document
|
||||
is durable replica state or an ephemeral live value. The provider still owns
|
||||
the value; the transport and renderer own neither its persistence nor meaning.
|
||||
|
||||
**Inputs:** exact record/schema filters and an explicit
|
||||
`CultNetDatabaseSubscriptionDeliveryMode`. `ReplicateToCache` materializes
|
||||
bootstrap and durable state before notification. `Live` validates and decodes
|
||||
the same typed payload, then notifies the subscriber without a replica write.
|
||||
High-rate body subscriptions select `Live` by default; general database
|
||||
subscriptions retain the durable default because CultMesh cannot infer their
|
||||
ownership contract.
|
||||
|
||||
**Outputs:** both modes produce the same typed initial values and change event.
|
||||
Only durable replication mutates the consumer's CultCache.
|
||||
|
||||
`CultNetDatabaseSubscriptionClient.SubscribeLiveValueAsync<T>(...)` is the
|
||||
single-record ergonomic path. Its `CultNetLiveValue<T>` owns the exact
|
||||
record/schema filter, current value, typed change/removal notifications, and
|
||||
unsubscribe lifetime. Consumers no longer need a process-wide change handler,
|
||||
an object type switch, or a renderer-local replica cache to model one reactive
|
||||
variable. The value may start absent and become initialized on its first matching
|
||||
change without resubscribing.
|
||||
|
||||
**Derived state:** renderer-local presentation and reactive variables are
|
||||
derived from live notifications. They are not database records merely because
|
||||
CultNet carried them.
|
||||
|
||||
**Forbidden writers:** renderers and products cannot add polling, keepalive
|
||||
writes, or broad snapshots to repair callback latency. Ephemeral receipts,
|
||||
input facts, and frame-layout notifications cannot silently become disk-backed
|
||||
replica history.
|
||||
|
||||
**Shared paths:** exact subscription filters, wire schema validation,
|
||||
deserialization, unsubscribe, disconnect cleanup, and body-demand negotiation
|
||||
are identical in both modes. Only the final materialization decision differs.
|
||||
|
||||
**Cut line:** `CultNetDatabaseSubscriptionClient` no longer requires every
|
||||
received document to complete a CultCache write before the consumer may see it.
|
||||
Durable documents retain the existing replica path; live values bypass it.
|
||||
|
||||
**Cut line:** local frame publication writes directly into a mapped write lease
|
||||
and commits its descriptor. The compatibility byte-array publisher is copy-in
|
||||
only. The current remote frame representation may still use the verified CDN
|
||||
body path when remote demand exists; Phase 6 must replace that expiry-sensitive
|
||||
traffic with a stream/datagram body plane rather than enlarging snapshot or CDN
|
||||
timeouts.
|
||||
|
||||
### RUDP session mutation body map
|
||||
|
||||
**Owner:** each socket transport binding serializes access to its own RUDP
|
||||
reliability session. The server owns one serialization gate per peer; a client
|
||||
connection owns one gate for its session.
|
||||
|
||||
**Inputs:** concurrent typed publication, command and receipt sends, inbound
|
||||
ACK/data processing, handshake state, timeout checks, and resend polling.
|
||||
|
||||
**Outputs:** one coherent packet sequence and fragment stream per peer, with
|
||||
reliable-packet bookkeeping updated in the same critical section as packet
|
||||
creation and transmission.
|
||||
|
||||
**Derived state:** schema messages, database subscriptions, and Eve reactive
|
||||
variables are consumers of the reliable control plane. They do not own packet
|
||||
ordering and must not serialize their own publication loops.
|
||||
|
||||
**Forbidden writers:** daemon schedulers, renderers, and provider sessions
|
||||
cannot mutate `CultNetRudpSession` directly or add retries, replacement
|
||||
snapshots, and artificial publication delays to compensate for concurrent
|
||||
transport calls.
|
||||
|
||||
**Shared paths:** application send, receive/ACK, resend, connect, disconnect,
|
||||
ping, and timeout inspection all enter through the same per-session gate.
|
||||
Fragments belonging to one logical send are emitted before another thread may
|
||||
allocate sequence numbers for that peer.
|
||||
|
||||
**Cut line:** all socket-backed `CultNetRudpSession` mutation is behind the
|
||||
transport-owned gate. Product code no longer has to choose between concurrent
|
||||
simulation publication and reliable delivery.
|
||||
|
||||
Reliable control messages larger than the RUDP receive mask explicitly
|
||||
acknowledge the packet just received. A retransmit older than the rolling
|
||||
32-packet summary can therefore always leave the sender queue; the rolling mask
|
||||
remains useful for piggyback acknowledgements but is not allowed to strand a
|
||||
fragment indefinitely.
|
||||
|
||||
### Gate
|
||||
|
||||
- Two local consumers map one verified CDN artifact without duplicate process
|
||||
copies and observe identical content identity through the network fallback.
|
||||
- An EveUnity consumer reads successive SoA generations without torn frames,
|
||||
raw pointers, or overwrite of a leased slot.
|
||||
- Producer crash, lease expiry, schema upgrade, epoch rollover, and reconnect
|
||||
all reject stale mappings before interpretation.
|
||||
- A forged handle token, unauthorized producer, writable consumer request, or
|
||||
valid hash from an unauthorized publisher cannot cross its respective
|
||||
authority boundary.
|
||||
- Local and remote conformance packs expose the same typed body lifecycle and
|
||||
semantic payload.
|
||||
|
||||
## Phase 6: Distributed Stream Control
|
||||
|
||||
### Cut first
|
||||
|
||||
|
|
@ -386,7 +1174,7 @@ transient outage, or hand-assemble snapshot options from physical topology.
|
|||
- Local zero-copy and remote fallback paths expose the same stream identity and
|
||||
lifecycle.
|
||||
|
||||
## Phase 6: Consumer Convergence and API Reduction
|
||||
## Phase 7: Consumer Convergence and API Reduction
|
||||
|
||||
Migrate consumers in increasing order of operational risk:
|
||||
|
||||
|
|
@ -422,6 +1210,8 @@ cover:
|
|||
- typed failure reasons
|
||||
- authority decision evidence
|
||||
- content transfer progress and verified ranges
|
||||
- shared-body identity, schema/layout, epoch/sequence, access, lease, and
|
||||
transport negotiation
|
||||
- stream descriptor, publisher epoch, subscription, and gap state
|
||||
|
||||
These are typed CultNet/CultMesh documents. JSON is permitted only for schema
|
||||
|
|
@ -455,6 +1245,8 @@ The migration is complete only when:
|
|||
- one owner supervises connection reuse, reconnect, failover, and path state
|
||||
- peer contact cannot confer authority
|
||||
- CDN consumers request verified content instead of implementing chunk loops
|
||||
- local CDN and SoA consumers negotiate zero-copy bodies without changing
|
||||
logical identity, authority, or remote behavior
|
||||
- stream identity and liveness survive changes in body transport
|
||||
- old discovery, session, transfer, and stream decision paths cannot override
|
||||
the new owners
|
||||
|
|
|
|||
134
src/GameCult.Mesh/docs/transport-planes.md
Normal file
134
src/GameCult.Mesh/docs/transport-planes.md
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
# CultMesh Transport Planes
|
||||
|
||||
CultMesh selects a transport per workload. It does not ask one wire protocol to
|
||||
be equally good at files, realtime state, and same-machine memory access.
|
||||
|
||||
## Authority map
|
||||
|
||||
**Owner:** `CultMeshSessionManager` selects an advertised route through a
|
||||
registered connector for each traffic class. A connector owns only its physical
|
||||
connection and byte movement.
|
||||
|
||||
**Inputs:** stable endpoint identity, advertised physical candidates, connector
|
||||
support and priority, caller cancellation, and locality evidence for body
|
||||
negotiation.
|
||||
|
||||
**Outputs:**
|
||||
|
||||
| Workload | Preferred plane | Contract |
|
||||
| --- | --- | --- |
|
||||
| Schemas, commands, receipts, manifests | TCP | `cultnet+tcp://` through `ICultMeshTransportConnector` |
|
||||
| Immutable chunks and other file-shaped bodies | TCP byte stream | `cultmesh-content+tcp://` through `ICultMeshContentTransportConnector` |
|
||||
| Realtime state | QUIC streams or datagrams | `ICultMeshRealtimeTransportConnector` with an explicit delivery mode |
|
||||
| Same-machine SoA and large bodies | mapped/shared memory | body transport negotiation |
|
||||
|
||||
The TCP content plane sends typed CultNet request and response headers, then
|
||||
streams raw chunk bytes outside the schema envelope. The transfer service owns
|
||||
range hashing, resume checkpoints, provider failover, full-body verification,
|
||||
and atomic promotion regardless of the selected content connector.
|
||||
`CultMeshClient` installs the TCP schema and TCP content connectors by default.
|
||||
Passing explicit connector lists replaces those defaults.
|
||||
|
||||
Realtime frames declare whether they require reliable ordered delivery,
|
||||
latest-only delivery, or unreliable delivery. The optional
|
||||
`GameCult.Mesh.Quic` package provides the .NET 10/MsQuic connector and server.
|
||||
It maps reliable ordered frames to one persistent stream and latest-only frames
|
||||
to independent streams with keyed `(producer epoch, sequence)` pending-state
|
||||
replacement. Its
|
||||
`System.Net.Quic` adapter fails closed for unreliable frames because that API
|
||||
does not expose QUIC datagrams. `GameCult.Mesh.Quic.Native` owns the generic
|
||||
Unity/client boundary through the MsQuic C API. The Unity package carries its
|
||||
managed connector and the pinned Windows x64 Schannel runtime; consumers
|
||||
register `CultMeshNativeQuicRealtimeTransportConnector`, then ask CultMesh for
|
||||
the advertised realtime route. The connector currently receives provider state
|
||||
and fails closed if used to send; commands and receipts remain on the typed TCP
|
||||
control plane. No RUDP implementation is installed implicitly in its place.
|
||||
|
||||
Local mapped bodies remain the first state plane. A consumer opens the
|
||||
advertised mapping when it is actually reachable; otherwise it connects to the
|
||||
advertised QUIC route. Latest-only receivers must replace pending generations
|
||||
per body rather than queueing render debt.
|
||||
|
||||
Provider simulation owns state generation, not socket completion. Latest-only
|
||||
broadcast enqueues into a keyed, coalescing outbox owned by each physical peer
|
||||
and returns without waiting for network delivery. The peer's transport worker
|
||||
owns stream writes and eviction after disconnect or send failure. Thus a slow,
|
||||
stalled, or departed client cannot backpressure a simulation tick, while a
|
||||
healthy peer still converges on the newest generation. Reliable-ordered
|
||||
broadcast remains completion-bearing because dropping or replacing it would
|
||||
violate its declared delivery contract; caller cancellation can stop that
|
||||
operation.
|
||||
|
||||
**Derived state:** connector choice, physical endpoint, connection health, and
|
||||
transport diagnostics. None of these grant provider authority or become content
|
||||
identity.
|
||||
|
||||
**Forbidden writers:** applications and renderers do not choose unadvertised
|
||||
endpoints, implement reconnect loops, or bypass verification. Schema messages
|
||||
must not carry bulk bodies. RUDP/LiteNetLib cannot become an implicit default
|
||||
for any traffic class. QUIC does not own schemas or immutable files merely
|
||||
because it can transport bytes.
|
||||
|
||||
**Shared paths:** discovery and identity resolution remain common. Each traffic
|
||||
class has its own connector set, connection cache, priority tiers, and failure
|
||||
state. All content connectors feed the same transfer and promotion owner.
|
||||
|
||||
**Cut line:** the former RUDP content server is
|
||||
`CultMeshLegacyRudpContentServer`, and its connector must be registered
|
||||
explicitly. It has basement priority and exists for compatibility and parity
|
||||
measurement. The legacy datagram schema connector is likewise explicit and
|
||||
lower priority than TCP. Existing hot-state publishers that still package
|
||||
payloads as schema messages must move to the realtime connector contract; the
|
||||
new seam does not pretend that migration has already occurred.
|
||||
|
||||
## Security and release gate
|
||||
|
||||
The current TCP control and content connectors are plaintext and therefore
|
||||
restricted to local or otherwise trusted deployment. Adding TLS must not move
|
||||
discovery, authorization, content verification, or application semantics into
|
||||
the TCP adapter.
|
||||
|
||||
The QUIC adapter always uses TLS 1.3. Its certificate validation callback is
|
||||
given the advertised endpoint identity so the consumer can bind transport
|
||||
authentication to provider authorization. Test-only trust-all callbacks are not
|
||||
a release configuration. A trusted discovery record may carry
|
||||
`cert-sha256=<fingerprint>` on its QUIC route; absent a caller validator, the
|
||||
connector accepts a self-signed provider certificate only when that pin matches.
|
||||
The native client uses MsQuic's deferred-certificate contract: it completes the
|
||||
pin decision through `ConnectionCertificateValidationComplete` and returns
|
||||
`QUIC_STATUS_PENDING` from the certificate event. Transport failures report the
|
||||
MsQuic status, wire error, loaded runtime path, and pre-connect event sequence.
|
||||
|
||||
## Local parity evidence
|
||||
|
||||
The native suite can also connect to an independently running managed provider
|
||||
by setting `CULTMESH_NATIVE_EXTERNAL_ENDPOINT` to its advertised pinned QUIC
|
||||
route. This keeps the managed server and native client in separate processes,
|
||||
so one process-local MsQuic DLL cannot counterfeit cross-runtime parity.
|
||||
|
||||
On 2026-07-19, the parity harness moved a 13 MiB payload on loopback using
|
||||
1 MiB content chunks. Raw TCP reached 127.4 MiB/s, verified CultMesh TCP content
|
||||
reached 59.0 MiB/s, raw MsQuic reached 51.5 MiB/s, and legacy CultMesh RUDP
|
||||
reached 10.7 MiB/s while emitting 18,112,867 wire bytes. CultMesh TCP includes
|
||||
chunk hashing, durable checkpoints, final hashing, and atomic promotion, so this
|
||||
is not a claim of raw protocol parity. It is a repeatable workload comparison
|
||||
and leaves the remaining framework overhead visible.
|
||||
|
||||
The same harness now has a state-only workload. On 2026-07-19, 1,000 latest-only
|
||||
frames with 16 KiB payloads produced the following loopback result:
|
||||
|
||||
| Plane | Offered rate | Delivered | Highest generation | Settled time |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| CultMesh QUIC latest-only | 23.8 MiB/s | 989 / 1,000 | 999 | 655.4 ms |
|
||||
| CultNet RUDP latest | 45.6 MiB/s | 373 / 1,000 | 516 | 602.7 ms |
|
||||
|
||||
Offered rate measures publisher-side enqueue/write completion, not successful
|
||||
delivery. RUDP accepted bytes faster but failed to deliver the terminal
|
||||
generation after a 250 ms drain; that is a delivery failure, not useful
|
||||
throughput. QUIC's reliable independent streams reached the terminal generation
|
||||
while the receiver coalesced eleven superseded frames. Reproduce the workload
|
||||
with:
|
||||
|
||||
```text
|
||||
dotnet run --project tools/GameCult.TransportParity -- --state-only --state-bytes 16384 --state-frames 1000
|
||||
```
|
||||
|
|
@ -303,6 +303,14 @@ namespace GameCult.Networking
|
|||
RecordKeys = message.RecordKeys
|
||||
}));
|
||||
}
|
||||
else
|
||||
{
|
||||
peer.SendCultNet(new CultNetSnapshotResponseRawMessage
|
||||
{
|
||||
MessageId = message.MessageId,
|
||||
Documents = Array.Empty<CultNetRawDocumentRecord>()
|
||||
});
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,11 +3,21 @@ using System.Collections.Concurrent;
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
/// <summary>Controls whether subscription payloads become replica state or remain ephemeral typed events.</summary>
|
||||
public enum CultNetDatabaseSubscriptionDeliveryMode
|
||||
{
|
||||
/// <summary>Decode each payload and write it into the local CultCache before notifying observers.</summary>
|
||||
ReplicateToCache,
|
||||
/// <summary>Decode each payload and notify observers without writing replica state.</summary>
|
||||
Live
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replicates selected remote database records into a local typed CultCache over one retained session.
|
||||
/// </summary>
|
||||
|
|
@ -16,7 +26,9 @@ namespace GameCult.Networking
|
|||
private readonly ICultNetSchemaClient _client;
|
||||
private readonly CultCache _cache;
|
||||
private readonly CultNetDocumentRegistry _documents;
|
||||
private readonly ConcurrentDictionary<string, TaskCompletionSource<IReadOnlyList<object>>> _initialSnapshots = new();
|
||||
private readonly ConcurrentDictionary<string, PendingSubscription> _initialSnapshots = new();
|
||||
private readonly ConcurrentDictionary<string, CultNetDatabaseSubscriptionDeliveryMode> _deliveryModes =
|
||||
new(StringComparer.Ordinal);
|
||||
private readonly object _queueLock = new();
|
||||
private Task _queue = Task.CompletedTask;
|
||||
private bool _disposed;
|
||||
|
|
@ -39,6 +51,49 @@ namespace GameCult.Networking
|
|||
/// <summary>Gets the local reactive cache receiving replicated documents.</summary>
|
||||
public CultCache Cache => _cache;
|
||||
|
||||
/// <summary>Completes if the retained transport pump terminates with an unrecoverable error.</summary>
|
||||
public Task<Exception>? BackgroundFailure =>
|
||||
(_client as RudpCultNetSchemaClient)?.BackgroundFailure;
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to one exact typed record as an ephemeral reactive value. The returned value
|
||||
/// owns filtering and unsubscribe; no received payload is written into the local cache.
|
||||
/// </summary>
|
||||
public async Task<CultNetLiveValue<TDocument>> SubscribeLiveValueAsync<TDocument>(
|
||||
string subscriptionId,
|
||||
string recordKey,
|
||||
CancellationToken cancellationToken = default)
|
||||
where TDocument : class
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(recordKey))
|
||||
throw new ArgumentException("Record key is required.", nameof(recordKey));
|
||||
var schemaId = _documents.GetByDocumentType(typeof(TDocument))?.SchemaId ??
|
||||
_cache.Registry.GetRequired<TDocument>().SchemaId;
|
||||
var value = new CultNetLiveValue<TDocument>(this, subscriptionId, recordKey);
|
||||
try
|
||||
{
|
||||
var initial = await SubscribeAsync(
|
||||
subscriptionId,
|
||||
recordKeys: new[] { recordKey },
|
||||
schemaIds: new[] { schemaId },
|
||||
deliveryMode: CultNetDatabaseSubscriptionDeliveryMode.Live,
|
||||
cancellationToken: cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var documents = initial.OfType<TDocument>().ToArray();
|
||||
if (documents.Length > 1)
|
||||
throw new InvalidOperationException(
|
||||
$"Live value subscription '{subscriptionId}' expected at most one '{schemaId}' record '{recordKey}' but received {documents.Length}.");
|
||||
if (documents.Length == 1)
|
||||
value.Initialize(documents[0]);
|
||||
return value;
|
||||
}
|
||||
catch
|
||||
{
|
||||
value.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts a remote subscription and waits until its initial matching snapshot is in the local cache.
|
||||
/// </summary>
|
||||
|
|
@ -46,30 +101,63 @@ namespace GameCult.Networking
|
|||
string subscriptionId,
|
||||
IEnumerable<string>? recordKeys = null,
|
||||
IEnumerable<string>? schemaIds = null,
|
||||
bool includeSnapshot = true)
|
||||
bool includeSnapshot = true,
|
||||
CancellationToken cancellationToken = default,
|
||||
string? consumerRuntimeId = null,
|
||||
IEnumerable<string>? bodyIds = null,
|
||||
IEnumerable<string>? supportedBodyTransports = null,
|
||||
CultNetDatabaseSubscriptionDeliveryMode deliveryMode = CultNetDatabaseSubscriptionDeliveryMode.ReplicateToCache)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultNetDatabaseSubscriptionClient));
|
||||
if (!_client.Connected) throw new InvalidOperationException("CultNet schema client must be connected before subscribing.");
|
||||
if (string.IsNullOrWhiteSpace(subscriptionId)) throw new ArgumentException("Subscription id is required.", nameof(subscriptionId));
|
||||
|
||||
var messageId = Guid.NewGuid().ToString("N");
|
||||
TaskCompletionSource<IReadOnlyList<object>>? completion = null;
|
||||
if (includeSnapshot)
|
||||
var completion = new TaskCompletionSource<IReadOnlyList<object>>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
if (!_initialSnapshots.TryAdd(messageId, new PendingSubscription(subscriptionId, deliveryMode, completion)))
|
||||
throw new InvalidOperationException($"Duplicate database subscription message id '{messageId}'.");
|
||||
_deliveryModes[subscriptionId] = deliveryMode;
|
||||
|
||||
CancellationTokenRegistration cancellation = default;
|
||||
if (cancellationToken.CanBeCanceled)
|
||||
{
|
||||
completion = new TaskCompletionSource<IReadOnlyList<object>>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
if (!_initialSnapshots.TryAdd(messageId, completion))
|
||||
throw new InvalidOperationException($"Duplicate database subscription message id '{messageId}'.");
|
||||
cancellation = cancellationToken.Register(() =>
|
||||
{
|
||||
if (_initialSnapshots.TryRemove(messageId, out var pending))
|
||||
pending.Completion.TrySetCanceled(cancellationToken);
|
||||
});
|
||||
_ = completion.Task.ContinueWith(
|
||||
_ => cancellation.Dispose(),
|
||||
CancellationToken.None,
|
||||
TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default);
|
||||
}
|
||||
|
||||
_client.SendCultNet(new CultNetDatabaseSubscribeMessage
|
||||
try
|
||||
{
|
||||
MessageId = messageId,
|
||||
SubscriptionId = subscriptionId,
|
||||
RecordKeys = recordKeys?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray(),
|
||||
SchemaIds = schemaIds?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray(),
|
||||
IncludeSnapshot = includeSnapshot
|
||||
});
|
||||
return completion?.Task ?? Task.FromResult<IReadOnlyList<object>>(Array.Empty<object>());
|
||||
_client.SendCultNet(new CultNetDatabaseSubscribeMessage
|
||||
{
|
||||
MessageId = messageId,
|
||||
SubscriptionId = subscriptionId,
|
||||
RecordKeys = recordKeys?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray(),
|
||||
SchemaIds = schemaIds?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray(),
|
||||
IncludeSnapshot = includeSnapshot,
|
||||
ConsumerRuntimeId = consumerRuntimeId,
|
||||
BodyIds = bodyIds?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray(),
|
||||
SupportedBodyTransports = supportedBodyTransports?
|
||||
.Where(value => !string.IsNullOrWhiteSpace(value))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray()
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
_deliveryModes.TryRemove(subscriptionId, out _);
|
||||
if (_initialSnapshots.TryRemove(messageId, out var pending))
|
||||
pending.Completion.TrySetException(new InvalidOperationException("CultNet subscription request could not be sent."));
|
||||
throw;
|
||||
}
|
||||
return completion.Task;
|
||||
}
|
||||
|
||||
/// <summary>Stops one live remote subscription.</summary>
|
||||
|
|
@ -77,6 +165,7 @@ namespace GameCult.Networking
|
|||
{
|
||||
if (_disposed) return;
|
||||
if (string.IsNullOrWhiteSpace(subscriptionId)) throw new ArgumentException("Subscription id is required.", nameof(subscriptionId));
|
||||
_deliveryModes.TryRemove(subscriptionId, out _);
|
||||
_client.SendCultNet(new CultNetDatabaseUnsubscribeMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
|
|
@ -88,9 +177,10 @@ namespace GameCult.Networking
|
|||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
foreach (var completion in _initialSnapshots.Values)
|
||||
completion.TrySetException(new ObjectDisposedException(nameof(CultNetDatabaseSubscriptionClient)));
|
||||
foreach (var pending in _initialSnapshots.Values)
|
||||
pending.Completion.TrySetException(new ObjectDisposedException(nameof(CultNetDatabaseSubscriptionClient)));
|
||||
_initialSnapshots.Clear();
|
||||
_deliveryModes.Clear();
|
||||
_client.Dispose();
|
||||
}
|
||||
|
||||
|
|
@ -98,15 +188,23 @@ namespace GameCult.Networking
|
|||
{
|
||||
Enqueue(async () =>
|
||||
{
|
||||
if (!_initialSnapshots.TryRemove(message.MessageId, out var completion)) return;
|
||||
if (!_initialSnapshots.TryRemove(message.MessageId, out var pending)) return;
|
||||
try
|
||||
{
|
||||
var applied = await _documents.ApplyRawSnapshotResponseAsync(_cache, message).ConfigureAwait(false);
|
||||
completion.TrySetResult(applied);
|
||||
IReadOnlyList<object> applied;
|
||||
if (pending.DeliveryMode == CultNetDatabaseSubscriptionDeliveryMode.Live)
|
||||
{
|
||||
applied = message.Documents.Select(_documents.DeserializeRawDocument).ToArray();
|
||||
}
|
||||
else
|
||||
{
|
||||
applied = await _documents.ApplyRawSnapshotResponseAsync(_cache, message).ConfigureAwait(false);
|
||||
}
|
||||
pending.Completion.TrySetResult(applied);
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
completion.TrySetException(error);
|
||||
pending.Completion.TrySetException(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -115,9 +213,13 @@ namespace GameCult.Networking
|
|||
{
|
||||
Enqueue(async () =>
|
||||
{
|
||||
var deliveryMode = _deliveryModes.TryGetValue(message.SubscriptionId, out var configured)
|
||||
? configured
|
||||
: CultNetDatabaseSubscriptionDeliveryMode.ReplicateToCache;
|
||||
if (string.Equals(message.ChangeKind, "removed", StringComparison.Ordinal))
|
||||
{
|
||||
await DeleteAsync(message).ConfigureAwait(false);
|
||||
if (deliveryMode == CultNetDatabaseSubscriptionDeliveryMode.ReplicateToCache)
|
||||
await DeleteAsync(message).ConfigureAwait(false);
|
||||
Changed?.Invoke(new CultNetReplicatedDocumentChange(
|
||||
message.SubscriptionId,
|
||||
"removed",
|
||||
|
|
@ -128,13 +230,15 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
if (message.Document == null) return;
|
||||
var document = await _documents.ApplyRawDocumentPutMessageAsync(
|
||||
_cache,
|
||||
new CultNetDocumentPutRawMessage
|
||||
{
|
||||
MessageId = message.MessageId,
|
||||
Document = message.Document
|
||||
}).ConfigureAwait(false);
|
||||
var document = deliveryMode == CultNetDatabaseSubscriptionDeliveryMode.Live
|
||||
? _documents.DeserializeRawDocument(message.Document)
|
||||
: await _documents.ApplyRawDocumentPutMessageAsync(
|
||||
_cache,
|
||||
new CultNetDocumentPutRawMessage
|
||||
{
|
||||
MessageId = message.MessageId,
|
||||
Document = message.Document
|
||||
}).ConfigureAwait(false);
|
||||
Changed?.Invoke(new CultNetReplicatedDocumentChange(
|
||||
message.SubscriptionId,
|
||||
message.ChangeKind,
|
||||
|
|
@ -167,6 +271,123 @@ namespace GameCult.Networking
|
|||
TaskScheduler.Default).Unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class PendingSubscription
|
||||
{
|
||||
public PendingSubscription(
|
||||
string subscriptionId,
|
||||
CultNetDatabaseSubscriptionDeliveryMode deliveryMode,
|
||||
TaskCompletionSource<IReadOnlyList<object>> completion)
|
||||
{
|
||||
SubscriptionId = subscriptionId;
|
||||
DeliveryMode = deliveryMode;
|
||||
Completion = completion;
|
||||
}
|
||||
|
||||
public string SubscriptionId { get; }
|
||||
public CultNetDatabaseSubscriptionDeliveryMode DeliveryMode { get; }
|
||||
public TaskCompletionSource<IReadOnlyList<object>> Completion { get; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One exact typed remote record kept as an ephemeral current value.</summary>
|
||||
public sealed class CultNetLiveValue<TDocument> : IDisposable where TDocument : class
|
||||
{
|
||||
private readonly CultNetDatabaseSubscriptionClient _owner;
|
||||
private readonly string _subscriptionId;
|
||||
private readonly string _recordKey;
|
||||
private readonly object _gate = new();
|
||||
private TDocument? _current;
|
||||
private bool _hasValue;
|
||||
private bool _disposed;
|
||||
|
||||
internal CultNetLiveValue(
|
||||
CultNetDatabaseSubscriptionClient owner,
|
||||
string subscriptionId,
|
||||
string recordKey)
|
||||
{
|
||||
_owner = owner ?? throw new ArgumentNullException(nameof(owner));
|
||||
_subscriptionId = string.IsNullOrWhiteSpace(subscriptionId)
|
||||
? throw new ArgumentException("Subscription id is required.", nameof(subscriptionId))
|
||||
: subscriptionId;
|
||||
_recordKey = recordKey;
|
||||
_owner.Changed += OnChanged;
|
||||
}
|
||||
|
||||
/// <summary>Raised when the provider publishes a new typed value.</summary>
|
||||
public event Action<TDocument>? Changed;
|
||||
|
||||
/// <summary>Raised when the provider removes the selected record.</summary>
|
||||
public event Action? Removed;
|
||||
|
||||
/// <summary>Gets whether the selected record currently exists.</summary>
|
||||
public bool HasValue
|
||||
{
|
||||
get { lock (_gate) return _hasValue; }
|
||||
}
|
||||
|
||||
/// <summary>Gets the current value, or fails when the record has not been published.</summary>
|
||||
public TDocument Current
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
return _hasValue
|
||||
? _current!
|
||||
: throw new InvalidOperationException(
|
||||
$"Live value '{_recordKey}' is not currently published.");
|
||||
}
|
||||
}
|
||||
|
||||
internal void Initialize(TDocument document)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || _hasValue) return;
|
||||
_current = document;
|
||||
_hasValue = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
}
|
||||
_owner.Changed -= OnChanged;
|
||||
_owner.Unsubscribe(_subscriptionId);
|
||||
}
|
||||
|
||||
private void OnChanged(CultNetReplicatedDocumentChange change)
|
||||
{
|
||||
if (!string.Equals(change.SubscriptionId, _subscriptionId, StringComparison.Ordinal) ||
|
||||
!string.Equals(change.RecordKey, _recordKey, StringComparison.Ordinal))
|
||||
return;
|
||||
|
||||
if (string.Equals(change.ChangeKind, "removed", StringComparison.Ordinal))
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_current = null;
|
||||
_hasValue = false;
|
||||
}
|
||||
Removed?.Invoke();
|
||||
return;
|
||||
}
|
||||
|
||||
if (change.Document is not TDocument document)
|
||||
return;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_current = document;
|
||||
_hasValue = true;
|
||||
}
|
||||
Changed?.Invoke(document);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Describes one typed document change after local replication.</summary>
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ using System.Collections.Generic;
|
|||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using R3;
|
||||
|
|
@ -19,8 +20,11 @@ namespace GameCult.Networking
|
|||
private readonly CultNetDatabase _database;
|
||||
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, Task> _subscribe;
|
||||
private readonly Func<CultNetDatabaseUnsubscribeMessage, ICultNetSchemaServerPeer, Task> _unsubscribe;
|
||||
private readonly ICultNetSchemaServerPeerLifecycle? _peerLifecycle;
|
||||
private readonly ConcurrentDictionary<SubscriptionKey, IDisposable> _subscriptions =
|
||||
new ConcurrentDictionary<SubscriptionKey, IDisposable>(SubscriptionKeyComparer.Instance);
|
||||
private readonly ConcurrentDictionary<SubscriptionKey, CultNetDatabaseSubscribeMessage> _requests =
|
||||
new ConcurrentDictionary<SubscriptionKey, CultNetDatabaseSubscribeMessage>(SubscriptionKeyComparer.Instance);
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Attaches live database subscription handlers to a schema server.</summary>
|
||||
|
|
@ -32,8 +36,18 @@ namespace GameCult.Networking
|
|||
_unsubscribe = HandleUnsubscribeAsync;
|
||||
_server.OnCultNet(_subscribe);
|
||||
_server.OnCultNet(_unsubscribe);
|
||||
_peerLifecycle = server as ICultNetSchemaServerPeerLifecycle;
|
||||
if (_peerLifecycle != null)
|
||||
_peerLifecycle.PeerDisconnected += HandlePeerDisconnected;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised when an exact subscription is activated or withdrawn. Providers can use
|
||||
/// the requested records and schemas to materialize reactive state only while a
|
||||
/// consumer needs it; body publishers additionally use the negotiated body route.
|
||||
/// </summary>
|
||||
public event Action<CultNetDatabaseSubscriptionDemand>? DemandChanged;
|
||||
|
||||
/// <summary>Detaches handlers and releases all active watches.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
|
|
@ -41,8 +55,28 @@ namespace GameCult.Networking
|
|||
_disposed = true;
|
||||
_server.RemoveCultNetMessageListener<CultNetDatabaseSubscribeMessage>(_subscribe);
|
||||
_server.RemoveCultNetMessageListener<CultNetDatabaseUnsubscribeMessage>(_unsubscribe);
|
||||
foreach (var subscription in _subscriptions.Values) subscription.Dispose();
|
||||
if (_peerLifecycle != null)
|
||||
_peerLifecycle.PeerDisconnected -= HandlePeerDisconnected;
|
||||
foreach (var entry in _subscriptions)
|
||||
{
|
||||
entry.Value.Dispose();
|
||||
if (_requests.TryRemove(entry.Key, out var request))
|
||||
PublishDemand(request, entry.Key, active: false);
|
||||
}
|
||||
_subscriptions.Clear();
|
||||
_requests.Clear();
|
||||
}
|
||||
|
||||
private void HandlePeerDisconnected(ICultNetSchemaServerPeer peer)
|
||||
{
|
||||
foreach (var key in _subscriptions.Keys.Where(candidate =>
|
||||
SubscriptionKeyComparer.SamePeer(candidate.Peer, peer)).ToArray())
|
||||
{
|
||||
if (_subscriptions.TryRemove(key, out var subscription))
|
||||
subscription.Dispose();
|
||||
if (_requests.TryRemove(key, out var request))
|
||||
PublishDemand(request, key, active: false);
|
||||
}
|
||||
}
|
||||
|
||||
private Task HandleSubscribeAsync(CultNetDatabaseSubscribeMessage request, ICultNetSchemaServerPeer peer)
|
||||
|
|
@ -57,6 +91,8 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
var key = new SubscriptionKey(peer, subscriptionId);
|
||||
if (_requests.TryGetValue(key, out var previous))
|
||||
PublishDemand(previous, key, active: false);
|
||||
_subscriptions.AddOrUpdate(
|
||||
key,
|
||||
_ => Watch(request, subscriptionId, peer),
|
||||
|
|
@ -65,6 +101,8 @@ namespace GameCult.Networking
|
|||
current.Dispose();
|
||||
return Watch(request, subscriptionId, peer);
|
||||
});
|
||||
_requests[key] = request;
|
||||
PublishDemand(request, key, active: true);
|
||||
if (request.IncludeSnapshot)
|
||||
{
|
||||
peer.SendCultNet(_database.Documents.CreateRawSnapshotResponse(
|
||||
|
|
@ -77,6 +115,14 @@ namespace GameCult.Networking
|
|||
RecordKeys = request.RecordKeys
|
||||
}));
|
||||
}
|
||||
else
|
||||
{
|
||||
peer.SendCultNet(new CultNetSnapshotResponseRawMessage
|
||||
{
|
||||
MessageId = request.MessageId,
|
||||
Documents = Array.Empty<CultNetRawDocumentRecord>()
|
||||
});
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
|
|
@ -85,12 +131,51 @@ namespace GameCult.Networking
|
|||
var subscriptionId = string.IsNullOrWhiteSpace(request.SubscriptionId)
|
||||
? request.MessageId
|
||||
: request.SubscriptionId;
|
||||
if (!string.IsNullOrWhiteSpace(subscriptionId) &&
|
||||
_subscriptions.TryRemove(new SubscriptionKey(peer, subscriptionId), out var subscription))
|
||||
subscription.Dispose();
|
||||
if (!string.IsNullOrWhiteSpace(subscriptionId))
|
||||
{
|
||||
var key = new SubscriptionKey(peer, subscriptionId);
|
||||
if (_subscriptions.TryRemove(key, out var subscription)) subscription.Dispose();
|
||||
if (_requests.TryRemove(key, out var subscribed))
|
||||
PublishDemand(subscribed, key, active: false);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void PublishDemand(
|
||||
CultNetDatabaseSubscribeMessage request,
|
||||
SubscriptionKey key,
|
||||
bool active)
|
||||
{
|
||||
DemandChanged?.Invoke(new CultNetDatabaseSubscriptionDemand(
|
||||
string.IsNullOrWhiteSpace(request.ConsumerRuntimeId) ? key.Id : request.ConsumerRuntimeId!,
|
||||
key.Id,
|
||||
(request.RecordKeys ?? Array.Empty<string>())
|
||||
.Where(value => !string.IsNullOrWhiteSpace(value))
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray(),
|
||||
(request.SchemaIds ?? Array.Empty<string>())
|
||||
.Where(value => !string.IsNullOrWhiteSpace(value))
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray(),
|
||||
(request.BodyIds ?? Array.Empty<string>())
|
||||
.Where(value => !string.IsNullOrWhiteSpace(value))
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray(),
|
||||
(request.SupportedBodyTransports ?? Array.Empty<string>())
|
||||
.Where(value => !string.IsNullOrWhiteSpace(value))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray(),
|
||||
IsSameMachine(key.Peer),
|
||||
active));
|
||||
}
|
||||
|
||||
private static bool IsSameMachine(ICultNetSchemaServerPeer peer)
|
||||
{
|
||||
if (peer is ICultNetSchemaServerPeerLocation located && located.RemoteEndPoint is IPEndPoint ip)
|
||||
return IPAddress.IsLoopback(ip.Address);
|
||||
return false;
|
||||
}
|
||||
|
||||
private IDisposable Watch(
|
||||
CultNetDatabaseSubscribeMessage request,
|
||||
string subscriptionId,
|
||||
|
|
@ -110,16 +195,17 @@ namespace GameCult.Networking
|
|||
{
|
||||
var changeType = change.GetType();
|
||||
var key = (CultRecordKey)(changeType.GetProperty("Key")?.GetValue(change) ?? new CultRecordKey(""));
|
||||
var schemaId = (string?)changeType.GetProperty("SchemaId")?.GetValue(change) ?? "";
|
||||
if (request.RecordKeys is { Length: > 0 } && !request.RecordKeys.Contains(key.Value, StringComparer.Ordinal))
|
||||
return null;
|
||||
if (request.SchemaIds is { Length: > 0 } && !request.SchemaIds.Contains(schemaId, StringComparer.Ordinal))
|
||||
return null;
|
||||
|
||||
var kind = (CultNetDatabaseChangeKind)(changeType.GetProperty("Kind")?.GetValue(change) ?? CultNetDatabaseChangeKind.Updated);
|
||||
var document = changeType.GetProperty("Document")?.GetValue(change);
|
||||
if (kind == CultNetDatabaseChangeKind.Removed || document == null)
|
||||
{
|
||||
var previous = changeType.GetProperty("PreviousDocument")?.GetValue(change);
|
||||
var schemaId = ResolveWireSchemaId(previous, (string?)changeType.GetProperty("SchemaId")?.GetValue(change) ?? "");
|
||||
if (!MatchesRequestedSchema(request.SchemaIds, previous, schemaId))
|
||||
return null;
|
||||
return new CultNetDatabaseChangeRawMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
|
|
@ -130,15 +216,33 @@ namespace GameCult.Networking
|
|||
};
|
||||
}
|
||||
|
||||
var raw = CreateRawRecord(key, document);
|
||||
if (!MatchesRequestedSchema(request.SchemaIds, document, raw.SchemaId))
|
||||
return null;
|
||||
return new CultNetDatabaseChangeRawMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
SubscriptionId = subscriptionId,
|
||||
ChangeKind = kind == CultNetDatabaseChangeKind.Added ? "added" : "updated",
|
||||
Document = CreateRawRecord(key, document)
|
||||
Document = raw
|
||||
};
|
||||
}
|
||||
|
||||
private string ResolveWireSchemaId(object? document, string fallback)
|
||||
{
|
||||
if (document == null) return fallback;
|
||||
return _database.Documents.GetByDocumentType(document.GetType())?.SchemaId ?? fallback;
|
||||
}
|
||||
|
||||
private bool MatchesRequestedSchema(string[]? requestedSchemaIds, object? document, string wireSchemaId)
|
||||
{
|
||||
if (requestedSchemaIds is not { Length: > 0 }) return true;
|
||||
if (requestedSchemaIds.Contains(wireSchemaId, StringComparer.Ordinal)) return true;
|
||||
return document != null && CultNetSchemaAliasMatching.MatchesAny(
|
||||
requestedSchemaIds,
|
||||
_database.Cache.Registry.GetRequired(document.GetType()));
|
||||
}
|
||||
|
||||
private CultNetRawDocumentRecord CreateRawRecord(CultRecordKey key, object document)
|
||||
{
|
||||
var method = typeof(CultNetDocumentRegistry)
|
||||
|
|
@ -169,9 +273,80 @@ namespace GameCult.Networking
|
|||
{
|
||||
public static SubscriptionKeyComparer Instance { get; } = new SubscriptionKeyComparer();
|
||||
public bool Equals(SubscriptionKey? x, SubscriptionKey? y) =>
|
||||
x != null && y != null && ReferenceEquals(x.Peer, y.Peer) && string.Equals(x.Id, y.Id, StringComparison.Ordinal);
|
||||
x != null && y != null && SamePeer(x.Peer, y.Peer) && string.Equals(x.Id, y.Id, StringComparison.Ordinal);
|
||||
public int GetHashCode(SubscriptionKey value) =>
|
||||
(RuntimeHelpers.GetHashCode(value.Peer) * 397) ^ StringComparer.Ordinal.GetHashCode(value.Id);
|
||||
(PeerHash(value.Peer) * 397) ^ StringComparer.Ordinal.GetHashCode(value.Id);
|
||||
|
||||
internal static bool SamePeer(ICultNetSchemaServerPeer left, ICultNetSchemaServerPeer right)
|
||||
{
|
||||
if (ReferenceEquals(left, right)) return true;
|
||||
if (left is RudpCultNetSchemaServerPeer leftRudp && right is RudpCultNetSchemaServerPeer rightRudp)
|
||||
return ReferenceEquals(leftRudp.TransportPeer, rightRudp.TransportPeer);
|
||||
if (left is CultNetServerPeer leftLite && right is CultNetServerPeer rightLite)
|
||||
return ReferenceEquals(leftLite.Peer, rightLite.Peer);
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int PeerHash(ICultNetSchemaServerPeer peer)
|
||||
{
|
||||
if (peer is RudpCultNetSchemaServerPeer rudp)
|
||||
return RuntimeHelpers.GetHashCode(rudp.TransportPeer);
|
||||
if (peer is CultNetServerPeer lite)
|
||||
return RuntimeHelpers.GetHashCode(lite.Peer);
|
||||
return RuntimeHelpers.GetHashCode(peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One active or withdrawn exact state subscription and its optional hot-body route.</summary>
|
||||
public sealed class CultNetDatabaseSubscriptionDemand
|
||||
{
|
||||
public CultNetDatabaseSubscriptionDemand(
|
||||
string consumerRuntimeId,
|
||||
string subscriptionId,
|
||||
IReadOnlyList<string> bodyIds,
|
||||
IReadOnlyList<string> supportedBodyTransports,
|
||||
bool sameMachine,
|
||||
bool active)
|
||||
: this(
|
||||
consumerRuntimeId,
|
||||
subscriptionId,
|
||||
Array.Empty<string>(),
|
||||
Array.Empty<string>(),
|
||||
bodyIds,
|
||||
supportedBodyTransports,
|
||||
sameMachine,
|
||||
active)
|
||||
{
|
||||
}
|
||||
|
||||
public CultNetDatabaseSubscriptionDemand(
|
||||
string consumerRuntimeId,
|
||||
string subscriptionId,
|
||||
IReadOnlyList<string> recordKeys,
|
||||
IReadOnlyList<string> schemaIds,
|
||||
IReadOnlyList<string> bodyIds,
|
||||
IReadOnlyList<string> supportedBodyTransports,
|
||||
bool sameMachine,
|
||||
bool active)
|
||||
{
|
||||
ConsumerRuntimeId = consumerRuntimeId;
|
||||
SubscriptionId = subscriptionId;
|
||||
RecordKeys = recordKeys;
|
||||
SchemaIds = schemaIds;
|
||||
BodyIds = bodyIds;
|
||||
SupportedBodyTransports = supportedBodyTransports;
|
||||
SameMachine = sameMachine;
|
||||
Active = active;
|
||||
}
|
||||
|
||||
public string ConsumerRuntimeId { get; }
|
||||
public string SubscriptionId { get; }
|
||||
public IReadOnlyList<string> RecordKeys { get; }
|
||||
public IReadOnlyList<string> SchemaIds { get; }
|
||||
public IReadOnlyList<string> BodyIds { get; }
|
||||
public IReadOnlyList<string> SupportedBodyTransports { get; }
|
||||
public bool SameMachine { get; }
|
||||
public bool Active { get; }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -352,17 +352,8 @@ namespace GameCult.Networking
|
|||
throw new ArgumentException("CultNet raw document message is missing its document payload.", nameof(message));
|
||||
}
|
||||
|
||||
ValidateRawDocumentRecord(message.Document);
|
||||
var binding = GetBySchemaId(message.Document.SchemaId);
|
||||
var descriptor = binding != null
|
||||
? _documents.GetRequired(binding.DocumentType)
|
||||
: ResolveDescriptorForRawDocument(message.Document);
|
||||
binding ??= new CultNetDocumentBinding(
|
||||
descriptor.DocumentType,
|
||||
descriptor.SchemaId,
|
||||
value => CultDocumentMessagePackSerialization.SerializeUntyped(value, value.GetType()),
|
||||
payload => CultDocumentMessagePackSerialization.DeserializeUntyped(descriptor.DocumentType, payload));
|
||||
var document = binding.PayloadDeserializer(message.Document.Payload);
|
||||
var document = DeserializeRawDocument(message.Document);
|
||||
var descriptor = ResolveDescriptorForRawDocument(message.Document);
|
||||
|
||||
var addMethod = typeof(CultCache).GetMethod(nameof(CultCache.AddAsync))!
|
||||
.MakeGenericMethod(descriptor.DocumentType);
|
||||
|
|
@ -373,6 +364,26 @@ namespace GameCult.Networking
|
|||
return document;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes one validated raw document without materializing it in a CultCache replica.
|
||||
/// Use this for ephemeral reactive subscriptions whose callback is the consumer.
|
||||
/// </summary>
|
||||
public object DeserializeRawDocument(CultNetRawDocumentRecord document)
|
||||
{
|
||||
if (document == null) throw new ArgumentNullException(nameof(document));
|
||||
ValidateRawDocumentRecord(document);
|
||||
var binding = GetBySchemaId(document.SchemaId);
|
||||
var descriptor = binding != null
|
||||
? _documents.GetRequired(binding.DocumentType)
|
||||
: ResolveDescriptorForRawDocument(document);
|
||||
binding ??= new CultNetDocumentBinding(
|
||||
descriptor.DocumentType,
|
||||
descriptor.SchemaId,
|
||||
value => CultDocumentMessagePackSerialization.SerializeUntyped(value, value.GetType()),
|
||||
payload => CultDocumentMessagePackSerialization.DeserializeUntyped(descriptor.DocumentType, payload));
|
||||
return binding.PayloadDeserializer(document.Payload);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a raw document put message and returns the typed document.
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
|
|
@ -130,12 +131,28 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
options ??= new CultNetHostOptions();
|
||||
var traceStartup = string.Equals(
|
||||
Environment.GetEnvironmentVariable("CULTMESH_TRACE_STARTUP_PHASES"),
|
||||
"1",
|
||||
StringComparison.Ordinal);
|
||||
var startupPhase = Stopwatch.StartNew();
|
||||
void Trace(string phase)
|
||||
{
|
||||
if (traceStartup)
|
||||
Console.WriteLine($"CultMesh local-host phase {phase} took {startupPhase.Elapsed.TotalMilliseconds:0.###}ms.");
|
||||
startupPhase.Restart();
|
||||
}
|
||||
|
||||
var cache = await CultCacheMessagePack.OpenAsync(cachePath, options.CacheOptions).ConfigureAwait(false);
|
||||
Trace("cache-open");
|
||||
var store = cache.BackingStores.OfType<SingleFileMessagePackBackingStore>().FirstOrDefault();
|
||||
var server = new Server(cache, options.Security ?? ServerSecurityOptions.Development());
|
||||
Trace("server");
|
||||
var databaseOptions = options.DatabaseOptions ?? new CultNetDatabaseOptions();
|
||||
var database = new CultNetDatabase(cache, databaseOptions);
|
||||
Trace("database");
|
||||
var databaseServer = new CultNetDatabaseServer(server, database, options.DatabaseServerOptions);
|
||||
Trace("database-server");
|
||||
options.ConfigureServer?.Invoke(server);
|
||||
|
||||
var host = new CultNetHost(cache, store, server, database, databaseServer);
|
||||
|
|
@ -143,6 +160,7 @@ namespace GameCult.Networking
|
|||
{
|
||||
host.Start();
|
||||
}
|
||||
Trace("server-start");
|
||||
|
||||
return host;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,23 @@ using System.Threading.Tasks;
|
|||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
/// <summary>
|
||||
/// Result of a bounded non-blocking RUDP schema-server drain.
|
||||
/// </summary>
|
||||
public readonly struct RudpCultNetSchemaPollResult
|
||||
{
|
||||
public RudpCultNetSchemaPollResult(int transportItemsConsumed, int messagesDispatched)
|
||||
{
|
||||
TransportItemsConsumed = transportItemsConsumed;
|
||||
MessagesDispatched = messagesDispatched;
|
||||
}
|
||||
|
||||
/// <summary>Gets transport work consumed, including ACK and connection control packets.</summary>
|
||||
public int TransportItemsConsumed { get; }
|
||||
/// <summary>Gets application schema messages dispatched.</summary>
|
||||
public int MessagesDispatched { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Options for hosting schema-v0 messages over the native CultNet RUDP listener.
|
||||
/// </summary>
|
||||
|
|
@ -53,7 +70,7 @@ namespace GameCult.Networking
|
|||
/// <summary>
|
||||
/// Peer context for a schema-v0 RUDP server.
|
||||
/// </summary>
|
||||
public sealed class RudpCultNetSchemaServerPeer : ICultNetSchemaServerPeer
|
||||
public sealed class RudpCultNetSchemaServerPeer : ICultNetSchemaServerPeer, ICultNetSchemaServerPeerLocation
|
||||
{
|
||||
private readonly RudpCultNetSchemaServer _server;
|
||||
|
||||
|
|
@ -87,7 +104,7 @@ namespace GameCult.Networking
|
|||
/// <summary>
|
||||
/// Multi-peer schema-v0 host over the native CultNet RUDP transport.
|
||||
/// </summary>
|
||||
public sealed class RudpCultNetSchemaServer : ICultNetSchemaServer, IDisposable
|
||||
public sealed class RudpCultNetSchemaServer : ICultNetSchemaServer, ICultNetSchemaServerPeerLifecycle, IDisposable
|
||||
{
|
||||
private readonly Socket _socket;
|
||||
private readonly CultNetRudpSocketTransportServer _transport;
|
||||
|
|
@ -121,6 +138,7 @@ namespace GameCult.Networking
|
|||
MaxPendingReliablePackets = options.MaxPendingReliablePackets,
|
||||
AcceptPayload = options.AcceptPayload
|
||||
});
|
||||
_transport.PeerDisconnected += OnTransportPeerDisconnected;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -143,6 +161,9 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public IReadOnlyCollection<CultNetRudpSocketServerPeer> Peers => _transport.Peers;
|
||||
|
||||
/// <inheritdoc />
|
||||
public event Action<ICultNetSchemaServerPeer>? PeerDisconnected;
|
||||
|
||||
/// <summary>
|
||||
/// Registers a schema-v0 handler.
|
||||
/// </summary>
|
||||
|
|
@ -223,12 +244,37 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public async Task<bool> PollOnceAsync()
|
||||
{
|
||||
var delivered = _transport.ReceiveOnce();
|
||||
if (delivered == null || !string.Equals(delivered.Frame.ChannelId, "schema", StringComparison.Ordinal))
|
||||
if (!_transport.TryReceiveOnce(out var delivered) || delivered == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return await DispatchAsync(delivered).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drains up to <paramref name="maxTransportItems"/> immediately available transport work items.
|
||||
/// Control packets count as progress so callers only idle when the transport is actually empty.
|
||||
/// </summary>
|
||||
public async Task<RudpCultNetSchemaPollResult> PollAvailableAsync(int maxTransportItems)
|
||||
{
|
||||
if (maxTransportItems <= 0) throw new ArgumentOutOfRangeException(nameof(maxTransportItems));
|
||||
var consumed = 0;
|
||||
var dispatched = 0;
|
||||
while (consumed < maxTransportItems && _transport.TryReceiveOnce(out var delivered))
|
||||
{
|
||||
consumed++;
|
||||
if (delivered != null && await DispatchAsync(delivered).ConfigureAwait(false))
|
||||
dispatched++;
|
||||
}
|
||||
return new RudpCultNetSchemaPollResult(consumed, dispatched);
|
||||
}
|
||||
|
||||
private async Task<bool> DispatchAsync(CultNetRudpSocketServerFrame delivered)
|
||||
{
|
||||
if (!string.Equals(delivered.Frame.ChannelId, "schema", StringComparison.Ordinal))
|
||||
return false;
|
||||
|
||||
var message = CultNetSchemaMessageSerialization.Deserialize(delivered.Frame.Payload);
|
||||
if (!_handlers.TryGetValue(message.GetType(), out var handler) || handler == null)
|
||||
{
|
||||
|
|
@ -260,7 +306,13 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
_disposed = true;
|
||||
_transport.PeerDisconnected -= OnTransportPeerDisconnected;
|
||||
_transport.Dispose();
|
||||
}
|
||||
|
||||
private void OnTransportPeerDisconnected(CultNetRudpSocketServerPeer peer)
|
||||
{
|
||||
PeerDisconnected?.Invoke(new RudpCultNetSchemaServerPeer(this, peer));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -247,15 +247,16 @@ namespace GameCult.Networking
|
|||
return;
|
||||
}
|
||||
|
||||
var message = transport.ReceiveSchemaMessageOnce();
|
||||
transport.PollResends();
|
||||
|
||||
if (message != null)
|
||||
var consumed = 0;
|
||||
while (consumed < 256 && transport.TryReceiveOnce(out var frame))
|
||||
{
|
||||
Dispatch(message);
|
||||
consumed++;
|
||||
if (frame != null && string.Equals(frame.ChannelId, "schema", StringComparison.Ordinal))
|
||||
Dispatch(CultNetSchemaMessageSerialization.Deserialize(frame.Payload));
|
||||
}
|
||||
|
||||
Thread.Sleep(1);
|
||||
transport.PollResends();
|
||||
if (consumed == 0)
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}
|
||||
catch (ObjectDisposedException) when (_disposed)
|
||||
|
|
@ -317,6 +318,9 @@ namespace GameCult.Networking
|
|||
return new RudpCultNetSchemaClient(runtimeId, connectionId, connectPayload, maxFragmentBytes, resendDelayMs);
|
||||
}
|
||||
|
||||
/// <summary>Creates the length-prefixed TCP schema client.</summary>
|
||||
public static ICultNetSchemaClient CreateTcpFramed() => new TcpFramedCultNetSchemaClient();
|
||||
|
||||
/// <summary>
|
||||
/// Creates the default schema client adapter for an advertised endpoint URI.
|
||||
/// </summary>
|
||||
|
|
@ -340,12 +344,18 @@ namespace GameCult.Networking
|
|||
return CreateRudp();
|
||||
}
|
||||
|
||||
if (string.Equals(uri.Scheme, "cultnet+tcp", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return CreateTcpFramed();
|
||||
}
|
||||
|
||||
if (string.Equals(uri.Scheme, "cultnet", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return CreateLiteNetLib(security, configureClient);
|
||||
}
|
||||
|
||||
throw new FormatException($"CultNet endpoint '{endpoint}' must use cultnet://host:port or rudp://host:port.");
|
||||
throw new FormatException(
|
||||
$"CultNet endpoint '{endpoint}' must use cultnet+tcp://host:port, cultnet://host:port, or rudp://host:port.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -74,6 +74,10 @@ namespace GameCult.Networking
|
|||
CultNetSchemaVersions.VerseCatalogResponse => Deserialize<CultMeshVerseCatalogResponseMessage>(payload),
|
||||
CultNetSchemaVersions.PeerExchangeRequest => Deserialize<CultMeshPeerExchangeRequestMessage>(payload),
|
||||
CultNetSchemaVersions.PeerExchangeResponse => Deserialize<CultMeshPeerExchangeResponseMessage>(payload),
|
||||
CultNetSchemaVersions.ContentChunkRequest => Deserialize<CultMeshContentChunkRequestMessage>(payload),
|
||||
CultNetSchemaVersions.ContentChunkResponse => Deserialize<CultMeshContentChunkResponseMessage>(payload),
|
||||
CultNetSchemaVersions.BodyReadRequest => Deserialize<CultMeshBodyReadRequestMessage>(payload),
|
||||
CultNetSchemaVersions.BodyReadResponse => Deserialize<CultMeshBodyReadResponseMessage>(payload),
|
||||
CultNetSchemaVersions.SchemaCatalogRequest => Deserialize<CultNetSchemaCatalogRequestMessage>(payload),
|
||||
CultNetSchemaVersions.SchemaCatalogResponse => Deserialize<CultNetSchemaCatalogResponseMessage>(payload),
|
||||
_ => throw new MessagePackSerializationException(
|
||||
|
|
|
|||
|
|
@ -143,6 +143,22 @@ namespace GameCult.Networking
|
|||
/// CultMesh peer exchange response contract identifier.
|
||||
/// </summary>
|
||||
public const string PeerExchangeResponse = "cultmesh.peer_exchange_response.v0";
|
||||
/// <summary>
|
||||
/// CultMesh content chunk request contract identifier.
|
||||
/// </summary>
|
||||
public const string ContentChunkRequest = "cultmesh.content_chunk_request.v1";
|
||||
/// <summary>
|
||||
/// CultMesh content chunk response contract identifier.
|
||||
/// </summary>
|
||||
public const string ContentChunkResponse = "cultmesh.content_chunk_response.v1";
|
||||
/// <summary>
|
||||
/// CultMesh ephemeral body read request contract identifier.
|
||||
/// </summary>
|
||||
public const string BodyReadRequest = "cultmesh.body_read_request.v1";
|
||||
/// <summary>
|
||||
/// CultMesh ephemeral body read response contract identifier.
|
||||
/// </summary>
|
||||
public const string BodyReadResponse = "cultmesh.body_read_response.v1";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -779,6 +795,18 @@ namespace GameCult.Networking
|
|||
/// Gets or sets whether the server should send a matching snapshot before live changes.
|
||||
/// </summary>
|
||||
[Key("includeSnapshot")] public bool IncludeSnapshot { get; set; } = true;
|
||||
/// <summary>
|
||||
/// Gets or sets the stable consumer runtime identity used for subscription diagnostics and body-plane demand.
|
||||
/// </summary>
|
||||
[Key("consumerRuntimeId")] public string? ConsumerRuntimeId { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets logical hot-body identities needed by this exact state subscription.
|
||||
/// </summary>
|
||||
[Key("bodyIds")] public string[]? BodyIds { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets body transports the consumer can open, ordered by consumer preference.
|
||||
/// </summary>
|
||||
[Key("supportedBodyTransports")] public string[]? SupportedBodyTransports { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -1303,6 +1331,82 @@ namespace GameCult.Networking
|
|||
[Key("peers")] public CultMeshPeerCardMessage[] Peers { get; set; } = Array.Empty<CultMeshPeerCardMessage>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requests one bounded content-addressed chunk over a managed CultMesh content session.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
public class CultMeshContentChunkRequestMessage : ICultNetSchemaMessage
|
||||
{
|
||||
/// <summary>Gets or sets the wire schema identity.</summary>
|
||||
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.ContentChunkRequest;
|
||||
/// <summary>Gets or sets the request correlation identity.</summary>
|
||||
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the canonical SHA-256 chunk identity.</summary>
|
||||
[Key("chunkHash")] public string ChunkHash { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the optional canonical CultCache record key.</summary>
|
||||
[Key("recordKey")] public string RecordKey { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the manifest-bound expected payload size.</summary>
|
||||
[Key("expectedSizeBytes")] public int ExpectedSizeBytes { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns one bounded content-addressed chunk without publishing it as snapshot state.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
public class CultMeshContentChunkResponseMessage : ICultNetSchemaMessage
|
||||
{
|
||||
/// <summary>Gets or sets the wire schema identity.</summary>
|
||||
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.ContentChunkResponse;
|
||||
/// <summary>Gets or sets the matching request correlation identity.</summary>
|
||||
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets whether a validated chunk is present.</summary>
|
||||
[Key("found")] public bool Found { get; set; }
|
||||
/// <summary>Gets or sets the canonical SHA-256 chunk identity.</summary>
|
||||
[Key("chunkHash")] public string ChunkHash { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the payload byte count.</summary>
|
||||
[Key("sizeBytes")] public int SizeBytes { get; set; }
|
||||
/// <summary>Gets or sets the bounded content payload.</summary>
|
||||
[Key("payload")] public byte[] Payload { get; set; } = Array.Empty<byte>();
|
||||
/// <summary>Gets or sets a typed-boundary failure description when the chunk is unavailable.</summary>
|
||||
[Key("error")] public string Error { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requests one immutable body generation from its capability owner. Body bytes travel on this
|
||||
/// dedicated plane; they are never database snapshot records.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
public class CultMeshBodyReadRequestMessage : ICultNetSchemaMessage
|
||||
{
|
||||
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.BodyReadRequest;
|
||||
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
|
||||
[Key("capabilityToken")] public string CapabilityToken { get; set; } = string.Empty;
|
||||
[Key("bodyId")] public string BodyId { get; set; } = string.Empty;
|
||||
[Key("bodySchemaId")] public string BodySchemaId { get; set; } = string.Empty;
|
||||
[Key("layoutVersion")] public int LayoutVersion { get; set; }
|
||||
[Key("producerEpoch")] public long ProducerEpoch { get; set; }
|
||||
[Key("sequence")] public long Sequence { get; set; }
|
||||
[Key("expectedSizeBytes")] public long ExpectedSizeBytes { get; set; }
|
||||
[Key("semanticHash")] public string SemanticHash { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Returns one bounded immutable body generation directly to its subscriber.</summary>
|
||||
[MessagePackObject]
|
||||
public class CultMeshBodyReadResponseMessage : ICultNetSchemaMessage
|
||||
{
|
||||
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.BodyReadResponse;
|
||||
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
|
||||
[Key("found")] public bool Found { get; set; }
|
||||
[Key("capabilityToken")] public string CapabilityToken { get; set; } = string.Empty;
|
||||
[Key("bodyId")] public string BodyId { get; set; } = string.Empty;
|
||||
[Key("producerEpoch")] public long ProducerEpoch { get; set; }
|
||||
[Key("sequence")] public long Sequence { get; set; }
|
||||
[Key("sizeBytes")] public long SizeBytes { get; set; }
|
||||
[Key("semanticHash")] public string SemanticHash { get; set; } = string.Empty;
|
||||
[Key("payload")] public byte[] Payload { get; set; } = Array.Empty<byte>();
|
||||
[Key("error")] public string Error { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wire representation of a CultMesh peer candidate.
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GameCult.Networking
|
||||
|
|
@ -32,4 +33,22 @@ namespace GameCult.Networking
|
|||
void RemoveCultNetMessageListener<TMessage>(Delegate callback)
|
||||
where TMessage : ICultNetSchemaMessage;
|
||||
}
|
||||
|
||||
/// <summary>Optional physical peer location used for locality-sensitive transport negotiation.</summary>
|
||||
public interface ICultNetSchemaServerPeerLocation
|
||||
{
|
||||
/// <summary>Gets the remote physical endpoint when the transport exposes one.</summary>
|
||||
EndPoint? RemoteEndPoint { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Optional transport-neutral peer lifetime surface for stateful service bridges.
|
||||
/// </summary>
|
||||
public interface ICultNetSchemaServerPeerLifecycle
|
||||
{
|
||||
/// <summary>
|
||||
/// Raised after a peer session is no longer able to receive service output.
|
||||
/// </summary>
|
||||
event Action<ICultNetSchemaServerPeer> PeerDisconnected;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -112,7 +112,8 @@ namespace GameCult.Networking
|
|||
!IsSupportedSchemaEndpointScheme(uri.Scheme) ||
|
||||
string.IsNullOrWhiteSpace(uri.Host))
|
||||
{
|
||||
throw new FormatException($"CultNet endpoint '{endpoint}' must use cultnet://host:port or rudp://host:port.");
|
||||
throw new FormatException(
|
||||
$"CultNet endpoint '{endpoint}' must use cultnet+tcp://host:port, cultnet://host:port, or rudp://host:port.");
|
||||
}
|
||||
|
||||
return (uri.Host, uri.IsDefaultPort ? 3075 : uri.Port);
|
||||
|
|
@ -135,7 +136,8 @@ namespace GameCult.Networking
|
|||
|
||||
private static bool IsSupportedSchemaEndpointScheme(string scheme)
|
||||
{
|
||||
return string.Equals(scheme, "cultnet", StringComparison.OrdinalIgnoreCase) ||
|
||||
return string.Equals(scheme, "cultnet+tcp", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(scheme, "cultnet", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(scheme, "rudp", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue