DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/TelemetryTracker.cs
Фролов da9e94b4b9 Modify telemetry tracker to keep remote and server dates.
Update related services.
Small refactor TelemetryController: exclude dictionaries updates  from tracker update. All tracker updates moved to services.
2021-10-28 10:56:18 +05:00

84 lines
3.0 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
{
class TrackerStat
{
//public int Id { get; set; }
public string RemoteUid { get; set; }
/// <summary>
/// Время последнего запроса (по времени сервера)
/// </summary>
public DateTime LastTimeServer { get; set; }
/// <summary>
/// Время указанное в данных последнего запроса (из удаленного источника)
/// </summary>
public DateTime LastTimeRemote { get; set; }
}
private readonly Dictionary<string, TrackerStat> requests;
public TelemetryTracker(CacheDb cacheDb)
{
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.Key,
Date = g.Max(t => t.Date)
})
.AsNoTracking()
.ToList();
requests = lastTelemetriesDates.Select(t => new
{
//Id = t.IdTelemetry,
RemoteUid = cacheTelemetry.FirstOrDefault(c => c.Id == t.IdTelemetry).RemoteUid,
LastTimeRemote = t.Date,
}).ToDictionary(t => t.RemoteUid, t => new TrackerStat {
//Id = t.Id,
RemoteUid = t.RemoteUid,
LastTimeRemote = t.LastTimeRemote,
LastTimeServer = t.LastTimeRemote,
});
}
public void SaveRequestDate(string uid, DateTime remoteDate)
{
var stat = requests.GetValueOrDefault(uid);
if(stat is null)
{
stat = new TrackerStat{ RemoteUid = uid };
requests[uid] = stat;
}
stat.LastTimeServer = DateTime.Now;
stat.LastTimeRemote = remoteDate;
}
public DateTime GetLastTelemetryDateByUid(string uid) =>
requests.GetValueOrDefault(uid)?.LastTimeRemote ?? default;
public IEnumerable<string> GetTransmittingTelemetriesUids() =>
requests.Keys;
}
}