Move economy server to Aetheria state spine
This commit is contained in:
parent
89e91ff4d7
commit
0a4f1530fb
7 changed files with 84 additions and 487 deletions
Binary file not shown.
|
|
@ -11,7 +11,6 @@ using Cinemachine;
|
|||
using Ink;
|
||||
using Ink.Runtime;
|
||||
using MessagePack;
|
||||
using Newtonsoft.Json;
|
||||
using TMPro;
|
||||
using UniRx;
|
||||
using UnityEngine;
|
||||
|
|
@ -38,30 +37,34 @@ public class ActionGameManager : MonoBehaviour
|
|||
get => _gameDataDirectory ??= new DirectoryInfo(Application.dataPath).Parent.CreateSubdirectory("GameData");
|
||||
}
|
||||
|
||||
private static CultCache _cultCache;
|
||||
public static string AetheriaStateFilePath => Path.Combine(GameDataDirectory.FullName, "aetheria-world.cc");
|
||||
public static string LegacyAetherDatabasePath => Path.Combine(GameDataDirectory.FullName, "AetherDB.msgpack");
|
||||
|
||||
public static CultCache CultCache
|
||||
private static CultCache _legacyCultCache;
|
||||
|
||||
public static CultCache LegacyCultCache
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_cultCache != null) return _cultCache;
|
||||
if (_legacyCultCache != null) return _legacyCultCache;
|
||||
|
||||
_cultCache = new CultCache();
|
||||
//RethinkConnection.RethinkConnect(_cultCache, "gamecult.org:28016", DatabaseName);
|
||||
//_cultCache.AddBackingStore(new MultiFileJsonBackingStore(GameDataDirectory.FullName));
|
||||
_cultCache.AddBackingStore(
|
||||
new SingleFileMessagePackBackingStore(Path.Combine(GameDataDirectory.FullName, "AetherDB.msgpack")));
|
||||
_legacyCultCache = new CultCache();
|
||||
_legacyCultCache.AddBackingStore(
|
||||
new SingleFileMessagePackBackingStore(LegacyAetherDatabasePath));
|
||||
|
||||
// Particularly heavy objects should be stored in / retrieved from MsgPack files as it's much tighter than JSON
|
||||
// Such as NameFiles, which are just huge collections of geonames used to condition Markov chains
|
||||
_cultCache.AddBackingStore(new MultiFileMessagePackBackingStore(GameDataDirectory.FullName), typeof(NameFile));
|
||||
_legacyCultCache.AddBackingStore(new MultiFileMessagePackBackingStore(GameDataDirectory.FullName), typeof(NameFile));
|
||||
|
||||
_cultCache.PullAllBackingStores();
|
||||
_legacyCultCache.PullAllBackingStores();
|
||||
|
||||
return _cultCache;
|
||||
return _legacyCultCache;
|
||||
}
|
||||
}
|
||||
|
||||
[Obsolete("Use LegacyCultCache only for migration-era catalog reads. Live state belongs in GameData/aetheria-world.cc through Aetheria.State.")]
|
||||
public static CultCache CultCache => LegacyCultCache;
|
||||
|
||||
private static PlayerSettings _playerSettings;
|
||||
public static PlayerSettings PlayerSettings
|
||||
{
|
||||
|
|
@ -263,7 +266,9 @@ public class ActionGameManager : MonoBehaviour
|
|||
EntityInstance.EffectManagerParent = EffectManagerParent;
|
||||
ConsoleController.MessageReceiver = this;
|
||||
|
||||
ItemManager = new ItemManager(CultCache, Settings.GameplaySettings, Debug.Log);
|
||||
Debug.Log($"Aetheria typed state file: {AetheriaStateFilePath}");
|
||||
Debug.Log($"Aetheria legacy item catalog: {LegacyAetherDatabasePath}");
|
||||
ItemManager = new ItemManager(LegacyCultCache, Settings.GameplaySettings, Debug.Log);
|
||||
ZoneRenderer.ItemManager = ItemManager;
|
||||
|
||||
// If hiding minimap asteroids, turn them off to start with
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ public class MainMenu : MonoBehaviour
|
|||
private float _fadeLerp;
|
||||
private bool _fading;
|
||||
private Vector3 _panelPosition;
|
||||
//private Task<DatabaseCache> _databaseLoad;
|
||||
|
||||
void Start()
|
||||
{
|
||||
|
|
@ -100,7 +99,7 @@ public class MainMenu : MonoBehaviour
|
|||
{
|
||||
ActionGameManager.IsTutorial = ActionGameManager.PlayerSettings.SavedRun.IsTutorial;
|
||||
ActionGameManager.CurrentGalaxy = new Galaxy(
|
||||
ActionGameManager.CultCache,
|
||||
ActionGameManager.LegacyCultCache,
|
||||
ActionGameManager.PlayerSettings.SavedRun,
|
||||
Debug.Log);
|
||||
SceneManager.LoadScene("ARPG");
|
||||
|
|
@ -131,7 +130,7 @@ public class MainMenu : MonoBehaviour
|
|||
Settings.SectorGenerationSettings,
|
||||
Settings.SectorBackgroundSettings,
|
||||
Settings.NameGeneratorSettings,
|
||||
ActionGameManager.CultCache,
|
||||
ActionGameManager.LegacyCultCache,
|
||||
Debug.Log,
|
||||
setState);
|
||||
Observable.NextFrame().Subscribe(_ =>
|
||||
|
|
@ -158,7 +157,7 @@ public class MainMenu : MonoBehaviour
|
|||
Settings.TutorialGenerationSettings,
|
||||
Settings.TutorialBackgroundSettings,
|
||||
Settings.NameGeneratorSettings,
|
||||
ActionGameManager.CultCache,
|
||||
ActionGameManager.LegacyCultCache,
|
||||
ActionGameManager.PlayerSettings,
|
||||
ActionGameManager.GameDataDirectory.CreateSubdirectory("Narrative"),
|
||||
Debug.Log,
|
||||
|
|
|
|||
|
|
@ -390,7 +390,7 @@ public class PropertiesPanel : MonoBehaviour
|
|||
AddProperty("Quantity", () => simpleCommodity.Quantity.ToString());
|
||||
|
||||
var sheet = AddStatSheet();
|
||||
var manufacturer = ActionGameManager.CultCache.Get<Faction>(data.Manufacturer);
|
||||
var manufacturer = ActionGameManager.LegacyCultCache.Get<Faction>(data.Manufacturer);
|
||||
sheet.AddStat("Manufacturer", () => manufacturer?.Name ?? "GameCult");
|
||||
sheet.AddStat("Mass", () => ActionGameManager.PlayerSettings.Format(GameManager.ItemManager.GetMass(item)));
|
||||
|
||||
|
|
|
|||
|
|
@ -2,20 +2,14 @@
|
|||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="1.1.3" />
|
||||
<PackageReference Include="MessagePack" Version="2.1.90" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="5.0.0-preview.1.20120.4" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.2-dev-10272" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0-dev-00864" />
|
||||
<PackageReference Include="System.Reactive.Linq" Version="4.3.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Economy.Shared\Economy.Shared.csproj" />
|
||||
<ProjectReference Include="..\Aetheria.State\Aetheria.State.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -1,234 +1,73 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reactive.Concurrency;
|
||||
using System.Reactive.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MessagePack;
|
||||
using MessagePack.Resolvers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using RethinkDb.Driver;
|
||||
using RethinkDb.Driver.Ast;
|
||||
using RethinkDb.Driver.Net;
|
||||
using Serilog;
|
||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||
using Aetheria.State;
|
||||
using Aetheria.State.Documents;
|
||||
|
||||
namespace ChatApp.Server
|
||||
namespace Aetheria.Server;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
class Program
|
||||
private static async Task Main(string[] args)
|
||||
{
|
||||
private static readonly RethinkDB R = RethinkDB.R;
|
||||
private static ILogger _logger;
|
||||
|
||||
static async Task Main(string[] args)
|
||||
var statePath = ResolveStatePath(args);
|
||||
Console.WriteLine($"Aetheria CultMesh state host starting: {statePath}");
|
||||
|
||||
await using var node = await AetheriaStateNode.OpenAsync(
|
||||
statePath,
|
||||
runtimeId: "aetheria-economy-server",
|
||||
startServer: true).ConfigureAwait(false);
|
||||
|
||||
await EnsureWorldDocumentAsync(node).ConfigureAwait(false);
|
||||
await node.FlushAsync().ConfigureAwait(false);
|
||||
|
||||
Console.WriteLine("Aetheria CultMesh state host is running. Press Ctrl+C to stop.");
|
||||
await WaitForShutdownAsync().ConfigureAwait(false);
|
||||
|
||||
Console.WriteLine("Aetheria CultMesh state host stopping.");
|
||||
}
|
||||
|
||||
private static string ResolveStatePath(IReadOnlyList<string> args)
|
||||
{
|
||||
for (var i = 0; i < args.Count - 1; i++)
|
||||
{
|
||||
var serilogger = new LoggerConfiguration()
|
||||
.WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
|
||||
.CreateLogger();
|
||||
var loggerFactory = LoggerFactory.Create(builder =>
|
||||
if (string.Equals(args[i], "--state", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
builder
|
||||
// .AddFilter("Microsoft", LogLevel.Warning)
|
||||
// .AddFilter("System", LogLevel.Warning)
|
||||
// .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
|
||||
.AddSerilog(serilogger)
|
||||
.AddConsole();
|
||||
});
|
||||
_logger = loggerFactory.CreateLogger<Program>();
|
||||
|
||||
// Register extensions to Json.NET Serialization
|
||||
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
|
||||
{
|
||||
Converters = new List<JsonConverter>
|
||||
{
|
||||
new MathJsonConverter(),
|
||||
Converter.DateTimeConverter,
|
||||
Converter.BinaryConverter,
|
||||
Converter.GroupingConverter,
|
||||
Converter.PocoExprConverter
|
||||
}
|
||||
};
|
||||
Converter.Serializer.Converters.Add(new MathJsonConverter());
|
||||
|
||||
// Register extensions to MessagePack Serialization
|
||||
var resolver = CompositeResolver.Create(
|
||||
MathResolver.Instance,
|
||||
NativeGuidResolver.Instance,
|
||||
StandardResolver.Instance
|
||||
);
|
||||
var options = MessagePackSerializerOptions.Standard.WithResolver(resolver);
|
||||
MessagePackSerializer.DefaultOptions = options;
|
||||
|
||||
var connection = R.Connection().Hostname("asgard.gamecult.games")
|
||||
.Port(RethinkDBConstants.DefaultPort).Timeout(60).Connect();
|
||||
|
||||
var cache = new DatabaseCache();
|
||||
|
||||
// When entries are changed locally, push the changes to RethinkDB
|
||||
cache.OnDataUpdateLocal += async entry =>
|
||||
{
|
||||
var table = entry.GetType().GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? "Other";
|
||||
var result = await R.Db("Aetheria").Table(table).Update(entry).RunAsync(connection);
|
||||
_logger.Log(LogLevel.Information, $"Uploaded entry to RethinkDB: {entry.ID} result: {result}");
|
||||
};
|
||||
|
||||
cache.OnDataInsertLocal += async entry =>
|
||||
{
|
||||
var table = entry.GetType().GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? "Other";
|
||||
var inserted = false;
|
||||
for (int i = 0; i < 5 && !inserted; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await R.Db("Aetheria").Table(table).Insert(entry).RunAsync(connection);
|
||||
_logger.Log(LogLevel.Information, $"Inserted entry to RethinkDB: {entry.ID} result: {result}");
|
||||
inserted = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError(e,e.Message);
|
||||
}
|
||||
}
|
||||
if(!inserted)
|
||||
_logger.LogError("Failed to insert after 5 attempts!");
|
||||
};
|
||||
|
||||
cache.OnDataDeleteLocal += async entry =>
|
||||
{
|
||||
var table = entry.GetType().GetCustomAttribute<RethinkTableAttribute>()?.TableName ?? "Other";
|
||||
var result = await R.Db("Aetheria").Table(table).Get(entry.ID).Delete().RunAsync(connection);
|
||||
_logger.Log(LogLevel.Information, $"Deleted entry from RethinkDB: {entry.ID} result: {result}");
|
||||
};
|
||||
|
||||
// Get data from RethinkDB
|
||||
await GetTable("Items", connection, cache);
|
||||
await GetTable("Galaxy", connection, cache);
|
||||
await GetTable("Users", connection, cache);
|
||||
|
||||
// Subscribe to changes from RethinkDB
|
||||
SubscribeTable("Items", connection, cache);
|
||||
SubscribeTable("Galaxy", connection, cache);
|
||||
SubscribeTable("Users", connection, cache);
|
||||
|
||||
var server = new MasterServer(cache)
|
||||
{
|
||||
Logger = _logger
|
||||
};
|
||||
server.Start();
|
||||
|
||||
var context = new GameContext(cache, s=>_logger.Log(LogLevel.Information, s));
|
||||
|
||||
context.MapLayers = cache.GetAll<GalaxyMapLayerData>().ToDictionary(m => m.Name);
|
||||
|
||||
server.AddMessageListener<GalaxyRequestMessage>(galaxyRequest => galaxyRequest.Peer.Send(
|
||||
new GalaxyResponseMessage
|
||||
{
|
||||
Zones = cache.GetAll<ZoneData>().Select(zd=>
|
||||
new GalaxyResponseZone
|
||||
{
|
||||
Name = zd.Name,
|
||||
Position = zd.Position,
|
||||
ZoneID = zd.ID,
|
||||
Links = zd.Wormholes?.ToArray() ?? Array.Empty<Guid>()
|
||||
}).ToArray(),
|
||||
GlobalData = context.GlobalData,
|
||||
StarDensity = context.MapLayers["StarDensity"]
|
||||
}));
|
||||
|
||||
server.AddMessageListener<BlueprintsRequestMessage>(blueprintRequest => blueprintRequest.Peer.Send(
|
||||
new BlueprintsResponseMessage
|
||||
{
|
||||
Blueprints = cache.GetAll<BlueprintData>().ToArray()
|
||||
}));
|
||||
|
||||
server.AddMessageListener<ZoneRequestMessage>(zoneRequest =>
|
||||
{
|
||||
var zone = cache.Get<ZoneData>(zoneRequest.ZoneID);
|
||||
|
||||
// Zone has not been populated, generate the contents now!
|
||||
if (!zone.Visited)
|
||||
{
|
||||
zone.Visited = true;
|
||||
OrbitData[] orbits;
|
||||
PlanetData[] planets;
|
||||
ZoneGenerator.GenerateZone(
|
||||
global: context.GlobalData,
|
||||
zone: zone,
|
||||
mapLayers: context.MapLayers.Values,
|
||||
resources: cache.GetAll<SimpleCommodityData>().Where(i=>i.ResourceDensity.Any()),
|
||||
orbitData: out orbits,
|
||||
planetsData: out planets);
|
||||
cache.AddAll(orbits);
|
||||
cache.AddAll(planets);
|
||||
cache.Add(zone);
|
||||
}
|
||||
zoneRequest.Peer.Send(
|
||||
new ZoneResponseMessage
|
||||
{
|
||||
Zone = zone,
|
||||
Contents = zone.Orbits.Select(id=>cache.Get(id))
|
||||
.Concat(zone.Planets.Select(id=>cache.Get(id)))
|
||||
.Concat(zone.Stations.Select(id=>cache.Get(id))).ToArray()
|
||||
});
|
||||
});
|
||||
|
||||
Observable.Timer(DateTimeOffset.Now, TimeSpan.FromSeconds(60)).SubscribeOn(NewThreadScheduler.Default).Subscribe(_ =>
|
||||
{
|
||||
_logger.Log(LogLevel.Information, R.Now().Run<DateTime>(connection).ToString() as string);
|
||||
});
|
||||
|
||||
while (true)
|
||||
{
|
||||
Thread.Sleep(100);
|
||||
return Path.GetFullPath(args[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
private static void SubscribeTable(string table, Connection connection, DatabaseCache cache)
|
||||
var repoRoot = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", ".."));
|
||||
return AetheriaStatePaths.ResolveDefaultStatePath(repoRoot);
|
||||
}
|
||||
|
||||
private static async Task EnsureWorldDocumentAsync(AetheriaStateNode node)
|
||||
{
|
||||
var existing = await node.GetWorldAsync().ConfigureAwait(false);
|
||||
if (existing != null)
|
||||
{
|
||||
Task.Run(async () =>
|
||||
{
|
||||
var result = await R.Db("Aetheria").Table(table).Changes()
|
||||
.RunChangesAsync<DatabaseEntry>(connection);
|
||||
while (await result.MoveNextAsync())
|
||||
{
|
||||
var change = result.Current;
|
||||
if (change.OldValue == null)
|
||||
{
|
||||
_logger.Log(LogLevel.Information,
|
||||
$"Received change from RethinkDB {table} table (Entry Created): {change.NewValue.GetType()} {(change.NewValue as INamedEntry)?.EntryName ?? ""}:{change.NewValue.ID}");
|
||||
cache.Add(change.NewValue, true);
|
||||
}
|
||||
else if (change.NewValue == null)
|
||||
{
|
||||
_logger.Log(LogLevel.Information,
|
||||
$"Received change from RethinkDB {table} table (Entry Deleted): {change.OldValue.GetType()} {(change.OldValue as INamedEntry)?.EntryName ?? ""}:{change.OldValue.ID}");
|
||||
cache.Delete(change.NewValue, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Log(LogLevel.Information,
|
||||
$"Received change from RethinkDB {table} table: {change.NewValue.GetType()} {(change.NewValue as INamedEntry)?.EntryName ?? ""}:{change.NewValue.ID}");
|
||||
cache.Add(change.NewValue, true);
|
||||
}
|
||||
}
|
||||
});
|
||||
existing.UpdatedAtUtc = DateTimeOffset.UtcNow.ToString("O");
|
||||
await node.PutWorldAsync(existing).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
private static async Task GetTable(string table, Connection connection, DatabaseCache cache)
|
||||
var now = DateTimeOffset.UtcNow.ToString("O");
|
||||
await node.PutWorldAsync(new AetheriaWorldState
|
||||
{
|
||||
var result = await R.Db("Aetheria").Table(table).RunCursorAsync<DatabaseEntry>(connection);
|
||||
while (await result.MoveNextAsync())
|
||||
{
|
||||
var entry = result.Current;
|
||||
_logger.Log(LogLevel.Information,
|
||||
$"Received {table} entry from RethinkDB: {entry.GetType()} {(entry as INamedEntry)?.EntryName ?? ""}:{entry.ID}");
|
||||
cache.Add(entry, true);
|
||||
}
|
||||
}
|
||||
Name = "Aetheria",
|
||||
WorldId = "aetheria",
|
||||
SchemaEpoch = 1,
|
||||
CreatedAtUtc = now,
|
||||
UpdatedAtUtc = now
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static Task WaitForShutdownAsync()
|
||||
{
|
||||
var stopped = new TaskCompletionSource<object?>();
|
||||
Console.CancelKeyPress += (_, eventArgs) =>
|
||||
{
|
||||
eventArgs.Cancel = true;
|
||||
stopped.TrySetResult(null);
|
||||
};
|
||||
|
||||
return stopped.Task;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,240 +0,0 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.RegularExpressions;
|
||||
using Isopoh.Cryptography.Argon2;
|
||||
using LiteNetLib;
|
||||
using MessagePack;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public class MasterServer
|
||||
{
|
||||
public ILogger Logger = null;
|
||||
|
||||
private const string EmailPattern =
|
||||
@"^([0-9a-zA-Z]" + //Start with a digit or alphabetical
|
||||
@"([\+\-_\.][0-9a-zA-Z]+)*" + // No continuous or ending +-_. chars in email
|
||||
@")+" +
|
||||
@"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
|
||||
|
||||
private const string UsernamePattern = @"^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$";
|
||||
private readonly Dictionary<Type, NotAnActionCollection> _messageCallbacks = new Dictionary<Type, NotAnActionCollection>();
|
||||
private readonly Dictionary<long, User> _users = new Dictionary<long, User>();
|
||||
private readonly Dictionary<Guid, Session> _sessions = new Dictionary<Guid, Session>();
|
||||
private List<User> _readyPlayers = new List<User>();
|
||||
private NetManager _netManager;
|
||||
private Stopwatch _timer;
|
||||
private Random _random = new Random();
|
||||
private readonly DatabaseCache _database;
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
|
||||
private float Time => (float)_timer.Elapsed.TotalSeconds;
|
||||
|
||||
public bool IsValidEmail(string email) => Regex.IsMatch(email, EmailPattern);
|
||||
public bool IsValidUsername(string name) => Regex.IsMatch(name, UsernamePattern);
|
||||
|
||||
public MasterServer(DatabaseCache cache)
|
||||
{
|
||||
_database = cache;
|
||||
}
|
||||
|
||||
public void ClearMessageListeners()
|
||||
{
|
||||
_messageCallbacks.Clear();
|
||||
}
|
||||
|
||||
public void AddMessageListener<T>(Action<T> callback) where T : Message
|
||||
{
|
||||
if (!_messageCallbacks.ContainsKey(typeof(T)))
|
||||
_messageCallbacks[typeof(T)] = new ActionCollection<T>();
|
||||
((ActionCollection<T>)_messageCallbacks[typeof(T)]).Add(callback);
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_netManager.Stop();
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_timer = new Stopwatch();
|
||||
_timer.Start();
|
||||
|
||||
EventBasedNetListener listener = new EventBasedNetListener();
|
||||
_netManager = new NetManager(listener)
|
||||
{
|
||||
UnsyncedEvents = true,
|
||||
NatPunchEnabled = true,
|
||||
};
|
||||
_netManager.Start(3075);
|
||||
|
||||
listener.NetworkErrorEvent += (point, code) => Logger.Log(LogLevel.Debug, $"{point.Address}: Error {code}");
|
||||
|
||||
listener.ConnectionRequestEvent += request => request.AcceptIfKey("aetheria-cc65a44d");
|
||||
|
||||
listener.PeerConnectedEvent += peer =>
|
||||
{
|
||||
Logger.Log(LogLevel.Debug, $"User Connected: {peer.EndPoint}"); // Show peer ip
|
||||
_users[peer.Id] = new User {Peer = peer};
|
||||
};
|
||||
|
||||
listener.PeerDisconnectedEvent += (peer, info) =>
|
||||
{
|
||||
Logger.Log(LogLevel.Debug, $"User Disconnected: {peer.EndPoint}"); // Show peer ip
|
||||
|
||||
// foreach (var verifiedUser in _users.Values.Where(IsVerified))
|
||||
// verifiedUser.Peer.Send("PlayerLeft", SessionData(verifiedUser.Peer).Username);
|
||||
|
||||
_users.Remove(peer.Id);
|
||||
};
|
||||
|
||||
listener.NetworkLatencyUpdateEvent += (peer, latency) =>
|
||||
{
|
||||
// Logger($"Received Ping: {latency}");
|
||||
_users[peer.Id].Latency = latency;
|
||||
};
|
||||
|
||||
listener.NetworkReceiveEvent += (peer, reader, method) =>
|
||||
{
|
||||
var bytes = reader.GetRemainingBytes();
|
||||
var message = MessagePackSerializer.Deserialize<Message>(bytes);
|
||||
Logger.Log(LogLevel.Information, $"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
|
||||
if (message == null)
|
||||
return;
|
||||
message.Peer = peer;
|
||||
var user = _users[peer.Id];
|
||||
var type = message.GetType();
|
||||
|
||||
if (type == typeof(LoginMessage) || type == typeof(RegisterMessage) || type == typeof(VerifyMessage))
|
||||
{
|
||||
if (IsVerified(user))
|
||||
{
|
||||
peer.Send(new LoginSuccessMessage {Session = _users[peer.Id].SessionGuid});
|
||||
return;
|
||||
}
|
||||
|
||||
Guid sessionGuid;
|
||||
switch (message)
|
||||
{
|
||||
case RegisterMessage register when !IsValidUsername(register.Name):
|
||||
peer.Send(new ErrorMessage {Error = "Username Invalid"});
|
||||
return;
|
||||
case RegisterMessage register when !IsValidEmail(register.Email):
|
||||
peer.Send(new ErrorMessage {Error = "Email Invalid"});
|
||||
return;
|
||||
case RegisterMessage register:
|
||||
{
|
||||
sessionGuid = Guid.NewGuid();
|
||||
peer.Send(new LoginSuccessMessage {Session = sessionGuid});
|
||||
|
||||
var newUserData = new Player
|
||||
{
|
||||
ID = Guid.NewGuid(),
|
||||
Email = register.Email,
|
||||
Password = Argon2.Hash(register.Password, null, memoryCost: 16384),
|
||||
Username = register.Name
|
||||
};
|
||||
_database.Add(newUserData);
|
||||
|
||||
_sessions[sessionGuid] = new Session {Data = newUserData, LastUpdate = DateTime.Now};
|
||||
if (!_users.ContainsKey(peer.Id))
|
||||
return;
|
||||
_users[peer.Id].SessionGuid = sessionGuid;
|
||||
break;
|
||||
}
|
||||
case VerifyMessage verify when _sessions.ContainsKey(verify.Session):
|
||||
_users[peer.Id].SessionGuid = verify.Session;
|
||||
peer.Send(new LoginSuccessMessage {Session = verify.Session});
|
||||
return;
|
||||
case LoginMessage login:
|
||||
{
|
||||
var isEmail = IsValidEmail(login.Auth);
|
||||
var userData = _database.GetAll<Player>().FirstOrDefault(x =>
|
||||
(isEmail ? x.Email : x.Username) == login.Auth);
|
||||
|
||||
if (userData == null)
|
||||
{
|
||||
peer.Send(new ErrorMessage {Error = isEmail ? "Email Not Found" : "Username Not Found"});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Argon2.Verify(userData.Password, login.Password))
|
||||
{
|
||||
peer.Send(new ErrorMessage {Error = "Password Incorrect"});
|
||||
return;
|
||||
}
|
||||
|
||||
sessionGuid = Guid.NewGuid();
|
||||
peer.Send(new LoginSuccessMessage {Session = sessionGuid});
|
||||
|
||||
_sessions.Add(sessionGuid, new Session { Data = userData, LastUpdate = DateTime.Now });
|
||||
// TODO: Intermittent: users getting disconnected before getting here, check that key exists!
|
||||
if (!_users.ContainsKey(peer.Id))
|
||||
return;
|
||||
_users[peer.Id].SessionGuid = sessionGuid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (IsVerified(user))
|
||||
{
|
||||
if (_messageCallbacks.ContainsKey(type))
|
||||
typeof(ActionCollection<>).MakeGenericType(new[] {type}).GetMethod("Invoke")
|
||||
.Invoke(_messageCallbacks[type], new object[] {message});
|
||||
else Logger.Log(LogLevel.Warning, $"Received {type.Name} message but no one is listening for it so I'll just leave it here ¯\\_(ツ)_/¯\n{MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
|
||||
_sessions[_users[peer.Id].SessionGuid].LastUpdate = DateTime.Now;
|
||||
}
|
||||
else
|
||||
peer.Send(new ErrorMessage {Error = "User Not Verified"});
|
||||
}
|
||||
};
|
||||
|
||||
AddMessageListener<ChatMessage>(message =>
|
||||
{
|
||||
foreach (var verifiedUser in _users.Values.Where(IsVerified))
|
||||
verifiedUser.Peer.Send(new ChatBroadcastMessage{User = SessionData(message.Peer).Username, Text = message.Text});
|
||||
});
|
||||
|
||||
AddMessageListener<ChangeNameMessage>(message =>
|
||||
{
|
||||
SessionData(message.Peer).Username = message.Name;
|
||||
_database.Add(SessionData(message.Peer));
|
||||
});
|
||||
|
||||
// Observable.Timer(DateTimeOffset.Now, TimeSpan.FromSeconds(30)).Subscribe(_ =>
|
||||
// {
|
||||
// foreach (var s in _sessions.ToArray())
|
||||
// {
|
||||
// if (DateTime.Now.Subtract(s.Value.LastUpdate).TotalSeconds > s.Value.DurationSeconds)
|
||||
// _sessions.Remove(s.Key);
|
||||
// }
|
||||
// });
|
||||
|
||||
Logger.LogInformation("LiteNetLib is now open to new connections. Please be gentle.");
|
||||
}
|
||||
|
||||
private bool IsVerified(User u) => _sessions.ContainsKey(u.SessionGuid);
|
||||
|
||||
public Player SessionData(NetPeer peer) => IsVerified(_users[peer.Id])?_sessions[_users[peer.Id].SessionGuid].Data:null;
|
||||
}
|
||||
|
||||
public class Session
|
||||
{
|
||||
public DateTime LastUpdate;
|
||||
public Player Data;
|
||||
public float DurationSeconds;
|
||||
}
|
||||
|
||||
public class User
|
||||
{
|
||||
public NetPeer Peer;
|
||||
public int Latency;
|
||||
public Guid SessionGuid;
|
||||
public float Tardiness;
|
||||
}
|
||||
Loading…
Reference in a new issue