AVS-Carton-Shipment-Verifier/Services/InMemoryScanHistoryStore.cs

73 lines
2.3 KiB
C#

using System.Collections.Concurrent;
using AVSCartonShipmentVerifier.DTOs;
namespace AVSCartonShipmentVerifier.Services;
public sealed class InMemoryScanHistoryStore : IScanHistoryStore
{
private const int MaxItems = 5;
private readonly ConcurrentQueue<ScannedRecordDto> _successful = new();
private readonly ConcurrentQueue<RejectedScanRecordDto> _rejected = new();
private readonly Lock _syncLock = new();
public Task AddSuccessfulScanAsync(ScannedRecordDto record, CancellationToken cancellationToken = default)
{
lock (_syncLock)
{
_successful.Enqueue(record);
while (_successful.Count > MaxItems)
{
_successful.TryDequeue(out _);
}
}
return Task.CompletedTask;
}
public Task AddRejectedScanAsync(RejectedScanRecordDto record, CancellationToken cancellationToken = default)
{
lock (_syncLock)
{
_rejected.Enqueue(record);
while (_rejected.Count > MaxItems)
{
_rejected.TryDequeue(out _);
}
}
return Task.CompletedTask;
}
public Task<IReadOnlyCollection<ScannedRecordDto>> GetLastFiveSuccessfulScansAsync(CancellationToken cancellationToken = default)
{
lock (_syncLock)
{
return Task.FromResult<IReadOnlyCollection<ScannedRecordDto>>(_successful.Reverse().ToArray());
}
}
public Task<IReadOnlyCollection<RejectedScanRecordDto>> GetLastFiveRejectedScansAsync(CancellationToken cancellationToken = default)
{
lock (_syncLock)
{
return Task.FromResult<IReadOnlyCollection<RejectedScanRecordDto>>(_rejected.Reverse().ToArray());
}
}
public Task<IReadOnlyCollection<ScannedRecordDto>> GetAllSuccessfulScansAsync(CancellationToken cancellationToken = default)
{
lock (_syncLock)
{
return Task.FromResult<IReadOnlyCollection<ScannedRecordDto>>(_successful.Reverse().ToArray());
}
}
public Task<IReadOnlyCollection<RejectedScanRecordDto>> GetAllRejectedScansAsync(CancellationToken cancellationToken = default)
{
lock (_syncLock)
{
return Task.FromResult<IReadOnlyCollection<RejectedScanRecordDto>>(_rejected.Reverse().ToArray());
}
}
}