This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using ShrinkEventBus;
|
||||
|
||||
namespace ShrinkNetwork.Integration
|
||||
{
|
||||
public readonly struct ShrinkNetworkEventRegistration
|
||||
{
|
||||
public ShrinkNetworkEventRegistration(Type eventType, int opcode, string? route,
|
||||
Func<IShrinkEvent, UniTask> dispatch,
|
||||
Func<ShrinkNetworkContext, IShrinkEvent, UniTask<object?>>? requestDispatch)
|
||||
{
|
||||
EventType = eventType ?? throw new ArgumentNullException(nameof(eventType));
|
||||
Opcode = opcode;
|
||||
Route = route;
|
||||
Dispatch = dispatch ?? throw new ArgumentNullException(nameof(dispatch));
|
||||
RequestDispatch = requestDispatch;
|
||||
}
|
||||
|
||||
public Type EventType { get; }
|
||||
public int Opcode { get; }
|
||||
public string? Route { get; }
|
||||
public Func<IShrinkEvent, UniTask> Dispatch { get; }
|
||||
public Func<ShrinkNetworkContext, IShrinkEvent, UniTask<object?>>? RequestDispatch { get; }
|
||||
}
|
||||
|
||||
public static class ShrinkNetworkEventRegistry
|
||||
{
|
||||
private static readonly object Gate = new();
|
||||
private static readonly Dictionary<Type, ShrinkNetworkEventRegistration> Registrations = new();
|
||||
|
||||
public static void Register<TEvent>(int opcode, string? route)
|
||||
where TEvent : IShrinkEvent, IShrinkNetworkMessage
|
||||
{
|
||||
var registration = new ShrinkNetworkEventRegistration(
|
||||
typeof(TEvent), opcode, route,
|
||||
static eventData => ShrinkNetworkEventBusBridge.DispatchGeneratedAsync((TEvent)eventData),
|
||||
typeof(IShrinkNetworkRequest).IsAssignableFrom(typeof(TEvent))
|
||||
? static (context, eventData) =>
|
||||
ShrinkNetworkEventBusBridge.DispatchGeneratedRequestAsync(context, (TEvent)eventData)
|
||||
: null);
|
||||
lock (Gate)
|
||||
Registrations[typeof(TEvent)] = registration;
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<ShrinkNetworkEventRegistration> Snapshot()
|
||||
{
|
||||
lock (Gate)
|
||||
return Registrations.Values.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user