ShiftScheduler/Services/TransportService.cs
Copilot 73abfac988
Implement caching for transport connection results with IMemoryCache (#26)
* Initial plan

* Implement caching for transport connection results with IMemoryCache

Co-authored-by: clayschaad <11883505+clayschaad@users.noreply.github.com>

* Change cache duration from minutes to days

Co-authored-by: clayschaad <11883505+clayschaad@users.noreply.github.com>

* Implement CachedTransportService design with interface separation

Co-authored-by: clayschaad <11883505+clayschaad@users.noreply.github.com>

* Implement persistent file-based cache to survive application restarts

Co-authored-by: clayschaad <11883505+clayschaad@users.noreply.github.com>

* Revert persistent file-based cache implementation, restore IMemoryCache usage

Co-authored-by: clayschaad <11883505+clayschaad@users.noreply.github.com>

* Code cleanup

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: clayschaad <11883505+clayschaad@users.noreply.github.com>
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
2025-08-25 21:15:13 +02:00

43 lines
No EOL
1.6 KiB
C#

using Microsoft.Extensions.Caching.Memory;
using ShiftScheduler.Shared;
namespace ShiftScheduler.Services
{
public class TransportService(ITransportApiService transportService, TransportConfiguration config, IMemoryCache cache) : ITransportService
{
public async Task<TransportConnection?> GetConnectionAsync(DateTime shiftStartTime)
{
var searchDate = shiftStartTime.ToString("yyyy-MM-dd");
var searchTime = shiftStartTime.AddMinutes(config.MaxLateArrivalMinutes).ToString("HH:mm");
// Generate cache key based on request parameters
var cacheKey = GenerateCacheKey(searchDate, searchTime);
// Try to get from cache first
if (cache.TryGetValue(cacheKey, out TransportConnection? cachedConnection) && cachedConnection != null)
{
return cachedConnection;
}
// Not in cache, call the underlying transport service
var connection = await transportService.GetConnectionAsync(shiftStartTime);
// Cache the connection result if valid
if (connection != null)
{
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(config.CacheDurationDays)
};
cache.Set(cacheKey, connection, cacheOptions);
}
return connection;
}
private string GenerateCacheKey(string searchDate, string searchTime)
{
return $"transport_{config.StartStation}_{config.EndStation}_{searchDate}_{searchTime}";
}
}
}