2020-08-08 08:53:35 +02:00
|
|
|
|
namespace Giants.Services
|
|
|
|
|
{
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
2020-08-09 01:31:16 +02:00
|
|
|
|
using System.Linq;
|
2020-08-08 08:53:35 +02:00
|
|
|
|
using System.Threading.Tasks;
|
2020-08-09 01:31:16 +02:00
|
|
|
|
using Giants.Services.Core;
|
|
|
|
|
using Microsoft.Extensions.Configuration;
|
2020-08-08 08:53:35 +02:00
|
|
|
|
|
|
|
|
|
public class ServerRegistryService : IServerRegistryService
|
|
|
|
|
{
|
|
|
|
|
private readonly IServerRegistryStore registryStore;
|
2020-08-09 01:31:16 +02:00
|
|
|
|
private readonly IConfiguration configuration;
|
|
|
|
|
private readonly IDateTimeProvider dateTimeProvider;
|
|
|
|
|
private readonly TimeSpan timeoutPeriod;
|
|
|
|
|
private readonly int maxServerCount;
|
2020-08-08 08:53:35 +02:00
|
|
|
|
|
2020-08-09 01:31:16 +02:00
|
|
|
|
public ServerRegistryService(
|
|
|
|
|
IServerRegistryStore registryStore,
|
|
|
|
|
IConfiguration configuration,
|
|
|
|
|
IDateTimeProvider dateTimeProvider)
|
2020-08-08 08:53:35 +02:00
|
|
|
|
{
|
|
|
|
|
this.registryStore = registryStore;
|
2020-08-09 01:31:16 +02:00
|
|
|
|
this.configuration = configuration;
|
|
|
|
|
this.dateTimeProvider = dateTimeProvider;
|
|
|
|
|
this.timeoutPeriod = TimeSpan.FromMinutes(Convert.ToDouble(this.configuration["ServerTimeoutPeriodInMinutes"]));
|
|
|
|
|
this.maxServerCount = Convert.ToInt32(this.configuration["MaxServerCount"]);
|
2020-08-08 08:53:35 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task AddServer(
|
|
|
|
|
ServerInfo server)
|
|
|
|
|
{
|
2020-08-09 01:31:16 +02:00
|
|
|
|
if (server == null)
|
2020-08-08 08:53:35 +02:00
|
|
|
|
{
|
2020-08-09 01:31:16 +02:00
|
|
|
|
throw new ArgumentNullException(nameof(server));
|
|
|
|
|
}
|
2020-08-08 08:53:35 +02:00
|
|
|
|
|
2020-08-09 01:31:16 +02:00
|
|
|
|
if (string.IsNullOrEmpty(server.HostIpAddress))
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentException(nameof(server.HostIpAddress));
|
2020-08-08 08:53:35 +02:00
|
|
|
|
}
|
|
|
|
|
|
2020-08-09 01:31:16 +02:00
|
|
|
|
await this.registryStore.UpsertServerInfo(server ?? throw new ArgumentNullException(nameof(server)));
|
2020-08-08 08:53:35 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<IEnumerable<ServerInfo>> GetAllServers()
|
|
|
|
|
{
|
2020-08-09 01:31:16 +02:00
|
|
|
|
return (await this.registryStore
|
2020-08-09 02:26:41 +02:00
|
|
|
|
.GetServerInfos(whereExpression: c => c.LastHeartbeat > this.dateTimeProvider.UtcNow - this.timeoutPeriod))
|
2020-08-09 01:31:16 +02:00
|
|
|
|
.Take(this.maxServerCount);
|
2020-08-08 08:53:35 +02:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|