Added join requests

This commit is contained in:
cxxpxr 2021-04-04 23:58:23 -04:00
parent 270ec22a9d
commit e2833d53bb
2 changed files with 47 additions and 11 deletions

View file

@ -3,6 +3,8 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LightReflectiveMirror.LoadBalancing
@ -28,6 +30,40 @@ namespace LightReflectiveMirror.LoadBalancing
else
await context.Response.SendResponseAsync(HttpStatusCode.Forbidden);
}
/// <summary>
/// Hooks into from unity side, client will call this to
/// find the least populated server to join
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
[RestRoute("Get", "/api/join/")]
public async Task JoinRelay(IHttpContext context)
{
var servers = Program.instance.availableRelayServers.ToList();
if(servers.Count == 0)
{
await context.Response.SendResponseAsync(HttpStatusCode.ServiceUnavailable);
return;
}
// need to copy over in order to avoid
// collection being modified while iterating.
KeyValuePair<string, RelayStats> lowest = new("Dummy", new RelayStats { ConnectedClients = int.MaxValue });
for (int i = 0; i < servers.Count; i++)
{
if (servers[i].Value.ConnectedClients < lowest.Value.ConnectedClients)
{
lowest = servers[i];
}
}
// respond with the server ip
// if the string is still dummy then theres no servers
await context.Response.SendResponseAsync(lowest.Key != "Dummy" ? lowest.Key : HttpStatusCode.InternalServerError);
}
}
public class EndpointServer

View file

@ -12,7 +12,7 @@ namespace LightReflectiveMirror.LoadBalancing
{
/// <summary>
/// Keeps track of all available relays.
/// Key is server address, value is CCU/Info.
/// Key is server address, value is CCU.
/// </summary>
public Dictionary<string, RelayStats> availableRelayServers = new();
@ -58,13 +58,13 @@ namespace LightReflectiveMirror.LoadBalancing
public async Task AddServer(string serverIP)
{
var stats = await InitialPingServer(serverIP);
var stats = await ManualPingServer(serverIP);
if(stats.PublicRoomCount != -1)
availableRelayServers.Add(serverIP, stats);
}
async Task<RelayStats> InitialPingServer(string serverIP)
async Task<RelayStats> ManualPingServer(string serverIP)
{
string url = serverIP + API_PATH;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
@ -145,6 +145,8 @@ namespace LightReflectiveMirror.LoadBalancing
Console.WriteLine(message);
}
}
[Serializable]
public struct RelayStats
{
@ -153,6 +155,4 @@ namespace LightReflectiveMirror.LoadBalancing
public int PublicRoomCount;
public TimeSpan Uptime;
}
}
}