Selector/Selector.Cache/Consumer/AudioInjectorCaching.cs

58 lines
1.7 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SpotifyAPI.Web;
using StackExchange.Redis;
namespace Selector.Cache
{
public class CachingAudioFeatureInjector : AudioFeatureInjector
{
private readonly IDatabaseAsync Db;
2021-11-11 19:54:28 +00:00
public TimeSpan CacheExpiry { get; set; } = TimeSpan.FromDays(14);
public CachingAudioFeatureInjector(
IPlayerWatcher watcher,
IDatabaseAsync db,
ITracksClient trackClient,
ILogger<CachingAudioFeatureInjector> logger = null,
CancellationToken token = default
) : base(watcher, trackClient, logger, token) {
Db = db;
NewFeature += CacheCallback;
}
public void CacheCallback(object sender, AnalysedTrack e)
{
Task.Run(async () =>
{
try
{
await AsyncCacheCallback(e);
}
catch (Exception e)
{
Logger.LogError(e, "Error occured during callback");
}
}, CancelToken);
}
public async Task AsyncCacheCallback(AnalysedTrack e)
{
var payload = JsonSerializer.Serialize(e.Features, JsonContext.Default.TrackAudioFeatures);
2022-07-01 22:04:17 +01:00
Logger.LogTrace("Caching current for [{track}]", e.Track.DisplayString());
var resp = await Db.StringSetAsync(Key.AudioFeature(e.Track.Id), payload, expiry: CacheExpiry);
2022-07-01 22:04:17 +01:00
Logger.LogDebug("Cached audio feature for [{track}], {state}", e.Track.DisplayString(), (resp ? "value set" : "value NOT set"));
}
}
}