Skip to content

Commit

Permalink
added AppId support for serverlist completey
Browse files Browse the repository at this point in the history
  • Loading branch information
Speidy674 committed Mar 13, 2023
1 parent fcac773 commit c00d1d7
Show file tree
Hide file tree
Showing 8 changed files with 110 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public struct Room
public string serverData;
public bool isPublic;
public int maxPlayers;

public int appId;
public string version;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@ public async Task ServerListUpdate(IHttpContext context)
_regionRooms[LRMRegions.Any].AddRange(requestedRooms);
_regionRooms[relays[i].Key.serverRegion].AddRange(requestedRooms);

List<List<Room>> _appRooms = requestedRooms.GroupBy(x => x.appId).Select(grp => grp.ToList()).ToList();

_appRooms.ForEach((rooms) =>
{
string jsonRooms = JsonConvert.SerializeObject(rooms, Formatting.Indented);
_regionRoomsAppId[LRMRegions.Any].Add(rooms.First().appId, rooms);
});

for (int x = 0; x < requestedRooms.Count; x++)
if (!Program.cachedRooms.TryAdd(requestedRooms[x].serverId, requestedRooms[x]))
Logger.ForceLogMessage("Conflicting Rooms! (That's ok)", ConsoleColor.Yellow);
Expand Down Expand Up @@ -172,19 +180,36 @@ public async Task GetMasterServerList(IHttpContext context)

if (int.TryParse("Info:" + region, out int regionID))
{
Logger.WriteLogMessage("Send Servers, " + _regionRooms[(LRMRegions)regionID].Count, ConsoleColor.Cyan);
Logger.WriteLogMessage("Send Servers(Cached), " + _cachedRegionRooms[(LRMRegions)regionID], ConsoleColor.Cyan);
await context.Response.SendResponseAsync(_cachedRegionRooms[(LRMRegions)regionID]);
return;
}

Logger.WriteLogMessage("Send Servers, "+_regionRooms[LRMRegions.Any].Count,ConsoleColor.Cyan);
Logger.WriteLogMessage("Send Servers(Cached), " + _cachedRegionRooms[LRMRegions.Any], ConsoleColor.Cyan);

// They didnt submit a region header, just give them all servers as they probably are viewing in browser.
await context.Response.SendResponseAsync(_cachedRegionRooms[LRMRegions.Any]);
}

/// <summary>
/// Returns all the servers from AppId on all the relay nodes.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
[RestRoute("Get", "/masterlist/{appId:num}")]
public async Task GetMasterServerListApp(IHttpContext context)
{
string region = context.Request.Headers["x-Region"];
int appId = int.Parse(context.Request.PathParameters["appId"]);


if (int.TryParse("Info:" + region, out int regionID))
{
await context.Response.SendResponseAsync(_cachedRegionRoomsAppId[(LRMRegions)regionID].GetValueOrDefault(appId,"[]"));
return;
}

// They didnt submit a region header, just give them all servers as they probably are viewing in browser.
await context.Response.SendResponseAsync(_cachedRegionRoomsAppId[LRMRegions.Any].GetValueOrDefault(appId, "[]"));
}

