DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/TelemetryTracker.cs
2021-10-25 16:32:55 +05:00

64 lines
2.3 KiB
C#

using AsbCloudApp.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using Microsoft.EntityFrameworkCore;
namespace AsbCloudInfrastructure.Services
{
public class TelemetryTracker : ITelemetryTracker
{
private Dictionary<string, DateTime> requests;
private readonly TimeSpan timeout;
public TelemetryTracker(CacheDb cacheDb)
{
timeout = TimeSpan.FromDays(7);
var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
.UseNpgsql("Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True")
.Options;
using var db = new AsbCloudDbContext(options);
var cacheTelemetry = cacheDb.GetCachedTable<Telemetry>(db);
var lastTelemetriesDates = (from d in db.TelemetryDataSaub
group d by d.IdTelemetry into g
select new
{
IdTelemetry = g.Max(t => t.IdTelemetry),
Date = g.Max(t => t.Date)
}).ToList();
requests = lastTelemetriesDates.Select(t => new
{
Uid = cacheTelemetry.FirstOrDefault(c => c.Id == t.IdTelemetry).RemoteUid,
t.Date
}).ToDictionary(t => t.Uid, u => u.Date);
}
public void SaveRequestDate(string uid)
{
requests[uid] = DateTime.Now;
DeleteOldRequestDates();
}
public DateTime GetLastTelemetryDateByUid(string uid) =>
requests.GetValueOrDefault(uid, DateTime.MinValue);
public IEnumerable<string> GetTransmittingTelemetryUids()
{
DeleteOldRequestDates();
return requests.Keys;
}
private void DeleteOldRequestDates() // TODO: удалить этот метод
{
requests = requests.Where(dValue => (DateTime.Now - dValue.Value) < timeout)
.ToDictionary(dValue => dValue.Key, dValue => dValue.Value);
}
}
}