86 lines
2.2 KiB
C#
86 lines
2.2 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Text.Json;
|
|
using System.Threading.Channels;
|
|
|
|
namespace GameServices;
|
|
|
|
/// <summary>
|
|
/// In-memory pub/sub hub for live world editor chunk delta events.
|
|
/// </summary>
|
|
public sealed class WorldEditDeltaHub
|
|
{
|
|
private readonly ConcurrentDictionary<string, ConcurrentDictionary<Guid, Channel<string>>> _subscribers = new();
|
|
|
|
public WorldEditSubscription Subscribe(string key)
|
|
{
|
|
var channel = Channel.CreateUnbounded<string>(new UnboundedChannelOptions
|
|
{
|
|
SingleReader = true,
|
|
SingleWriter = false
|
|
});
|
|
|
|
var id = Guid.NewGuid();
|
|
var bucket = _subscribers.GetOrAdd(key, _ => new ConcurrentDictionary<Guid, Channel<string>>());
|
|
bucket[id] = channel;
|
|
|
|
return new WorldEditSubscription(this, key, id, channel.Reader);
|
|
}
|
|
|
|
public void Publish(string key, object payload)
|
|
{
|
|
if (!_subscribers.TryGetValue(key, out var bucket) || bucket.Count == 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var json = JsonSerializer.Serialize(payload);
|
|
foreach (var (_, channel) in bucket)
|
|
{
|
|
channel.Writer.TryWrite(json);
|
|
}
|
|
}
|
|
|
|
private void Unsubscribe(string key, Guid id)
|
|
{
|
|
if (!_subscribers.TryGetValue(key, out var bucket))
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (bucket.TryRemove(id, out var channel))
|
|
{
|
|
channel.Writer.TryComplete();
|
|
}
|
|
|
|
if (bucket.IsEmpty)
|
|
{
|
|
_subscribers.TryRemove(key, out _);
|
|
}
|
|
}
|
|
|
|
public sealed class WorldEditSubscription : IDisposable
|
|
{
|
|
private readonly WorldEditDeltaHub _hub;
|
|
private readonly string _key;
|
|
private readonly Guid _id;
|
|
private bool _disposed;
|
|
|
|
internal WorldEditSubscription(WorldEditDeltaHub hub, string key, Guid id, ChannelReader<string> reader)
|
|
{
|
|
_hub = hub;
|
|
_key = key;
|
|
_id = id;
|
|
Reader = reader;
|
|
}
|
|
|
|
public ChannelReader<string> Reader { get; }
|
|
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
_hub.Unsubscribe(_key, _id);
|
|
}
|
|
}
|
|
}
|