using System;
using System.Threading;
using xAiApi.Interfaces;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace xAiApi.Providers
{
///
/// Periodically Removes Expired Document Sessions from In-Memory Vector Store ...
///
public class XInMemoryVectorStoreCleanupService : BackgroundService
{
///
/// Default Cleanup Interval ...
///
public static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(5);
private readonly TimeSpan interval;
private readonly IXInMemoryVectorStore vectorStore;
private readonly ILogger logger;
public XInMemoryVectorStoreCleanupService(
IXInMemoryVectorStore vectorStore,
ILogger logger
)
{
this.logger = logger;
this.vectorStore = vectorStore;
this.interval = DefaultInterval;
}
///
/// Cleanup Loop ...
///
///
///
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
//
try
{
//
while (!stoppingToken.IsCancellationRequested)
{
//
await Task.Delay(interval, stoppingToken);
//
try
{
//
var removed = vectorStore.RemoveExpired();
if (removed > 0)
{
//
logger.LogInformation(
"InMemoryVectorStore Cleanup: {Removed} Expired Session(s) Removed, {Count} Remaining",
removed,
vectorStore.Count
);
}
}
catch (Exception ex)
{
logger.LogError(ex, "InMemoryVectorStore Cleanup Failed");
}
}
}
catch (OperationCanceledException)
{
// Shutdown ...
}
}
}
}