Big cleanup
This commit is contained in:
@@ -1,82 +0,0 @@
|
||||
// Server.Services.Characters/CharacterService.cs
|
||||
using Microsoft.Extensions.Logging;
|
||||
using DataServer.Data;
|
||||
|
||||
namespace Server.Services.Characters;
|
||||
|
||||
public sealed class CharacterService : ICharacterService
|
||||
{
|
||||
private readonly ILogger<CharacterService> _log;
|
||||
private readonly ICharactersRepository _repo;
|
||||
|
||||
public CharacterService(ILogger<CharacterService> log, ICharactersRepository repo)
|
||||
{ _log = log; _repo = repo; }
|
||||
|
||||
public async Task<(bool ok, string? error, Old_Character[] list)> ListAsync(ulong accountId, CancellationToken ct)
|
||||
{
|
||||
var one = await _repo.FindByAccountAsync(accountId, ct);
|
||||
return (true, null, one is null ? Array.Empty<Old_Character>() : new[] { one });
|
||||
}
|
||||
|
||||
public async Task<(bool ok, string? error, Old_Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name) || name.Length is < 3 or > 32)
|
||||
return (false, "invalid_name", null!);
|
||||
|
||||
name = name.Trim();
|
||||
|
||||
// 1 char / account
|
||||
if (await _repo.FindByAccountAsync(accountId, ct) is not null)
|
||||
return (false, "char_limit", null!);
|
||||
|
||||
// unique names
|
||||
if (await _repo.FindByNameAsync(name, ct) is not null)
|
||||
return (false, "name_taken", null!);
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
|
||||
var c = new Old_Character
|
||||
{
|
||||
AccountId = accountId,
|
||||
Name = name,
|
||||
|
||||
Level = 1,
|
||||
Xp = 0,
|
||||
|
||||
StatStrength = 1,
|
||||
StatDexterity = 1,
|
||||
StatWisdom = 1,
|
||||
StatIntelligence = 1,
|
||||
StatEndurance = 1,
|
||||
|
||||
HpCurrent = 10,
|
||||
HpMax = 10,
|
||||
MpCurrent = 0,
|
||||
MpMax = 0,
|
||||
StaminaCurrent = 0,
|
||||
StaminaMax = 0,
|
||||
|
||||
ZoneId = 1,
|
||||
PosX = 0,
|
||||
PosY = 0,
|
||||
PosZ = 0,
|
||||
FacingDeg = 0f,
|
||||
|
||||
AppearanceJson = null,
|
||||
CreatedAt = now,
|
||||
UpdatedAt = now
|
||||
};
|
||||
|
||||
var created = await _repo.AddAsync(c, ct);
|
||||
_log.LogInformation("Character {Id} '{Name}' created for account {Acct}", created.Id, created.Name, accountId);
|
||||
return (true, null, created);
|
||||
}
|
||||
|
||||
public async Task<(bool ok, string? error, Old_Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct)
|
||||
{
|
||||
var c = await _repo.FindByIdAsync(characterId, ct);
|
||||
if (c is null || c.AccountId != accountId)
|
||||
return (false, "char_not_found", null!);
|
||||
return (true, null, c);
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DataServer.Data;
|
||||
|
||||
public interface ICharactersRepository
|
||||
{
|
||||
Task<Old_Character?> FindByIdAsync(ulong id, CancellationToken ct);
|
||||
Task<Old_Character?> FindByNameAsync(string name, CancellationToken ct);
|
||||
Task<Old_Character?> FindByAccountAsync(ulong accountId, CancellationToken ct); // 1 char / account (unique)
|
||||
Task<Old_Character> AddAsync(Old_Character c, CancellationToken ct);
|
||||
Task SaveAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class CharactersRepository : ICharactersRepository
|
||||
{
|
||||
private readonly GameDbContext _db;
|
||||
public CharactersRepository(GameDbContext db) => _db = db;
|
||||
|
||||
public Task<Old_Character?> FindByIdAsync(ulong id, CancellationToken ct) =>
|
||||
_db.Characters.FirstOrDefaultAsync(x => x.Id == id, ct);
|
||||
|
||||
public Task<Old_Character?> FindByNameAsync(string name, CancellationToken ct) =>
|
||||
_db.Characters.FirstOrDefaultAsync(x => x.Name == name, ct);
|
||||
|
||||
public Task<Old_Character?> FindByAccountAsync(ulong accountId, CancellationToken ct) =>
|
||||
_db.Characters.FirstOrDefaultAsync(x => x.AccountId == accountId, ct);
|
||||
|
||||
public async Task<Old_Character> AddAsync(Old_Character c, CancellationToken ct)
|
||||
{
|
||||
_db.Characters.Add(c);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
return c;
|
||||
}
|
||||
|
||||
public Task SaveAsync(CancellationToken ct) => _db.SaveChangesAsync(ct);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
using DataServer.Data;
|
||||
|
||||
namespace Server.Services.Characters;
|
||||
|
||||
public interface ICharacterService
|
||||
{
|
||||
Task<(bool ok, string? error, Old_Character[] list)> ListAsync(ulong accountId, CancellationToken ct);
|
||||
Task<(bool ok, string? error, Old_Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct);
|
||||
Task<(bool ok, string? error, Old_Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace Server.Services;
|
||||
public interface IZoneLeaseService
|
||||
{
|
||||
ValueTask<bool> TryAcquireAsync(ulong zoneId, CancellationToken ct = default);
|
||||
ValueTask<bool> RenewAsync(ulong zoneId, CancellationToken ct = default);
|
||||
ValueTask ReleaseAsync(ulong zoneId, CancellationToken ct = default);
|
||||
bool IsOwner(ulong zoneId);
|
||||
long CurrentFence(ulong zoneId);
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
// Server.Services.World/WorldHandler.cs
|
||||
using Server.Networking;
|
||||
using Server.Networking.Handling;
|
||||
using Server.Networking.Messages;
|
||||
using Server.Services.Auth;
|
||||
|
||||
namespace Server.Services.World;
|
||||
|
||||
public sealed class WorldHandler : IClientMessageHandler
|
||||
{
|
||||
private readonly ILogger<WorldHandler> _log;
|
||||
private readonly IWorldService _world;
|
||||
private readonly ISessionRegistry _sessions;
|
||||
private readonly IZoneLeaseService _lease;
|
||||
private readonly IMessageSerializer _ser;
|
||||
private readonly HandlerContext _ctx;
|
||||
|
||||
public WorldHandler(
|
||||
ILogger<WorldHandler> log,
|
||||
IWorldService world,
|
||||
ISessionRegistry sessions,
|
||||
IZoneLeaseService lease,
|
||||
IMessageSerializer ser)
|
||||
{
|
||||
_log = log; _world = world; _sessions = sessions; _lease = lease; _ser = ser;
|
||||
_ctx = new HandlerContext(ser);
|
||||
}
|
||||
|
||||
public IReadOnlyCollection<int> SupportedOpCodes => new[]
|
||||
{
|
||||
OpCodes.WORLD_SPAWN_REQUEST,
|
||||
OpCodes.WORLD_INPUT
|
||||
};
|
||||
|
||||
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
||||
{
|
||||
// Expect: TryGet(connId, out accountId, out token)
|
||||
if (!_sessions.TryGet(connection.Id, out var accountId, out var token))
|
||||
{
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "auth_required" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Expect: TryGetCharacter(connId, out characterId) ← add this to ISessionRegistry if missing
|
||||
if (!_sessions.TryGetCharacter(connection.Id, out var charId))
|
||||
{
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "character_required" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (opCode)
|
||||
{
|
||||
case OpCodes.WORLD_SPAWN_REQUEST:
|
||||
{
|
||||
var req = _ser.Deserialize<WorldSpawnRequest>(payload);
|
||||
if (!_lease.IsOwner((ulong)req.ZoneId))
|
||||
{
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "not_owner_zone" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var result = await _world.SpawnAsync(accountId, charId, ct);
|
||||
var ok = result.ok; var error = result.error; var self = result.self; var neighbors = result.neighbors;
|
||||
|
||||
if (!ok)
|
||||
{
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = error ?? "spawn_failed" }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.WORLD_SPAWN, self, ct);
|
||||
foreach (var n in neighbors)
|
||||
await _ctx.ReplyObjectAsync(connection, OpCodes.WORLD_SPAWN, n, ct);
|
||||
break;
|
||||
}
|
||||
|
||||
case OpCodes.WORLD_INPUT:
|
||||
{
|
||||
var req = _ser.Deserialize<WorldInput>(payload);
|
||||
if (!_lease.IsOwner((ulong)req.ZoneId)) return; // ignore for MVP
|
||||
_world.EnqueueInput((ulong)req.ZoneId, charId, req.Dx, req.Dy, req.Facing, req.ClientSeq);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
// Server.Services.World/WorldService.cs
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using DataServer.Data;
|
||||
using Server.World;
|
||||
using StackExchange.Redis;
|
||||
using Server.Networking.Messages;
|
||||
|
||||
namespace Server.Services.World;
|
||||
|
||||
public sealed class WorldService : IWorldService
|
||||
{
|
||||
private readonly ILogger<WorldService> _log;
|
||||
private readonly ICharactersRepository _chars;
|
||||
private readonly IPresenceStore _presence;
|
||||
private readonly IDatabase _db; // Redis
|
||||
private readonly TimeSpan _cellTtl = TimeSpan.FromSeconds(30);
|
||||
|
||||
// In-memory zone state (per owner node)
|
||||
private sealed record Entity(ulong Id, string Name, float X, float Y, float Z, float FacingRad, float Speed);
|
||||
|
||||
private readonly ConcurrentDictionary<ulong, ConcurrentDictionary<ulong, Entity>> _zones = new();
|
||||
private readonly ConcurrentDictionary<ulong, ConcurrentQueue<(ulong CharId, float Dx, float Dy, float FacingRad)>> _inputs = new();
|
||||
|
||||
public WorldService(
|
||||
ILogger<WorldService> log,
|
||||
ICharactersRepository chars,
|
||||
IPresenceStore presence,
|
||||
IDatabase db)
|
||||
{
|
||||
_log = log; _chars = chars; _presence = presence; _db = db;
|
||||
}
|
||||
|
||||
public async Task<(bool ok, string? error, WorldSpawn self, IEnumerable<WorldSpawn> neighbors)>
|
||||
SpawnAsync(ulong accountId, ulong characterId, CancellationToken ct)
|
||||
{
|
||||
// Prefer Redis presence; fallback to DB row.
|
||||
var pos = await _presence.GetAsync(characterId, ct);
|
||||
Old_Character? row;
|
||||
|
||||
if (pos is null)
|
||||
{
|
||||
row = await _chars.FindByIdAsync(characterId, ct);
|
||||
if (row is null || row.AccountId != accountId)
|
||||
return (false, "char_not_found", default!, Array.Empty<WorldSpawn>());
|
||||
|
||||
var facingRad = row.FacingDeg * (MathF.PI / 180f);
|
||||
pos = new Pos(row.ZoneId, (float)row.PosX, (float)row.PosY, (float)row.PosZ, facingRad);
|
||||
await _presence.SetAsync(characterId, pos, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
row = await _chars.FindByIdAsync(characterId, ct);
|
||||
if (row is null)
|
||||
return (false, "char_not_found", default!, Array.Empty<WorldSpawn>());
|
||||
}
|
||||
|
||||
// Update spatial cell
|
||||
var cell = SpatialIndex.Cell(pos.X, pos.Y, pos.Z);
|
||||
await SpatialIndex.UpdateAsync(_db, pos.ZoneId, characterId, cell, cell, _cellTtl);
|
||||
|
||||
// Track in-memory entity
|
||||
var zone = _zones.GetOrAdd(pos.ZoneId, _ => new());
|
||||
var ent = new Entity(characterId, row!.Name, pos.X, pos.Y, pos.Z, pos.FacingRad, 5f);
|
||||
zone[characterId] = ent;
|
||||
|
||||
var self = new WorldSpawn(ent.Id, ent.Name, (int)pos.ZoneId, ent.X, ent.Y, ent.Z, ent.FacingRad, ent.Speed);
|
||||
var neighbors = zone.Values.Where(e => e.Id != ent.Id)
|
||||
.Select(e => new WorldSpawn(e.Id, e.Name, (int)pos.ZoneId, e.X, e.Y, e.Z, e.FacingRad, e.Speed))
|
||||
.ToArray();
|
||||
|
||||
return (true, null, self, neighbors);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void EnqueueInput(ulong zoneId, ulong characterId, float dx, float dy, float facingRad, uint clientSeq)
|
||||
{
|
||||
var q = _inputs.GetOrAdd(zoneId, _ => new());
|
||||
q.Enqueue((characterId, dx, dy, facingRad));
|
||||
}
|
||||
|
||||
public async Task TickOwnerAsync(ulong zoneId, float dt, CancellationToken ct)
|
||||
{
|
||||
if (!_zones.TryGetValue(zoneId, out var ents)) return;
|
||||
|
||||
if (_inputs.TryGetValue(zoneId, out var q))
|
||||
{
|
||||
while (q.TryDequeue(out var itm))
|
||||
{
|
||||
if (!ents.TryGetValue(itm.CharId, out var e)) continue;
|
||||
|
||||
// Normalize input
|
||||
var dx = itm.Dx; var dy = itm.Dy;
|
||||
var mag = MathF.Sqrt(dx * dx + dy * dy);
|
||||
if (mag > 1e-4f) { dx /= mag; dy /= mag; }
|
||||
|
||||
var nx = e.X + dx * e.Speed * dt;
|
||||
var ny = e.Y + dy * e.Speed * dt;
|
||||
var nf = float.IsFinite(itm.FacingRad) ? itm.FacingRad : e.FacingRad;
|
||||
|
||||
var updated = e with { X = nx, Y = ny, FacingRad = nf };
|
||||
ents[e.Id] = updated;
|
||||
|
||||
await _presence.SetAsync(e.Id, new Pos(zoneId, nx, ny, e.Z, nf), ct);
|
||||
|
||||
var oldCell = SpatialIndex.Cell(e.X, e.Y, e.Z);
|
||||
var newCell = SpatialIndex.Cell(nx, ny, e.Z);
|
||||
await SpatialIndex.UpdateAsync(_db, zoneId, e.Id, oldCell, newCell, _cellTtl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public WorldState BuildSnapshot(ulong zoneId, long tick)
|
||||
{
|
||||
if (!_zones.TryGetValue(zoneId, out var ents))
|
||||
return new WorldState((int)zoneId, tick, Array.Empty<WorldEntityState>());
|
||||
|
||||
var list = ents.Values.Select(e => new WorldEntityState(e.Id, e.X, e.Y, e.Z, e.FacingRad, e.Speed)).ToArray();
|
||||
return new WorldState((int)zoneId, tick, list);
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Server.Redis;
|
||||
|
||||
namespace Server.Services;
|
||||
|
||||
public sealed class ZoneLeaseService : IZoneLeaseService, IHostedService, IDisposable
|
||||
{
|
||||
private readonly IRedisManager _redis;
|
||||
private readonly ILogger<ZoneLeaseService> _log;
|
||||
private readonly string _podId = Environment.GetEnvironmentVariable("POD_ID") ?? Guid.NewGuid().ToString("N");
|
||||
private readonly TimeSpan _ttl = TimeSpan.FromSeconds(5);
|
||||
private readonly TimeSpan _renew = TimeSpan.FromSeconds(2);
|
||||
private readonly ConcurrentDictionary<ulong, long> _owned = new();
|
||||
private Timer? _timer;
|
||||
|
||||
public ZoneLeaseService(IRedisManager redis, ILogger<ZoneLeaseService> log)
|
||||
{ _redis = redis; _log = log; }
|
||||
|
||||
public bool IsOwner(ulong zoneId) => _owned.ContainsKey(zoneId);
|
||||
public long CurrentFence(ulong zoneId) => _owned.TryGetValue(zoneId, out var f) ? f : -1;
|
||||
|
||||
public async ValueTask<bool> TryAcquireAsync(ulong zoneId, CancellationToken ct = default)
|
||||
{
|
||||
var fence = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
var val = $"{_podId}:{fence}";
|
||||
var key = $"zone:owner:{{{zoneId}}}"; // hash tag for cluster
|
||||
var ok = await _redis.Db.StringSetAsync(key, val, _ttl, when: StackExchange.Redis.When.NotExists);
|
||||
if (ok) { _owned[zoneId] = fence; _log.LogInformation("Zone {Zone} acquired, fence={Fence}", zoneId, fence); }
|
||||
return ok;
|
||||
}
|
||||
|
||||
public async ValueTask<bool> RenewAsync(ulong zoneId, CancellationToken ct = default)
|
||||
{
|
||||
if (!_owned.TryGetValue(zoneId, out var fence)) return false;
|
||||
var key = $"zone:owner:{{{zoneId}}}";
|
||||
// renew if matches (Lua CAS)
|
||||
const string lua = @"
|
||||
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
||||
redis.call('PEXPIRE', KEYS[1], ARGV[2]); return 1
|
||||
else return 0 end";
|
||||
var res = (int)(long)await _redis.Db.ScriptEvaluateAsync(lua,
|
||||
new StackExchange.Redis.RedisKey[] { key },
|
||||
new StackExchange.Redis.RedisValue[] { $"{_podId}:{fence}", (long)_ttl.TotalMilliseconds });
|
||||
return res == 1;
|
||||
}
|
||||
|
||||
public async ValueTask ReleaseAsync(ulong zoneId, CancellationToken ct = default)
|
||||
{
|
||||
if (!_owned.TryRemove(zoneId, out var fence)) return;
|
||||
var key = $"zone:owner:{{{zoneId}}}";
|
||||
const string lua = @"if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end";
|
||||
await _redis.Db.ScriptEvaluateAsync(lua,
|
||||
new StackExchange.Redis.RedisKey[] { key },
|
||||
new StackExchange.Redis.RedisValue[] { $"{_podId}:{fence}" });
|
||||
_log.LogInformation("Zone {Zone} released", zoneId);
|
||||
}
|
||||
|
||||
// Background renew loop
|
||||
public Task StartAsync(CancellationToken _) { _timer = new Timer(async _ => await RenewAll(), null, _renew, _renew); return Task.CompletedTask; }
|
||||
public Task StopAsync(CancellationToken _) { _timer?.Dispose(); return Task.CompletedTask; }
|
||||
private async Task RenewAll()
|
||||
{
|
||||
foreach (var z in _owned.Keys) { if (!await RenewAsync(z)) _owned.TryRemove(z, out _); }
|
||||
}
|
||||
public void Dispose() => _timer?.Dispose();
|
||||
}
|
||||
Reference in New Issue
Block a user