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