68 lines
3.1 KiB
C#
68 lines
3.1 KiB
C#
using System.Collections.Concurrent;
|
|
using Microsoft.Extensions.Logging;
|
|
using Server.Redis;
|
|
|
|
namespace Server.Services;
|
|
|
|
public sealed class ZoneLeaseService : IZoneLeaseService, IHostedService, IDisposable
|
|
{
|
|
private readonly IRedisManager _redis;
|
|
private readonly ILogger<ZoneLeaseService> _log;
|
|
private readonly string _podId = Environment.GetEnvironmentVariable("POD_ID") ?? Guid.NewGuid().ToString("N");
|
|
private readonly TimeSpan _ttl = TimeSpan.FromSeconds(5);
|
|
private readonly TimeSpan _renew = TimeSpan.FromSeconds(2);
|
|
private readonly ConcurrentDictionary<ulong, long> _owned = new();
|
|
private Timer? _timer;
|
|
|
|
public ZoneLeaseService(IRedisManager redis, ILogger<ZoneLeaseService> log)
|
|
{ _redis = redis; _log = log; }
|
|
|
|
public bool IsOwner(ulong zoneId) => _owned.ContainsKey(zoneId);
|
|
public long CurrentFence(ulong zoneId) => _owned.TryGetValue(zoneId, out var f) ? f : -1;
|
|
|
|
public async ValueTask<bool> TryAcquireAsync(ulong zoneId, CancellationToken ct = default)
|
|
{
|
|
var fence = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
|
var val = $"{_podId}:{fence}";
|
|
var key = $"zone:owner:{{{zoneId}}}"; // hash tag for cluster
|
|
var ok = await _redis.Db.StringSetAsync(key, val, _ttl, when: StackExchange.Redis.When.NotExists);
|
|
if (ok) { _owned[zoneId] = fence; _log.LogInformation("Zone {Zone} acquired, fence={Fence}", zoneId, fence); }
|
|
return ok;
|
|
}
|
|
|
|
public async ValueTask<bool> RenewAsync(ulong zoneId, CancellationToken ct = default)
|
|
{
|
|
if (!_owned.TryGetValue(zoneId, out var fence)) return false;
|
|
var key = $"zone:owner:{{{zoneId}}}";
|
|
// renew if matches (Lua CAS)
|
|
const string lua = @"
|
|
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 _redis.Db.ScriptEvaluateAsync(lua,
|
|
new StackExchange.Redis.RedisKey[] { key },
|
|
new StackExchange.Redis.RedisValue[] { $"{_podId}:{fence}", (long)_ttl.TotalMilliseconds });
|
|
return res == 1;
|
|
}
|
|
|
|
public async ValueTask ReleaseAsync(ulong zoneId, CancellationToken ct = default)
|
|
{
|
|
if (!_owned.TryRemove(zoneId, out var fence)) return;
|
|
var key = $"zone:owner:{{{zoneId}}}";
|
|
const string lua = @"if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end";
|
|
await _redis.Db.ScriptEvaluateAsync(lua,
|
|
new StackExchange.Redis.RedisKey[] { key },
|
|
new StackExchange.Redis.RedisValue[] { $"{_podId}:{fence}" });
|
|
_log.LogInformation("Zone {Zone} released", zoneId);
|
|
}
|
|
|
|
// Background renew loop
|
|
public Task StartAsync(CancellationToken _) { _timer = new Timer(async _ => await RenewAll(), null, _renew, _renew); return Task.CompletedTask; }
|
|
public Task StopAsync(CancellationToken _) { _timer?.Dispose(); return Task.CompletedTask; }
|
|
private async Task RenewAll()
|
|
{
|
|
foreach (var z in _owned.Keys) { if (!await RenewAsync(z)) _owned.TryRemove(z, out _); }
|
|
}
|
|
public void Dispose() => _timer?.Dispose();
|
|
}
|