namespace Khaemhat.Core.Caching;
///
/// The application cache (SPEC §9): in memory, or Redis when KHAEMHAT_REDIS is set. Values are stored as JSON
/// in both cases, so the behaviour is the same with and without Redis. Keys follow .
///
public interface ICacheProvider
{
/// Whether the cache is shared between instances (Redis reachable).
bool IsDistributed { get; }
/// Reads a value.
/// The value type.
/// The key.
/// Cancellation.
/// The value, or when missing or expired.
ValueTask GetAsync(string key, CancellationToken cancellationToken = default);
/// Stores a value.
/// The value type.
/// The key.
/// The value.
/// How long it stays.
/// Cancellation.
/// A task.
ValueTask SetAsync(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default);
/// Removes a value.
/// The key.
/// Cancellation.
/// A task.
ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default);
/// Removes every key that starts with .
/// The prefix, for example kh:DEMO:permissions:.
/// Cancellation.
/// A task.
ValueTask RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default);
/// Reads a value, or creates and stores it.
/// The value type.
/// The key.
/// Creates the value when missing.
/// How long it stays.
/// Cancellation.
/// The value.
ValueTask GetOrCreateAsync(string key, Func> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default);
///
/// Removes the keys with here and tells the other instances to do the same (Redis pub/sub).
///
/// The prefix.
/// Cancellation.
/// A task.
ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default);
}
/// Cache keys: kh:{company}:{area}:{key}, with _ for the instance (SPEC §9).
public static class CacheKeys
{
/// The instance scope.
public const string Instance = "_";
/// A key.
/// The company code, or for the instance.
/// The area, for example permissions.
/// The key inside the area.
/// The full key.
public static string For(string? company, string area, string key) => Prefix(company, area) + key;
/// The prefix of an area, for .
/// The company code, or for the instance.
/// The area.
/// The prefix, ending with a colon.
public static string Prefix(string? company, string area)
{
ArgumentException.ThrowIfNullOrWhiteSpace(area);
return "kh:" + (string.IsNullOrEmpty(company) ? Instance : company) + ":" + area + ":";
}
}