Initial commit with inital CMS
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Availability.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Persistente implementatie van de IAvailabilityService met Circuit Breaker.
|
||||
/// </summary>
|
||||
public class PersistentAvailabilityService : IAvailabilityService
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly AvailabilityOptions _options;
|
||||
|
||||
// Circuit Breaker state
|
||||
private static DateTimeOffset _lastErrorTime = DateTimeOffset.MinValue;
|
||||
private static AvailabilityStatus _cachedStatus = AvailabilityStatus.Available;
|
||||
|
||||
public PersistentAvailabilityService(ApplicationDbContext context, IOptions<AvailabilityOptions> options)
|
||||
{
|
||||
_context = context;
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
public async Task<AvailabilityStatus> IsAvailableAsync()
|
||||
{
|
||||
// Check Circuit Breaker
|
||||
if (DateTimeOffset.UtcNow - _lastErrorTime < TimeSpan.FromSeconds(_options.CircuitBreakerSeconds))
|
||||
{
|
||||
return _cachedStatus;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var state = await _context.AvailabilityStates.FirstOrDefaultAsync();
|
||||
|
||||
// Als er nog geen state is, maken we een default aan (Available)
|
||||
if (state == null)
|
||||
{
|
||||
return AvailabilityStatus.Available;
|
||||
}
|
||||
|
||||
_cachedStatus = state.Status;
|
||||
return state.Status;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Database fout: activeer Circuit Breaker
|
||||
_lastErrorTime = DateTimeOffset.UtcNow;
|
||||
_cachedStatus = AvailabilityStatus.Available; // Veilige fallback
|
||||
return _cachedStatus;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update de globale systeemstatus.
|
||||
/// </summary>
|
||||
public async Task UpdateStatusAsync(AvailabilityStatus newStatus, string? reason, string? updatedBy)
|
||||
{
|
||||
var state = await _context.AvailabilityStates.FirstOrDefaultAsync();
|
||||
|
||||
if (state == null)
|
||||
{
|
||||
state = new GlobalAvailabilityState
|
||||
{
|
||||
Id = Guid.NewGuid()
|
||||
};
|
||||
_context.AvailabilityStates.Add(state);
|
||||
}
|
||||
|
||||
state.Status = newStatus;
|
||||
state.Message = reason;
|
||||
state.LastUpdatedAt = DateTimeOffset.UtcNow;
|
||||
state.UpdatedBy = updatedBy;
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Reset cache
|
||||
_cachedStatus = newStatus;
|
||||
_lastErrorTime = DateTimeOffset.MinValue;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user