using System.Globalization; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Text.Json; using Khaemhat.Core.Caching; using Microsoft.Extensions.Logging; namespace Khaemhat.Infrastructure.Caching; /// /// Where Redis is (KHAEMHAT_REDIS, SPEC §6): redis://[[user]:password@]host[:6379][/db], or /// rediss:// for TLS. The password never appears in . /// public sealed class RedisEndpoint { private RedisEndpoint(string host, int port, bool tls, string? user, string? password, int database) { Host = host; Port = port; UseTls = tls; User = user; Password = password; Database = database; } /// The host. public string Host { get; } /// The port. public int Port { get; } /// Whether to use TLS. public bool UseTls { get; } /// The ACL user, if any. public string? User { get; } /// The password, if any. public string? Password { get; } /// The database number. public int Database { get; } /// Parses the URL. /// The URL. /// The endpoint. /// The URL is not valid (the message does not repeat it). public static RedisEndpoint Parse(string url) { if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("redis" or "rediss") || string.IsNullOrEmpty(uri.Host)) { throw new FormatException("KHAEMHAT_REDIS must be redis://[:password@]host:6379/0 or rediss://."); } string? user = null, password = null; if (uri.UserInfo.Length > 0) { var colon = uri.UserInfo.IndexOf(':', StringComparison.Ordinal); user = colon < 0 ? null : Uri.UnescapeDataString(uri.UserInfo[..colon]); password = Uri.UnescapeDataString(colon < 0 ? uri.UserInfo : uri.UserInfo[(colon + 1)..]); user = string.IsNullOrEmpty(user) ? null : user; } var path = uri.AbsolutePath.Trim('/'); var database = path.Length == 0 ? 0 : int.TryParse(path, NumberStyles.None, CultureInfo.InvariantCulture, out var db) ? db : throw new FormatException("The Redis database must be a number."); return new RedisEndpoint(uri.Host, uri.IsDefaultPort ? 6379 : uri.Port, uri.Scheme == "rediss", user, password, database); } /// public override string ToString() => (UseTls ? "rediss://" : "redis://") + (Password is null ? string.Empty : "***@") + Host + ":" + Port.ToString(CultureInfo.InvariantCulture) + "/" + Database.ToString(CultureInfo.InvariantCulture); } /// /// A minimal Redis client written in house (SPEC §1.2: no external libraries): one connection, one command at a time, /// reconnecting after an error. Enough for the cache; pipelining and clustering are not needed. /// /// Where Redis is. public sealed class RedisClient(RedisEndpoint endpoint) : IAsyncDisposable { private readonly SemaphoreSlim _gate = new(1, 1); private TcpClient? _tcp; private Stream? _stream; private BufferedReader? _reader; /// The endpoint. public RedisEndpoint Endpoint { get; } = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); /// The time allowed to connect and for each command. public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(2); /// Sends a command and reads its reply. /// The command and its arguments. /// The reply. /// Redis answered with an error. /// The connection failed. public Task ExecuteAsync(params IReadOnlyList arguments) => ExecuteAsync(arguments, CancellationToken.None); /// Sends a command and reads its reply. /// The command and its arguments. /// Cancellation. /// The reply. public async Task ExecuteAsync(IReadOnlyList arguments, CancellationToken cancellationToken) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(Timeout); await _gate.WaitAsync(timeout.Token).ConfigureAwait(false); try { if (_stream is null) { await ConnectAsync(timeout.Token).ConfigureAwait(false); } var reply = await SendAsync(arguments, timeout.Token).ConfigureAwait(false); return reply.Kind == RespKind.Error ? throw new RedisException(reply.Text ?? "Redis error.") : reply; } catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException or AuthenticationException) { Close(); if (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested) { throw new IOException("Redis did not answer in time.", ex); } throw; } finally { _gate.Release(); } } /// public ValueTask DisposeAsync() { Close(); _gate.Dispose(); return ValueTask.CompletedTask; } private async Task ConnectAsync(CancellationToken cancellationToken) { var tcp = new TcpClient { NoDelay = true }; try { await tcp.ConnectAsync(Endpoint.Host, Endpoint.Port, cancellationToken).ConfigureAwait(false); Stream stream = tcp.GetStream(); if (Endpoint.UseTls) { var ssl = new SslStream(stream, leaveInnerStreamOpen: false); await ssl.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = Endpoint.Host }, cancellationToken).ConfigureAwait(false); stream = ssl; } _tcp = tcp; _stream = stream; _reader = new BufferedReader(stream); } catch { tcp.Dispose(); throw; } if (Endpoint.Password is not null) { var auth = await SendAsync(Endpoint.User is null ? ["AUTH", Endpoint.Password] : ["AUTH", Endpoint.User, Endpoint.Password], cancellationToken).ConfigureAwait(false); if (auth.Kind == RespKind.Error) { Close(); throw new RedisException("Redis refused the credentials."); } } if (Endpoint.Database != 0) { var select = await SendAsync(["SELECT", Endpoint.Database], cancellationToken).ConfigureAwait(false); if (select.Kind == RespKind.Error) { Close(); throw new RedisException(select.Text ?? "SELECT failed."); } } } private async Task SendAsync(IReadOnlyList arguments, CancellationToken cancellationToken) { await _stream!.WriteAsync(Resp.Command(arguments), cancellationToken).ConfigureAwait(false); await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); return await Resp.ReadAsync(_reader!, cancellationToken).ConfigureAwait(false); } private void Close() { _stream?.Dispose(); _tcp?.Dispose(); _stream = null; _tcp = null; _reader = null; } } /// /// The shared cache on Redis (SPEC §9.3), for instances that run side by side. Values are JSON with a time to live. /// When Redis cannot be reached the cache falls back to memory and says so in the log (once a minute): nothing fails /// because of the cache. /// public sealed partial class RedisCacheProvider : ICacheProvider, IAsyncDisposable { private const string InvalidationChannel = "kh:invalidate"; private readonly RedisClient _client; private readonly MemoryCacheProvider _fallback; private readonly TimeProvider _clock; private readonly ILogger _logger; private DateTimeOffset _lastWarning = DateTimeOffset.MinValue; private volatile bool _healthy = true; /// Creates the cache. /// The Redis client. /// The clock. /// The log. public RedisCacheProvider(RedisClient client, TimeProvider clock, ILogger logger) { ArgumentNullException.ThrowIfNull(client); ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(logger); _client = client; _clock = clock; _logger = logger; _fallback = new MemoryCacheProvider(clock); } /// public bool IsDistributed => _healthy; /// public async ValueTask GetAsync(string key, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(key); var reply = await TryAsync(["GET", key], cancellationToken).ConfigureAwait(false); if (reply is null) { return await _fallback.GetAsync(key, cancellationToken).ConfigureAwait(false); } return reply.Bytes is { } bytes ? JsonSerializer.Deserialize(bytes) : default; } /// public async ValueTask SetAsync(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(key); var json = JsonSerializer.SerializeToUtf8Bytes(value); var milliseconds = Math.Max(1, (long)timeToLive.TotalMilliseconds); if (await TryAsync(["SET", key, json, "PX", milliseconds], cancellationToken).ConfigureAwait(false) is null) { _fallback.SetRaw(key, json, timeToLive); } } /// public async ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(key); await _fallback.RemoveAsync(key, cancellationToken).ConfigureAwait(false); await TryAsync(["DEL", key], cancellationToken).ConfigureAwait(false); } /// public async ValueTask RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(prefix); await _fallback.RemoveByPrefixAsync(prefix, cancellationToken).ConfigureAwait(false); var cursor = "0"; do { var reply = await TryAsync(["SCAN", cursor, "MATCH", EscapePattern(prefix) + "*", "COUNT", 500], cancellationToken).ConfigureAwait(false); if (reply?.Items is not [var next, { Items: { } keys }]) { return; } cursor = next.Text ?? "0"; if (keys.Count > 0) { await TryAsync(["DEL", .. keys.Select(k => (object)k.Bytes!)], cancellationToken).ConfigureAwait(false); } } while (cursor != "0"); } /// public async ValueTask GetOrCreateAsync(string key, Func> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(factory); var reply = await TryAsync(["GET", key], cancellationToken).ConfigureAwait(false); if (reply is null) { return await _fallback.GetOrCreateAsync(key, factory, timeToLive, cancellationToken).ConfigureAwait(false); } if (reply.Bytes is { } bytes) { return JsonSerializer.Deserialize(bytes)!; } var value = await factory(cancellationToken).ConfigureAwait(false); await SetAsync(key, value, timeToLive, cancellationToken).ConfigureAwait(false); return value; } /// /// Keys live only in Redis, so deleting them is enough; the message lets future local copies follow. public async ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default) { await RemoveByPrefixAsync(prefix, cancellationToken).ConfigureAwait(false); await TryAsync(["PUBLISH", InvalidationChannel, prefix], cancellationToken).ConfigureAwait(false); } /// Checks the connection (PING), for the start log and the system page. /// Cancellation. /// when Redis answered. public async Task PingAsync(CancellationToken cancellationToken = default) => (await TryAsync(["PING"], cancellationToken).ConfigureAwait(false))?.Text == "PONG"; /// public ValueTask DisposeAsync() => _client.DisposeAsync(); /// Escapes the glob characters of a key prefix for SCAN MATCH. /// The prefix. /// The escaped prefix. public static string EscapePattern(string prefix) { ArgumentNullException.ThrowIfNull(prefix); var builder = new System.Text.StringBuilder(prefix.Length + 8); foreach (var c in prefix) { if (c is '*' or '?' or '[' or ']' or '\\') { builder.Append('\\'); } builder.Append(c); } return builder.ToString(); } private async Task TryAsync(IReadOnlyList arguments, CancellationToken cancellationToken) { try { var reply = await _client.ExecuteAsync(arguments, cancellationToken).ConfigureAwait(false); if (!_healthy) { _healthy = true; LogRecovered(_logger, _client.Endpoint.ToString()); } return reply; } catch (Exception ex) when (ex is IOException or SocketException or RedisException or AuthenticationException) { _healthy = false; var now = _clock.GetUtcNow(); if (now - _lastWarning > TimeSpan.FromMinutes(1)) { _lastWarning = now; LogUnavailable(_logger, _client.Endpoint.ToString(), ex.Message); } return null; } } [LoggerMessage(Level = LogLevel.Warning, Message = "Redis {Endpoint} is not available, the cache works in memory: {Reason}")] private static partial void LogUnavailable(ILogger logger, string endpoint, string reason); [LoggerMessage(Level = LogLevel.Information, Message = "Redis {Endpoint} is available again.")] private static partial void LogRecovered(ILogger logger, string endpoint); }