DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/Cache/CacheTable.cs

369 lines
13 KiB
C#
Raw Normal View History

2021-04-07 18:01:56 +05:00
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2021-10-03 20:08:17 +05:00
using System.Collections;
using System.Diagnostics;
2021-04-07 18:01:56 +05:00
namespace AsbCloudInfrastructure.Services.Cache
{
2021-09-08 11:51:55 +05:00
public class CacheTable<TEntity> : IEnumerable<TEntity>
where TEntity : class
2021-04-07 18:01:56 +05:00
{
2021-10-03 20:08:17 +05:00
private const int semaphoreTimeout = 5_000;
private static readonly SemaphoreSlim semaphore = new(1);
2021-11-10 17:01:18 +05:00
private static readonly TimeSpan minPeriodRefresh = TimeSpan.FromSeconds(3);
2021-04-07 18:01:56 +05:00
private readonly DbContext context;
2021-10-03 20:08:17 +05:00
private (DateTime refreshDate, IEnumerable entities) data;
private readonly List<TEntity> cached;
private readonly DbSet<TEntity> dbSet;
2021-04-07 18:01:56 +05:00
2021-10-03 20:08:17 +05:00
internal CacheTable(DbContext context, (DateTime refreshDate, IEnumerable entities) data)
2021-04-07 18:01:56 +05:00
{
this.context = context;
this.data = data;
dbSet = context.Set<TEntity>();
2021-10-03 20:08:17 +05:00
cached = (List<TEntity>)data.entities;
if (cached.Count == 0)
2021-11-10 17:01:18 +05:00
Refresh(false);
2021-04-07 18:01:56 +05:00
}
2021-04-23 10:21:25 +05:00
public TEntity this[int index] { get => cached.ElementAt(index); }
2021-04-07 18:01:56 +05:00
2021-10-04 15:52:22 +05:00
/// <summary>
/// Runs action like atomic operation.
/// wasFree is action argument indicates that semaphore was free.
/// It may be needed to avoid multiple operations like Refresh().
/// </summary>
/// <param name="action">(wasFree) => {...}</param>
/// <returns>false - semaphore.Wait returned by timeout</returns>
private static bool Sync(Action<bool> action)
2021-04-07 18:01:56 +05:00
{
2021-10-03 20:08:17 +05:00
var wasFree = semaphore.CurrentCount > 0;
2021-10-04 15:52:22 +05:00
if (!semaphore.Wait(semaphoreTimeout))
return false;
2021-10-03 20:08:17 +05:00
try
2021-04-07 18:01:56 +05:00
{
2021-10-04 15:52:22 +05:00
action?.Invoke(wasFree);
2021-04-07 18:01:56 +05:00
}
2021-10-03 20:08:17 +05:00
catch (Exception ex)
2021-04-07 18:01:56 +05:00
{
2021-10-04 15:52:22 +05:00
Trace.WriteLine($"{DateTime.Now:yyyy.MM.dd HH:mm:ss:fff} error in CacheTable<{typeof(TEntity).Name}>.Sync()");
2021-10-03 20:08:17 +05:00
Trace.WriteLine(ex.Message);
2021-10-04 15:52:22 +05:00
Trace.WriteLine(ex.StackTrace);
2021-04-07 18:01:56 +05:00
}
2021-10-03 20:08:17 +05:00
finally
{
semaphore.Release();
}
2021-10-04 15:52:22 +05:00
return true;
2021-04-07 18:01:56 +05:00
}
2021-10-04 15:52:22 +05:00
/// <summary>
/// Runs action like atomic operation.
/// wasFree is action argument indicates that semaphore was free.
/// It may be needed to avoid multiple operations like Refresh().
/// </summary>
/// <param name="action">(wasFree) => {...}</param>
/// <returns>false - semaphore.Wait returned by timeout</returns>
private static async Task<bool> SyncAsync(Func<bool, CancellationToken, Task> task, CancellationToken token = default)
2021-04-07 18:01:56 +05:00
{
2021-10-03 20:08:17 +05:00
var wasFree = semaphore.CurrentCount > 0;
if (!await semaphore.WaitAsync(semaphoreTimeout, token).ConfigureAwait(false))
2021-10-04 15:52:22 +05:00
return false;
2021-10-03 20:08:17 +05:00
try
2021-04-07 18:01:56 +05:00
{
2021-10-04 15:52:22 +05:00
await task?.Invoke(wasFree, token);
2021-04-07 18:01:56 +05:00
}
2021-10-03 20:08:17 +05:00
catch (Exception ex)
2021-04-07 18:01:56 +05:00
{
2021-10-04 15:52:22 +05:00
Trace.WriteLine($"{DateTime.Now:yyyy.MM.dd HH:mm:ss:fff} error in CacheTable<{typeof(TEntity).Name}>.SyncAsync()");
2021-10-03 20:08:17 +05:00
Trace.WriteLine(ex.Message);
2021-10-04 15:52:22 +05:00
Trace.WriteLine(ex.StackTrace);
2021-04-07 18:01:56 +05:00
}
2021-10-03 20:08:17 +05:00
finally
{
semaphore.Release();
}
2021-10-04 15:52:22 +05:00
return true;
}
2021-11-10 17:01:18 +05:00
private void InternalRefresh(bool force)
2021-10-04 15:52:22 +05:00
{
2021-11-10 17:01:18 +05:00
if (!force && (data.refreshDate + minPeriodRefresh >= DateTime.Now))
return;
2021-10-04 15:52:22 +05:00
cached.Clear();
var entities = dbSet.AsNoTracking().ToList();
2021-11-10 17:01:18 +05:00
Trace.WriteLine($"CacheTable<{typeof(TEntity).Name}> refresh");
2021-10-04 15:52:22 +05:00
cached.AddRange(entities);
2021-11-10 17:01:18 +05:00
data.refreshDate = DateTime.Now;
2021-10-04 15:52:22 +05:00
}
2021-11-10 17:01:18 +05:00
private async Task InternalRefreshAsync(bool force, CancellationToken token = default)
2021-10-04 15:52:22 +05:00
{
2021-11-10 17:01:18 +05:00
if (!force && (data.refreshDate + minPeriodRefresh >= DateTime.Now))
return;
2021-10-04 15:52:22 +05:00
cached.Clear();
var entities = await context.Set<TEntity>().AsNoTracking()
.ToListAsync(token).ConfigureAwait(false);
2021-11-10 17:01:18 +05:00
Trace.WriteLine($"CacheTable<{typeof(TEntity).Name}> refresh");
2021-10-04 15:52:22 +05:00
cached.AddRange(entities);
data.refreshDate = DateTime.Now;
}
2021-11-10 17:01:18 +05:00
public int Refresh(bool force)
2021-10-04 15:52:22 +05:00
{
Sync((wasFree) => {
if (wasFree)
2021-11-10 17:01:18 +05:00
InternalRefresh(force);
2021-10-04 15:52:22 +05:00
});
return cached.Count;
}
2021-11-10 17:01:18 +05:00
public async Task<int> RefreshAsync(bool force, CancellationToken token = default)
2021-10-04 15:52:22 +05:00
{
await SyncAsync(async (wasFree, token) => {
if (wasFree)
2021-11-10 17:01:18 +05:00
await InternalRefreshAsync(force, token).ConfigureAwait(false);
2021-10-04 15:52:22 +05:00
}, token).ConfigureAwait(false);
2021-10-03 20:08:17 +05:00
return cached.Count;
2021-04-07 18:01:56 +05:00
}
2021-10-03 20:08:17 +05:00
public bool Contains(Func<TEntity, bool> predicate)
=> FirstOrDefault(predicate) != default;
2021-04-07 18:01:56 +05:00
2021-10-03 20:08:17 +05:00
public async Task<bool> ContainsAsync(Func<TEntity, bool> predicate, CancellationToken token = default)
=> await FirstOrDefaultAsync(predicate, token) != default;
2021-04-07 18:01:56 +05:00
2021-10-04 15:52:22 +05:00
public TEntity GetOrCreate(Func<TEntity, bool> predicate, Func<TEntity> makeNew)
{
TEntity result = default;
Sync(wasFree => {
result = cached.FirstOrDefault(predicate);
if (result != default)
return;
2021-11-10 17:01:18 +05:00
InternalRefresh(true);
2021-10-04 15:52:22 +05:00
result = cached.FirstOrDefault(predicate);
if (result != default)
return;
var entry = dbSet.Add(makeNew());
context.SaveChanges();
2021-11-10 17:01:18 +05:00
InternalRefresh(true);
2021-10-04 15:52:22 +05:00
result = entry.Entity;
});
return result;
}
2021-10-03 20:08:17 +05:00
public TEntity FirstOrDefault()
2021-04-07 18:01:56 +05:00
{
2021-04-23 10:21:25 +05:00
var result = cached.FirstOrDefault();
2021-10-03 20:08:17 +05:00
if (result != default)
return result;
2021-11-10 17:01:18 +05:00
Refresh(false);
2021-10-03 20:08:17 +05:00
return cached.FirstOrDefault();
2021-04-07 18:01:56 +05:00
}
2021-10-03 20:08:17 +05:00
public async Task<TEntity> FirstOrDefaultAsync(CancellationToken token = default)
2021-04-07 18:01:56 +05:00
{
2021-04-23 10:21:25 +05:00
var result = cached.FirstOrDefault();
2021-10-03 20:08:17 +05:00
if (result != default)
return result;
2021-04-07 18:01:56 +05:00
2021-11-10 17:01:18 +05:00
await RefreshAsync(false, token);
2021-10-04 15:52:22 +05:00
return cached.FirstOrDefault();
2021-10-03 20:08:17 +05:00
}
2021-04-07 18:01:56 +05:00
2021-10-03 20:08:17 +05:00
public TEntity FirstOrDefault(Func<TEntity, bool> predicate)
2021-04-07 18:01:56 +05:00
{
2021-04-23 10:21:25 +05:00
var result = cached.FirstOrDefault(predicate);
2021-10-03 20:08:17 +05:00
if (result != default)
return result;
2021-11-10 17:01:18 +05:00
Refresh(false);
2021-10-03 20:08:17 +05:00
return cached.FirstOrDefault(predicate);
2021-04-07 18:01:56 +05:00
}
2021-10-03 20:08:17 +05:00
public async Task<TEntity> FirstOrDefaultAsync(Func<TEntity, bool> predicate, CancellationToken token = default)
2021-04-07 18:01:56 +05:00
{
2021-04-23 10:21:25 +05:00
var result = cached.FirstOrDefault(predicate);
2021-10-03 20:08:17 +05:00
if (result != default)
return result;
2021-08-27 17:55:22 +05:00
2021-11-10 17:01:18 +05:00
await RefreshAsync(false, token);
2021-10-03 20:08:17 +05:00
return cached.FirstOrDefault(predicate);
}
2021-04-07 18:01:56 +05:00
2021-10-03 20:08:17 +05:00
public IEnumerable<TEntity> Where(Func<TEntity, bool> predicate = default)
2021-04-07 18:01:56 +05:00
{
var result = (predicate != default)
? cached.Where(predicate)
: cached;
2021-10-03 20:08:17 +05:00
if (result.Any())
return result;
2021-11-10 17:01:18 +05:00
Refresh(false);
2021-10-03 20:08:17 +05:00
result = (predicate != default)
? cached.Where(predicate)
: cached;
2021-04-07 18:01:56 +05:00
return result;
}
2021-10-04 15:52:22 +05:00
public Task<IEnumerable<TEntity>> WhereAsync(CancellationToken token = default) =>
WhereAsync(default, token);
public async Task<IEnumerable<TEntity>> WhereAsync(Func<TEntity, bool> predicate = default,
2021-10-03 20:08:17 +05:00
CancellationToken token = default)
2021-04-07 18:01:56 +05:00
{
var result = (predicate != default)
? cached.Where(predicate)
: cached;
2021-10-03 20:08:17 +05:00
if (result.Any())
return result;
2021-11-10 17:01:18 +05:00
await RefreshAsync(false, token);
2021-10-03 20:08:17 +05:00
result = (predicate != default)
? cached.Where(predicate)
: cached;
2021-04-07 18:01:56 +05:00
return result;
}
2021-10-04 15:52:22 +05:00
public void Upsert(TEntity entity)
2021-04-23 10:21:25 +05:00
{
2021-10-04 15:52:22 +05:00
if (entity == default)
return;
Sync((wasFree) =>
2021-07-20 12:28:56 +05:00
{
2021-10-04 15:52:22 +05:00
if (dbSet.Contains(entity))
dbSet.Update(entity);
2021-07-20 12:28:56 +05:00
else
2021-10-04 15:52:22 +05:00
dbSet.Add(entity);
context.SaveChanges();
2021-11-10 17:01:18 +05:00
InternalRefresh(true);
2021-10-04 15:52:22 +05:00
});
2021-04-23 10:21:25 +05:00
}
2021-10-04 15:52:22 +05:00
public Task UpsertAsync(TEntity entity, CancellationToken token = default)
=> SyncAsync(async (wasFree, token) => {
2021-07-20 12:28:56 +05:00
if (dbSet.Contains(entity))
2021-10-04 15:52:22 +05:00
dbSet.Update(entity);
2021-07-20 12:28:56 +05:00
else
2021-10-04 15:52:22 +05:00
dbSet.Add(entity);
await context.SaveChangesAsync(token).ConfigureAwait(false);
2021-11-10 17:01:18 +05:00
await InternalRefreshAsync(true, token).ConfigureAwait(false);
2021-10-04 15:52:22 +05:00
}, token);
2021-07-16 09:15:10 +05:00
2021-10-04 15:52:22 +05:00
public void Upsert(IEnumerable<TEntity> entities)
2021-04-07 18:01:56 +05:00
{
2021-10-04 15:52:22 +05:00
if (!entities.Any())
return;
Sync((wasFree) =>
{
foreach (var entity in entities)
{
if (dbSet.Contains(entity)) // TODO: это очень ммедленно
dbSet.Update(entity);
else
dbSet.Add(entity);
}
context.SaveChanges();
2021-11-10 17:01:18 +05:00
InternalRefresh(true);
2021-10-04 15:52:22 +05:00
});
2021-04-07 18:01:56 +05:00
}
2021-10-04 15:52:22 +05:00
public async Task UpsertAsync(IEnumerable<TEntity> entities, CancellationToken token = default)
2021-04-07 18:01:56 +05:00
{
2021-10-04 15:52:22 +05:00
if (!entities.Any())
return;
await SyncAsync(async (wasFree, token) => {
var upsertedEntries = new List<TEntity>(entities.Count());
foreach (var entity in entities)
{
if (dbSet.Contains(entity))
dbSet.Update(entity);
else
dbSet.Add(entity);
}
await context.SaveChangesAsync(token).ConfigureAwait(false);
2021-11-10 17:01:18 +05:00
await InternalRefreshAsync(true, token).ConfigureAwait(false);
2021-10-04 15:52:22 +05:00
}, token);
2021-04-07 18:01:56 +05:00
}
2021-10-04 15:52:22 +05:00
public void Remove(Func<TEntity, bool> predicate)
=> Sync(_ =>
{
dbSet.RemoveRange(dbSet.Where(predicate));
context.SaveChanges();
2021-11-10 17:01:18 +05:00
InternalRefresh(true);
2021-10-04 15:52:22 +05:00
});
public Task RemoveAsync(Func<TEntity, bool> predicate, CancellationToken token = default)
=> SyncAsync(async (wasFree, token) => {
dbSet.RemoveRange(dbSet.Where(predicate));
await context.SaveChangesAsync(token).ConfigureAwait(false);
2021-11-10 17:01:18 +05:00
await InternalRefreshAsync(true, token).ConfigureAwait(false);
2021-10-04 15:52:22 +05:00
}, token);
2021-04-07 18:01:56 +05:00
public TEntity Insert(TEntity entity)
{
2021-10-04 15:52:22 +05:00
TEntity result = default;
Sync(_ =>
{
var entry = dbSet.Add(entity);
context.SaveChanges();
2021-11-10 17:01:18 +05:00
InternalRefresh(true);
2021-10-04 15:52:22 +05:00
result = entry.Entity;
});
return result;
2021-04-07 18:01:56 +05:00
}
public async Task<TEntity> InsertAsync(TEntity entity, CancellationToken token = default)
{
2021-10-04 15:52:22 +05:00
TEntity result = default;
await SyncAsync(async (wasFree, token) =>
{
var entry = dbSet.Add(entity);
await context.SaveChangesAsync(token).ConfigureAwait(false);
2021-11-10 17:01:18 +05:00
await InternalRefreshAsync(true, token).ConfigureAwait(false);
2021-10-04 15:52:22 +05:00
result = entry.Entity;
}, token);
return result;
2021-04-07 18:01:56 +05:00
}
2021-10-03 20:08:17 +05:00
public int Insert(IEnumerable<TEntity> newEntities)
2021-04-07 18:01:56 +05:00
{
2021-10-04 15:52:22 +05:00
int result = 0;
Sync(_ => {
dbSet.AddRange(newEntities);
result = context.SaveChanges();
2021-11-10 17:01:18 +05:00
InternalRefresh(true);
2021-10-04 15:52:22 +05:00
});
2021-10-03 20:08:17 +05:00
return result;
2021-04-07 18:01:56 +05:00
}
2021-10-03 20:08:17 +05:00
public async Task<int> InsertAsync(IEnumerable<TEntity> newEntities, CancellationToken token = default)
2021-04-07 18:01:56 +05:00
{
2021-10-04 15:52:22 +05:00
int result = 0;
await SyncAsync(async (wasFree, token) => {
dbSet.AddRange(newEntities);
result = await context.SaveChangesAsync(token).ConfigureAwait(false);
2021-11-10 17:01:18 +05:00
await InternalRefreshAsync(true, token).ConfigureAwait(false);
2021-10-04 15:52:22 +05:00
}, token);
2021-10-03 20:08:17 +05:00
return result;
}
2021-09-08 11:51:55 +05:00
public IEnumerator<TEntity> GetEnumerator() => Where().GetEnumerator();
2021-10-03 20:08:17 +05:00
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
2021-04-07 18:01:56 +05:00
}
}