Add Redis, Wal, Services
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using StackExchange.Redis;
|
||||
using System.Linq;
|
||||
|
||||
namespace Server.Redis;
|
||||
|
||||
public interface IRedisManager : IAsyncDisposable
|
||||
{
|
||||
IDatabase Db { get; }
|
||||
ISubscriber Bus { get; }
|
||||
|
||||
Task<bool> AcquireLeaseAsync(string key, string value, TimeSpan ttl);
|
||||
Task<bool> RenewLeaseAsync(string key, string value, TimeSpan ttl); // compare-and-set
|
||||
Task<bool> ReleaseLeaseAsync(string key, string value);
|
||||
|
||||
Task<bool> SetJsonAsync<T>(string key, T value, TimeSpan? ttl = null);
|
||||
Task<T?> GetJsonAsync<T>(string key);
|
||||
|
||||
Task<long> StreamAddAsync(string stream, string json, string? id = "*");
|
||||
Task<RedisValue[]> StreamReadGroupAsync(string stream, string group, string consumer, int count = 100, int blockMs = 0);
|
||||
Task AcknowledgeAsync(string stream, string group, params string[] ids);
|
||||
}
|
||||
|
||||
public sealed class RedisManager : IRedisManager
|
||||
{
|
||||
private readonly ILogger<RedisManager> _logger;
|
||||
private readonly ConnectionMultiplexer _mux;
|
||||
|
||||
public IDatabase Db => _mux.GetDatabase();
|
||||
public ISubscriber Bus => _mux.GetSubscriber();
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
WriteIndented = false
|
||||
};
|
||||
|
||||
public RedisManager(ILogger<RedisManager> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
|
||||
var connString = BuildRedisConnectionStringFromEnv();
|
||||
_mux = ConnectionMultiplexer.Connect(connString);
|
||||
_logger.LogInformation("Connected to Redis: {Endpoints}",
|
||||
string.Join(",", _mux.GetEndPoints().Select(ep => ep.ToString())));
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
try { await _mux.CloseAsync(); } catch { }
|
||||
_mux.Dispose();
|
||||
}
|
||||
|
||||
// ---------- Leases (simple Redlock-ish) ----------
|
||||
public async Task<bool> AcquireLeaseAsync(string key, string value, TimeSpan ttl)
|
||||
{
|
||||
return await Db.StringSetAsync(key, value, ttl, When.NotExists);
|
||||
}
|
||||
|
||||
public async Task<bool> RenewLeaseAsync(string key, string value, TimeSpan ttl)
|
||||
{
|
||||
// Lua script: if value matches, update TTL (PEXPIRE) and keep value
|
||||
const string script = @"
|
||||
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
||||
redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
||||
return 1
|
||||
else
|
||||
return 0
|
||||
end";
|
||||
var res = (int)(long)await Db.ScriptEvaluateAsync(script,
|
||||
new RedisKey[] { key },
|
||||
new RedisValue[] { value, (long)ttl.TotalMilliseconds });
|
||||
return res == 1;
|
||||
}
|
||||
|
||||
public async Task<bool> ReleaseLeaseAsync(string key, string value)
|
||||
{
|
||||
// Lua script: delete only if owned by 'value'
|
||||
const string script = @"
|
||||
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
||||
return redis.call('DEL', KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end";
|
||||
var res = (int)(long)await Db.ScriptEvaluateAsync(script,
|
||||
new RedisKey[] { key },
|
||||
new RedisValue[] { value });
|
||||
return res == 1;
|
||||
}
|
||||
|
||||
// ---------- JSON helpers ----------
|
||||
public async Task<bool> SetJsonAsync<T>(string key, T value, TimeSpan? ttl = null)
|
||||
{
|
||||
var bytes = JsonSerializer.SerializeToUtf8Bytes(value, JsonOptions);
|
||||
return await Db.StringSetAsync(key, bytes, ttl);
|
||||
}
|
||||
|
||||
public async Task<T?> GetJsonAsync<T>(string key)
|
||||
{
|
||||
var bytes = await Db.StringGetAsync(key);
|
||||
if (bytes.IsNullOrEmpty) return default;
|
||||
return JsonSerializer.Deserialize<T>((byte[])bytes!, JsonOptions);
|
||||
}
|
||||
|
||||
// ---------- Streams (write-ahead) ----------
|
||||
public async Task<long> StreamAddAsync(string stream, string json, string? id = "*")
|
||||
{
|
||||
var entryId = await Db.StreamAddAsync(stream, "data", json,
|
||||
maxLength: null, useApproximateMaxLength: false, messageId: id ?? "*");
|
||||
return entryId.HasValue ? 1 : 0;
|
||||
}
|
||||
|
||||
|
||||
public async Task<RedisValue[]> StreamReadGroupAsync(
|
||||
string stream, string group, string consumer, int count = 100, int blockMs = 0)
|
||||
{
|
||||
// Ensure group exists (create if not present)
|
||||
try
|
||||
{
|
||||
await Db.StreamCreateConsumerGroupAsync(stream, group, "$", createStream: true);
|
||||
}
|
||||
catch (RedisServerException ex) when (ex.Message.Contains("BUSYGROUP"))
|
||||
{
|
||||
// group already exists
|
||||
}
|
||||
|
||||
var deadline = blockMs > 0 ? DateTime.UtcNow.AddMilliseconds(blockMs) : (DateTime?)null;
|
||||
StackExchange.Redis.StreamEntry[] entries;
|
||||
|
||||
// Poll until we have entries or we hit the deadline
|
||||
while (true)
|
||||
{
|
||||
entries = await Db.StreamReadGroupAsync(stream, group, consumer, count: count, noAck: false);
|
||||
if (entries.Length > 0) break;
|
||||
if (deadline == null) break;
|
||||
|
||||
var remainingMs = (int)(deadline.Value - DateTime.UtcNow).TotalMilliseconds;
|
||||
if (remainingMs <= 0) break;
|
||||
|
||||
// small sleep to avoid hot loop
|
||||
await Task.Delay(Math.Min(remainingMs, 100));
|
||||
}
|
||||
|
||||
// Return the "data" field only (matches your current interface)
|
||||
var result = new RedisValue[entries.Length];
|
||||
for (int i = 0; i < entries.Length; i++)
|
||||
result[i] = entries[i].Values[0].Value; // field "data"
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public async Task AcknowledgeAsync(string stream, string group, params string[] ids)
|
||||
{
|
||||
if (ids.Length == 0) return;
|
||||
await Db.StreamAcknowledgeAsync(stream, group, Array.ConvertAll(ids, x => (RedisValue)x));
|
||||
}
|
||||
|
||||
// ---------- Conn string from env ----------
|
||||
private static string BuildRedisConnectionStringFromEnv()
|
||||
{
|
||||
var full = Environment.GetEnvironmentVariable("REDIS_CONNECTION_STRING");
|
||||
if (!string.IsNullOrWhiteSpace(full)) return full;
|
||||
|
||||
var host = Environment.GetEnvironmentVariable("REDIS_HOST") ?? "localhost";
|
||||
var port = int.TryParse(Environment.GetEnvironmentVariable("REDIS_PORT"), out var p) ? p : 6379;
|
||||
var password = Environment.GetEnvironmentVariable("REDIS_PASSWORD");
|
||||
var db = int.TryParse(Environment.GetEnvironmentVariable("REDIS_DB"), out var d) ? d : 0;
|
||||
|
||||
var cs = $"{host}:{port},defaultDatabase={db},abortConnect=false,syncTimeout=10000,connectRetry=3,connectTimeout=5000";
|
||||
if (!string.IsNullOrWhiteSpace(password)) cs += $",password={password}";
|
||||
return cs;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user