[RestRoute("Options", "/masterlist/")]
public async Task GetMasterServerListOptions(IHttpContext context)
{
Expand Down Expand Up @@ -220,6 +245,9 @@ public static void Initialize()
{
_regionRooms.Add(region, new());
_cachedRegionRooms.Add(region, "[]");

_regionRoomsAppId.Add(region, new());
_cachedRegionRoomsAppId.Add(region, new());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,30 @@ public partial class Endpoint
{
static void CacheAllServers()
{
Logger.WriteLogMessage($"CacheAllServers[{_regionRooms.Count}]", ConsoleColor.Cyan);

foreach (var region in _regionRooms)
{
Logger.WriteLogMessage($"CacheAllServers[{region.Key}][{region.Value.Count}]", ConsoleColor.Cyan);

_cachedRegionRooms[region.Key] = JsonConvert.SerializeObject(region.Value,Formatting.Indented);
}

Logger.WriteLogMessage($"CacheAllServers[{region.Key}][{region.Value.Count}] {_cachedRegionRooms[region.Key]}", ConsoleColor.Cyan);
foreach (var region in _regionRoomsAppId)
{
foreach(var appId in region.Value)
{
_cachedRegionRoomsAppId[region.Key][appId.Key] = JsonConvert.SerializeObject(appId.Value, Formatting.Indented);
}
}
}

static void ClearAllServersLists()
{
foreach (var region in _regionRooms)
region.Value.Clear();

foreach (var regionAppId in _regionRoomsAppId)
regionAppId.Value.Clear();

foreach (var regionAppId in _cachedRegionRoomsAppId)
regionAppId.Value.Clear();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ public partial class Endpoint
private static Dictionary<LRMRegions, List<Room>> _regionRooms = new();
private static Dictionary<LRMRegions, string> _cachedRegionRooms = new();

private static Dictionary<LRMRegions, Dictionary<int,List<Room>>> _regionRoomsAppId = new();
private static Dictionary<LRMRegions, Dictionary<int,string>> _cachedRegionRoomsAppId = new();

private LoadBalancerStats _stats
{
get => new()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
Expand Down
64 changes: 56 additions & 8 deletions ServerProject-DONT-IMPORT-INTO-UNITY/LRM/Endpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LightReflectiveMirror.Endpoints
Expand All @@ -23,25 +24,45 @@ struct RelayStats
[RestResource(BasePath = "/api/")]
public class Endpoint
{

private static Dictionary<int,string> _cachedServerListAppId = new ();
private static Dictionary<int, string> _cachedCompressedServerListAppId = new ();


private static string _cachedServerList = "[]";
private static string _cachedCompressedServerList;
public static DateTime lastPing = DateTime.Now;

private static List<Room> _rooms { get => Program.instance.GetRooms().Where(x => x.isPublic).ToList(); }
private static List<List<Room>> _appRooms { get => Program.instance.GetRooms().GroupBy(x => x.appId).Select(grp => grp.ToList()).ToList(); }

private RelayStats _stats { get => new()
private RelayStats _stats
{
ConnectedClients = Program.instance.GetConnections(),
RoomCount = Program.instance.GetRooms().Count,
PublicRoomCount = Program.instance.GetPublicRoomCount(),
Uptime = Program.instance.GetUptime()
}; }
get => new()
{
ConnectedClients = Program.instance.GetConnections(),
RoomCount = Program.instance.GetRooms().Count,
PublicRoomCount = Program.instance.GetPublicRoomCount(),
Uptime = Program.instance.GetUptime()
};
}

public static void RoomsModified()
{
_cachedServerList = JsonConvert.SerializeObject(_rooms, Formatting.Indented);
_cachedCompressedServerList = _cachedServerList.Compress();

_cachedServerListAppId.Clear();
_cachedCompressedServerListAppId.Clear();

_appRooms.ForEach((rooms) =>
{
string jsonRooms = JsonConvert.SerializeObject(rooms, Formatting.Indented);
_cachedServerListAppId.Add(rooms.First().appId, jsonRooms);
_cachedCompressedServerListAppId.Add(rooms.First().appId, jsonRooms.Compress());
});


if (Program.conf.UseLoadBalancer)
Program.instance.UpdateLoadBalancerServers();
}
Expand All @@ -65,6 +86,18 @@ public async Task ServerList(IHttpContext context)
await context.Response.SendResponseAsync(HttpStatusCode.Forbidden);
}

[RestRoute("Get", "/servers/{appId:num}")]
public async Task ServerListAppId(IHttpContext context)
{
if (Program.conf.EndpointServerList)
{
int appId = int.Parse(context.Request.PathParameters["appId"]);
await context.Response.SendResponseAsync(_cachedServerListAppId.GetValueOrDefault(appId, "[]"));
}
else
await context.Response.SendResponseAsync(HttpStatusCode.Forbidden);
}

[RestRoute("Get", "/compressed/servers")]
public async Task ServerListCompressed(IHttpContext context)
{
Expand All @@ -79,6 +112,21 @@ public async Task ServerListCompressed(IHttpContext context)
await context.Response.SendResponseAsync(HttpStatusCode.Forbidden);
}

[RestRoute("Get", "/compressed/servers/{appId:num}")]
public async Task ServerListCompressedAppId(IHttpContext context)
{
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");

if (Program.conf.EndpointServerList)
{
int appId = int.Parse(context.Request.PathParameters["appId"]);
await context.Response.SendResponseAsync(_cachedCompressedServerListAppId.GetValueOrDefault(appId,"[]".Compress()));
}
else
await context.Response.SendResponseAsync(HttpStatusCode.Forbidden);
}

[RestRoute("Options", "/compressed/servers")]
public async Task ServerListCompressedOptions(IHttpContext context)
{
Expand All @@ -94,7 +142,7 @@ public async Task ServerListCompressedOptions(IHttpContext context)

public class EndpointServer
{
public bool Start(ushort port = 8080,bool ssl = false)
public bool Start(ushort port = 8080, bool ssl = false)
{
try
{
Expand All @@ -103,7 +151,7 @@ public bool Start(ushort port = 8080,bool ssl = false)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
.Build();

var server = new RestServerBuilder(new ServiceCollection(), config,
var server = new RestServerBuilder(new ServiceCollection(), config,
(services) =>
{
services.AddLogging(configure => configure.AddConsole());
Expand Down
2 changes: 1 addition & 1 deletion UnityProject/Assets/LRMTestScene.unity
Original file line number Diff line number Diff line change
Expand Up @@ -1352,7 +1352,7 @@ MonoBehaviour:
m_Calls: []
serverStatus: Not Started.
serverId:
appId: 42
appId: 1
region: 1
--- !u!1 &1458789072
GameObject:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ IEnumerator GetServerList(LRMRegions region)
{
if (!useLoadBalancer)
{
string uri = $"http://{serverIP}:{endpointServerPort}/api/compressed/servers";
string uri = $"http://{serverIP}:{endpointServerPort}/api/compressed/servers/{appId}";

using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
Expand Down Expand Up @@ -179,7 +179,7 @@ IEnumerator GetServerList(LRMRegions region)
/// <returns></returns>
IEnumerator RetrieveMasterServerListFromLoadBalancer(LRMRegions region)
{
string uri = $"http://{loadBalancerAddress}:{loadBalancerPort}/api/masterlist/";
string uri = $"http://{loadBalancerAddress}:{loadBalancerPort}/api/masterlist/{appId}";

using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
Expand Down

0 comments on commit c00d1d7

Please sign in to comment.