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