using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using GameCult.Caching; using GameCult.Caching.MessagePack; using GameCult.Networking; using R3; namespace GameCult.Mesh { /// /// Options for creating a local CultMesh node. /// public sealed class CultMeshNodeOptions { /// /// Gets or sets the cache-open options used for the underlying CultCache. /// public CultCacheOpenOptions? CacheOptions { get; set; } /// /// Gets or sets the server security configuration. When omitted, development defaults are used. /// public ServerSecurityOptions? Security { get; set; } /// /// Gets or sets whether the server should start immediately after creation. /// public bool StartServer { get; set; } = true; /// /// Gets or sets the mesh database sharding options used for the hosted CultCache. /// public CultNetDatabaseOptions? DatabaseOptions { get; set; } /// /// Gets or sets whether CultMesh should attach a file-backed authoritative shard-log store when none is supplied. /// public bool EnableDurableShardLogs { get; set; } /// /// Gets or sets the directory used for file-backed authoritative shard logs. /// public string? ShardLogPath { get; set; } /// /// Gets or sets the database server bridge options used for shard routing and forwarding. /// public CultNetDatabaseServerOptions? DatabaseServerOptions { get; set; } /// /// Gets or sets an optional callback used to customize the server before start. /// public Action? ConfigureServer { get; set; } internal CultNetHostOptions ToCultNetOptions(string cachePath) { return new CultNetHostOptions { CacheOptions = CacheOptions, Security = Security, StartServer = StartServer, DatabaseOptions = CreateDatabaseOptions(cachePath), DatabaseServerOptions = DatabaseServerOptions, ConfigureServer = ConfigureServer }; } private CultNetDatabaseOptions? CreateDatabaseOptions(string cachePath) { if (!EnableDurableShardLogs) { return DatabaseOptions; } var source = DatabaseOptions ?? new CultNetDatabaseOptions(); if (source.MutationLogStore != null) { return source; } return new CultNetDatabaseOptions { RuntimeId = source.RuntimeId, Shards = source.Shards, ClientAuthorityScopes = source.ClientAuthorityScopes, DocumentRegistry = source.DocumentRegistry, MutationLogStore = new CultNetFileShardMutationLogStore(ResolveShardLogPath(cachePath)) }; } private string ResolveShardLogPath(string cachePath) { if (!string.IsNullOrWhiteSpace(ShardLogPath)) { return ShardLogPath!; } var fullPath = Path.GetFullPath(cachePath); var directory = Path.GetDirectoryName(fullPath) ?? Directory.GetCurrentDirectory(); var name = Path.GetFileNameWithoutExtension(fullPath); return Path.Combine(directory, name + ".cultmesh", "shard-logs"); } } /// /// Options for opening one typed document from a remote CultNet snapshot endpoint. /// public sealed class CultMeshPeerSnapshotDocumentOptions { /// Gets or sets the semantic document id. Defaults to the record key. public string? DocumentId { get; set; } /// Gets or sets the source id advertised by diagnostics. Defaults to the record key. public string? SourceId { get; set; } /// Gets or sets the route hint for the resulting handle. public CultMeshRouteHint? RouteHint { get; set; } /// Gets or sets the response timeout for each snapshot request. public TimeSpan ResponseTimeout { get; set; } = TimeSpan.FromSeconds(5); /// Gets or sets the connection timeout for endpoint-created clients. public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(5); /// Gets or sets the polling interval for watch fallback. public TimeSpan PollInterval { get; set; } = TimeSpan.FromMilliseconds(250); /// Gets or sets the message id prefix used for snapshot requests. public string? MessageIdPrefix { get; set; } /// Gets or sets schema ids to request. Empty means the document type schema is requested. public IReadOnlyList? SchemaIds { get; set; } /// Gets or sets the target shard id, when the endpoint is shard-aware. public string? ShardId { get; set; } /// Gets or sets the target shard epoch, when the endpoint is shard-aware. public long? ShardEpoch { get; set; } /// Gets or sets client security options for endpoint-created clients. public ClientSecurityOptions? Security { get; set; } /// Gets or sets a callback used to configure endpoint-created LiteNetLib clients. public Action? ConfigureClient { get; set; } /// Gets or sets the runtime id used by endpoint-created RUDP clients. public string? RudpRuntimeId { get; set; } /// Gets or sets the connection id used by endpoint-created RUDP clients. public uint RudpConnectionId { get; set; } = 0x43554c54; /// Gets or sets the connect payload used by endpoint-created RUDP clients. public string RudpConnectPayload { get; set; } = "cultnet-schema-rudp"; /// Gets or sets the maximum fragment size used by endpoint-created RUDP clients. public int RudpMaxFragmentBytes { get; set; } = 1024; /// Gets or sets the resend delay used by endpoint-created RUDP clients. public long RudpResendDelayMs { get; set; } = 25; } /// /// Options for opening one typed document from a CultCache backing-store publication. /// public sealed class CultMeshStoreDocumentOptions { /// Gets or sets the semantic document id. Defaults to the record key. public string? DocumentId { get; set; } /// Gets or sets the source id advertised by diagnostics. Defaults to the record key. public string? SourceId { get; set; } /// Gets or sets the route hint for the resulting handle. public CultMeshRouteHint? RouteHint { get; set; } /// Gets or sets the polling interval for watch fallback. public TimeSpan PollInterval { get; set; } = TimeSpan.FromMilliseconds(250); /// Gets or sets the document registry used to resolve persisted schema aliases. public CultDocumentRegistry? Registry { get; set; } } /// /// Describes where a typed document publication should be read from. /// public abstract class CultMeshDocumentPublicationSource { private CultMeshDocumentPublicationSource() { } /// Creates a publication source from a CultCache backing store. public static CultMeshDocumentPublicationSource Store(CacheBackingStore store) { return new StoreSource(store); } /// Creates a publication source from a single-file MessagePack CultCache publication. public static CultMeshDocumentPublicationSource SingleFile(string path) { return new SingleFileSource(path); } /// Creates a publication source from a remote CultNet snapshot response provider. public static CultMeshDocumentPublicationSource PeerSnapshot(Func> snapshot) { return new PeerSnapshotSource(snapshot); } /// Creates a publication source from a remote CultNet schema endpoint. public static CultMeshDocumentPublicationSource PeerSnapshot(string endpoint) { return new PeerSnapshotEndpointSource(endpoint); } /// Creates a publication source from a remote CultNet schema client factory. public static CultMeshDocumentPublicationSource PeerSnapshot(Func createClient, string endpoint) { return new PeerSnapshotClientSource(createClient, endpoint); } internal sealed class StoreSource : CultMeshDocumentPublicationSource { public StoreSource(CacheBackingStore store) { BackingStore = store ?? throw new ArgumentNullException(nameof(store)); } public CacheBackingStore BackingStore { get; } } internal sealed class SingleFileSource : CultMeshDocumentPublicationSource { public SingleFileSource(string path) { Path = string.IsNullOrWhiteSpace(path) ? throw new ArgumentException("Value must be non-empty.", nameof(path)) : path; } public string Path { get; } } internal sealed class PeerSnapshotSource : CultMeshDocumentPublicationSource { public PeerSnapshotSource(Func> snapshot) { Snapshot = snapshot ?? throw new ArgumentNullException(nameof(snapshot)); } public Func> Snapshot { get; } } internal sealed class PeerSnapshotEndpointSource : CultMeshDocumentPublicationSource { public PeerSnapshotEndpointSource(string endpoint) { Endpoint = string.IsNullOrWhiteSpace(endpoint) ? throw new ArgumentException("Value must be non-empty.", nameof(endpoint)) : endpoint; } public string Endpoint { get; } } internal sealed class PeerSnapshotClientSource : CultMeshDocumentPublicationSource { public PeerSnapshotClientSource(Func createClient, string endpoint) { CreateClient = createClient ?? throw new ArgumentNullException(nameof(createClient)); Endpoint = string.IsNullOrWhiteSpace(endpoint) ? throw new ArgumentException("Value must be non-empty.", nameof(endpoint)) : endpoint; } public Func CreateClient { get; } public string Endpoint { get; } } } /// /// A locally hosted CultMesh node over CultCache, CultNet transport, and the mesh database facade. /// public sealed class CultMeshNode : IDisposable { private readonly CultNetHost _host; internal CultMeshNode(CultNetHost host) { _host = host ?? throw new ArgumentNullException(nameof(host)); } /// /// Gets the durable cache used by the node. /// public CultCache Cache => _host.Cache; /// /// Gets the canonical single-file MessagePack store, when one is attached. /// public SingleFileMessagePackBackingStore? Store => _host.Store; /// /// Gets the underlying CultNet server. /// public Server Server => _host.Server; /// /// Gets the distributed realtime database facade. /// public CultNetDatabase Database => _host.Database; /// /// Gets the schema-v0 server bridge for distributed database messages. /// public CultNetDatabaseServer DatabaseServer => _host.DatabaseServer; /// /// Starts the underlying server. /// public void Start() { _host.Start(); } /// /// Flushes the durable cache. /// public Task FlushAsync(bool soft = false) { return _host.FlushAsync(soft); } /// public void Dispose() { _host.Dispose(); } } /// /// Parsed CultMesh RUDP endpoint. /// public sealed class CultMeshRudpEndpoint { /// /// Creates a parsed RUDP endpoint. /// public CultMeshRudpEndpoint(string host, int port, string uri) { Host = string.IsNullOrWhiteSpace(host) ? throw new ArgumentException("Host must be non-empty.", nameof(host)) : host; if (port <= 0 || port > 65535) { throw new ArgumentOutOfRangeException(nameof(port), "Port must be between 1 and 65535."); } Port = port; Uri = string.IsNullOrWhiteSpace(uri) ? throw new ArgumentException("Uri must be non-empty.", nameof(uri)) : uri; } /// Gets the endpoint host. public string Host { get; } /// Gets the endpoint port. public int Port { get; } /// Gets the normalized rudp:// URI. public string Uri { get; } } /// /// Options for CultMesh-branded RUDP socket helpers. /// public sealed class CultMeshRudpSocketOptions { /// Gets or sets the local bind host. public string BindHost { get; set; } = "127.0.0.1"; /// Gets or sets the local bind port. public int BindPort { get; set; } /// Gets or sets a caller-owned bound socket. public Socket? Socket { get; set; } /// Gets or sets the first local packet sequence. public uint InitialSequence { get; set; } = 1; /// Gets or sets the reliable resend delay in milliseconds. public long ResendDelayMs { get; set; } = 250; /// Gets or sets the advertised transport id. public string TransportId { get; set; } = "rudp"; /// Gets or sets the advertised maximum payload size. public int? MaxPayloadBytes { get; set; } /// Gets or sets the maximum RUDP fragment size. public int? MaxFragmentBytes { get; set; } /// Gets or sets the maximum pending reliable packet count. public int? MaxPendingReliablePackets { get; set; } /// Gets or sets the advertised reconnect policy. public CultNetReconnectPolicy? ReconnectPolicy { get; set; } } /// /// Options for CultMesh-branded connected RUDP client helpers. /// public sealed class CultMeshRudpClientOptions { /// Gets or sets the socket construction and transport profile options. public CultMeshRudpSocketOptions SocketOptions { get; set; } = new(); /// Gets or sets the handshake payload. public byte[] ConnectPayload { get; set; } = Array.Empty(); /// Gets or sets the handshake timeout. public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(1); /// Gets or sets the handshake polling interval. public TimeSpan PollInterval { get; set; } = TimeSpan.FromMilliseconds(5); } /// /// Public CultMesh entrypoints. /// public static partial class CultMesh { /// /// Creates a local CultMesh node with a durable CultCache and the canonical MessagePack backing store. /// public static async Task CreateNodeAsync(string cachePath, CultMeshNodeOptions? options = null) { var host = await CultNetLocal.CreateHostAsync( cachePath, (options ?? new CultMeshNodeOptions()).ToCultNetOptions(cachePath)).ConfigureAwait(false); return new CultMeshNode(host); } /// /// Creates and starts a local CultMesh node with development-friendly defaults. /// public static Task StartNodeAsync(string cachePath, CultMeshNodeOptions? options = null) { options ??= new CultMeshNodeOptions(); options.StartServer = true; return CreateNodeAsync(cachePath, options); } /// /// Creates a local reactive catalog for discovered Verses. /// public static CultMeshVerseCatalog CreateVerseCatalog() { return new CultMeshVerseCatalog(); } /// /// Creates a local reactive catalog for discovered peers. /// public static CultMeshPeerCatalog CreatePeerCatalog() { return new CultMeshPeerCatalog(); } /// /// Creates a local authority lease catalog. /// public static CultMeshAuthorityLeaseCatalog CreateAuthorityLeaseCatalog() { return new CultMeshAuthorityLeaseCatalog(); } /// /// Creates a local stream catalog for zero-copy-oriented audio, video, tensor, and byte frame streams. /// public static CultMeshStreamCatalog CreateStreamCatalog() { return new CultMeshStreamCatalog(); } /// /// Creates a managed Verse context for generated domain sugar. /// public static CultMeshVerse Verse( string verseId, string runtimeId, CultMeshRouteHint? routeHint = null, IEnumerable? claims = null) { return new CultMeshVerse(new CultMeshVerseContext(verseId, runtimeId, routeHint, claims)); } /// /// Creates a managed Verse context for generated domain sugar. /// public static Task ConnectVerseAsync( string verseId, string runtimeId, CultMeshRouteHint? routeHint = null, IEnumerable? claims = null) { return Task.FromResult(Verse(verseId, runtimeId, routeHint, claims)); } /// /// Starts a fluent typed operation context for one runtime. /// public static CultMeshOperationContextBuilder OperationContextFor(string runtimeId) { return new CultMeshOperationContextBuilder(runtimeId); } /// /// Starts a fluent typed query context for one runtime. /// public static CultMeshQueryContextBuilder QueryContextFor(string runtimeId) { return new CultMeshQueryContextBuilder(runtimeId); } /// /// Binds a typed operation handle to a Verse context. /// public static CultMeshBoundOperationHandle BindOperation( CultMeshVerseContext context, CultMeshOperationHandle operation) { return new CultMeshBoundOperationHandle(context, operation); } /// /// Binds a typed operation handle to a Verse. /// public static CultMeshBoundOperationHandle BindOperation( CultMeshVerse verse, CultMeshOperationHandle operation) { if (verse == null) throw new ArgumentNullException(nameof(verse)); return BindOperation(verse.Context, operation); } /// /// Binds a typed query surface to a Verse context. /// public static CultMeshBoundQuerySurface BindQuery( CultMeshVerseContext context, CultMeshQuerySurface query) { return new CultMeshBoundQuerySurface(context, query); } /// /// Binds a typed query surface to a Verse. /// public static CultMeshBoundQuerySurface BindQuery( CultMeshVerse verse, CultMeshQuerySurface query) { if (verse == null) throw new ArgumentNullException(nameof(verse)); return BindQuery(verse.Context, query); } /// /// Binds a typed live feed to a Verse context. /// public static CultMeshBoundLiveFeed BindLiveFeed( CultMeshVerseContext context, CultMeshLiveFeed feed) { return new CultMeshBoundLiveFeed(context, feed); } /// /// Binds a typed live feed to a Verse. /// public static CultMeshBoundLiveFeed BindLiveFeed( CultMeshVerse verse, CultMeshLiveFeed feed) { if (verse == null) throw new ArgumentNullException(nameof(verse)); return BindLiveFeed(verse.Context, feed); } /// /// Binds a typed document live feed to a Verse context. /// public static CultMeshDocumentHandle BindDocument( CultMeshVerseContext context, CultMeshLiveFeed feed) where TDocument : class { return new CultMeshDocumentHandle(BindLiveFeed(context, feed)); } /// /// Binds a mutable typed document live feed to a Verse context. /// public static CultMeshDocumentHandle BindDocument( CultMeshVerseContext context, CultMeshLiveFeed feed, Func replace) where TDocument : class { if (replace == null) throw new ArgumentNullException(nameof(replace)); return new CultMeshDocumentHandle(BindLiveFeed(context, feed), replace); } /// /// Binds a mutable predicted typed document live feed to a Verse context. /// public static CultMeshDocumentHandle BindDocument( CultMeshVerseContext context, CultMeshLiveFeed feed, Func replace, Func submitPrediction) where TDocument : class { if (replace == null) throw new ArgumentNullException(nameof(replace)); if (submitPrediction == null) throw new ArgumentNullException(nameof(submitPrediction)); return new CultMeshDocumentHandle(BindLiveFeed(context, feed), replace, submitPrediction); } /// /// Binds a typed document live feed to a Verse. /// public static CultMeshDocumentHandle BindDocument( CultMeshVerse verse, CultMeshLiveFeed feed) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return BindDocument(verse.Context, feed); } /// /// Binds a mutable typed document live feed to a Verse. /// public static CultMeshDocumentHandle BindDocument( CultMeshVerse verse, CultMeshLiveFeed feed, Func replace) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return BindDocument(verse.Context, feed, replace); } /// /// Binds a mutable predicted typed document live feed to a Verse. /// public static CultMeshDocumentHandle BindDocument( CultMeshVerse verse, CultMeshLiveFeed feed, Func replace, Func submitPrediction) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return BindDocument(verse.Context, feed, replace, submitPrediction); } /// /// Binds a typed state pointer to a Verse context. /// public static CultMeshBoundStatePointer BindStatePointer( CultMeshVerseContext context, CultMeshStatePointer pointer) { return new CultMeshBoundStatePointer(context, pointer); } /// /// Binds a typed state pointer to a Verse. /// public static CultMeshBoundStatePointer BindStatePointer( CultMeshVerse verse, CultMeshStatePointer pointer) { if (verse == null) throw new ArgumentNullException(nameof(verse)); return BindStatePointer(verse.Context, pointer); } /// /// Binds a mutable typed state pointer to a Verse context. /// public static CultMeshBoundMutableStatePointer BindMutableStatePointer( CultMeshVerseContext context, CultMeshMutableStatePointer pointer) { return new CultMeshBoundMutableStatePointer(context, pointer); } /// /// Binds a mutable typed state pointer to a Verse. /// public static CultMeshBoundMutableStatePointer BindMutableStatePointer( CultMeshVerse verse, CultMeshMutableStatePointer pointer) { if (verse == null) throw new ArgumentNullException(nameof(verse)); return BindMutableStatePointer(verse.Context, pointer); } /// /// Creates a typed state pointer to Verse state. /// public static CultMeshStatePointer StatePointer( string pointerId, Func> resolve, Func> watch, CultMeshRouteHint? routeHint = null, IEnumerable? sources = null) { return new CultMeshStatePointer( pointerId, resolve, watch, routeHint, sources); } /// /// Creates a typed state pointer to Verse state that can resolve through a query context. /// public static CultMeshStatePointer StatePointer( string pointerId, Func> resolve, Func> watch, CultMeshRouteHint? routeHint = null, IEnumerable? sources = null) { return new CultMeshStatePointer( pointerId, resolve, watch, routeHint, sources); } /// /// Creates a mutable typed state pointer to Verse state. /// public static CultMeshMutableStatePointer MutableStatePointer( string pointerId, Func> resolve, Func> watch, Func replace, CultMeshRouteHint? routeHint = null, IEnumerable? sources = null) { return new CultMeshMutableStatePointer( pointerId, resolve, watch, replace, routeHint, sources); } /// /// Creates a mutable typed state pointer to Verse state that can operate through a query context. /// public static CultMeshMutableStatePointer MutableStatePointer( string pointerId, Func> resolve, Func> watch, Func replace, CultMeshRouteHint? routeHint = null, IEnumerable? sources = null) { return new CultMeshMutableStatePointer( pointerId, resolve, watch, replace, routeHint, sources); } /// /// Creates a typed projection source descriptor. /// public static CultMeshProjectionSource ProjectionSource( string sourceId, string? schemaId = null, string? description = null) { return new CultMeshProjectionSource(sourceId, schemaId, description); } /// /// Creates a named state-reference resolver for portable UI/tool surfaces. /// public static CultMeshStateRefResolver StateRefResolver( string resolverId, Func resolve, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) { if (resolve == null) throw new ArgumentNullException(nameof(resolve)); return new CultMeshStateRefResolver( resolverId, (stateRef, _context) => resolve(stateRef), sources, routeHint); } /// /// Creates a named state-reference resolver for portable UI/tool surfaces. /// public static CultMeshStateRefResolver StateRefResolver( string resolverId, Func resolve, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) { return new CultMeshStateRefResolver(resolverId, resolve, sources, routeHint); } /// /// Describes a state-reference resolver for catalogs and tools. /// public static CultMeshStateRefResolverDiagnostic DescribeStateRefResolver( CultMeshStateRefResolver resolver) { if (resolver == null) throw new ArgumentNullException(nameof(resolver)); return new CultMeshStateRefResolverDiagnostic( resolver.ResolverId, resolver.RouteHint, resolver.Sources); } /// /// Creates a UI/tool binding descriptor from a component property to a typed state pointer. /// public static CultMeshStateBindingDescriptor StateBinding( string targetProp, CultMeshStatePointer pointer) { return CultMeshStateBindingDescriptor.FromPointer(targetProp, pointer); } /// /// Creates a UI/tool binding descriptor from a component property to a mutable typed state pointer. /// public static CultMeshStateBindingDescriptor StateBinding( string targetProp, CultMeshMutableStatePointer pointer) { if (pointer == null) throw new ArgumentNullException(nameof(pointer)); return CultMeshStateBindingDescriptor.FromPointer(targetProp, pointer.AsStatePointer()); } /// /// Creates a UI/tool binding descriptor from a component property to a state pointer id. /// public static CultMeshStateBindingDescriptor StateBinding( string targetProp, string pointerId, string? sourceId = null, string? schemaId = null, CultMeshRouteHint? routeHint = null) { return new CultMeshStateBindingDescriptor(targetProp, pointerId, sourceId, schemaId, routeHint); } /// /// Creates transport-friendly fields from a state binding descriptor. /// public static CultMeshStateBindingRecord StateBindingRecord(CultMeshStateBindingDescriptor? binding) { return CultMeshStateBindingRecord.FromBinding(binding); } /// /// Creates transport-friendly state binding fields directly. /// public static CultMeshStateBindingRecord StateBindingRecord( string? targetProp, string? pointerId, string? sourceId = null, string? schemaId = null, string? routeKind = null, string? routeDescription = null) { return new CultMeshStateBindingRecord( targetProp, pointerId, sourceId, schemaId, routeKind, routeDescription); } /// /// Creates a UI/tool command binding descriptor from a typed operation handle. /// public static CultMeshOperationBindingDescriptor OperationBinding( CultMeshOperationHandle operation, string? label = null, string? schemaId = null, CultMeshRouteHint? routeHint = null) { return CultMeshOperationBindingDescriptor.FromOperation(operation, label, schemaId, routeHint); } /// /// Creates a UI/tool command binding descriptor from a typed operation id. /// public static CultMeshOperationBindingDescriptor OperationBinding( string operationId, string? label = null, string? schemaId = null, CultMeshRouteHint? routeHint = null) { return new CultMeshOperationBindingDescriptor(operationId, label, schemaId, routeHint); } /// /// Creates transport-friendly fields from an operation binding descriptor. /// public static CultMeshOperationBindingRecord OperationBindingRecord( CultMeshOperationBindingDescriptor? binding) { return CultMeshOperationBindingRecord.FromBinding(binding); } /// /// Creates transport-friendly operation binding fields directly. /// public static CultMeshOperationBindingRecord OperationBindingRecord( string? operationId, string? label = null, string? schemaId = null, string? routeKind = null, string? routeDescription = null) { return new CultMeshOperationBindingRecord( operationId, label, schemaId, routeKind, routeDescription); } /// /// Creates a concrete invocation descriptor from an advertised operation binding. /// public static CultMeshOperationInvocationDescriptor OperationInvocation( CultMeshOperationBindingDescriptor binding, string? idempotencyKey = null) { return CultMeshOperationInvocationDescriptor.FromBinding(binding, idempotencyKey); } /// /// Creates a concrete invocation descriptor from a typed operation handle. /// public static CultMeshOperationInvocationDescriptor OperationInvocation( CultMeshOperationHandle operation, string? schemaId = null, CultMeshRouteHint? routeHint = null, string? idempotencyKey = null) { return CultMeshOperationInvocationDescriptor.FromOperation( operation, schemaId, routeHint, idempotencyKey); } /// /// Creates a concrete invocation descriptor from a typed operation id. /// public static CultMeshOperationInvocationDescriptor OperationInvocation( string operationId, string? schemaId = null, CultMeshRouteHint? routeHint = null, string? idempotencyKey = null) { return new CultMeshOperationInvocationDescriptor(operationId, schemaId, routeHint, idempotencyKey); } /// /// Creates transport-friendly fields from a route hint. /// public static CultMeshRouteRecord RouteRecord(CultMeshRouteHint? routeHint) { return CultMeshRouteRecord.FromRoute(routeHint); } /// /// Creates transport-friendly route fields directly. /// public static CultMeshRouteRecord RouteRecord(string? kind, string? description = null) { return new CultMeshRouteRecord(kind, description); } /// /// Creates transport-friendly fields from a typed operation invocation. /// public static CultMeshOperationInvocationRecord OperationInvocationRecord( CultMeshOperationInvocationDescriptor? invocation, string? fallbackOperationId = null, string? fallbackSchemaId = null, CultMeshRouteHint? fallbackRouteHint = null, string? fallbackIdempotencyKey = null) { return CultMeshOperationInvocationRecord.FromInvocation( invocation, fallbackOperationId, fallbackSchemaId, fallbackRouteHint, fallbackIdempotencyKey); } /// /// Creates transport-friendly operation invocation fields directly. /// public static CultMeshOperationInvocationRecord OperationInvocationRecord( string? operationId, string? schemaId = null, string? routeKind = null, string? routeDescription = null, string? idempotencyKey = null) { return new CultMeshOperationInvocationRecord( operationId, schemaId, routeKind, routeDescription, idempotencyKey); } /// /// Creates an empty shared operation payload. /// public static CultMeshOperationPayload OperationPayload() { return CultMeshOperationPayload.Empty; } /// /// Creates a shared operation payload from string-compatible fields. /// public static CultMeshOperationPayload OperationPayload( IEnumerable>? fields) { return CultMeshOperationPayload.FromStrings(fields); } /// /// Creates a shared operation payload from key/value pairs. /// public static CultMeshOperationPayload OperationPayload(params (string Key, string Value)[] fields) { var pairs = fields?.Select(field => new KeyValuePair(field.Key, field.Value)); return CultMeshOperationPayload.FromStrings(pairs); } /// /// Creates a reusable projection recipe over typed source state. /// public static CultMeshProjectionRecipe ProjectionRecipe( string projectionId, IEnumerable sources, Func> project, CultMeshRouteHint? routeHint = null, Func>? watch = null) { return new CultMeshProjectionRecipe( projectionId, sources, project, routeHint, watch); } /// /// Creates a typed live feed surface for coherent client snapshots. /// public static CultMeshLiveFeed LiveFeed( string feedId, Func> snapshot, Func>? watch = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) { return new CultMeshLiveFeed( feedId, snapshot, watch, sources, routeHint); } /// /// Creates a typed document handle from snapshot/watch delegates and binds it to a Verse context. /// public static CultMeshDocumentHandle Document( string documentId, CultMeshVerseContext context, Func> latest, Func> watch, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (latest == null) throw new ArgumentNullException(nameof(latest)); if (watch == null) throw new ArgumentNullException(nameof(watch)); var feed = LiveFeed( documentId, (_parameters, queryContext) => latest(queryContext), (_parameters, queryContext) => watch(queryContext), sources, routeHint); return BindDocument(context, feed); } /// /// Creates a mutable typed document handle from snapshot/watch/replace delegates and binds it to a Verse context. /// public static CultMeshDocumentHandle Document( string documentId, CultMeshVerseContext context, Func> latest, Func> watch, Func replace, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (replace == null) throw new ArgumentNullException(nameof(replace)); var feed = LiveFeed( documentId, (_parameters, queryContext) => latest(queryContext), (_parameters, queryContext) => watch(queryContext), sources, routeHint); return BindDocument(context, feed, replace); } /// /// Creates a mutable predicted typed document handle from snapshot/watch/replace/prediction delegates and binds it to a Verse context. /// public static CultMeshDocumentHandle Document( string documentId, CultMeshVerseContext context, Func> latest, Func> watch, Func replace, Func submitPrediction, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (replace == null) throw new ArgumentNullException(nameof(replace)); if (submitPrediction == null) throw new ArgumentNullException(nameof(submitPrediction)); var feed = LiveFeed( documentId, (_parameters, queryContext) => latest(queryContext), (_parameters, queryContext) => watch(queryContext), sources, routeHint); return BindDocument(context, feed, replace, submitPrediction); } /// /// Creates a typed document handle from snapshot/watch delegates and binds it to a Verse. /// public static CultMeshDocumentHandle Document( string documentId, CultMeshVerse verse, Func> latest, Func> watch, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return Document(documentId, verse.Context, latest, watch, sources, routeHint); } /// /// Creates a mutable typed document handle from snapshot/watch/replace delegates and binds it to a Verse. /// public static CultMeshDocumentHandle Document( string documentId, CultMeshVerse verse, Func> latest, Func> watch, Func replace, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return Document(documentId, verse.Context, latest, watch, replace, sources, routeHint); } /// /// Creates a mutable predicted typed document handle from snapshot/watch/replace/prediction delegates and binds it to a Verse. /// public static CultMeshDocumentHandle Document( string documentId, CultMeshVerse verse, Func> latest, Func> watch, Func replace, Func submitPrediction, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return Document(documentId, verse.Context, latest, watch, replace, submitPrediction, sources, routeHint); } /// /// Creates a typed document handle directly over one CultCache record. /// public static CultMeshDocumentHandle Document( CultCache cache, CultRecordKey key, CultMeshVerseContext context, string? documentId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (cache == null) throw new ArgumentNullException(nameof(cache)); if (context == null) throw new ArgumentNullException(nameof(context)); var descriptor = cache.Registry.GetRequired(); var sourceList = sources?.ToArray() ?? new[] { ProjectionSource(key.Value, descriptor.SchemaId, "CultCache record") }; var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.InProcess, "CultCache document"); return Document( ResolveDocumentId(documentId, key), context, _ => Task.FromResult(ReadRequired(cache, key)), _ => cache.WatchRecord(key) .Where(change => change.Document != null) .Select(change => change.Document!), async value => { await cache.UpsertAsync(value, new CultRecordHandle(key)).ConfigureAwait(false); }, sourceList, route); } /// /// Creates a typed document handle directly over one CultCache record. /// public static CultMeshDocumentHandle Document( CultCache cache, CultRecordKey key, CultMeshVerse verse, string? documentId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return Document(cache, key, verse.Context, documentId, sources, routeHint); } /// /// Creates a typed document handle directly over one CultCache record with a local Verse context. /// public static CultMeshDocumentHandle Document( CultCache cache, CultRecordKey key, string? documentId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { return Document( cache, key, Verse("local", "local", routeHint).Context, documentId, sources, routeHint); } /// /// Creates a read-only typed document handle over one CultCache backing-store publication. /// public static CultMeshDocumentHandle DocumentFromStore( CacheBackingStore store, CultRecordKey key, CultMeshVerseContext context, CultMeshStoreDocumentOptions? options = null) where TDocument : class { if (store == null) throw new ArgumentNullException(nameof(store)); if (context == null) throw new ArgumentNullException(nameof(context)); var resolvedOptions = options ?? new CultMeshStoreDocumentOptions(); var cache = new CultCache(resolvedOptions.Registry ?? CultDocumentRegistry.Shared); cache.AddBackingStore(store); var descriptor = cache.Registry.GetRequired(); var documentId = ResolveDocumentId(resolvedOptions.DocumentId, key); var route = resolvedOptions.RouteHint ?? new CultMeshRouteHint(CultMeshLocalityKind.InProcess, "CultCache backing store"); var sources = new[] { ProjectionSource( string.IsNullOrWhiteSpace(resolvedOptions.SourceId) ? key.Value : resolvedOptions.SourceId!, descriptor.SchemaId, "CultCache backing store") }; Func> latest = async _ => { await cache.PullAllBackingStoresAsync().ConfigureAwait(false); return ReadRequired(cache, key); }; var watch = PollingQueryWatcher( async (_parameters, queryContext) => await latest(queryContext).ConfigureAwait(false), new CultMeshPollingWatchOptions(resolvedOptions.PollInterval)); return Document( documentId, context, latest, queryContext => watch(CultMeshDocumentQueryParameters.Empty, queryContext), sources, route); } /// /// Creates a read-only typed document handle over one CultCache backing-store publication. /// public static CultMeshDocumentHandle DocumentFromStore( CacheBackingStore store, CultRecordKey key, CultMeshVerse verse, CultMeshStoreDocumentOptions? options = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return DocumentFromStore(store, key, verse.Context, options); } /// /// Creates a read-only typed document handle over one single-file MessagePack CultCache publication. /// public static CultMeshDocumentHandle DocumentFromSingleFile( string path, CultRecordKey key, CultMeshVerseContext context, CultMeshStoreDocumentOptions? options = null) where TDocument : class { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Value must be non-empty.", nameof(path)); var resolvedOptions = options ?? new CultMeshStoreDocumentOptions(); var fileOptions = new CultMeshStoreDocumentOptions { DocumentId = resolvedOptions.DocumentId, SourceId = resolvedOptions.SourceId, RouteHint = resolvedOptions.RouteHint ?? new CultMeshRouteHint(CultMeshLocalityKind.SharedMemory, path), PollInterval = resolvedOptions.PollInterval, Registry = resolvedOptions.Registry }; return DocumentFromStore( new SingleFileMessagePackBackingStore(path), key, context, fileOptions); } /// /// Creates a read-only typed document handle over one single-file MessagePack CultCache publication. /// public static CultMeshDocumentHandle DocumentFromSingleFile( string path, CultRecordKey key, CultMeshVerse verse, CultMeshStoreDocumentOptions? options = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return DocumentFromSingleFile(path, key, verse.Context, options); } /// /// Creates a typed document handle from a configured publication source. /// public static CultMeshDocumentHandle DocumentFromPublication( CultMeshDocumentPublicationSource source, CultRecordKey key, CultMeshVerseContext context, CultMeshStoreDocumentOptions? storeOptions = null, CultMeshPeerSnapshotDocumentOptions? peerOptions = null) where TDocument : class { if (source == null) throw new ArgumentNullException(nameof(source)); if (context == null) throw new ArgumentNullException(nameof(context)); switch (source) { case CultMeshDocumentPublicationSource.StoreSource store: return DocumentFromStore(store.BackingStore, key, context, storeOptions); case CultMeshDocumentPublicationSource.SingleFileSource file: return DocumentFromSingleFile(file.Path, key, context, storeOptions); case CultMeshDocumentPublicationSource.PeerSnapshotSource snapshot: return DocumentFromPeerSnapshot(snapshot.Snapshot, key.Value, context, peerOptions); case CultMeshDocumentPublicationSource.PeerSnapshotEndpointSource endpoint: return DocumentFromPeerSnapshot(endpoint.Endpoint, key.Value, context, peerOptions); case CultMeshDocumentPublicationSource.PeerSnapshotClientSource client: return DocumentFromPeerSnapshot(client.CreateClient, client.Endpoint, key.Value, context, peerOptions); default: throw new NotSupportedException( $"Unsupported CultMesh document publication source '{source.GetType().FullName}'."); } } /// /// Creates a typed document handle from a configured publication source. /// public static CultMeshDocumentHandle DocumentFromPublication( CultMeshDocumentPublicationSource source, CultRecordKey key, CultMeshVerse verse, CultMeshStoreDocumentOptions? storeOptions = null, CultMeshPeerSnapshotDocumentOptions? peerOptions = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return DocumentFromPublication(source, key, verse.Context, storeOptions, peerOptions); } /// /// Creates a typed document handle directly over one distributed CultNet database record. /// public static CultMeshDocumentHandle Document( CultNetDatabase database, CultRecordKey key, CultMeshVerseContext context, string? documentId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (database == null) throw new ArgumentNullException(nameof(database)); if (context == null) throw new ArgumentNullException(nameof(context)); var descriptor = CultDocumentRegistry.Shared.GetRequired(); var sourceList = sources?.ToArray() ?? new[] { ProjectionSource(key.Value, descriptor.SchemaId, "CultNet database record") }; var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.Automatic, "CultNet database document"); return Document( ResolveDocumentId(documentId, key), context, async _ => await ReadRequiredAsync(database, key).ConfigureAwait(false), _ => database.WatchRecord(key) .Where(change => change.Document != null) .Select(change => change.Document!), async value => { await database.PutAsync(key, value).ConfigureAwait(false); }, async value => { await database.PutPredictedAsync(key, value).ConfigureAwait(false); }, sourceList, route); } /// /// Creates a typed document handle directly over one distributed CultNet database record. /// public static CultMeshDocumentHandle Document( CultNetDatabase database, CultRecordKey key, CultMeshVerse verse, string? documentId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return Document(database, key, verse.Context, documentId, sources, routeHint); } /// /// Creates a typed document handle over one remote CultNet snapshot response provider. /// public static CultMeshDocumentHandle DocumentFromPeerSnapshot( Func> snapshot, string recordKey, CultMeshVerseContext context, CultMeshPeerSnapshotDocumentOptions? options = null) where TDocument : class { if (snapshot == null) throw new ArgumentNullException(nameof(snapshot)); if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Value must be non-empty.", nameof(recordKey)); if (context == null) throw new ArgumentNullException(nameof(context)); var descriptor = CultDocumentRegistry.Shared.GetRequired(); var resolvedOptions = options ?? new CultMeshPeerSnapshotDocumentOptions(); var documentId = string.IsNullOrWhiteSpace(resolvedOptions.DocumentId) ? recordKey : resolvedOptions.DocumentId!; var route = resolvedOptions.RouteHint ?? new CultMeshRouteHint(CultMeshLocalityKind.Network, "CultNet snapshot"); var sources = new[] { ProjectionSource( string.IsNullOrWhiteSpace(resolvedOptions.SourceId) ? recordKey : resolvedOptions.SourceId!, descriptor.SchemaId, "CultNet snapshot") }; Func> latest = async queryContext => ReadDocumentFromSnapshotResponse( await snapshot(queryContext).ConfigureAwait(false), descriptor.SchemaId, recordKey); var watch = PollingQueryWatcher( async (_parameters, queryContext) => await latest(queryContext).ConfigureAwait(false), new CultMeshPollingWatchOptions(resolvedOptions.PollInterval)); return Document( documentId, context, latest, queryContext => watch(CultMeshDocumentQueryParameters.Empty, queryContext), sources, route); } /// /// Creates a typed document handle over one remote CultNet snapshot response provider. /// public static CultMeshDocumentHandle DocumentFromPeerSnapshot( Func> snapshot, string recordKey, CultMeshVerse verse, CultMeshPeerSnapshotDocumentOptions? options = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return DocumentFromPeerSnapshot(snapshot, recordKey, verse.Context, options); } /// /// Creates a typed document handle over one remote CultNet schema endpoint. /// public static CultMeshDocumentHandle DocumentFromPeerSnapshot( string endpoint, string recordKey, CultMeshVerseContext context, CultMeshPeerSnapshotDocumentOptions? options = null) where TDocument : class { if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentException("Value must be non-empty.", nameof(endpoint)); var resolvedOptions = options ?? new CultMeshPeerSnapshotDocumentOptions(); return DocumentFromPeerSnapshot( queryContext => RequestPeerSnapshotAsync( () => CultNetSchemaClients.CreateForEndpoint(endpoint, resolvedOptions.Security, resolvedOptions.ConfigureClient), endpoint, recordKey, queryContext, resolvedOptions), recordKey, context, resolvedOptions); } /// /// Creates a typed document handle over one remote CultNet schema endpoint. /// public static CultMeshDocumentHandle DocumentFromPeerSnapshot( string endpoint, string recordKey, CultMeshVerse verse, CultMeshPeerSnapshotDocumentOptions? options = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return DocumentFromPeerSnapshot(endpoint, recordKey, verse.Context, options); } /// /// Creates a typed document handle over one remote CultNet schema client factory. /// public static CultMeshDocumentHandle DocumentFromPeerSnapshot( Func createClient, string endpoint, string recordKey, CultMeshVerseContext context, CultMeshPeerSnapshotDocumentOptions? options = null) where TDocument : class { if (createClient == null) throw new ArgumentNullException(nameof(createClient)); if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentException("Value must be non-empty.", nameof(endpoint)); var resolvedOptions = options ?? new CultMeshPeerSnapshotDocumentOptions(); return DocumentFromPeerSnapshot( queryContext => RequestPeerSnapshotAsync( createClient, endpoint, recordKey, queryContext, resolvedOptions), recordKey, context, resolvedOptions); } /// /// Creates a typed document handle over one remote CultNet schema client factory. /// public static CultMeshDocumentHandle DocumentFromPeerSnapshot( Func createClient, string endpoint, string recordKey, CultMeshVerse verse, CultMeshPeerSnapshotDocumentOptions? options = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return DocumentFromPeerSnapshot(createClient, endpoint, recordKey, verse.Context, options); } /// /// Creates a typed document handle directly over one CultMesh node database record. /// public static CultMeshDocumentHandle Document( CultMeshNode node, CultRecordKey key, CultMeshVerseContext context, string? documentId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (node == null) throw new ArgumentNullException(nameof(node)); return Document(node.Database, key, context, documentId, sources, routeHint); } /// /// Creates a typed document handle directly over one CultMesh node database record. /// public static CultMeshDocumentHandle Document( CultMeshNode node, CultRecordKey key, CultMeshVerse verse, string? documentId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (verse == null) throw new ArgumentNullException(nameof(verse)); return Document(node, key, verse.Context, documentId, sources, routeHint); } /// /// Creates a schema-aware catalog over typed document handles. /// public static CultMeshDocumentCatalog Documents(IEnumerable documents) { return new CultMeshDocumentCatalog(documents); } /// /// Creates a schema-aware catalog over typed document handles. /// public static CultMeshDocumentCatalog Documents(params ICultMeshDocumentHandle[] documents) { return new CultMeshDocumentCatalog(documents); } /// /// Reads two typed document handles and projects them into one caller-defined view. /// public static async Task LatestAsync( CultMeshDocumentHandle first, CultMeshDocumentHandle second, Func project) where TFirst : class where TSecond : class { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (project == null) throw new ArgumentNullException(nameof(project)); var firstTask = first.LatestAsync(); var secondTask = second.LatestAsync(); await Task.WhenAll(firstTask, secondTask).ConfigureAwait(false); return project( await firstTask.ConfigureAwait(false), await secondTask.ConfigureAwait(false)); } /// /// Reads three typed document handles and projects them into one caller-defined view. /// public static async Task LatestAsync( CultMeshDocumentHandle first, CultMeshDocumentHandle second, CultMeshDocumentHandle third, Func project) where TFirst : class where TSecond : class where TThird : class { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (third == null) throw new ArgumentNullException(nameof(third)); if (project == null) throw new ArgumentNullException(nameof(project)); var firstTask = first.LatestAsync(); var secondTask = second.LatestAsync(); var thirdTask = third.LatestAsync(); await Task.WhenAll(firstTask, secondTask, thirdTask).ConfigureAwait(false); return project( await firstTask.ConfigureAwait(false), await secondTask.ConfigureAwait(false), await thirdTask.ConfigureAwait(false)); } /// /// Creates a typed collection handle over all local CultCache records assignable to the document type. /// public static CultMeshCollectionHandle Collection( CultCache cache, string? collectionId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (cache == null) throw new ArgumentNullException(nameof(cache)); var descriptor = cache.Registry.GetRequired(); var sourceList = sources?.ToArray() ?? new[] { ProjectionSource(CollectionId(collectionId, descriptor), descriptor.SchemaId, "CultCache collection") }; var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.InProcess, "CultCache collection"); return new CultMeshCollectionHandle( CollectionId(collectionId, descriptor), () => Task.FromResult>(cache.GetAll().ToArray()), () => cache.Watch().Select(change => ToCollectionChange(change, descriptor.SchemaId)), sourceList, route); } /// /// Creates a typed collection handle over the local CultCache record with the supplied CultName. /// public static CultMeshCollectionHandle CollectionByName( CultCache cache, string name, string? collectionId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (cache == null) throw new ArgumentNullException(nameof(cache)); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value must be non-empty.", nameof(name)); var descriptor = cache.Registry.GetRequired(); var resolvedId = collectionId ?? $"{descriptor.SchemaId}:name:{name}"; var sourceList = sources?.ToArray() ?? new[] { ProjectionSource(resolvedId, descriptor.SchemaId, "CultCache named collection") }; var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.InProcess, "CultCache named collection"); return new CultMeshCollectionHandle( resolvedId, () => Task.FromResult>(Optional(cache.GetByName(name))), () => cache.Watch() .Where(change => MatchesName(cache, name, change)) .Select(change => ToCollectionChange(change, descriptor.SchemaId)), sourceList, route); } /// /// Creates a typed collection handle over local CultCache records matched by an indexed value. /// public static CultMeshCollectionHandle CollectionByIndex( CultCache cache, string alias, string value, string? collectionId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (cache == null) throw new ArgumentNullException(nameof(cache)); if (string.IsNullOrWhiteSpace(alias)) throw new ArgumentException("Value must be non-empty.", nameof(alias)); if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Value must be non-empty.", nameof(value)); var descriptor = cache.Registry.GetRequired(); var resolvedId = collectionId ?? $"{descriptor.SchemaId}:index:{alias}:{value}"; var sourceList = sources?.ToArray() ?? new[] { ProjectionSource(resolvedId, descriptor.SchemaId, "CultCache indexed collection") }; var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.InProcess, "CultCache indexed collection"); return new CultMeshCollectionHandle( resolvedId, () => Task.FromResult>(Optional(cache.GetByIndex(alias, value))), () => cache.Watch() .Where(change => MatchesIndex(cache, alias, value, change)) .Select(change => ToCollectionChange(change, descriptor.SchemaId)), sourceList, route); } /// /// Creates a typed collection handle over all distributed CultNet database records assignable to the document type. /// public static CultMeshCollectionHandle Collection( CultNetDatabase database, string? collectionId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (database == null) throw new ArgumentNullException(nameof(database)); var descriptor = CultDocumentRegistry.Shared.GetRequired(); var sourceList = sources?.ToArray() ?? new[] { ProjectionSource(CollectionId(collectionId, descriptor), descriptor.SchemaId, "CultNet database collection") }; var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.Automatic, "CultNet database collection"); return new CultMeshCollectionHandle( CollectionId(collectionId, descriptor), () => Task.FromResult>(database.GetAll().ToArray()), () => database.Watch().Select(ToCollectionChange), sourceList, route); } /// /// Creates a typed collection handle over the distributed CultNet database record with the supplied CultName. /// public static CultMeshCollectionHandle CollectionByName( CultNetDatabase database, string name, string? collectionId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (database == null) throw new ArgumentNullException(nameof(database)); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value must be non-empty.", nameof(name)); var descriptor = CultDocumentRegistry.Shared.GetRequired(); var resolvedId = collectionId ?? $"{descriptor.SchemaId}:name:{name}"; var sourceList = sources?.ToArray() ?? new[] { ProjectionSource(resolvedId, descriptor.SchemaId, "CultNet database named collection") }; var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.Automatic, "CultNet database named collection"); return new CultMeshCollectionHandle( resolvedId, () => Task.FromResult>(Optional(database.GetByName(name))), () => database.WatchByName(name).Select(ToCollectionChange), sourceList, route); } /// /// Creates a typed collection handle over distributed CultNet database records matched by an indexed value. /// public static CultMeshCollectionHandle CollectionByIndex( CultNetDatabase database, string alias, string value, string? collectionId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (database == null) throw new ArgumentNullException(nameof(database)); if (string.IsNullOrWhiteSpace(alias)) throw new ArgumentException("Value must be non-empty.", nameof(alias)); if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Value must be non-empty.", nameof(value)); var descriptor = CultDocumentRegistry.Shared.GetRequired(); var resolvedId = collectionId ?? $"{descriptor.SchemaId}:index:{alias}:{value}"; var sourceList = sources?.ToArray() ?? new[] { ProjectionSource(resolvedId, descriptor.SchemaId, "CultNet database indexed collection") }; var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.Automatic, "CultNet database indexed collection"); return new CultMeshCollectionHandle( resolvedId, () => Task.FromResult>(Optional(database.GetByIndex(alias, value))), () => database.WatchByIndex(alias, value).Select(ToCollectionChange), sourceList, route); } /// /// Creates a typed collection handle over all CultMesh node database records assignable to the document type. /// public static CultMeshCollectionHandle Collection( CultMeshNode node, string? collectionId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (node == null) throw new ArgumentNullException(nameof(node)); return Collection(node.Database, collectionId, sources, routeHint); } /// /// Creates a typed collection handle over the CultMesh node database record with the supplied CultName. /// public static CultMeshCollectionHandle CollectionByName( CultMeshNode node, string name, string? collectionId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (node == null) throw new ArgumentNullException(nameof(node)); return CollectionByName(node.Database, name, collectionId, sources, routeHint); } /// /// Creates a typed collection handle over CultMesh node database records matched by an indexed value. /// public static CultMeshCollectionHandle CollectionByIndex( CultMeshNode node, string alias, string value, string? collectionId = null, IEnumerable? sources = null, CultMeshRouteHint? routeHint = null) where TDocument : class { if (node == null) throw new ArgumentNullException(nameof(node)); return CollectionByIndex(node.Database, alias, value, collectionId, sources, routeHint); } /// /// Describes a typed live feed surface for tooling, UI, and diagnostics. /// public static CultMeshLiveFeedDiagnostic DescribeLiveFeed( CultMeshLiveFeed feed) { if (feed == null) throw new ArgumentNullException(nameof(feed)); return new CultMeshLiveFeedDiagnostic(feed.FeedId, feed.RouteHint, feed.Sources); } /// /// Describes a typed query surface for tooling, UI, and diagnostics. /// public static CultMeshQuerySurfaceDiagnostic DescribeQuerySurface( CultMeshQuerySurface query) { if (query == null) throw new ArgumentNullException(nameof(query)); return new CultMeshQuerySurfaceDiagnostic(query.QueryId, query.RouteHint, query.Sources); } /// /// Describes a typed operation handle for tooling, UI, and diagnostics. /// public static CultMeshOperationHandleDiagnostic DescribeOperationHandle( CultMeshOperationHandle operation) { if (operation == null) throw new ArgumentNullException(nameof(operation)); return new CultMeshOperationHandleDiagnostic(operation.OperationId); } /// /// Describes a typed state pointer for tooling, UI, and diagnostics. /// public static CultMeshStatePointerDiagnostic DescribeStatePointer( CultMeshStatePointer pointer) { if (pointer == null) throw new ArgumentNullException(nameof(pointer)); return new CultMeshStatePointerDiagnostic(pointer.PointerId, pointer.RouteHint, pointer.Sources); } /// /// Describes a mutable typed state pointer for tooling, UI, and diagnostics. /// public static CultMeshStatePointerDiagnostic DescribeStatePointer( CultMeshMutableStatePointer pointer) { if (pointer == null) throw new ArgumentNullException(nameof(pointer)); return new CultMeshStatePointerDiagnostic(pointer.PointerId, pointer.RouteHint, pointer.Sources); } /// /// Describes a native slice view for tooling, UI, and diagnostics. /// public static CultMeshNativeSliceViewDiagnostic DescribeNativeSliceView( CultMeshNativeSliceViewDescriptor view) { return new CultMeshNativeSliceViewDiagnostic(view); } /// /// Describes a typed projection recipe for tooling, UI, and diagnostics. /// public static CultMeshProjectionRecipeDiagnostic DescribeProjectionRecipe( CultMeshProjectionRecipe recipe) { if (recipe == null) throw new ArgumentNullException(nameof(recipe)); return new CultMeshProjectionRecipeDiagnostic(recipe.ProjectionId, recipe.RouteHint, recipe.Sources); } /// /// Describes a typed query surface as one entry in a surface catalog. /// public static CultMeshSurfaceDiagnostic DescribeSurface( CultMeshQuerySurface query) { if (query == null) throw new ArgumentNullException(nameof(query)); return new CultMeshSurfaceDiagnostic(CultMeshSurfaceKind.Query, query.QueryId, query.RouteHint, query.Sources); } /// /// Describes a typed operation handle as one entry in a surface catalog. /// public static CultMeshSurfaceDiagnostic DescribeSurface( CultMeshOperationHandle operation) { if (operation == null) throw new ArgumentNullException(nameof(operation)); return new CultMeshSurfaceDiagnostic(CultMeshSurfaceKind.Operation, operation.OperationId); } /// /// Describes a typed projection recipe as one entry in a surface catalog. /// public static CultMeshSurfaceDiagnostic DescribeSurface( CultMeshProjectionRecipe recipe) { if (recipe == null) throw new ArgumentNullException(nameof(recipe)); return new CultMeshSurfaceDiagnostic(CultMeshSurfaceKind.ProjectionRecipe, recipe.ProjectionId, recipe.RouteHint, recipe.Sources); } /// /// Describes a typed live feed as one entry in a surface catalog. /// public static CultMeshSurfaceDiagnostic DescribeSurface( CultMeshLiveFeed feed) { if (feed == null) throw new ArgumentNullException(nameof(feed)); return new CultMeshSurfaceDiagnostic(CultMeshSurfaceKind.LiveFeed, feed.FeedId, feed.RouteHint, feed.Sources); } /// /// Describes a typed document handle as one entry in a surface catalog. /// public static CultMeshSurfaceDiagnostic DescribeSurface( ICultMeshDocumentHandle document) { if (document == null) throw new ArgumentNullException(nameof(document)); return new CultMeshSurfaceDiagnostic( CultMeshSurfaceKind.Document, document.DocumentId, document.RouteHint, document.Sources); } /// /// Describes a typed collection handle as one entry in a surface catalog. /// public static CultMeshSurfaceDiagnostic DescribeSurface( CultMeshCollectionHandle collection) where TDocument : class { if (collection == null) throw new ArgumentNullException(nameof(collection)); return new CultMeshSurfaceDiagnostic( CultMeshSurfaceKind.Collection, collection.CollectionId, collection.RouteHint, collection.Sources); } /// /// Describes a typed state pointer as one entry in a surface catalog. /// public static CultMeshSurfaceDiagnostic DescribeSurface( CultMeshStatePointer pointer) { if (pointer == null) throw new ArgumentNullException(nameof(pointer)); return new CultMeshSurfaceDiagnostic( CultMeshSurfaceKind.StatePointer, pointer.PointerId, pointer.RouteHint, pointer.Sources); } /// /// Describes a mutable typed state pointer as one entry in a surface catalog. /// public static CultMeshSurfaceDiagnostic DescribeSurface( CultMeshMutableStatePointer pointer) { if (pointer == null) throw new ArgumentNullException(nameof(pointer)); return new CultMeshSurfaceDiagnostic( CultMeshSurfaceKind.StatePointer, pointer.PointerId, pointer.RouteHint, pointer.Sources); } /// /// Describes a native slice view as one entry in a surface catalog. /// public static CultMeshSurfaceDiagnostic DescribeSurface( CultMeshNativeSliceViewDescriptor view) { if (view == null) throw new ArgumentNullException(nameof(view)); return new CultMeshSurfaceDiagnostic(CultMeshSurfaceKind.NativeSliceView, view.ViewId, view.Route); } /// /// Creates a typed surface catalog diagnostic for tooling, UI, and generated bindings. /// public static CultMeshSurfaceCatalogDiagnostic DescribeSurfaceCatalog( string catalogId, IEnumerable surfaces) { return new CultMeshSurfaceCatalogDiagnostic(catalogId, surfaces); } /// /// Creates a kind-indexed surface catalog diagnostic for generated bindings, UI, and tools. /// public static CultMeshSurfaceCatalogIndexDiagnostic DescribeSurfaceCatalogIndex( CultMeshSurfaceCatalogDiagnostic catalog) { if (catalog == null) throw new ArgumentNullException(nameof(catalog)); return catalog.IndexByKind(); } /// /// Creates a timer-backed query watcher for runtimes that do not yet have native reactive transport. /// public static Func> PollingQueryWatcher( Func> sample, CultMeshPollingWatchOptions? options = null) { if (sample == null) throw new ArgumentNullException(nameof(sample)); var resolvedOptions = options ?? new CultMeshPollingWatchOptions(); return (parameters, context) => R3.Observable.Create(observer => { var watcher = new CultMeshPollingWatcher( sample, parameters, context, resolvedOptions); var subscription = watcher.Observable.Subscribe(observer); return new CultMeshCompositeDisposable(subscription, watcher); }); } private static async Task RequestPeerSnapshotAsync( Func createClient, string endpoint, string recordKey, CultMeshQueryContext context, CultMeshPeerSnapshotDocumentOptions options) where TDocument : class { var descriptor = CultDocumentRegistry.Shared.GetRequired(); return await FetchSnapshotAsync( createClient, endpoint, ToSnapshotRequestOptions( options, context, options.SchemaIds ?? new[] { descriptor.SchemaId }, new[] { recordKey })) .ConfigureAwait(false); } private static CultMeshSnapshotRequestOptions ToSnapshotRequestOptions( CultMeshPeerSnapshotDocumentOptions options, CultMeshQueryContext context, IReadOnlyList? schemaIds, IReadOnlyList? recordKeys) { return new CultMeshSnapshotRequestOptions { SchemaIds = schemaIds, RecordKeys = recordKeys, ShardId = options.ShardId, ShardEpoch = options.ShardEpoch, ResponseTimeout = options.ResponseTimeout, ConnectTimeout = options.ConnectTimeout, MessageIdPrefix = string.IsNullOrWhiteSpace(options.MessageIdPrefix) ? $"cultmesh:{context.RuntimeId}:snapshot" : options.MessageIdPrefix, Security = options.Security, ConfigureClient = options.ConfigureClient, RudpRuntimeId = string.IsNullOrWhiteSpace(options.RudpRuntimeId) ? context.RuntimeId : options.RudpRuntimeId, RudpConnectionId = options.RudpConnectionId, RudpConnectPayload = options.RudpConnectPayload, RudpMaxFragmentBytes = options.RudpMaxFragmentBytes, RudpResendDelayMs = options.RudpResendDelayMs }; } private static TDocument ReadDocumentFromSnapshotResponse( CultNetSnapshotResponseRawMessage response, string schemaId, string recordKey) where TDocument : class { if (response == null) throw new ArgumentNullException(nameof(response)); var record = response.Documents.FirstOrDefault(candidate => string.Equals(candidate.SchemaId, schemaId, StringComparison.Ordinal) && string.Equals(candidate.RecordKey, recordKey, StringComparison.Ordinal)) ?? response.Documents.FirstOrDefault(candidate => string.Equals(candidate.SchemaId, schemaId, StringComparison.Ordinal)) ?? response.Documents.FirstOrDefault(candidate => string.Equals(candidate.RecordKey, recordKey, StringComparison.Ordinal)); if (record == null) { throw new InvalidOperationException( $"CultNet snapshot response '{response.MessageId}' did not contain schema '{schemaId}' record '{recordKey}'."); } if (!string.Equals(record.PayloadEncoding, "messagepack", StringComparison.Ordinal)) { throw new InvalidOperationException( $"CultNet raw document payloadEncoding must be \"messagepack\", not \"{record.PayloadEncoding}\"."); } return (TDocument)CultDocumentMessagePackSerialization.DeserializeUntyped( typeof(TDocument), record.Payload); } /// /// Parses a rudp://host:port endpoint into its host/port parts. /// public static CultMeshRudpEndpoint ParseRudpEndpoint(string endpoint) { if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentException("Value must be non-empty.", nameof(endpoint)); if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || !string.Equals(uri.Scheme, "rudp", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("RUDP endpoint must use the rudp:// scheme.", nameof(endpoint)); } if (string.IsNullOrWhiteSpace(uri.Host) || uri.Port <= 0 || uri.Port > 65535) { throw new ArgumentException("RUDP endpoint must include a host and port.", nameof(endpoint)); } var host = uri.Host; var uriHost = host.Contains(':', StringComparison.Ordinal) && !host.StartsWith("[", StringComparison.Ordinal) ? $"[{host}]" : host; return new CultMeshRudpEndpoint(host, uri.Port, $"rudp://{uriHost}:{uri.Port}"); } /// /// Creates a CultNet RUDP server transport with CultMesh-branded defaults. /// public static CultNetRudpSocketTransportConnection CreateRudpServer( string runtimeId, uint connectionId, CultMeshRudpSocketOptions? options = null) { options ??= new CultMeshRudpSocketOptions(); return new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions { RuntimeId = runtimeId, Socket = options.Socket ?? BindRudpSocket(options.BindHost, options.BindPort), Mode = CultNetRudpSocketMode.Server, ConnectionId = connectionId, InitialSequence = options.InitialSequence, ResendDelayMs = options.ResendDelayMs, TransportId = options.TransportId, MaxPayloadBytes = options.MaxPayloadBytes, MaxFragmentBytes = options.MaxFragmentBytes, MaxPendingReliablePackets = options.MaxPendingReliablePackets, ReconnectPolicy = options.ReconnectPolicy }); } /// /// Creates a CultNet RUDP client transport for a parsed endpoint. /// public static CultNetRudpSocketTransportConnection CreateRudpClient( string runtimeId, uint connectionId, CultMeshRudpEndpoint endpoint, CultMeshRudpSocketOptions? options = null) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); options ??= new CultMeshRudpSocketOptions(); return new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions { RuntimeId = runtimeId, Socket = options.Socket ?? BindRudpSocket(options.BindHost, options.BindPort), Mode = CultNetRudpSocketMode.Client, RemoteEndPoint = new IPEndPoint(ResolveRudpAddress(endpoint.Host), endpoint.Port), ConnectionId = connectionId, InitialSequence = options.InitialSequence, ResendDelayMs = options.ResendDelayMs, TransportId = options.TransportId, MaxPayloadBytes = options.MaxPayloadBytes, MaxFragmentBytes = options.MaxFragmentBytes, MaxPendingReliablePackets = options.MaxPendingReliablePackets, ReconnectPolicy = options.ReconnectPolicy }); } /// /// Creates a CultNet RUDP client transport for a rudp://host:port endpoint. /// public static CultNetRudpSocketTransportConnection CreateRudpClient( string runtimeId, uint connectionId, string endpoint, CultMeshRudpSocketOptions? options = null) { return CreateRudpClient(runtimeId, connectionId, ParseRudpEndpoint(endpoint), options); } /// /// Creates a CultNet RUDP client transport from a peer-card contact hint. /// public static CultNetRudpSocketTransportConnection CreateRudpClientForPeer( string runtimeId, uint connectionId, CultMeshPeerCard peer, CultMeshRudpSocketOptions? options = null) { if (peer == null) throw new ArgumentNullException(nameof(peer)); var endpoint = peer.Endpoints.FirstOrDefault(value => value.StartsWith("rudp://", StringComparison.OrdinalIgnoreCase)); if (endpoint == null) { throw new InvalidOperationException($"Peer {peer.PeerId} does not advertise a RUDP endpoint."); } return CreateRudpClient(runtimeId, connectionId, endpoint, options); } /// /// Creates a CultNet RUDP client transport from the first peer authorized for a Verse role. /// public static CultNetRudpSocketTransportConnection CreateRudpClientForAuthorizedPeer( string runtimeId, uint connectionId, CultMeshPeerCatalog peers, CultMeshAuthorityLeaseCatalog leases, string verseId, string role, string? shardId = null, DateTimeOffset? at = null, CultMeshRudpSocketOptions? options = null) { 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); if (peer == null) { throw new InvalidOperationException($"No authorized RUDP peer for role {role} in Verse {verseId}."); } return CreateRudpClientForPeer(runtimeId, connectionId, peer, options); } /// /// Creates and handshakes a CultNet RUDP client transport for a parsed endpoint. /// public static CultNetRudpSocketTransportConnection ConnectRudpClient( string runtimeId, uint connectionId, CultMeshRudpEndpoint endpoint, CultMeshRudpClientOptions? options = null) { options ??= new CultMeshRudpClientOptions(); var client = CreateRudpClient(runtimeId, connectionId, endpoint, options.SocketOptions); if (!client.ConnectAndWait(options.ConnectPayload, options.ConnectTimeout, options.PollInterval)) { client.Dispose(); throw new TimeoutException($"Timed out waiting for RUDP client {runtimeId} to connect."); } return client; } /// /// Creates and handshakes a CultNet RUDP client transport for a rudp://host:port endpoint. /// public static CultNetRudpSocketTransportConnection ConnectRudpClient( string runtimeId, uint connectionId, string endpoint, CultMeshRudpClientOptions? options = null) { return ConnectRudpClient(runtimeId, connectionId, ParseRudpEndpoint(endpoint), options); } /// /// Creates and handshakes a CultNet RUDP client transport from a peer-card contact hint. /// public static CultNetRudpSocketTransportConnection ConnectRudpClientForPeer( string runtimeId, uint connectionId, CultMeshPeerCard peer, CultMeshRudpClientOptions? options = null) { if (peer == null) throw new ArgumentNullException(nameof(peer)); var endpoint = peer.Endpoints.FirstOrDefault(value => value.StartsWith("rudp://", StringComparison.OrdinalIgnoreCase)); if (endpoint == null) { throw new InvalidOperationException($"Peer {peer.PeerId} does not advertise a RUDP endpoint."); } return ConnectRudpClient(runtimeId, connectionId, endpoint, options); } /// /// Creates and handshakes a CultNet RUDP client transport from the first peer authorized for a Verse role. /// public static CultNetRudpSocketTransportConnection ConnectRudpClientForAuthorizedPeer( string runtimeId, uint connectionId, CultMeshPeerCatalog peers, CultMeshAuthorityLeaseCatalog leases, string verseId, string role, string? shardId = null, DateTimeOffset? at = null, CultMeshRudpClientOptions? options = null) { 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); if (peer == null) { throw new InvalidOperationException($"No authorized RUDP peer for role {role} in Verse {verseId}."); } return ConnectRudpClientForPeer(runtimeId, connectionId, peer, options); } /// /// Creates a committer for writing quorum simulation facts to a mesh database. /// public static CultMeshSimulationFactCommitter CreateSimulationFactCommitter(CultNetDatabase database) { return new CultMeshSimulationFactCommitter(database); } /// /// Creates a gameplay-facing session facade over a CultMesh node. /// public static CultMeshGameSession CreateGameSession( CultMeshNode node, CultMeshGameSessionOptions? options = null) { return new CultMeshGameSession(node, options); } /// /// Attaches Verse discovery responses to a CultMesh node. /// public static CultMeshVerseDiscoveryServer ServeVerseCatalog( CultMeshNode node, CultMeshVerseCatalog catalog) { if (node == null) throw new ArgumentNullException(nameof(node)); return new CultMeshVerseDiscoveryServer(node.Server, catalog); } /// /// Creates a client for fetching Verse catalogs from discovery endpoints. /// public static CultMeshVerseDiscoveryClient CreateVerseDiscoveryClient( CultMeshVerseDiscoveryClientOptions? options = null) { return new CultMeshVerseDiscoveryClient(options); } /// /// Attaches peer exchange responses to a CultMesh node. /// public static CultMeshPeerExchangeServer ServePeerExchange( CultMeshNode node, CultMeshPeerCatalog catalog) { if (node == null) throw new ArgumentNullException(nameof(node)); return new CultMeshPeerExchangeServer(node.Server, catalog); } /// /// Creates a client for fetching peer cards from peer exchange endpoints. /// public static CultMeshPeerExchangeClient CreatePeerExchangeClient( CultMeshPeerExchangeClientOptions? options = null) { return new CultMeshPeerExchangeClient(options); } /// /// Creates a CultNet client configured for CultMesh use. /// public static Client CreateClient(ClientSecurityOptions? security = null, Action? configureClient = null) { return CultNetLocal.CreateClient(security, configureClient); } /// /// Creates and connects a CultNet client to a CultMesh node. /// public static Client ConnectClient( string host = "localhost", int port = 3075, ClientSecurityOptions? security = null, Action? configureClient = null) { return CultNetLocal.ConnectClient(host, port, security, configureClient); } private static Socket BindRudpSocket(string host, int port) { var address = ResolveRudpAddress(host); var socket = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); socket.Bind(new IPEndPoint(address, port)); socket.ReceiveTimeout = 20; return socket; } private static IPAddress ResolveRudpAddress(string host) { if (string.IsNullOrWhiteSpace(host)) throw new ArgumentException("Value must be non-empty.", nameof(host)); if (IPAddress.TryParse(host, out var parsed)) { return parsed; } return Dns.GetHostAddresses(host).FirstOrDefault() ?? throw new InvalidOperationException($"Could not resolve RUDP host {host}."); } private static string ResolveDocumentId(string? documentId, CultRecordKey key) { return string.IsNullOrWhiteSpace(documentId) ? key.Value : documentId!; } private static string CollectionId(string? collectionId, CultDocumentDescriptor descriptor) { return string.IsNullOrWhiteSpace(collectionId) ? descriptor.SchemaId : collectionId!; } private static IReadOnlyList Optional(TDocument? document) where TDocument : class { return document == null ? Array.Empty() : new[] { document }; } private static bool MatchesName( CultCache cache, string name, CultCacheDocumentChange change) where TDocument : class { var current = cache.GetByName(name); return (change.Document != null && ReferenceEquals(current, change.Document)) || (change.PreviousDocument != null && ReferenceEquals(current, change.PreviousDocument)); } private static bool MatchesIndex( CultCache cache, string alias, string value, CultCacheDocumentChange change) where TDocument : class { var current = cache.GetByIndex(alias, value); return (change.Document != null && ReferenceEquals(current, change.Document)) || (change.PreviousDocument != null && ReferenceEquals(current, change.PreviousDocument)); } private static CultMeshCollectionChange ToCollectionChange( CultCacheDocumentChange change, string schemaId) where TDocument : class { return new CultMeshCollectionChange( change.Kind switch { CultCacheDocumentChangeKind.Added => CultMeshCollectionChangeKind.Added, CultCacheDocumentChangeKind.Updated => CultMeshCollectionChangeKind.Updated, CultCacheDocumentChangeKind.Removed => CultMeshCollectionChangeKind.Removed, _ => CultMeshCollectionChangeKind.Updated }, change.Key, schemaId, change.Document, change.PreviousDocument); } private static CultMeshCollectionChange ToCollectionChange( CultNetDatabaseChange change) where TDocument : class { return new CultMeshCollectionChange( change.Kind switch { CultNetDatabaseChangeKind.Added => CultMeshCollectionChangeKind.Added, CultNetDatabaseChangeKind.Updated => CultMeshCollectionChangeKind.Updated, CultNetDatabaseChangeKind.Removed => CultMeshCollectionChangeKind.Removed, CultNetDatabaseChangeKind.Predicted => CultMeshCollectionChangeKind.Predicted, CultNetDatabaseChangeKind.Reconciled => CultMeshCollectionChangeKind.Reconciled, CultNetDatabaseChangeKind.SchemaMigrated => CultMeshCollectionChangeKind.SchemaMigrated, CultNetDatabaseChangeKind.Rejected => CultMeshCollectionChangeKind.Rejected, _ => CultMeshCollectionChangeKind.Updated }, change.Key, change.SchemaId, change.Document, change.PreviousDocument, change.Message); } private static TDocument ReadRequired(CultCache cache, CultRecordKey key) where TDocument : class { return cache.Get(key) ?? throw new KeyNotFoundException( $"CultMesh document '{key.Value}' was not found as {typeof(TDocument).FullName}."); } private static async Task ReadRequiredAsync( CultNetDatabase database, CultRecordKey key) where TDocument : class { var document = await database.GetAsync(key).ConfigureAwait(false); return document ?? throw new KeyNotFoundException( $"CultMesh document '{key.Value}' was not found as {typeof(TDocument).FullName}."); } } }