using Mapster; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json.Linq; using Persistence.Database.Model; using Persistence.Models; namespace Persistence.Repository.Repositories; public class TimeSeriesDataCachedRepository : TimeSeriesDataRepository where TEntity : class, ITimestampedData, new() where TDto : class, ITimeSeriesAbstractDto, new() { public static TDto FirstByDate { get; set; } = default!; public static CyclicArray LastData { get; set; } = null!; private const int CacheItemsCount = 3600; public TimeSeriesDataCachedRepository(DbContext db) : base(db) { Task.Run(async () => { LastData = new CyclicArray(CacheItemsCount); var firstDateItem = await base.GetFirstAsync(CancellationToken.None); if (firstDateItem == null) { return; } FirstByDate = firstDateItem; var dtos = await base.GetLastAsync(CacheItemsCount, CancellationToken.None); dtos = dtos.OrderBy(d => d.Date); LastData.AddRange(dtos); }).Wait(); } public override async Task> GetAsync(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token) { if (LastData.Count() == 0 || LastData[0].Date > dateBegin) { var dtos = await base.GetAsync(dateBegin, dateEnd, token); return dtos; } var items = LastData .Where(i => i.Date >= dateBegin && i.Date <= dateEnd); return items; } public override async Task InsertRange(IEnumerable dtos, CancellationToken token) { var result = await base.InsertRange(dtos, token); if (result > 0) { dtos = dtos.OrderBy(x => x.Date); FirstByDate = dtos.First(); LastData.AddRange(dtos); } return result; } }