Rewrite CultCache as attribute-first storage

This commit is contained in:
Meta Vens 2026-05-08 01:13:15 +01:00
commit da94389ee2
29 changed files with 1496 additions and 2488 deletions

View file

@ -6,14 +6,14 @@
"required": [
"schemaVersion",
"messageId",
"documentType",
"documentKey"
"schemaId",
"recordKey"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.document_delete.v0" },
"messageId": { "type": "string", "minLength": 1 },
"documentType": { "type": "string", "minLength": 1 },
"documentKey": { "type": "string", "minLength": 1 }
"schemaId": { "type": "string", "minLength": 1 },
"recordKey": { "type": "string", "minLength": 1 }
}
}

View file

@ -4,17 +4,16 @@
"title": "CultNet Document Record",
"type": "object",
"required": [
"documentType",
"documentKey",
"schemaId",
"recordKey",
"storedAt",
"payload"
],
"additionalProperties": false,
"properties": {
"documentType": { "type": "string", "minLength": 1 },
"documentKey": { "type": "string", "minLength": 1 },
"schemaId": { "type": "string", "minLength": 1 },
"recordKey": { "type": "string", "minLength": 1 },
"storedAt": { "type": "string", "minLength": 1 },
"payloadSchemaVersion": { "type": "string", "minLength": 1 },
"payload": {},
"sourceRuntimeId": { "type": "string", "minLength": 1 },
"sourceAgentId": { "type": "string", "minLength": 1 },

View file

@ -4,18 +4,17 @@
"title": "CultNet Raw Document Record",
"type": "object",
"required": [
"documentType",
"documentKey",
"schemaId",
"recordKey",
"storedAt",
"payloadEncoding",
"payload"
],
"additionalProperties": false,
"properties": {
"documentType": { "type": "string", "minLength": 1 },
"documentKey": { "type": "string", "minLength": 1 },
"schemaId": { "type": "string", "minLength": 1 },
"recordKey": { "type": "string", "minLength": 1 },
"storedAt": { "type": "string", "minLength": 1 },
"payloadSchemaVersion": { "type": "string", "minLength": 1 },
"payloadEncoding": { "const": "messagepack" },
"payload": {
"type": "string",

View file

@ -11,11 +11,11 @@
"properties": {
"schemaVersion": { "const": "cultnet.snapshot_request.v0" },
"messageId": { "type": "string", "minLength": 1 },
"documentTypes": {
"schemaIds": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
},
"documentKeys": {
"recordKeys": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
}

View file

@ -8,9 +8,6 @@ using GameCult.Caching.MessagePack;
namespace GameCult.Networking
{
/// <summary>
/// Optional metadata attached when CultNet emits a document message.
/// </summary>
public sealed class CultNetDocumentMessageOptions
{
public string? StoredAt { get; set; }
@ -20,90 +17,60 @@ namespace GameCult.Networking
public string[]? Tags { get; set; }
}
/// <summary>
/// Maps a concrete CultCache entry type to a shared CultNet document contract.
/// </summary>
public sealed class CultNetDocumentBinding
{
internal CultNetDocumentBinding(
Type entryType,
string documentType,
string? payloadSchemaVersion,
Func<DatabaseEntry, string> documentKeySelector,
Func<DatabaseEntry, byte[]> payloadSerializer,
Func<byte[], DatabaseEntry> payloadDeserializer)
Type documentType,
string schemaId,
Func<object, byte[]> payloadSerializer,
Func<byte[], object> payloadDeserializer)
{
EntryType = entryType ?? throw new ArgumentNullException(nameof(entryType));
DocumentType = string.IsNullOrWhiteSpace(documentType)
? throw new ArgumentException("DocumentType must be non-empty.", nameof(documentType))
: documentType;
PayloadSchemaVersion = payloadSchemaVersion;
DocumentKeySelector = documentKeySelector ?? throw new ArgumentNullException(nameof(documentKeySelector));
PayloadSerializer = payloadSerializer ?? throw new ArgumentNullException(nameof(payloadSerializer));
PayloadDeserializer = payloadDeserializer ?? throw new ArgumentNullException(nameof(payloadDeserializer));
DocumentType = documentType;
SchemaId = schemaId;
PayloadSerializer = payloadSerializer;
PayloadDeserializer = payloadDeserializer;
}
public Type EntryType { get; }
public string DocumentType { get; }
public string? PayloadSchemaVersion { get; }
public Func<DatabaseEntry, string> DocumentKeySelector { get; }
public Func<DatabaseEntry, byte[]> PayloadSerializer { get; }
public Func<byte[], DatabaseEntry> PayloadDeserializer { get; }
public Type DocumentType { get; }
public string SchemaId { get; }
public Func<object, byte[]> PayloadSerializer { get; }
public Func<byte[], object> PayloadDeserializer { get; }
public static CultNetDocumentBinding ForEntry<T>(
string documentType,
string? payloadSchemaVersion = null,
Func<T, string>? documentKeySelector = null,
public static CultNetDocumentBinding ForDocument<T>(
CultDocumentRegistry? registry = null,
Func<T, byte[]>? payloadSerializer = null,
Func<byte[], T>? payloadDeserializer = null)
where T : DatabaseEntry
where T : class
{
var descriptor = (registry ?? CultDocumentRegistry.Shared).GetRequired<T>();
return new CultNetDocumentBinding(
typeof(T),
documentType,
payloadSchemaVersion,
entry =>
descriptor.SchemaId,
document =>
{
if (entry is not T typedEntry)
{
throw new InvalidOperationException(
$"Document binding for {typeof(T).Name} received {entry.GetType().Name}.");
}
return documentKeySelector != null
? documentKeySelector(typedEntry)
: typedEntry.ID.ToString("D", CultureInfo.InvariantCulture);
},
entry =>
{
if (entry is not T typedEntry)
{
throw new InvalidOperationException(
$"Document binding for {typeof(T).Name} received {entry.GetType().Name}.");
}
var typed = (T)document;
return payloadSerializer != null
? payloadSerializer(typedEntry)
: CultCacheEnvelopeSerialization.SerializePayload(typedEntry);
? payloadSerializer(typed)
: CultDocumentMessagePackSerialization.Serialize(typed);
},
payload => payloadDeserializer != null
? payloadDeserializer(payload)
: CultCacheEnvelopeSerialization.DeserializePayload<T>(payload));
: CultDocumentMessagePackSerialization.Deserialize<T>(payload));
}
}
/// <summary>
/// Creates and applies CultNet raw document/snapshot messages for bound CultCache entry types.
/// </summary>
public sealed class CultNetDocumentRegistry
{
private readonly Dictionary<string, CultNetDocumentBinding> _bindingsByDocumentType =
new Dictionary<string, CultNetDocumentBinding>(StringComparer.Ordinal);
private readonly Dictionary<Type, CultNetDocumentBinding> _bindingsByEntryType =
new Dictionary<Type, CultNetDocumentBinding>();
private readonly CultDocumentRegistry _documents;
private readonly Dictionary<string, CultNetDocumentBinding> _bindingsBySchemaId =
new(StringComparer.Ordinal);
private readonly Dictionary<Type, CultNetDocumentBinding> _bindingsByType = new();
public CultNetDocumentRegistry(IEnumerable<CultNetDocumentBinding>? bindings = null)
public CultNetDocumentRegistry(
CultDocumentRegistry? documents = null,
IEnumerable<CultNetDocumentBinding>? bindings = null)
{
_documents = documents ?? CultDocumentRegistry.Shared;
if (bindings == null)
{
return;
@ -117,86 +84,73 @@ namespace GameCult.Networking
public CultNetDocumentRegistry Register(CultNetDocumentBinding binding)
{
if (binding == null) throw new ArgumentNullException(nameof(binding));
_bindingsByDocumentType[binding.DocumentType] = binding;
_bindingsByEntryType[binding.EntryType] = binding;
_bindingsBySchemaId[binding.SchemaId] = binding;
_bindingsByType[binding.DocumentType] = binding;
return this;
}
public CultNetDocumentBinding? GetByDocumentType(string documentType)
public CultNetDocumentBinding? GetBySchemaId(string schemaId)
{
if (documentType == null) throw new ArgumentNullException(nameof(documentType));
return _bindingsByDocumentType.TryGetValue(documentType, out var binding) ? binding : null;
return _bindingsBySchemaId.TryGetValue(schemaId, out var binding) ? binding : null;
}
public CultNetDocumentBinding? GetByEntryType(Type entryType)
public CultNetDocumentBinding? GetByDocumentType(Type documentType)
{
if (entryType == null) throw new ArgumentNullException(nameof(entryType));
return _bindingsByEntryType.TryGetValue(entryType, out var binding) ? binding : null;
return _bindingsByType.TryGetValue(documentType, out var binding) ? binding : null;
}
public CultNetDocumentDeleteMessage CreateDocumentDeleteMessage(
string messageId,
string documentType,
string documentKey)
string schemaId,
string recordKey)
{
return new CultNetDocumentDeleteMessage
{
MessageId = RequireNonEmpty(messageId, nameof(messageId)),
DocumentType = RequireNonEmpty(documentType, nameof(documentType)),
DocumentKey = RequireNonEmpty(documentKey, nameof(documentKey))
SchemaId = RequireNonEmpty(schemaId, nameof(schemaId)),
RecordKey = RequireNonEmpty(recordKey, nameof(recordKey))
};
}
public CultNetDocumentPutRawMessage CreateRawDocumentPutMessage(
public CultNetDocumentPutRawMessage CreateRawDocumentPutMessage<T>(
string messageId,
DatabaseEntry entry,
CultRecordHandle<T> handle,
T document,
CultNetDocumentMessageOptions? options = null)
where T : class
{
if (entry == null) throw new ArgumentNullException(nameof(entry));
var binding = RequireBinding(entry.GetType());
var descriptor = _documents.GetRequired<T>();
var binding = GetByDocumentType(typeof(T)) ?? CultNetDocumentBinding.ForDocument<T>(_documents);
var storedAt = ResolveStoredAt(options);
var documentKey = binding.DocumentKeySelector(entry);
return new CultNetDocumentPutRawMessage
{
MessageId = RequireNonEmpty(messageId, nameof(messageId)),
Document = CreateRawDocumentRecord(binding, entry, documentKey, storedAt, options)
};
}
public CultNetDocumentPutRawMessage CreateRawDocumentPutMessageFromEnvelope(
string messageId,
CultCacheEnvelope envelope)
{
if (envelope == null) throw new ArgumentNullException(nameof(envelope));
var binding = RequireBinding(envelope.Type);
return new CultNetDocumentPutRawMessage
{
MessageId = RequireNonEmpty(messageId, nameof(messageId)),
Document = new CultNetRawDocumentRecord
{
DocumentType = envelope.Type,
DocumentKey = envelope.Key,
StoredAt = envelope.StoredAt,
PayloadSchemaVersion = binding.PayloadSchemaVersion,
SchemaId = descriptor.SchemaId,
RecordKey = handle.Key.Value,
StoredAt = storedAt,
PayloadEncoding = "messagepack",
Payload = envelope.Payload.ToArray()
Payload = binding.PayloadSerializer(document),
SourceRuntimeId = options?.SourceRuntimeId,
SourceAgentId = options?.SourceAgentId,
SourceRole = options?.SourceRole,
Tags = options?.Tags
}
};
}
public CultNetSnapshotRequestMessage CreateSnapshotRequest(
string messageId,
IEnumerable<string>? documentTypes = null,
IEnumerable<string>? documentKeys = null)
IEnumerable<string>? schemaIds = null,
IEnumerable<string>? recordKeys = null)
{
return new CultNetSnapshotRequestMessage
{
MessageId = RequireNonEmpty(messageId, nameof(messageId)),
DocumentTypes = documentTypes?.ToArray(),
DocumentKeys = documentKeys?.ToArray()
SchemaIds = schemaIds?.ToArray(),
RecordKeys = recordKeys?.ToArray()
};
}
@ -206,42 +160,62 @@ namespace GameCult.Networking
CultNetSnapshotRequestMessage? filter = null,
CultNetDocumentMessageOptions? options = null)
{
if (cache == null) throw new ArgumentNullException(nameof(cache));
var requestedDocumentTypes = filter?.DocumentTypes != null
? new HashSet<string>(filter.DocumentTypes, StringComparer.Ordinal)
var requestedSchemaIds = filter?.SchemaIds != null
? new HashSet<string>(filter.SchemaIds, StringComparer.Ordinal)
: null;
var requestedDocumentKeys = filter?.DocumentKeys != null
? new HashSet<string>(filter.DocumentKeys, StringComparer.Ordinal)
var requestedRecordKeys = filter?.RecordKeys != null
? new HashSet<string>(filter.RecordKeys, StringComparer.Ordinal)
: null;
var storedAt = ResolveStoredAt(options);
var documents = new List<CultNetRawDocumentRecord>();
foreach (var entry in cache.AllEntries)
foreach (var document in cache.AllEntries)
{
var binding = GetByEntryType(entry.GetType());
if (binding == null)
var descriptor = _documents.GetRequired(document.GetType());
if (requestedSchemaIds != null && !requestedSchemaIds.Contains(descriptor.SchemaId))
{
continue;
}
if (requestedDocumentTypes != null && !requestedDocumentTypes.Contains(binding.DocumentType))
var handleMethod = typeof(CultCache)
.GetMethod(nameof(CultCache.TryGetHandle))!
.MakeGenericMethod(document.GetType());
var handleObject = handleMethod.Invoke(cache, new[] { document });
if (handleObject == null)
{
continue;
}
var documentKey = binding.DocumentKeySelector(entry);
if (requestedDocumentKeys != null && !requestedDocumentKeys.Contains(documentKey))
var keyProperty = handleObject.GetType().GetProperty("Value");
var handleValue = keyProperty?.GetValue(handleObject) ?? handleObject;
var recordKeyProperty = handleValue.GetType().GetProperty("Key");
var recordKey = recordKeyProperty?.GetValue(handleValue);
var valueProperty = recordKey?.GetType().GetProperty("Value");
var key = (string?)(valueProperty?.GetValue(recordKey)) ?? string.Empty;
if (requestedRecordKeys != null && !requestedRecordKeys.Contains(key))
{
continue;
}
documents.Add(CreateRawDocumentRecord(
binding,
entry,
documentKey,
storedAt,
options));
var binding = GetByDocumentType(document.GetType()) ??
new CultNetDocumentBinding(
document.GetType(),
descriptor.SchemaId,
value => CultDocumentMessagePackSerialization.SerializeUntyped(value, value.GetType()),
payload => CultDocumentMessagePackSerialization.DeserializeUntyped(document.GetType(), payload));
documents.Add(new CultNetRawDocumentRecord
{
SchemaId = descriptor.SchemaId,
RecordKey = key,
StoredAt = storedAt,
PayloadEncoding = "messagepack",
Payload = binding.PayloadSerializer(document),
SourceRuntimeId = options?.SourceRuntimeId,
SourceAgentId = options?.SourceAgentId,
SourceRole = options?.SourceRole,
Tags = options?.Tags
});
}
return new CultNetSnapshotResponseRawMessage
@ -251,68 +225,56 @@ namespace GameCult.Networking
};
}
public async Task<DatabaseEntry> ApplyRawDocumentPutMessageAsync(
public async Task<object> ApplyRawDocumentPutMessageAsync(
CultCache cache,
CultNetDocumentPutRawMessage message)
{
if (cache == null) throw new ArgumentNullException(nameof(cache));
if (message == null) throw new ArgumentNullException(nameof(message));
if (message.Document == null) throw new ArgumentException("CultNet raw document message is missing its document payload.", nameof(message));
if (message.Document == null)
{
throw new ArgumentException("CultNet raw document message is missing its document payload.", nameof(message));
}
var binding = RequireBinding(message.Document.DocumentType);
ValidateRawDocumentRecord(message.Document);
var descriptor = _documents.GetRequiredBySchemaId(message.Document.SchemaId);
var binding = GetBySchemaId(message.Document.SchemaId) ??
new CultNetDocumentBinding(
descriptor.DocumentType,
descriptor.SchemaId,
value => CultDocumentMessagePackSerialization.SerializeUntyped(value, value.GetType()),
payload => CultDocumentMessagePackSerialization.DeserializeUntyped(descriptor.DocumentType, payload));
var document = binding.PayloadDeserializer(message.Document.Payload);
var entry = binding.PayloadDeserializer(message.Document.Payload);
if (!binding.EntryType.IsInstanceOfType(entry))
{
throw new InvalidOperationException(
$"CultNet raw document type \"{message.Document.DocumentType}\" expected {binding.EntryType.Name} but decoded {entry.GetType().Name}.");
}
var expectedKey = binding.DocumentKeySelector(entry);
if (!string.Equals(expectedKey, message.Document.DocumentKey, StringComparison.Ordinal))
{
throw new InvalidOperationException(
$"CultNet raw document key mismatch for \"{message.Document.DocumentType}\": payload resolved to \"{expectedKey}\" but wire metadata said \"{message.Document.DocumentKey}\".");
}
await cache.AddAsync(entry);
return entry;
var addMethod = typeof(CultCache).GetMethod(nameof(CultCache.AddAsync))!
.MakeGenericMethod(descriptor.DocumentType);
var handleType = typeof(CultRecordHandle<>).MakeGenericType(descriptor.DocumentType);
var optionalHandle = Activator.CreateInstance(typeof(Nullable<>).MakeGenericType(handleType), new object[] { Activator.CreateInstance(handleType, new object[] { new CultRecordKey(message.Document.RecordKey) })! });
var task = (Task)addMethod.Invoke(cache, [document, optionalHandle])!;
await task.ConfigureAwait(false);
return document;
}
public async Task<T> ApplyRawDocumentPutMessageAsync<T>(
CultCache cache,
CultNetDocumentPutRawMessage message)
where T : DatabaseEntry
where T : class
{
var entry = await ApplyRawDocumentPutMessageAsync(cache, message);
if (entry is not T typedEntry)
{
throw new InvalidOperationException(
$"CultNet raw document message resolved to {entry.GetType().Name}, not {typeof(T).Name}.");
}
return typedEntry;
return (T)await ApplyRawDocumentPutMessageAsync(cache, message).ConfigureAwait(false);
}
public async Task<IReadOnlyList<DatabaseEntry>> ApplyRawSnapshotResponseAsync(
public async Task<IReadOnlyList<object>> ApplyRawSnapshotResponseAsync(
CultCache cache,
CultNetSnapshotResponseRawMessage response)
{
if (cache == null) throw new ArgumentNullException(nameof(cache));
if (response == null) throw new ArgumentNullException(nameof(response));
var applied = new List<DatabaseEntry>(response.Documents.Length);
var applied = new List<object>(response.Documents.Length);
foreach (var document in response.Documents)
{
var entry = await ApplyRawDocumentPutMessageAsync(
applied.Add(await ApplyRawDocumentPutMessageAsync(
cache,
new CultNetDocumentPutRawMessage
{
MessageId = response.MessageId,
Document = document
});
applied.Add(entry);
}).ConfigureAwait(false));
}
return applied;
@ -321,54 +283,9 @@ namespace GameCult.Networking
public async Task<IReadOnlyList<T>> ApplyRawSnapshotResponseAsync<T>(
CultCache cache,
CultNetSnapshotResponseRawMessage response)
where T : DatabaseEntry
where T : class
{
var applied = await ApplyRawSnapshotResponseAsync(cache, response);
return applied.OfType<T>().ToArray();
}
private CultNetRawDocumentRecord CreateRawDocumentRecord(
CultNetDocumentBinding binding,
DatabaseEntry entry,
string documentKey,
string storedAt,
CultNetDocumentMessageOptions? options)
{
var envelope = new CultCacheEnvelope
{
Key = documentKey,
Type = binding.DocumentType,
StoredAt = storedAt,
Payload = binding.PayloadSerializer(entry)
};
return new CultNetRawDocumentRecord
{
DocumentType = envelope.Type,
DocumentKey = envelope.Key,
StoredAt = envelope.StoredAt,
PayloadSchemaVersion = binding.PayloadSchemaVersion,
PayloadEncoding = "messagepack",
Payload = envelope.Payload,
SourceRuntimeId = options?.SourceRuntimeId,
SourceAgentId = options?.SourceAgentId,
SourceRole = options?.SourceRole,
Tags = options?.Tags
};
}
private CultNetDocumentBinding RequireBinding(Type entryType)
{
return GetByEntryType(entryType)
?? throw new InvalidOperationException(
$"No CultNet document binding is registered for {entryType.FullName}.");
}
private CultNetDocumentBinding RequireBinding(string documentType)
{
return GetByDocumentType(documentType)
?? throw new InvalidOperationException(
$"No CultNet document binding is registered for \"{documentType}\".");
return (await ApplyRawSnapshotResponseAsync(cache, response).ConfigureAwait(false)).OfType<T>().ToArray();
}
private static void ValidateRawDocumentRecord(CultNetRawDocumentRecord document)
@ -379,14 +296,13 @@ namespace GameCult.Networking
$"CultNet raw document payloadEncoding must be \"messagepack\", not \"{document.PayloadEncoding}\".");
}
RequireNonEmpty(document.SchemaId, nameof(document.SchemaId));
RequireNonEmpty(document.RecordKey, nameof(document.RecordKey));
RequireNonEmpty(document.StoredAt, nameof(document.StoredAt));
if (document.Payload == null || document.Payload.Length == 0)
{
throw new InvalidOperationException("CultNet raw document payload must be non-empty.");
}
RequireNonEmpty(document.DocumentType, nameof(document.DocumentType));
RequireNonEmpty(document.DocumentKey, nameof(document.DocumentKey));
RequireNonEmpty(document.StoredAt, nameof(document.StoredAt));
}
private static string ResolveStoredAt(CultNetDocumentMessageOptions? options)

View file

@ -114,10 +114,9 @@ namespace GameCult.Networking
[MessagePackObject]
public class CultNetRawDocumentRecord
{
[Key("documentType")] public string DocumentType { get; set; } = string.Empty;
[Key("documentKey")] public string DocumentKey { get; set; } = string.Empty;
[Key("schemaId")] public string SchemaId { get; set; } = string.Empty;
[Key("recordKey")] public string RecordKey { get; set; } = string.Empty;
[Key("storedAt")] public string StoredAt { get; set; } = string.Empty;
[Key("payloadSchemaVersion")] public string? PayloadSchemaVersion { get; set; }
[Key("payloadEncoding")] public string PayloadEncoding { get; set; } = "messagepack";
[Key("payload")] public byte[] Payload { get; set; } = Array.Empty<byte>();
[Key("sourceRuntimeId")] public string? SourceRuntimeId { get; set; }
@ -131,8 +130,8 @@ namespace GameCult.Networking
{
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.DocumentDelete;
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
[Key("documentType")] public string DocumentType { get; set; } = string.Empty;
[Key("documentKey")] public string DocumentKey { get; set; } = string.Empty;
[Key("schemaId")] public string SchemaId { get; set; } = string.Empty;
[Key("recordKey")] public string RecordKey { get; set; } = string.Empty;
}
[MessagePackObject]
@ -148,8 +147,8 @@ namespace GameCult.Networking
{
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SnapshotRequest;
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
[Key("documentTypes")] public string[]? DocumentTypes { get; set; }
[Key("documentKeys")] public string[]? DocumentKeys { get; set; }
[Key("schemaIds")] public string[]? SchemaIds { get; set; }
[Key("recordKeys")] public string[]? RecordKeys { get; set; }
}
[MessagePackObject]

View file

@ -1,39 +1,26 @@
using System;
using GameCult.Caching;
using MessagePack;
namespace GameCult.Networking
{
/// <summary>
/// Player data stored in the database.
/// For MessagePack serialization, uses [MessagePackObject] and [Key(n)] attributes.
/// </summary>
public class PlayerData : DatabaseEntry, INamedEntry
[CultDocument("gamecult.player_data", "gamecult.player_data.v1")]
[MessagePackObject]
public class PlayerData
{
[Key(0)]
[CultIndex]
public Guid PlayerId = Guid.NewGuid();
/// <summary>
/// Email address of the player.
/// </summary>
[Key(1)]
[CultIndex]
public string Email = string.Empty;
/// <summary>
/// Password hash of the player.
/// </summary>
[Key(2)]
public string PasswordHash = string.Empty;
/// <summary>
/// Username of the player.
/// </summary>
[Key(3)]
[CultName]
public string Username = string.Empty;
/// <inheritdoc/>
[IgnoreMember]
public string EntryName
{
get => Username;
set => Username = value;
}
}
}

View file

@ -84,7 +84,8 @@ Schema-v0 message families include:
The raw document/snapshot lane is meant for neighbors that already share the
same payload schema and MessagePack semantics. It carries exact payload bytes
plus explicit type metadata; it does not guess what a blob "probably" means.
plus `schemaId`/record-key metadata; it does not guess what a blob "probably"
means.
## Authentication Model

View file

@ -59,7 +59,6 @@ namespace GameCult.Networking
{
_database = cache;
_security = security ?? ServerSecurityOptions.FromEnvironment();
_database.RegisterIndex<PlayerData>("Email");
_cleanupSubscription = Observable.Timer(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60))
.Subscribe(_ => CleanupExpiredSessions());
}
@ -256,7 +255,7 @@ namespace GameCult.Networking
return;
}
if (_database.GetIdByName<PlayerData>(message.Name) != null)
if (_database.GetByName<PlayerData>(message.Name) != null)
{
message.Peer?.Send(new ErrorMessage { Error = "Username Taken" });
return;
@ -310,13 +309,13 @@ namespace GameCult.Networking
return;
}
if (_database.GetIdByIndex<PlayerData>("Email", email) != null)
if (_database.GetByIndex<PlayerData>("Email", email) != null)
{
peer.Send(new ErrorMessage { Error = "Email Taken" });
return;
}
if (_database.GetIdByName<PlayerData>(name) != null)
if (_database.GetByName<PlayerData>(name) != null)
{
peer.Send(new ErrorMessage { Error = "Username Taken" });
return;
@ -330,15 +329,15 @@ namespace GameCult.Networking
var newUserData = new PlayerData
{
ID = Guid.NewGuid(),
PlayerId = Guid.NewGuid(),
Email = email,
PasswordHash = Argon2.Hash(password, memoryCost: 16384),
Username = name
};
await _database.AddAsync(newUserData);
AttachUser(user, newUserData.ID);
SendSessionToken(peer, newUserData.ID);
AttachUser(user, newUserData.PlayerId);
SendSessionToken(peer, newUserData.PlayerId);
}
private void HandleVerify(NetPeer peer, User user, VerifyMessage verify)
@ -350,7 +349,7 @@ namespace GameCult.Networking
return;
}
if (_database.Get<PlayerData>(playerId) == null)
if (_database.GetByIndex<PlayerData>("PlayerId", playerId.ToString("D")) == null)
{
peer.Send(new ErrorMessage { Error = "Session Not Found" });
return;
@ -387,18 +386,18 @@ namespace GameCult.Networking
return;
}
AttachUser(user, userData.ID);
SendSessionToken(peer, userData.ID);
AttachUser(user, userData.PlayerId);
SendSessionToken(peer, userData.PlayerId);
}
private bool IsVerified(User? user) =>
user != null &&
user.PlayerId != Guid.Empty &&
user.SessionExpiresAt > DateTimeOffset.UtcNow &&
_database.Get<PlayerData>(user.PlayerId) != null;
_database.GetByIndex<PlayerData>("PlayerId", user.PlayerId.ToString("D")) != null;
private PlayerData? SessionData(User user) =>
IsVerified(user) ? _database.Get<PlayerData>(user.PlayerId) : null;
IsVerified(user) ? _database.GetByIndex<PlayerData>("PlayerId", user.PlayerId.ToString("D")) : null;
private bool CheckRateLimit(string ip)
{