GiantsTools/Giants.Services/Services/ServerRegistryService.cs

54 lines
1.9 KiB
C#
Raw Normal View History

namespace Giants.Services
{
using System;
using System.Collections.Generic;
2020-08-09 01:31:16 +02:00
using System.Linq;
using System.Threading.Tasks;
2020-08-09 01:31:16 +02:00
using Giants.Services.Core;
using Microsoft.Extensions.Configuration;
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-09 01:31:16 +02:00
public ServerRegistryService(
IServerRegistryStore registryStore,
IConfiguration configuration,
IDateTimeProvider dateTimeProvider)
{
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"]);
}
public async Task AddServer(
ServerInfo server)
{
2020-08-09 01:31:16 +02:00
if (server == null)
{
2020-08-09 01:31:16 +02:00
throw new ArgumentNullException(nameof(server));
}
2020-08-09 01:31:16 +02:00
if (string.IsNullOrEmpty(server.HostIpAddress))
{
throw new ArgumentException(nameof(server.HostIpAddress));
}
2020-08-09 01:31:16 +02:00
await this.registryStore.UpsertServerInfo(server ?? throw new ArgumentNullException(nameof(server)));
}
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);
}
}
}