Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0449e82c0c
|
||
|
|
901ad18453
|
||
|
|
95844e11ff
|
||
|
|
240d24ba7a
|
||
|
|
a92c9d2cea
|
||
|
|
8acccdcc4b
|
||
|
|
2cea8a7ff5
|
||
|
|
8c6c464ae1
|
||
|
|
93bd33c59b
|
||
|
|
c15c14e394
|
||
|
|
67a8216c64
|
||
|
|
7f7d938fc2
|
||
|
|
fbd014a582
|
||
|
|
0ff6cba0e7
|
||
|
|
c247a207da
|
||
|
|
ed8e896fe8
|
||
|
|
6c3ab86df2
|
||
|
|
7d9e0566dd
|
||
|
|
f64289406f
|
||
|
|
98acdda3b2
|
||
|
|
e0e009a12d
|
||
|
|
1edf2172fd
|
||
|
|
8b4e6f6b75
|
||
|
|
94d58dba12
|
||
|
|
f09625fb4d
|
||
|
|
8549ba5c80
|
||
|
|
3dfbccc9d6 |
No files matched your search
@@ -2,6 +2,34 @@
|
||||
|
||||
本文件记录 `ShrinkEventBus` 在当前工作区中的包内变更。
|
||||
|
||||
## [2.3.2] - 2026-11-06
|
||||
|
||||
### Performance
|
||||
|
||||
- 诊断观察者列表在订阅或退订时生成不可变快照,消除每次诊断派发的列表分配,保留逐个观察者的异常隔离。
|
||||
- 同步排队直接保存回调,移除额外闭包;主线程调度器复用泵送回调,保持延后事件的批次边界。
|
||||
|
||||
## [2.3.0] - 2026-11-06
|
||||
|
||||
### Added
|
||||
|
||||
- 新增 `EventBus.PostDeferred(bus, event)`,把 MainThread Bus 的事件推迟到下一次主线程泵送;重入发布不会在同一次泵送中立即执行。
|
||||
- 新增公开的 `EventBus.ObserveDiagnostics(...)` 与 `ShrinkEventDiagnostic`,供编辑器和外部工具读取分发时间、Bus、调度器、线程、耗时、结果与同步标记,不再依赖私有事件或反射。
|
||||
- `ShrinkPostFailure` 新增 `DeferredUnsupported`,用于 `Inline`、`DedicatedThread`、`TaskPool` 或宿主没有延后派发能力的情况。
|
||||
|
||||
### Changed
|
||||
|
||||
- Runtime Abstractions 0.2.0 新增 `IShrinkDeferredMainThreadDispatcher`;Unity PlayerLoop 与共享 `SynchronizationContext` 调度器实现该接口。
|
||||
- 诊断观察者逐个隔离异常,单个观察者失败不会阻断业务 handler 或其他观察者。
|
||||
|
||||
## [2.2.3] - 2026-10-03
|
||||
|
||||
- Unity 可独立通过 Git URL 安装,必装依赖仅保留 UniTask 和官方 Mono.Cecil。
|
||||
- Shared Runtime 与 Shared CodeGen 改为可选集成,由包版本宏自动启用。
|
||||
- 内置独立特性订阅织入器,支持实例、静态、UniTask 和 MonoBehaviour 生命周期绑定;安装 Shared CodeGen 后由共享生成器接管。
|
||||
- Unity 主线程调度契约改为 `IShrinkEventBusMainThreadDispatcher`;共享接口通过 `ShrinkSharedMainThreadDispatcher` 适配,.NET/Godot 接口不变。
|
||||
- 独立验证工程取消私有 registry 要求,增加外部消费程序集的生成绑定测试及可选调度适配测试。
|
||||
|
||||
## [2.0.1] - 2026-08-28
|
||||
|
||||
### Added
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
#nullable enable
|
||||
#if !SHRINK_EVENTBUS_HAS_SHARED_CODEGEN
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Mono.Cecil;
|
||||
using Mono.Cecil.Cil;
|
||||
|
||||
namespace ShrinkEventBus.CodeGen
|
||||
{
|
||||
internal static class EventBusAssemblyWeaver
|
||||
{
|
||||
private const string EventRuntime = "ShrinkEventBus.Runtime";
|
||||
private const string Marker = "ShrinkEventBus.Generated.StandaloneWeaveMarker";
|
||||
|
||||
public static bool Weave(ModuleDefinition module)
|
||||
{
|
||||
if (!References(module, EventRuntime) || module.GetType(Marker) != null)
|
||||
return false;
|
||||
var instances = 0;
|
||||
var statics = 0;
|
||||
WeaveEventBus(module, ref instances, ref statics);
|
||||
if (instances == 0 && statics == 0)
|
||||
return false;
|
||||
module.Types.Add(new TypeDefinition("ShrinkEventBus.Generated", "StandaloneWeaveMarker",
|
||||
TypeAttributes.NotPublic | TypeAttributes.Abstract | TypeAttributes.Sealed, module.TypeSystem.Object));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void WeaveEventBus(ModuleDefinition module,
|
||||
ref int instanceCount, ref int staticCount)
|
||||
{
|
||||
var subscriberAttribute = RequireType(module, "ShrinkEventBus.ShrinkEventSubscriberAttribute", EventRuntime);
|
||||
var subscribeAttribute = RequireType(module, "ShrinkEventBus.ShrinkSubscribeAttribute", EventRuntime);
|
||||
var allTypes = AllTypes(module.Types).Where(type => !type.IsInterface).ToArray();
|
||||
foreach (var type in allTypes.Where(type => HasAttribute(type, subscriberAttribute)))
|
||||
{
|
||||
var instanceHandlers = type.Methods.Where(method => !method.IsStatic && HasAttribute(method, subscribeAttribute)).ToArray();
|
||||
if (instanceHandlers.Length > 0)
|
||||
{
|
||||
var lifetime = ReadInt(type.CustomAttributes.First(a => a.AttributeType.FullName == subscriberAttribute.FullName), "Lifetime", 0);
|
||||
if (InjectInstanceBinding(module, type, instanceHandlers, subscribeAttribute))
|
||||
instanceCount++;
|
||||
if (lifetime == 1)
|
||||
InjectAwakeToDestroyLifetime(type, module);
|
||||
else if (lifetime != 0)
|
||||
throw new InvalidOperationException($"{type.FullName}: unsupported subscriber lifetime.");
|
||||
}
|
||||
}
|
||||
|
||||
var staticTypes = allTypes.Where(type => HasAttribute(type, subscriberAttribute))
|
||||
.Where(type => type.Methods.Any(method => method.IsStatic && HasAttribute(method, subscribeAttribute)))
|
||||
.ToArray();
|
||||
if (staticTypes.Length > 0)
|
||||
{
|
||||
staticCount = staticTypes.Sum(type => type.Methods.Count(method => method.IsStatic && HasAttribute(method, subscribeAttribute)));
|
||||
InjectStaticBootstrap(module, staticTypes, subscriberAttribute, subscribeAttribute);
|
||||
}
|
||||
}
|
||||
|
||||
private static void InjectAwakeToDestroyLifetime(TypeDefinition type, ModuleDefinition module)
|
||||
{
|
||||
if (!InheritsFrom(type, "UnityEngine.MonoBehaviour"))
|
||||
throw new InvalidOperationException($"[ShrinkEventSubscriber(Lifetime = AwakeToDestroy)] requires MonoBehaviour: {type.FullName}.");
|
||||
|
||||
const string bindingFieldName = "__shrinkEventBusAwakeToDestroyBinding";
|
||||
if (type.Fields.Any(field => field.Name == bindingFieldName))
|
||||
throw new InvalidOperationException($"Reserved generated field already exists on {type.FullName}: {bindingFieldName}.");
|
||||
|
||||
var disposableType = new TypeReference("System", "IDisposable", module, module.TypeSystem.CoreLibrary);
|
||||
var bindingField = new FieldDefinition(bindingFieldName, FieldAttributes.Private, disposableType);
|
||||
type.Fields.Add(bindingField);
|
||||
var eventBusType = RequireType(module, "ShrinkEventBus.EventBus", EventRuntime);
|
||||
var attachMethod = ImportMethod(module, eventBusType,
|
||||
method => method.Name == "Attach" && method.IsStatic && method.Parameters.Count == 2);
|
||||
var disposeMethod = new MethodReference("Dispose", module.TypeSystem.Void, disposableType) { HasThis = true };
|
||||
InjectAwake(type, module, bindingField, attachMethod);
|
||||
InjectOnDestroy(type, module, bindingField, disposeMethod);
|
||||
}
|
||||
|
||||
private static void InjectAwake(TypeDefinition type, ModuleDefinition module,
|
||||
FieldDefinition bindingField, MethodReference attachMethod)
|
||||
{
|
||||
var awake = type.Methods.FirstOrDefault(method =>
|
||||
method.Name == "Awake" && !method.IsStatic && method.Parameters.Count == 0);
|
||||
if (awake != null)
|
||||
{
|
||||
InsertAttachAtStart(awake, module, bindingField, attachMethod);
|
||||
return;
|
||||
}
|
||||
|
||||
var baseAwake = FindBaseMethodReference(type, "Awake", module);
|
||||
awake = new MethodDefinition("Awake",
|
||||
baseAwake != null
|
||||
? MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.Virtual
|
||||
: MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot,
|
||||
module.TypeSystem.Void);
|
||||
awake.Body.InitLocals = true;
|
||||
var il = awake.Body.GetILProcessor();
|
||||
if (baseAwake != null)
|
||||
{
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Call, baseAwake);
|
||||
}
|
||||
EmitAttach(il, awake, module, bindingField, attachMethod);
|
||||
il.Emit(OpCodes.Ret);
|
||||
type.Methods.Add(awake);
|
||||
}
|
||||
|
||||
private static void InjectOnDestroy(TypeDefinition type, ModuleDefinition module,
|
||||
FieldDefinition bindingField, MethodReference disposeMethod)
|
||||
{
|
||||
var onDestroy = type.Methods.FirstOrDefault(method =>
|
||||
method.Name == "OnDestroy" && !method.IsStatic && method.Parameters.Count == 0);
|
||||
if (onDestroy != null)
|
||||
{
|
||||
InsertDisposeAtStart(onDestroy, bindingField, disposeMethod);
|
||||
return;
|
||||
}
|
||||
|
||||
var baseOnDestroy = FindBaseMethodReference(type, "OnDestroy", module);
|
||||
onDestroy = new MethodDefinition("OnDestroy",
|
||||
baseOnDestroy != null
|
||||
? MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.Virtual
|
||||
: MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot,
|
||||
module.TypeSystem.Void);
|
||||
var il = onDestroy.Body.GetILProcessor();
|
||||
EmitDispose(il, bindingField, disposeMethod);
|
||||
if (baseOnDestroy != null)
|
||||
{
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Call, baseOnDestroy);
|
||||
}
|
||||
il.Emit(OpCodes.Ret);
|
||||
type.Methods.Add(onDestroy);
|
||||
}
|
||||
|
||||
private static void InsertAttachAtStart(MethodDefinition method, ModuleDefinition module,
|
||||
FieldDefinition bindingField, MethodReference attachMethod)
|
||||
{
|
||||
if (!method.HasBody || method.Body.Instructions.Count == 0)
|
||||
throw new InvalidOperationException($"Awake has no body: {method.FullName}.");
|
||||
method.Body.InitLocals = true;
|
||||
var processor = method.Body.GetILProcessor();
|
||||
var instructions = BuildAttachInstructions(processor, method, module, bindingField, attachMethod);
|
||||
var first = method.Body.Instructions[0];
|
||||
foreach (var instruction in instructions)
|
||||
processor.InsertBefore(first, instruction);
|
||||
}
|
||||
|
||||
private static void EmitAttach(ILProcessor il, MethodDefinition method, ModuleDefinition module,
|
||||
FieldDefinition bindingField, MethodReference attachMethod)
|
||||
{
|
||||
foreach (var instruction in BuildAttachInstructions(il, method, module, bindingField, attachMethod))
|
||||
il.Append(instruction);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<Instruction> BuildAttachInstructions(ILProcessor il,
|
||||
MethodDefinition method, ModuleDefinition module, FieldDefinition bindingField,
|
||||
MethodReference attachMethod)
|
||||
{
|
||||
var defaultBusType = module.ImportReference(attachMethod.Parameters[1].ParameterType);
|
||||
var defaultBus = new VariableDefinition(defaultBusType);
|
||||
method.Body.Variables.Add(defaultBus);
|
||||
var attached = il.Create(OpCodes.Nop);
|
||||
return new[]
|
||||
{
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldfld, bindingField),
|
||||
il.Create(OpCodes.Brtrue_S, attached),
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldloca_S, defaultBus),
|
||||
il.Create(OpCodes.Initobj, defaultBusType),
|
||||
il.Create(OpCodes.Ldloc, defaultBus),
|
||||
il.Create(OpCodes.Call, attachMethod),
|
||||
il.Create(OpCodes.Stfld, bindingField),
|
||||
attached
|
||||
};
|
||||
}
|
||||
|
||||
private static void InsertDisposeAtStart(MethodDefinition method,
|
||||
FieldDefinition bindingField, MethodReference disposeMethod)
|
||||
{
|
||||
if (!method.HasBody || method.Body.Instructions.Count == 0)
|
||||
throw new InvalidOperationException($"OnDestroy has no body: {method.FullName}.");
|
||||
var processor = method.Body.GetILProcessor();
|
||||
var instructions = BuildDisposeInstructions(processor, bindingField, disposeMethod);
|
||||
var first = method.Body.Instructions[0];
|
||||
foreach (var instruction in instructions)
|
||||
processor.InsertBefore(first, instruction);
|
||||
}
|
||||
|
||||
private static void EmitDispose(ILProcessor il, FieldDefinition bindingField,
|
||||
MethodReference disposeMethod)
|
||||
{
|
||||
foreach (var instruction in BuildDisposeInstructions(il, bindingField, disposeMethod))
|
||||
il.Append(instruction);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<Instruction> BuildDisposeInstructions(ILProcessor il,
|
||||
FieldDefinition bindingField, MethodReference disposeMethod)
|
||||
{
|
||||
var disposed = il.Create(OpCodes.Nop);
|
||||
return new[]
|
||||
{
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldfld, bindingField),
|
||||
il.Create(OpCodes.Brfalse_S, disposed),
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldfld, bindingField),
|
||||
il.Create(OpCodes.Callvirt, disposeMethod),
|
||||
il.Create(OpCodes.Ldarg_0),
|
||||
il.Create(OpCodes.Ldnull),
|
||||
il.Create(OpCodes.Stfld, bindingField),
|
||||
disposed
|
||||
};
|
||||
}
|
||||
|
||||
private static MethodReference? FindBaseMethodReference(TypeDefinition type,
|
||||
string methodName, ModuleDefinition module)
|
||||
{
|
||||
try
|
||||
{
|
||||
var baseTypeReference = type.BaseType;
|
||||
while (baseTypeReference != null)
|
||||
{
|
||||
var baseType = baseTypeReference.Resolve();
|
||||
if (baseType == null) break;
|
||||
var method = baseType.Methods.FirstOrDefault(candidate =>
|
||||
candidate.Name == methodName && !candidate.IsStatic && candidate.IsVirtual &&
|
||||
candidate.Parameters.Count == 0);
|
||||
if (method != null)
|
||||
{
|
||||
if (baseTypeReference is GenericInstanceType genericBase)
|
||||
{
|
||||
return new MethodReference(method.Name, module.ImportReference(method.ReturnType),
|
||||
module.ImportReference(genericBase))
|
||||
{
|
||||
HasThis = method.HasThis,
|
||||
ExplicitThis = method.ExplicitThis,
|
||||
CallingConvention = method.CallingConvention
|
||||
};
|
||||
}
|
||||
return module.ImportReference(method);
|
||||
}
|
||||
baseTypeReference = baseType.BaseType;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool InheritsFrom(TypeDefinition type, string expectedFullName)
|
||||
{
|
||||
var current = type.BaseType;
|
||||
while (current != null)
|
||||
{
|
||||
if (current.FullName == expectedFullName) return true;
|
||||
try { current = current.Resolve()?.BaseType; }
|
||||
catch { return false; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool InjectInstanceBinding(ModuleDefinition module, TypeDefinition owner,
|
||||
IReadOnlyList<MethodDefinition> handlers, TypeReference subscribeAttribute)
|
||||
{
|
||||
var generatedInterface = RequireType(module, "ShrinkEventBus.IShrinkGeneratedSubscriber", EventRuntime);
|
||||
if (owner.Interfaces.Any(item => item.InterfaceType.FullName == generatedInterface.FullName))
|
||||
return false;
|
||||
var resolverType = RequireType(module, "ShrinkEventBus.IShrinkBusResolver", EventRuntime);
|
||||
var busKeyType = RequireType(module, "ShrinkEventBus.ShrinkBusKey", EventRuntime);
|
||||
var bindingType = RequireType(module, "ShrinkEventBus.ShrinkEventBinding", EventRuntime);
|
||||
var helperType = RequireType(module, "ShrinkEventBus.ShrinkGeneratedBinding", EventRuntime);
|
||||
var disposableType = RequireType(module, "System.IDisposable", module.TypeSystem.CoreLibrary.Name);
|
||||
var nullableBusKey = GenericType(module, "System.Nullable`1", true, busKeyType);
|
||||
var bindingCtor = ImportMethod(module, bindingType, method => method.IsConstructor && method.Parameters.Count == 0);
|
||||
var bindingAdd = ImportMethod(module, bindingType, method => method.Name == "Add" && method.Parameters.Count == 1);
|
||||
var interfaceMethod = ImportMethod(module, generatedInterface, method => method.Name == "AttachGenerated");
|
||||
var syncSubscribe = ImportMethod(module, helperType, method => method.Name == "Subscribe" && method.HasGenericParameters);
|
||||
var asyncSubscribe = ImportMethod(module, helperType, method => method.Name == "SubscribeAsync" && method.HasGenericParameters);
|
||||
var legacySubscribe = ImportMethod(module, helperType, method => method.Name == "SubscribeAsyncLegacy" && method.HasGenericParameters);
|
||||
var asyncHandlerType = RequireType(module, "ShrinkEventBus.ShrinkAsyncEventHandler`1", EventRuntime);
|
||||
|
||||
var generated = new MethodDefinition("ShrinkEventBus.IShrinkGeneratedSubscriber.AttachGenerated",
|
||||
MethodAttributes.Private | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual,
|
||||
disposableType);
|
||||
generated.Parameters.Add(new ParameterDefinition("resolver", ParameterAttributes.None, resolverType));
|
||||
generated.Parameters.Add(new ParameterDefinition("defaultBus", ParameterAttributes.Optional, nullableBusKey));
|
||||
generated.Overrides.Add(interfaceMethod);
|
||||
generated.Body.InitLocals = true;
|
||||
var bindingLocal = new VariableDefinition(bindingType);
|
||||
generated.Body.Variables.Add(bindingLocal);
|
||||
var il = generated.Body.GetILProcessor();
|
||||
il.Emit(OpCodes.Newobj, bindingCtor);
|
||||
il.Emit(OpCodes.Stloc, bindingLocal);
|
||||
var classDefaultBus = ReadString(owner.CustomAttributes.First(a => a.AttributeType.FullName == "ShrinkEventBus.ShrinkEventSubscriberAttribute"), "DefaultBus");
|
||||
foreach (var handler in handlers)
|
||||
EmitInstanceSubscription(module, il, handler, handler.CustomAttributes.First(a => a.AttributeType.FullName == subscribeAttribute.FullName), classDefaultBus,
|
||||
bindingLocal, bindingAdd, syncSubscribe, asyncSubscribe, legacySubscribe, asyncHandlerType);
|
||||
il.Emit(OpCodes.Ldloc, bindingLocal);
|
||||
il.Emit(OpCodes.Ret);
|
||||
owner.Interfaces.Add(new InterfaceImplementation(generatedInterface));
|
||||
owner.Methods.Add(generated);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void EmitInstanceSubscription(ModuleDefinition module, ILProcessor il, MethodDefinition handler,
|
||||
CustomAttribute attribute, string classDefaultBus, VariableDefinition bindingLocal, MethodReference bindingAdd,
|
||||
MethodReference syncSubscribe, MethodReference asyncSubscribe, MethodReference legacySubscribe, TypeReference asyncHandlerType)
|
||||
{
|
||||
var signature = ResolveEventHandler(module, handler, syncSubscribe, asyncSubscribe, legacySubscribe, asyncHandlerType);
|
||||
var bus = ReadString(attribute, "Bus");
|
||||
if (string.IsNullOrWhiteSpace(bus)) bus = classDefaultBus;
|
||||
il.Emit(OpCodes.Ldloc, bindingLocal);
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
il.Emit(OpCodes.Ldarg_2);
|
||||
il.Emit(OpCodes.Ldstr, bus ?? string.Empty);
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Ldftn, module.ImportReference(handler));
|
||||
il.Emit(OpCodes.Newobj, DelegateConstructor(module, signature.DelegateType));
|
||||
EmitOptions(il, attribute);
|
||||
il.Emit(OpCodes.Call, signature.Method);
|
||||
il.Emit(OpCodes.Callvirt, bindingAdd);
|
||||
}
|
||||
|
||||
private static void InjectStaticBootstrap(ModuleDefinition module, IReadOnlyList<TypeDefinition> types,
|
||||
TypeReference subscriberAttribute, TypeReference subscribeAttribute)
|
||||
{
|
||||
if (module.Types.Any(type => type.FullName == "ShrinkEventBus.Generated.ShrinkGeneratedStaticBindings"))
|
||||
return;
|
||||
var registry = RequireType(module, "ShrinkEventBus.ShrinkStaticBindingRegistry", EventRuntime);
|
||||
var syncRegister = ImportMethod(module, registry, method => method.Name == "Register" && method.HasGenericParameters);
|
||||
var asyncRegister = ImportMethod(module, registry, method => method.Name == "RegisterAsync" && method.HasGenericParameters);
|
||||
var legacyRegister = ImportMethod(module, registry, method => method.Name == "RegisterAsyncLegacy" && method.HasGenericParameters);
|
||||
var asyncHandlerType = RequireType(module, "ShrinkEventBus.ShrinkAsyncEventHandler`1", EventRuntime);
|
||||
var bootstrap = new TypeDefinition("ShrinkEventBus.Generated", "ShrinkGeneratedStaticBindings",
|
||||
TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.NotPublic, module.TypeSystem.Object);
|
||||
module.Types.Add(bootstrap);
|
||||
var register = new MethodDefinition("Register", MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig, module.TypeSystem.Void);
|
||||
bootstrap.Methods.Add(register);
|
||||
var il = register.Body.GetILProcessor();
|
||||
foreach (var type in types)
|
||||
{
|
||||
var classBus = ReadString(type.CustomAttributes.First(a => a.AttributeType.FullName == subscriberAttribute.FullName), "DefaultBus");
|
||||
foreach (var handler in type.Methods.Where(method => method.IsStatic && HasAttribute(method, subscribeAttribute)).ToArray())
|
||||
{
|
||||
var attribute = handler.CustomAttributes.First(a => a.AttributeType.FullName == subscribeAttribute.FullName);
|
||||
var signature = ResolveEventHandler(module, handler, syncRegister, asyncRegister, legacyRegister, asyncHandlerType);
|
||||
var bus = ReadString(attribute, "Bus");
|
||||
if (string.IsNullOrWhiteSpace(bus)) bus = classBus;
|
||||
var bridge = CreateStaticBridge(module, handler);
|
||||
il.Emit(OpCodes.Ldstr, bus ?? string.Empty);
|
||||
il.Emit(OpCodes.Ldnull);
|
||||
il.Emit(OpCodes.Ldftn, bridge);
|
||||
il.Emit(OpCodes.Newobj, DelegateConstructor(module, signature.DelegateType));
|
||||
EmitOptions(il, attribute);
|
||||
il.Emit(OpCodes.Call, signature.Method);
|
||||
}
|
||||
}
|
||||
il.Emit(OpCodes.Ret);
|
||||
var moduleType = module.Types.First(type => type.Name == "<Module>");
|
||||
var initializer = moduleType.Methods.FirstOrDefault(method => method.Name == ".cctor");
|
||||
if (initializer == null)
|
||||
{
|
||||
initializer = new MethodDefinition(".cctor", MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig |
|
||||
MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, module.TypeSystem.Void);
|
||||
initializer.Body.GetILProcessor().Emit(OpCodes.Ret);
|
||||
moduleType.Methods.Add(initializer);
|
||||
}
|
||||
initializer.Body.GetILProcessor().InsertBefore(initializer.Body.Instructions[0], Instruction.Create(OpCodes.Call, register));
|
||||
}
|
||||
|
||||
private static (MethodReference Method, TypeReference DelegateType) ResolveEventHandler(ModuleDefinition module,
|
||||
MethodDefinition handler, MethodReference sync, MethodReference async, MethodReference legacy, TypeReference asyncHandlerType)
|
||||
{
|
||||
if (handler.Parameters.Count is < 1 or > 2)
|
||||
throw new InvalidOperationException($"{handler.FullName}: [ShrinkSubscribe] requires one event parameter and an optional CancellationToken.");
|
||||
var eventType = module.ImportReference(handler.Parameters[0].ParameterType);
|
||||
var eventInterface = RequireType(module, "ShrinkEventBus.IShrinkEvent", EventRuntime);
|
||||
if (!Implements(eventType, eventInterface.FullName))
|
||||
throw new InvalidOperationException($"{handler.FullName}: event parameter must implement IShrinkEvent.");
|
||||
|
||||
MethodReference open;
|
||||
TypeReference delegateType;
|
||||
if (handler.ReturnType.MetadataType == MetadataType.Void && handler.Parameters.Count == 1)
|
||||
{
|
||||
open = sync;
|
||||
delegateType = GenericType(module, "System.Action`1", false, eventType);
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" && handler.Parameters.Count == 1)
|
||||
{
|
||||
open = legacy;
|
||||
delegateType = GenericType(module, "System.Func`2", false, eventType, module.ImportReference(handler.ReturnType));
|
||||
}
|
||||
else if (handler.ReturnType.FullName == "Cysharp.Threading.Tasks.UniTask" && handler.Parameters.Count == 2 &&
|
||||
handler.Parameters[1].ParameterType.FullName == "System.Threading.CancellationToken")
|
||||
{
|
||||
open = async;
|
||||
delegateType = new GenericInstanceType(asyncHandlerType) { GenericArguments = { eventType } };
|
||||
}
|
||||
else
|
||||
throw new InvalidOperationException($"Unsupported [ShrinkSubscribe] signature: {handler.FullName}.");
|
||||
var closed = new GenericInstanceMethod(open);
|
||||
closed.GenericArguments.Add(eventType);
|
||||
return (closed, delegateType);
|
||||
}
|
||||
|
||||
private static MethodReference CreateStaticBridge(ModuleDefinition module, MethodDefinition handler)
|
||||
{
|
||||
var bridge = new MethodDefinition($"ShrinkEventBus.GeneratedStaticHandler_{handler.MetadataToken.ToInt32():X8}",
|
||||
MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig, module.ImportReference(handler.ReturnType));
|
||||
foreach (var parameter in handler.Parameters)
|
||||
bridge.Parameters.Add(new ParameterDefinition(parameter.Name, parameter.Attributes, module.ImportReference(parameter.ParameterType)));
|
||||
var il = bridge.Body.GetILProcessor();
|
||||
foreach (var parameter in bridge.Parameters) il.Emit(OpCodes.Ldarg, parameter);
|
||||
il.Emit(OpCodes.Call, module.ImportReference(handler));
|
||||
il.Emit(OpCodes.Ret);
|
||||
handler.DeclaringType.Methods.Add(bridge);
|
||||
return bridge;
|
||||
}
|
||||
|
||||
private static void EmitOptions(ILProcessor il, CustomAttribute attribute)
|
||||
{
|
||||
il.Emit(OpCodes.Ldc_I4, ReadInt(attribute, "Priority", 2));
|
||||
il.Emit(OpCodes.Ldc_I4, ReadInt(attribute, "NumericPriority", 0));
|
||||
il.Emit(ReadBool(attribute, "ReceiveCanceled", false) ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
|
||||
}
|
||||
|
||||
private static bool References(ModuleDefinition module, string assemblyName) =>
|
||||
module.AssemblyReferences.Any(reference => string.Equals(reference.Name, assemblyName, StringComparison.Ordinal));
|
||||
|
||||
private static TypeReference RequireType(ModuleDefinition module, string fullName, string assemblyName) =>
|
||||
FindType(module, fullName, assemblyName) ?? throw new InvalidOperationException($"Required type {fullName} was not found in {assemblyName}.");
|
||||
|
||||
private static TypeReference? FindType(ModuleDefinition module, string fullName, string assemblyName)
|
||||
{
|
||||
if (string.Equals(module.Assembly.Name.Name, assemblyName, StringComparison.Ordinal))
|
||||
return module.GetType(fullName);
|
||||
var reference = module.AssemblyReferences.FirstOrDefault(item => string.Equals(item.Name, assemblyName, StringComparison.Ordinal));
|
||||
if (reference == null) return null;
|
||||
var assembly = module.AssemblyResolver.Resolve(reference);
|
||||
return assembly?.MainModule.GetType(fullName) is { } definition ? module.ImportReference(definition) : null;
|
||||
}
|
||||
|
||||
private static MethodReference ImportMethod(ModuleDefinition module, TypeReference type, Func<MethodDefinition, bool> predicate)
|
||||
{
|
||||
var definition = type.Resolve() ?? throw new InvalidOperationException($"Unable to resolve {type.FullName}.");
|
||||
var method = definition.Methods.SingleOrDefault(predicate) ?? throw new InvalidOperationException($"Required method was not found on {type.FullName}.");
|
||||
return module.ImportReference(method);
|
||||
}
|
||||
|
||||
private static IEnumerable<TypeDefinition> AllTypes(IEnumerable<TypeDefinition> roots)
|
||||
{
|
||||
foreach (var type in roots)
|
||||
{
|
||||
yield return type;
|
||||
foreach (var nested in AllTypes(type.NestedTypes)) yield return nested;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HasAttribute(ICustomAttributeProvider provider, TypeReference attribute) => HasAttribute(provider, attribute.FullName);
|
||||
private static bool HasAttribute(ICustomAttributeProvider provider, string fullName) => provider.CustomAttributes.Any(a => a.AttributeType.FullName == fullName);
|
||||
|
||||
private static bool Implements(TypeReference type, string interfaceFullName)
|
||||
{
|
||||
try
|
||||
{
|
||||
TypeDefinition? current = type.Resolve();
|
||||
while (current != null)
|
||||
{
|
||||
if (current.Interfaces.Any(item => item.InterfaceType.FullName == interfaceFullName)) return true;
|
||||
current = current.BaseType?.Resolve();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return false;
|
||||
}
|
||||
|
||||
private static TypeReference GenericType(ModuleDefinition module, string name, bool valueType, params TypeReference[] arguments)
|
||||
{
|
||||
var open = new TypeReference("System", name.Substring(name.LastIndexOf('.') + 1), module, module.TypeSystem.CoreLibrary, valueType);
|
||||
var result = new GenericInstanceType(open);
|
||||
foreach (var argument in arguments) result.GenericArguments.Add(argument);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static MethodReference DelegateConstructor(ModuleDefinition module, TypeReference delegateType)
|
||||
{
|
||||
var ctor = new MethodReference(".ctor", module.TypeSystem.Void, delegateType) { HasThis = true };
|
||||
ctor.Parameters.Add(new ParameterDefinition(module.TypeSystem.Object));
|
||||
ctor.Parameters.Add(new ParameterDefinition(module.TypeSystem.IntPtr));
|
||||
return ctor;
|
||||
}
|
||||
|
||||
private static string ReadString(CustomAttribute attribute, string name) =>
|
||||
attribute.Properties.FirstOrDefault(item => item.Name == name).Argument.Value as string ?? string.Empty;
|
||||
private static int ReadInt(CustomAttribute attribute, string name, int fallback) =>
|
||||
attribute.Properties.FirstOrDefault(item => item.Name == name) is { Name: not null } item ? Convert.ToInt32(item.Argument.Value) : fallback;
|
||||
private static bool ReadBool(CustomAttribute attribute, string name, bool fallback) =>
|
||||
attribute.Properties.FirstOrDefault(item => item.Name == name) is { Name: not null } item ? Convert.ToBoolean(item.Argument.Value) : fallback;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 578fc703a63d4b8e9a414eb8c19a472a
|
||||
@@ -1,7 +1,10 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using ShrinkShared.CodeGen;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Mono.Cecil;
|
||||
using Mono.Cecil.Cil;
|
||||
using Unity.CompilationPipeline.Common.Diagnostics;
|
||||
using Unity.CompilationPipeline.Common.ILPostProcessing;
|
||||
|
||||
@@ -11,12 +14,66 @@ namespace ShrinkEventBus.CodeGen
|
||||
{
|
||||
public override ILPostProcessor GetInstance() => this;
|
||||
|
||||
public override bool WillProcess(ICompiledAssembly compiledAssembly) =>
|
||||
UnityShrinkCodeGenAdapter.ReferencesAny(compiledAssembly, "ShrinkEventBus.Runtime");
|
||||
public override bool WillProcess(ICompiledAssembly compiledAssembly)
|
||||
{
|
||||
#if SHRINK_EVENTBUS_HAS_SHARED_CODEGEN
|
||||
// The shared processor owns event weaving when its package is installed.
|
||||
return false;
|
||||
#else
|
||||
return compiledAssembly.Name != "ShrinkEventBus.Runtime" &&
|
||||
compiledAssembly.References.Any(path =>
|
||||
Path.GetFileNameWithoutExtension(path) == "ShrinkEventBus.Runtime");
|
||||
#endif
|
||||
}
|
||||
|
||||
public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly) =>
|
||||
WillProcess(compiledAssembly)
|
||||
? UnityShrinkCodeGenAdapter.Process(compiledAssembly, "ShrinkEventBus.CodeGen")
|
||||
: new ILPostProcessResult(compiledAssembly.InMemoryAssembly, new List<DiagnosticMessage>());
|
||||
public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly)
|
||||
{
|
||||
var diagnostics = new List<DiagnosticMessage>();
|
||||
#if !SHRINK_EVENTBUS_HAS_SHARED_CODEGEN
|
||||
if (!WillProcess(compiledAssembly))
|
||||
return new ILPostProcessResult(compiledAssembly.InMemoryAssembly, diagnostics);
|
||||
try
|
||||
{
|
||||
using var resolver = new PostProcessorAssemblyResolver(compiledAssembly);
|
||||
using var pe = new MemoryStream(compiledAssembly.InMemoryAssembly.PeData);
|
||||
var pdbData = compiledAssembly.InMemoryAssembly.PdbData;
|
||||
var hasSymbols = pdbData != null && pdbData.Length > 0;
|
||||
using var pdb = hasSymbols ? new MemoryStream(pdbData!) : null;
|
||||
using var assembly = AssemblyDefinition.ReadAssembly(pe, new ReaderParameters
|
||||
{
|
||||
AssemblyResolver = resolver,
|
||||
ReadingMode = ReadingMode.Immediate,
|
||||
ReflectionImporterProvider = new PostProcessorReflectionImporterProvider(),
|
||||
ReadSymbols = hasSymbols,
|
||||
SymbolStream = pdb,
|
||||
SymbolReaderProvider = hasSymbols ? new PortablePdbReaderProvider() : null
|
||||
});
|
||||
resolver.AddAssemblyDefinitionBeingOperatedOn(assembly);
|
||||
if (assembly.Name.HasPublicKey)
|
||||
throw new InvalidOperationException("Signed assemblies cannot be woven by the standalone EventBus processor.");
|
||||
if (!EventBusAssemblyWeaver.Weave(assembly.MainModule))
|
||||
return new ILPostProcessResult(compiledAssembly.InMemoryAssembly, diagnostics);
|
||||
using var outputPe = new MemoryStream();
|
||||
using var outputPdb = new MemoryStream();
|
||||
assembly.Write(outputPe, new WriterParameters
|
||||
{
|
||||
WriteSymbols = hasSymbols,
|
||||
SymbolStream = hasSymbols ? outputPdb : null,
|
||||
SymbolWriterProvider = hasSymbols ? new PortablePdbWriterProvider() : null
|
||||
});
|
||||
return new ILPostProcessResult(new InMemoryAssembly(outputPe.ToArray(),
|
||||
hasSymbols ? outputPdb.ToArray() : Array.Empty<byte>()), diagnostics);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
diagnostics.Add(new DiagnosticMessage
|
||||
{
|
||||
DiagnosticType = DiagnosticType.Error,
|
||||
MessageData = $"[ShrinkEventBus.CodeGen] {exception.Message}"
|
||||
});
|
||||
}
|
||||
#endif
|
||||
return new ILPostProcessResult(compiledAssembly.InMemoryAssembly, diagnostics);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,9 @@ namespace ShrinkEventBus.CodeGen
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var assembly in _cache.Values)
|
||||
assembly.Dispose();
|
||||
_cache.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,29 @@
|
||||
{
|
||||
"name": "Unity.ShrinkEventBus.CodeGen",
|
||||
"rootNamespace": "ShrinkEventBus.CodeGen",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime",
|
||||
"Unity.ShrinkShared.CodeGen"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": true,
|
||||
"overrideReferences": true,
|
||||
"precompiledReferences": [
|
||||
"Mono.Cecil.dll",
|
||||
"Mono.Cecil.Mdb.dll",
|
||||
"Mono.Cecil.Pdb.dll",
|
||||
"Mono.Cecil.Rocks.dll"
|
||||
],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [],
|
||||
"noEngineReferences": false
|
||||
"name": "Unity.ShrinkEventBus.CodeGen",
|
||||
"rootNamespace": "ShrinkEventBus.CodeGen",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": true,
|
||||
"overrideReferences": true,
|
||||
"precompiledReferences": [
|
||||
"Mono.Cecil.dll",
|
||||
"Mono.Cecil.Mdb.dll",
|
||||
"Mono.Cecil.Pdb.dll",
|
||||
"Mono.Cecil.Rocks.dll"
|
||||
],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.cneicy.shrink-shared-codegen",
|
||||
"expression": "0.2.1",
|
||||
"define": "SHRINK_EVENTBUS_HAS_SHARED_CODEGEN"
|
||||
}
|
||||
],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.Collections;
|
||||
using System.Threading;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using NUnit.Framework;
|
||||
using ShrinkEventBus;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
namespace EventBusConsumer
|
||||
{
|
||||
internal readonly struct Ping : IShrinkEvent { }
|
||||
|
||||
[ShrinkEventSubscriber]
|
||||
internal sealed class Subscriber
|
||||
{
|
||||
public int SyncHits;
|
||||
public int AsyncHits;
|
||||
[ShrinkSubscribe] private void OnPing(Ping value) => SyncHits++;
|
||||
[ShrinkSubscribe] private async UniTask OnPingAsync(Ping value, CancellationToken token)
|
||||
{
|
||||
await UniTask.Yield(cancellationToken: token);
|
||||
AsyncHits++;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ConsumerTests
|
||||
{
|
||||
[UnityTest]
|
||||
public IEnumerator ConsumerAssemblyGeneratesBindingsAndDisposesThem()
|
||||
{
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var bus = host.CreateBus(ShrinkBusKey.Game, ShrinkBusOptions.Inline());
|
||||
var target = new Subscriber();
|
||||
Assert.IsInstanceOf<IShrinkGeneratedSubscriber>(target);
|
||||
var binding = host.Attach(target, ShrinkBusKey.Game);
|
||||
yield return bus.PostAsync(new Ping()).ToCoroutine();
|
||||
Assert.AreEqual(1, target.SyncHits);
|
||||
Assert.AreEqual(1, target.AsyncHits);
|
||||
binding.Dispose();
|
||||
yield return bus.PostAsync(new Ping()).ToCoroutine();
|
||||
Assert.AreEqual(1, target.SyncHits);
|
||||
Assert.AreEqual(1, target.AsyncHits);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "EventBus.Consumer.Tests",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime",
|
||||
"UniTask"
|
||||
],
|
||||
"optionalUnityReferences": [
|
||||
"TestAssemblies"
|
||||
],
|
||||
"defineConstraints": [
|
||||
"UNITY_INCLUDE_TESTS"
|
||||
],
|
||||
"autoReferenced": false
|
||||
}
|
||||
@@ -1,13 +1,4 @@
|
||||
{
|
||||
"scopedRegistries": [
|
||||
{
|
||||
"name": "ShrinkSDK",
|
||||
"url": "https://git.crash.work/api/packages/ShrinkSDK/npm/",
|
||||
"scopes": [
|
||||
"com.cneicy"
|
||||
]
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"com.unity.test-framework": "1.1.33",
|
||||
"com.cneicy.shrink-eventbus": "file:../../..",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<AssemblyName>ShrinkEventBus.Runtime</AssemblyName>
|
||||
<RootNamespace>ShrinkEventBus</RootNamespace>
|
||||
<PackageId>ShrinkSDK.EventBus</PackageId>
|
||||
<Version>2.1.0</Version>
|
||||
<Version>2.3.2</Version>
|
||||
<Description>ShrinkSDK typed event bus runtime.</Description>
|
||||
<ShrinkCodeGenEnabled>false</ShrinkCodeGenEnabled>
|
||||
</PropertyGroup>
|
||||
@@ -13,7 +13,7 @@
|
||||
<Compile Include="..\Runtime\**\*.cs"
|
||||
Exclude="..\Runtime\ShrinkMonoEventScope.cs" />
|
||||
<PackageReference Include="UniTask" Version="2.5.10" />
|
||||
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.1.0" PrivateAssets="compile;runtime;contentfiles;native" />
|
||||
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.1.0" />
|
||||
<PackageReference Include="ShrinkSDK.CodeGen" Version="0.2.0" PrivateAssets="compile;runtime;contentfiles;native" />
|
||||
<PackageReference Include="ShrinkSDK.Runtime.Abstractions" Version="0.2.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 27180d887eae401ca4e2547c96534ec4
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: eae196d52d4a4091bdf0aa90888b6c97
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "ShrinkEventBus.Integration.Runtime",
|
||||
"rootNamespace": "ShrinkEventBus.Integration",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime",
|
||||
"ShrinkRuntime.Abstractions"
|
||||
],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [
|
||||
"SHRINK_EVENTBUS_HAS_SHARED_RUNTIME"
|
||||
],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.cneicy.shrink-runtime-abstractions",
|
||||
"expression": "0.1.0",
|
||||
"define": "SHRINK_EVENTBUS_HAS_SHARED_RUNTIME"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 86c48423db2e41e1b208c468296b7faf
|
||||
@@ -0,0 +1,20 @@
|
||||
#if SHRINK_EVENTBUS_HAS_SHARED_RUNTIME
|
||||
using System;
|
||||
using ShrinkSDK.Runtime;
|
||||
|
||||
namespace ShrinkEventBus.Integration
|
||||
{
|
||||
public sealed class ShrinkSharedMainThreadDispatcher : IShrinkEventBusMainThreadDispatcher
|
||||
{
|
||||
private readonly IShrinkMainThreadDispatcher _dispatcher;
|
||||
|
||||
public ShrinkSharedMainThreadDispatcher(IShrinkMainThreadDispatcher dispatcher)
|
||||
{
|
||||
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
|
||||
}
|
||||
|
||||
public bool IsMainThread => _dispatcher.IsMainThread;
|
||||
public bool TryPost(Action action) => _dispatcher.TryPost(action);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f818313cb4e3447f9622b71decefa86c
|
||||
@@ -0,0 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bc17b8a03b8d4abe8068d9310fe12f19
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
@@ -0,0 +1,43 @@
|
||||
#if SHRINK_EVENTBUS_HAS_SHARED_RUNTIME
|
||||
using System;
|
||||
using NUnit.Framework;
|
||||
using ShrinkSDK.Runtime;
|
||||
|
||||
namespace ShrinkEventBus.Integration.Tests
|
||||
{
|
||||
public sealed class SharedDispatcherTests
|
||||
{
|
||||
private sealed class Dispatcher : IShrinkMainThreadDispatcher
|
||||
{
|
||||
public bool IsMainThread => false;
|
||||
public Action Pending;
|
||||
public bool TryPost(Action action) { Pending = action; return true; }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AdapterPreservesAffinityAndPostsThroughSharedDispatcher()
|
||||
{
|
||||
var original = ShrinkEventBusRuntime.MainThreadDispatcher;
|
||||
try
|
||||
{
|
||||
var dispatcher = new Dispatcher();
|
||||
var adapter = new ShrinkSharedMainThreadDispatcher(dispatcher);
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(adapter);
|
||||
Assert.IsFalse(ShrinkEventBusRuntime.MainThreadDispatcher.IsMainThread);
|
||||
var hits = 0;
|
||||
Assert.IsTrue(ShrinkEventBusRuntime.MainThreadDispatcher.TryPost(() => hits++));
|
||||
Assert.AreEqual(0, hits);
|
||||
dispatcher.Pending();
|
||||
Assert.AreEqual(1, hits);
|
||||
}
|
||||
finally { ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(original); }
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AdapterRejectsNullDispatcher()
|
||||
{
|
||||
Assert.Throws<ArgumentNullException>(() => new ShrinkSharedMainThreadDispatcher(null));
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 87e04bff7dc943dd9a8205b37e631c19
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "ShrinkEventBus.Integration.Runtime.Tests",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime",
|
||||
"ShrinkEventBus.Integration.Runtime",
|
||||
"ShrinkRuntime.Abstractions"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
],
|
||||
"optionalUnityReferences": [
|
||||
"TestAssemblies"
|
||||
],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": [
|
||||
"UNITY_INCLUDE_TESTS",
|
||||
"SHRINK_EVENTBUS_HAS_SHARED_RUNTIME"
|
||||
],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.cneicy.shrink-runtime-abstractions",
|
||||
"expression": "0.1.0",
|
||||
"define": "SHRINK_EVENTBUS_HAS_SHARED_RUNTIME"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4062d02e94ea4577957d4185688d1454
|
||||
@@ -1,9 +1,69 @@
|
||||
# ShrinkEventBus 2.0
|
||||
# ShrinkEventBus
|
||||
|
||||
ShrinkEventBus 2.0 是面向 Unity、普通 C# 宿主和 Entities/Burst 生产端的统一事件总线。运行时只有一种事件模型、一个订阅入口和一组发布 API;不同 Bus 只表达生命周期、所有权与调度策略。
|
||||
|
||||
Godot 和普通 .NET 项目安装 `ShrinkSDK.EventBus`;可打包源码位于 `DotNet~`,订阅注册由 `ShrinkSDK.CodeGen` 在构建时织入。
|
||||
|
||||
## Unity 安装
|
||||
|
||||
要求 Unity 2022.3 或更新版本。在 Package Manager 中使用 **Add package from git URL**,依次安装:
|
||||
|
||||
```text
|
||||
https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#7c0f199fe0d3fc528024488ccd671e6c7b27745b
|
||||
https://github.com/cneicy/ShrinkEventBus.git
|
||||
```
|
||||
|
||||
第一个地址固定 UniTask 2.5.10。Mono.Cecil 1.11.4 由 Unity 官方 registry 自动解析;无需配置 ShrinkSDK registry。需要锁定 EventBus 版本时,在 Git URL 后添加 `#<commit>`。
|
||||
|
||||
### 可选 ShrinkSDK 集成
|
||||
|
||||
| 已安装的共享包 | 行为 |
|
||||
|---|---|
|
||||
| 无 | 使用包内调度接口和 EventBus 专用 ILPostProcessor |
|
||||
| Runtime Abstractions 0.2.0+ | 额外启用共享主线程调度器适配程序集,并支持显式延后发布 |
|
||||
| Shared CodeGen 0.2.1+ | 停用包内织入,交给共享 CodeGen 统一生成订阅 |
|
||||
| 两者都有 | 同时启用上述两项集成 |
|
||||
|
||||
通过 asmdef `versionDefines` 自动生成 `SHRINK_EVENTBUS_HAS_SHARED_RUNTIME` 和 `SHRINK_EVENTBUS_HAS_SHARED_CODEGEN`,不需要手工设置宏。两个共享包由完整工程自行安装,EventBus 不再强制拉取它们。
|
||||
|
||||
Unity 自定义调度器现在实现 `IShrinkEventBusMainThreadDispatcher`。已有的共享 `IShrinkMainThreadDispatcher` 实现使用以下适配方式:
|
||||
|
||||
```csharp
|
||||
using ShrinkEventBus;
|
||||
using ShrinkEventBus.Integration;
|
||||
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(
|
||||
new ShrinkSharedMainThreadDispatcher(sharedDispatcher));
|
||||
```
|
||||
|
||||
使用自定义 asmdef 的业务程序集还需引用 `ShrinkEventBus.Integration.Runtime`。默认 UniTask PlayerLoop 调度无需配置;请在创建需要自定义调度的 Bus 前完成配置。此调整只影响 Unity,现有 .NET/Godot 配置接口保持不变。
|
||||
|
||||
### 最小使用示例
|
||||
|
||||
业务 asmdef 引用 `ShrinkEventBus.Runtime`,使用 UniTask 时再引用 `UniTask`。无需 `partial`、反射注册或手工生成绑定:
|
||||
|
||||
```csharp
|
||||
using ShrinkEventBus;
|
||||
using UnityEngine;
|
||||
|
||||
public readonly struct PlayerJoined : IShrinkEvent { }
|
||||
|
||||
[ShrinkEventSubscriber]
|
||||
public sealed class PlayerHandlers
|
||||
{
|
||||
[ShrinkSubscribe]
|
||||
private void OnJoined(PlayerJoined value) => Debug.Log("Player joined");
|
||||
}
|
||||
|
||||
// 在 Unity 主线程执行;binding 应由实际宿主持有并在生命周期结束时释放。
|
||||
using (var binding = EventBus.Attach(new PlayerHandlers()))
|
||||
{
|
||||
EventBus.Post(new PlayerJoined());
|
||||
}
|
||||
```
|
||||
|
||||
包内 `Development~/UnityProject` 是独立验证工程,包含外部消费程序集的同步/异步订阅测试。使用 Unity Test Runner 运行 EditMode 和 PlayMode 测试;包本身的测试通过 manifest 的 `testables` 开启。
|
||||
|
||||
## 核心契约
|
||||
|
||||
```csharp
|
||||
@@ -106,23 +166,31 @@ public static class GlobalHandlers
|
||||
}
|
||||
```
|
||||
|
||||
Unity ILPostProcessor 会生成直接调用桥和静态模块初始化注册;纯 .NET incremental generator 要求 subscriber 是 `partial`,并生成 ValueTask handler 绑定。生产路径不枚举程序集和方法,不使用 `MethodInfo.Invoke`、`DynamicInvoke` 或 `object[]` 参数。
|
||||
Unity ILPostProcessor 会生成直接调用桥和静态模块初始化注册;NuGet 包通过 `ShrinkSDK.CodeGen` 生成绑定。生产路径不枚举程序集和方法,不使用 `MethodInfo.Invoke`、`DynamicInvoke` 或 `object[]` 参数。
|
||||
|
||||
## Unity 与纯 .NET
|
||||
|
||||
Unity 包依赖 UniTask:
|
||||
Unity 和正式 NuGet 包 `ShrinkSDK.EventBus` 均使用 UniTask,可直接 `await`:
|
||||
|
||||
```csharp
|
||||
UniTask<ShrinkPostResult> PostAsync<TEvent>(...)
|
||||
```
|
||||
|
||||
纯 .NET 实现在 `Tools~/DotNet/ShrinkEventBus.Core`:
|
||||
普通 C# 项目无需安装 Unity 或 Godot。使用 .NET 8 或更新 SDK 新建控制台项目后配置包源并安装:
|
||||
|
||||
```csharp
|
||||
ValueTask<ShrinkPostResult> PostAsync<TEvent>(...)
|
||||
```shell
|
||||
dotnet new console -n EventBusDemo
|
||||
cd EventBusDemo
|
||||
dotnet new nugetconfig
|
||||
dotnet nuget add source https://git.crash.work/api/packages/ShrinkSDK/nuget/index.json --name ShrinkSDK --configfile nuget.config
|
||||
dotnet add package ShrinkSDK.EventBus --version 2.3.2
|
||||
```
|
||||
|
||||
两边共享事件与特性契约,awaitable 和调度实现按宿主选择,不把 UniTask/ValueTask 写进事件数据。
|
||||
UniTask、Runtime.Abstractions 和构建时 CodeGen 会随包自动还原,不需要手动添加分析器或项目引用。完整可运行示例见 [Samples~/DotNetConsole](Samples~/DotNetConsole/Program.cs),可用它替换新项目的 `Program.cs` 后执行 `dotnet run -c Release`。
|
||||
|
||||
控制台和后台服务建议显式创建 `Inline`、`DedicatedThread` 或 `TaskPool` Bus。`MainThread` 跨线程派发及 `PostDeferred` 需要宿主提供可用的主线程调度器;普通控制台没有 Unity/Godot 的帧循环。
|
||||
|
||||
`Tools~/DotNet/ShrinkEventBus.Core` 是独立的 ValueTask 工具实现,不是上述正式 NuGet 包的运行时。事件数据不应依赖 UniTask/ValueTask。
|
||||
|
||||
## ECS/Burst
|
||||
|
||||
@@ -139,6 +207,29 @@ Burst Job 只写 unmanaged 事实事件到 NativeQueue;Playback 在托管/ECS
|
||||
|
||||
`ShrinkBusOptions` 配置队列容量、溢出策略、最大并发、关闭排空和超时。关键业务默认使用 `Reject`;`DropNewest/DropOldest` 只适用于明确允许丢失的数据;`Wait` 只由 `PostAsync` 使用。
|
||||
|
||||
## 延后发布与诊断
|
||||
|
||||
MainThread Bus 可以用 `PostDeferred` 把事件推迟到下一次主线程泵送:
|
||||
|
||||
```csharp
|
||||
var result = EventBus.PostDeferred(gameBus, new PlayerReadyEvent());
|
||||
if (!result.Accepted)
|
||||
Debug.LogWarning($"deferred post rejected: {result.Failure}");
|
||||
```
|
||||
|
||||
延后发布只接受 `MainThread` 调度且宿主实现了 `IShrinkDeferredMainThreadDispatcher` 的 Bus;其他调度器返回 `DeferredUnsupported`,不会退化成同步分发。队列仍遵守 `QueueCapacity` 与 `OverflowPolicy`,重入发布的事件留到下一次泵送。
|
||||
|
||||
需要外部工具观察分发时使用公开诊断订阅:
|
||||
|
||||
```csharp
|
||||
using var subscription = EventBus.ObserveDiagnostics(diagnostic =>
|
||||
{
|
||||
Debug.Log($"{diagnostic.BusKey} {diagnostic.EventType.Name} {diagnostic.Result.Failure}");
|
||||
});
|
||||
```
|
||||
|
||||
`ShrinkEventDiagnostic` 提供时间、事件类型、Bus、调度器、分发模式、线程、耗时、发布结果和同步标记,不暴露事件对象。观察者抛出的异常会记录并隔离,不影响业务分发或其他观察者。
|
||||
|
||||
## UI Toolkit 调试器
|
||||
|
||||
菜单:`ShrinkSDK/事件总线/事件查看器`。
|
||||
@@ -147,6 +238,8 @@ Burst Job 只写 unmanaged 事实事件到 NativeQueue;Playback 在托管/ECS
|
||||
|
||||
它只观察静态 `EventBus` 宿主管理的 Bus,不捕获独立 `ShrinkEventBusHost`;性能基准仍使用独立 Host,避免 UI 采样进入被测热路径。
|
||||
|
||||
Godot 项目安装 `ShrinkSDK.EventBus.Godot` 后可在编辑器中使用同一套诊断数据的独立调试窗口。
|
||||
|
||||
## Benchmark
|
||||
|
||||
实现位于 `Benchmark/ShrinkEventBusBenchmark.cs`,入口:
|
||||
@@ -181,4 +274,14 @@ ShrinkEventBusBenchmark.Run(
|
||||
- 外部 Mod DLL 必须携带生成合同;没有合同的生产 DLL 不自动反射注册。
|
||||
- Editor 诊断是可选观察层,不参与正式无诊断热路径。
|
||||
|
||||
架构审计与来源说明见 `Docs/JustAnyProjectArchitectureAudit.md` 和根目录 `DESIGN.md`。
|
||||
Unity 独立安装不包含 Entities/Burst 适配包;需要时由宿主额外安装。
|
||||
|
||||
## 可复用能力
|
||||
|
||||
<!-- shrink:capabilities -->
|
||||
Capability: 按类型发布事实和请求,支持同步、异步、优先级和可撤回订阅
|
||||
Aliases: 事件 事件未触发 消息 订阅 通知 event bus
|
||||
Limits: EventBus 不等于业务状态机或资源计量;并行派发须由业务明确选择
|
||||
Extension: IShrinkEvent、ShrinkSubscribe、BusOptions 和拥有者 Attach/Dispose
|
||||
Evidence: [EventBus](Runtime/EventBus.cs); [ShrinkSubscribeAttribute](Runtime/ShrinkEventAttributes.cs); [ShrinkGeneratedBinding](Runtime/ShrinkEventBindings.cs)
|
||||
<!-- /shrink:capabilities -->
|
||||
+92
-11
@@ -57,6 +57,8 @@ namespace ShrinkEventBus
|
||||
private static readonly IShrinkEventBus DefaultBus = CreateDefaultBus();
|
||||
private static Action<IShrinkEvent, Type, ShrinkBusKey>? _posted;
|
||||
private static Action<ShrinkEventTrace>? _detailedPosted;
|
||||
private static readonly object DetailedObserverGate = new();
|
||||
private static Action<ShrinkEventTrace>[]? _detailedObserverSnapshot;
|
||||
|
||||
internal static event Action<IShrinkEvent, Type, ShrinkBusKey> Posted
|
||||
{
|
||||
@@ -78,14 +80,41 @@ namespace ShrinkEventBus
|
||||
|
||||
internal static event Action<ShrinkEventTrace> DetailedPosted
|
||||
{
|
||||
add => _detailedPosted += value;
|
||||
remove => _detailedPosted -= value;
|
||||
add
|
||||
{
|
||||
lock (DetailedObserverGate)
|
||||
{
|
||||
_detailedPosted += value;
|
||||
PublishDetailedObserverSnapshot();
|
||||
}
|
||||
}
|
||||
remove
|
||||
{
|
||||
lock (DetailedObserverGate)
|
||||
{
|
||||
_detailedPosted -= value;
|
||||
PublishDetailedObserverSnapshot();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void PublishDetailedObserverSnapshot()
|
||||
{
|
||||
var invocationList = _detailedPosted?.GetInvocationList();
|
||||
Action<ShrinkEventTrace>[]? snapshot = null;
|
||||
if (invocationList != null)
|
||||
{
|
||||
snapshot = new Action<ShrinkEventTrace>[invocationList.Length];
|
||||
for (var i = 0; i < snapshot.Length; i++)
|
||||
snapshot[i] = (Action<ShrinkEventTrace>)invocationList[i];
|
||||
}
|
||||
Volatile.Write(ref _detailedObserverSnapshot, snapshot);
|
||||
}
|
||||
|
||||
internal static bool HasDetailedPostedObservers
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get => Volatile.Read(ref _detailedPosted) != null;
|
||||
get => Volatile.Read(ref _detailedObserverSnapshot) != null;
|
||||
}
|
||||
|
||||
public static IShrinkEventBus Default => DefaultBus;
|
||||
@@ -133,6 +162,30 @@ namespace ShrinkEventBus
|
||||
CancellationToken cancellationToken = default)
|
||||
where TEvent : IShrinkEvent => DefaultBus.PostAsync(eventData, cancellationToken);
|
||||
|
||||
public static ShrinkPostResult PostDeferred<TEvent>(IShrinkEventBus bus, TEvent eventData)
|
||||
where TEvent : IShrinkEvent
|
||||
{
|
||||
if (bus == null)
|
||||
throw new ArgumentNullException(nameof(bus));
|
||||
return bus is ShrinkEventBusInstance instance
|
||||
? instance.PostDeferred(in eventData)
|
||||
: ShrinkPostResult.Rejected(ShrinkPostFailure.DeferredUnsupported);
|
||||
}
|
||||
|
||||
public static IDisposable ObserveDiagnostics(Action<ShrinkEventDiagnostic> observer)
|
||||
{
|
||||
if (observer == null)
|
||||
throw new ArgumentNullException(nameof(observer));
|
||||
|
||||
void Handler(ShrinkEventTrace trace) => observer(new ShrinkEventDiagnostic(
|
||||
trace.TimestampUtc, trace.EventType, trace.BusKey, trace.Scheduler,
|
||||
trace.DispatchMode, trace.ThreadId, trace.ElapsedTimestampTicks,
|
||||
trace.Result, trace.IsAsync));
|
||||
|
||||
DetailedPosted += Handler;
|
||||
return new DiagnosticSubscription(Handler);
|
||||
}
|
||||
|
||||
public static IDisposable Attach(object target, ShrinkBusKey? defaultBus = null)
|
||||
{
|
||||
if (target == null)
|
||||
@@ -143,6 +196,14 @@ namespace ShrinkEventBus
|
||||
return generated.AttachGenerated(Resolver, defaultBus ?? ShrinkBusKey.Game);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<(Type EventType, System.Reflection.MethodInfo Handler)> CaptureBindings(IShrinkEventBus bus)
|
||||
{
|
||||
if (bus is ShrinkEventBusInstance instance) return instance.CaptureBindings();
|
||||
throw new NotSupportedException("This event bus does not expose binding diagnostics.");
|
||||
}
|
||||
|
||||
public static IReadOnlyList<IShrinkEventBus> CaptureNamedBuses() => new List<IShrinkEventBus>(Buses.Values);
|
||||
|
||||
internal static IReadOnlyList<(ShrinkBusKey Key, ShrinkBusOptions Options, int Subscribers)> Snapshot()
|
||||
{
|
||||
var snapshot = new List<(ShrinkBusKey, ShrinkBusOptions, int)>(Buses.Count);
|
||||
@@ -180,20 +241,40 @@ namespace ShrinkEventBus
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static void NotifyDetailedPosted(ShrinkEventTrace trace)
|
||||
{
|
||||
var observers = Volatile.Read(ref _detailedPosted);
|
||||
var observers = Volatile.Read(ref _detailedObserverSnapshot);
|
||||
if (observers == null)
|
||||
return;
|
||||
try
|
||||
{
|
||||
observers(trace);
|
||||
}
|
||||
catch (Exception exception)
|
||||
for (var i = 0; i < observers.Length; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
observers[i](trace);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
UnityEngine.Debug.LogException(exception);
|
||||
UnityEngine.Debug.LogException(exception);
|
||||
#else
|
||||
System.Diagnostics.Trace.TraceError(exception.ToString());
|
||||
System.Diagnostics.Trace.TraceError(exception.ToString());
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class DiagnosticSubscription : IDisposable
|
||||
{
|
||||
private Action<ShrinkEventTrace>? _handler;
|
||||
|
||||
public DiagnosticSubscription(Action<ShrinkEventTrace> handler)
|
||||
{
|
||||
_handler = handler;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
var handler = Interlocked.Exchange(ref _handler, null);
|
||||
if (handler != null)
|
||||
DetailedPosted -= handler;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
using System;
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
public interface IShrinkEventBusMainThreadDispatcher
|
||||
{
|
||||
bool IsMainThread { get; }
|
||||
bool TryPost(Action action);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9ff0b939fcee4292a6183fd899974c9c
|
||||
+133
-48
@@ -1,23 +1,39 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using ShrinkSDK.Runtime;
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
using MainThreadDispatcherContract = ShrinkEventBus.IShrinkEventBusMainThreadDispatcher;
|
||||
#else
|
||||
using MainThreadDispatcherContract = ShrinkSDK.Runtime.IShrinkMainThreadDispatcher;
|
||||
#endif
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
internal interface IShrinkBusScheduler : IDisposable
|
||||
{
|
||||
bool IsOnSchedulerThread { get; }
|
||||
bool SupportsDeferred { get; }
|
||||
bool TryPost(Action action);
|
||||
ShrinkDeferredPostStatus TryPostDeferred(Action action);
|
||||
UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken);
|
||||
UniTask ShutdownAsync(bool drain, TimeSpan timeout);
|
||||
}
|
||||
|
||||
internal enum ShrinkDeferredPostStatus
|
||||
{
|
||||
Accepted,
|
||||
QueueFull,
|
||||
SchedulerRejected,
|
||||
Unsupported,
|
||||
Stopped
|
||||
}
|
||||
|
||||
internal sealed class ShrinkQueueFullException : InvalidOperationException
|
||||
{
|
||||
public ShrinkQueueFullException(string schedulerName)
|
||||
@@ -43,15 +59,29 @@ namespace ShrinkEventBus
|
||||
internal sealed class ShrinkSchedulerWorkItem
|
||||
{
|
||||
private readonly UniTaskCompletionSource? _completion;
|
||||
private readonly Delegate _action;
|
||||
|
||||
public ShrinkSchedulerWorkItem(Action action)
|
||||
{
|
||||
_action = action ?? throw new ArgumentNullException(nameof(action));
|
||||
}
|
||||
|
||||
public ShrinkSchedulerWorkItem(Func<UniTask> action, bool awaitable)
|
||||
{
|
||||
Action = action ?? throw new ArgumentNullException(nameof(action));
|
||||
_action = action ?? throw new ArgumentNullException(nameof(action));
|
||||
if (awaitable)
|
||||
_completion = new UniTaskCompletionSource();
|
||||
}
|
||||
|
||||
public Func<UniTask> Action { get; }
|
||||
public UniTask Invoke()
|
||||
{
|
||||
if (_action is Action synchronousAction)
|
||||
{
|
||||
synchronousAction();
|
||||
return UniTask.CompletedTask;
|
||||
}
|
||||
return ((Func<UniTask>)_action)();
|
||||
}
|
||||
public UniTask Completion => _completion?.Task ?? UniTask.CompletedTask;
|
||||
|
||||
public void Complete() => _completion?.TrySetResult();
|
||||
@@ -77,6 +107,7 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
public bool IsEmpty => _queue.IsEmpty;
|
||||
public int Count => _queue.Count;
|
||||
|
||||
public bool TryEnqueue(ShrinkSchedulerWorkItem item)
|
||||
{
|
||||
@@ -152,7 +183,7 @@ namespace ShrinkEventBus
|
||||
{
|
||||
try
|
||||
{
|
||||
await item.Action();
|
||||
await item.Invoke();
|
||||
item.Complete();
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
@@ -170,7 +201,7 @@ namespace ShrinkEventBus
|
||||
{
|
||||
try
|
||||
{
|
||||
item.Action().GetAwaiter().GetResult();
|
||||
item.Invoke().GetAwaiter().GetResult();
|
||||
item.Complete();
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
@@ -188,6 +219,7 @@ namespace ShrinkEventBus
|
||||
internal sealed class ShrinkInlineScheduler : IShrinkBusScheduler
|
||||
{
|
||||
public bool IsOnSchedulerThread => true;
|
||||
public bool SupportsDeferred => false;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
@@ -195,6 +227,9 @@ namespace ShrinkEventBus
|
||||
return true;
|
||||
}
|
||||
|
||||
public ShrinkDeferredPostStatus TryPostDeferred(Action action) =>
|
||||
ShrinkDeferredPostStatus.Unsupported;
|
||||
|
||||
public UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
@@ -208,37 +243,52 @@ namespace ShrinkEventBus
|
||||
internal sealed class ShrinkMainThreadScheduler : IShrinkBusScheduler
|
||||
{
|
||||
private readonly ShrinkSchedulerQueue _queue;
|
||||
private readonly IShrinkMainThreadDispatcher _dispatcher;
|
||||
private readonly MainThreadDispatcherContract _dispatcher;
|
||||
private readonly ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher? _deferredDispatcher;
|
||||
private readonly object _gate = new();
|
||||
private readonly Action _pump;
|
||||
private int _pumpScheduled;
|
||||
private int _disposed;
|
||||
private bool _discardPending;
|
||||
|
||||
public ShrinkMainThreadScheduler(string name, ShrinkBusOptions options)
|
||||
{
|
||||
_queue = new ShrinkSchedulerQueue(name, options);
|
||||
_dispatcher = ShrinkEventBusRuntime.MainThreadDispatcher;
|
||||
_deferredDispatcher = _dispatcher as ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher;
|
||||
_pump = () => PumpAsync().Forget();
|
||||
}
|
||||
|
||||
public bool IsOnSchedulerThread => _dispatcher.IsMainThread;
|
||||
public bool SupportsDeferred => _deferredDispatcher != null;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return false;
|
||||
if (Volatile.Read(ref _disposed) != 0) return false;
|
||||
if (IsOnSchedulerThread)
|
||||
{
|
||||
action();
|
||||
return true;
|
||||
}
|
||||
return Enqueue(action) == ShrinkDeferredPostStatus.Accepted;
|
||||
}
|
||||
|
||||
var item = new ShrinkSchedulerWorkItem(() =>
|
||||
public ShrinkDeferredPostStatus TryPostDeferred(Action action)
|
||||
{
|
||||
if (action == null) throw new ArgumentNullException(nameof(action));
|
||||
if (_deferredDispatcher == null) return ShrinkDeferredPostStatus.Unsupported;
|
||||
return Enqueue(action);
|
||||
}
|
||||
|
||||
private ShrinkDeferredPostStatus Enqueue(Action action)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
action();
|
||||
return UniTask.CompletedTask;
|
||||
}, awaitable: false);
|
||||
if (!_queue.TryEnqueue(item))
|
||||
return false;
|
||||
SchedulePump();
|
||||
return true;
|
||||
if (_disposed != 0) return ShrinkDeferredPostStatus.Stopped;
|
||||
var item = new ShrinkSchedulerWorkItem(action);
|
||||
if (!_queue.TryEnqueue(item)) return ShrinkDeferredPostStatus.QueueFull;
|
||||
return SchedulePump() ? ShrinkDeferredPostStatus.Accepted : ShrinkDeferredPostStatus.SchedulerRejected;
|
||||
}
|
||||
}
|
||||
|
||||
public async UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
|
||||
@@ -251,19 +301,24 @@ namespace ShrinkEventBus
|
||||
await action();
|
||||
return;
|
||||
}
|
||||
|
||||
var item = new ShrinkSchedulerWorkItem(action, awaitable: true);
|
||||
await _queue.EnqueueAsync(item, cancellationToken);
|
||||
SchedulePump();
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed != 0) _queue.DropPending();
|
||||
else SchedulePump();
|
||||
}
|
||||
await item.Completion.AttachExternalCancellation(cancellationToken);
|
||||
}
|
||||
|
||||
public async UniTask ShutdownAsync(bool drain, TimeSpan timeout)
|
||||
{
|
||||
Interlocked.Exchange(ref _disposed, 1);
|
||||
if (!drain)
|
||||
_queue.DropPending();
|
||||
else
|
||||
lock (_gate)
|
||||
{
|
||||
_disposed = 1;
|
||||
if (!drain) { _discardPending = true; _queue.DropPending(); }
|
||||
}
|
||||
if (drain)
|
||||
await ShrinkSchedulerShutdown.WaitUntilDrainedAsync(
|
||||
_queue, () => Volatile.Read(ref _pumpScheduled) != 0, timeout);
|
||||
_queue.Dispose();
|
||||
@@ -271,34 +326,66 @@ namespace ShrinkEventBus
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
_queue.Dispose();
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed != 0) return;
|
||||
_disposed = 1;
|
||||
_discardPending = true;
|
||||
_queue.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void SchedulePump()
|
||||
// All queued work shares one FIFO and capacity. Prefer the deferred dispatcher
|
||||
// so a normal worker-thread post cannot pull deferred events into an inline pump.
|
||||
private bool SchedulePump()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _pumpScheduled, 1) != 0)
|
||||
return;
|
||||
if (_dispatcher.TryPost(() => PumpAsync().Forget()))
|
||||
return;
|
||||
Interlocked.Exchange(ref _pumpScheduled, 0);
|
||||
ShrinkEventDiagnostics.LogException(new InvalidOperationException(
|
||||
"The configured main-thread dispatcher rejected an EventBus pump."));
|
||||
if (_pumpScheduled != 0) return true;
|
||||
_pumpScheduled = 1;
|
||||
bool accepted;
|
||||
try
|
||||
{
|
||||
accepted = _deferredDispatcher != null
|
||||
? _deferredDispatcher.TryPostDeferred(_pump)
|
||||
: _dispatcher.TryPost(_pump);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_pumpScheduled = 0;
|
||||
_queue.DropPending();
|
||||
throw;
|
||||
}
|
||||
if (accepted) return true;
|
||||
_pumpScheduled = 0;
|
||||
_queue.DropPending();
|
||||
return false;
|
||||
}
|
||||
|
||||
private async UniTask PumpAsync()
|
||||
{
|
||||
ShrinkSchedulerWorkItem[] batch;
|
||||
var count = 0;
|
||||
lock (_gate)
|
||||
{
|
||||
var capacity = _queue.Count;
|
||||
batch = ArrayPool<ShrinkSchedulerWorkItem>.Shared.Rent(Math.Max(1, capacity));
|
||||
while (count < capacity && _queue.TryDequeue(out var item)) batch[count++] = item;
|
||||
}
|
||||
try
|
||||
{
|
||||
while (_queue.TryDequeue(out var item))
|
||||
await ShrinkSchedulerWorkItemRunner.RunAsync(item);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (_discardPending) batch[i].Drop(nameof(ShrinkMainThreadScheduler));
|
||||
else await ShrinkSchedulerWorkItemRunner.RunAsync(batch[i]);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref _pumpScheduled, 0);
|
||||
if (!_queue.IsEmpty && Volatile.Read(ref _disposed) == 0)
|
||||
SchedulePump();
|
||||
ArrayPool<ShrinkSchedulerWorkItem>.Shared.Return(batch, clearArray: true);
|
||||
lock (_gate)
|
||||
{
|
||||
_pumpScheduled = 0;
|
||||
if (!_queue.IsEmpty) SchedulePump();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -317,22 +404,21 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
public bool IsOnSchedulerThread => false;
|
||||
public bool SupportsDeferred => false;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return false;
|
||||
var item = new ShrinkSchedulerWorkItem(() =>
|
||||
{
|
||||
action();
|
||||
return UniTask.CompletedTask;
|
||||
}, awaitable: false);
|
||||
var item = new ShrinkSchedulerWorkItem(action);
|
||||
if (!_queue.TryEnqueue(item))
|
||||
return false;
|
||||
ScheduleWorkers();
|
||||
return true;
|
||||
}
|
||||
|
||||
public ShrinkDeferredPostStatus TryPostDeferred(Action action) => ShrinkDeferredPostStatus.Unsupported;
|
||||
|
||||
public async UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
@@ -413,6 +499,7 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
public bool IsOnSchedulerThread => Thread.CurrentThread.ManagedThreadId == Volatile.Read(ref _threadId);
|
||||
public bool SupportsDeferred => false;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
@@ -424,17 +511,15 @@ namespace ShrinkEventBus
|
||||
return true;
|
||||
}
|
||||
|
||||
var item = new ShrinkSchedulerWorkItem(() =>
|
||||
{
|
||||
action();
|
||||
return UniTask.CompletedTask;
|
||||
}, awaitable: false);
|
||||
var item = new ShrinkSchedulerWorkItem(action);
|
||||
if (!_queue.TryEnqueue(item))
|
||||
return false;
|
||||
_signal.Set();
|
||||
return true;
|
||||
}
|
||||
|
||||
public ShrinkDeferredPostStatus TryPostDeferred(Action action) => ShrinkDeferredPostStatus.Unsupported;
|
||||
|
||||
public async UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"name": "ShrinkEventBus.Runtime",
|
||||
"rootNamespace": "ShrinkEventBus",
|
||||
"references": [
|
||||
"UniTask",
|
||||
"ShrinkRuntime.Abstractions"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": false,
|
||||
"autoReferenced": true
|
||||
"name": "ShrinkEventBus.Runtime",
|
||||
"rootNamespace": "ShrinkEventBus",
|
||||
"references": [
|
||||
"UniTask",
|
||||
"ShrinkRuntime.Abstractions"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": false,
|
||||
"autoReferenced": true
|
||||
}
|
||||
@@ -14,6 +14,7 @@ namespace ShrinkEventBus
|
||||
internal interface IShrinkEventChannel
|
||||
{
|
||||
int Count { get; }
|
||||
void CaptureBindings(List<(Type EventType, System.Reflection.MethodInfo Handler)> bindings);
|
||||
bool RemoveSubscription(long subscriptionId);
|
||||
void Clear();
|
||||
void DetachSlot(int slot);
|
||||
@@ -87,6 +88,15 @@ namespace ShrinkEventBus
|
||||
private Action<TEvent>? _syncDispatcher;
|
||||
|
||||
public int Count => _snapshot.Length;
|
||||
public void CaptureBindings(List<(Type EventType, System.Reflection.MethodInfo Handler)> bindings)
|
||||
{
|
||||
var snapshot = _snapshot;
|
||||
foreach (var entry in snapshot)
|
||||
{
|
||||
var method = entry.SyncHandler?.Method ?? entry.AsyncHandler?.Method;
|
||||
if (method != null) bindings.Add((typeof(TEvent), method));
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(long subscriptionId, long registrationOrder, Action<TEvent> handler,
|
||||
ShrinkSubscribeDescriptor descriptor)
|
||||
|
||||
@@ -75,7 +75,7 @@ namespace ShrinkEventBus
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public virtual ShrinkPostResult Post<TEvent>(in TEvent eventData) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (eventData is null)
|
||||
if (!typeof(TEvent).IsValueType && eventData is null)
|
||||
throw new ArgumentNullException(nameof(eventData));
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return TraceWithoutDispatch(in eventData,
|
||||
@@ -84,6 +84,35 @@ namespace ShrinkEventBus
|
||||
if (_isInline || _scheduler.IsOnSchedulerThread)
|
||||
return Dispatch(in eventData);
|
||||
|
||||
return PostScheduled(in eventData);
|
||||
}
|
||||
|
||||
internal ShrinkPostResult PostDeferred<TEvent>(in TEvent eventData) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (!typeof(TEvent).IsValueType && eventData is null)
|
||||
throw new ArgumentNullException(nameof(eventData));
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return TraceWithoutDispatch(in eventData,
|
||||
ShrinkPostResult.Rejected(ShrinkPostFailure.BusStopped), false);
|
||||
if (Options.Scheduler != ShrinkBusSchedulerKind.MainThread || !_scheduler.SupportsDeferred)
|
||||
return TraceWithoutDispatch(in eventData,
|
||||
ShrinkPostResult.Rejected(ShrinkPostFailure.DeferredUnsupported), false);
|
||||
|
||||
var queuedEvent = eventData;
|
||||
var status = _scheduler.TryPostDeferred(() => Dispatch(in queuedEvent));
|
||||
if (status == ShrinkDeferredPostStatus.Accepted) return new ShrinkPostResult(true, false, false);
|
||||
var failure = status switch
|
||||
{
|
||||
ShrinkDeferredPostStatus.Unsupported => ShrinkPostFailure.DeferredUnsupported,
|
||||
ShrinkDeferredPostStatus.Stopped => ShrinkPostFailure.BusStopped,
|
||||
ShrinkDeferredPostStatus.SchedulerRejected => ShrinkPostFailure.SchedulerRejected,
|
||||
_ => ShrinkPostFailure.QueueFull
|
||||
};
|
||||
return TraceWithoutDispatch(in eventData, ShrinkPostResult.Rejected(failure), false);
|
||||
}
|
||||
|
||||
private ShrinkPostResult PostScheduled<TEvent>(in TEvent eventData) where TEvent : IShrinkEvent
|
||||
{
|
||||
var queuedEvent = eventData;
|
||||
if (_scheduler.TryPost(() => Dispatch(in queuedEvent)))
|
||||
return new ShrinkPostResult(true, false, false);
|
||||
@@ -94,7 +123,7 @@ namespace ShrinkEventBus
|
||||
public virtual UniTask<ShrinkPostResult> PostAsync<TEvent>(TEvent eventData,
|
||||
CancellationToken cancellationToken = default) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (eventData is null)
|
||||
if (!typeof(TEvent).IsValueType && eventData is null)
|
||||
throw new ArgumentNullException(nameof(eventData));
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return UniTask.FromResult(TraceWithoutDispatch(in eventData,
|
||||
@@ -168,6 +197,13 @@ namespace ShrinkEventBus
|
||||
return new EventSubscription(this, subscriptionId);
|
||||
}
|
||||
|
||||
internal IReadOnlyList<(Type EventType, System.Reflection.MethodInfo Handler)> CaptureBindings()
|
||||
{
|
||||
var bindings = new List<(Type, System.Reflection.MethodInfo)>();
|
||||
lock (_channelGate) foreach (var channel in _channels.Values) channel.CaptureBindings(bindings);
|
||||
return bindings;
|
||||
}
|
||||
|
||||
internal int SubscriberCount
|
||||
{
|
||||
get
|
||||
@@ -195,7 +231,7 @@ namespace ShrinkEventBus
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
protected ShrinkPostResult Dispatch<TEvent>(in TEvent eventData) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (_postObserver != null && EventBus.HasDetailedPostedObservers)
|
||||
if (EventBus.HasDetailedPostedObservers)
|
||||
return DispatchObserved(in eventData);
|
||||
|
||||
var channel = ShrinkEventChannelSlots<TEvent>.Get(_busSlot);
|
||||
@@ -210,7 +246,7 @@ namespace ShrinkEventBus
|
||||
protected async UniTask<ShrinkPostResult> DispatchAsync<TEvent>(TEvent eventData,
|
||||
CancellationToken cancellationToken) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (_postObserver != null && EventBus.HasDetailedPostedObservers)
|
||||
if (EventBus.HasDetailedPostedObservers)
|
||||
return await DispatchAsyncObserved(eventData, cancellationToken);
|
||||
|
||||
var channel = ShrinkEventChannelSlots<TEvent>.Get(_busSlot);
|
||||
@@ -246,8 +282,8 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
var elapsedTicks = Stopwatch.GetTimestamp() - startedAt;
|
||||
if (EventBus.HasPostedObservers)
|
||||
_postObserver!(eventData, typeof(TEvent), Key);
|
||||
if (_postObserver != null && EventBus.HasPostedObservers)
|
||||
_postObserver(eventData, typeof(TEvent), Key);
|
||||
EventBus.NotifyDetailedPosted(new ShrinkEventTrace(DateTime.UtcNow, typeof(TEvent), Key,
|
||||
Options, threadId, elapsedTicks, result, false));
|
||||
return result;
|
||||
@@ -257,7 +293,7 @@ namespace ShrinkEventBus
|
||||
protected ShrinkPostResult TraceWithoutDispatch<TEvent>(in TEvent eventData,
|
||||
ShrinkPostResult result, bool isAsync) where TEvent : IShrinkEvent
|
||||
{
|
||||
if (_postObserver != null && EventBus.HasDetailedPostedObservers)
|
||||
if (EventBus.HasDetailedPostedObservers)
|
||||
{
|
||||
EventBus.NotifyDetailedPosted(new ShrinkEventTrace(DateTime.UtcNow, typeof(TEvent), Key,
|
||||
Options, Thread.CurrentThread.ManagedThreadId, 0L, result, isAsync));
|
||||
@@ -297,8 +333,8 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
var elapsedTicks = Stopwatch.GetTimestamp() - startedAt;
|
||||
if (EventBus.HasPostedObservers)
|
||||
_postObserver!(eventData, typeof(TEvent), Key);
|
||||
if (_postObserver != null && EventBus.HasPostedObservers)
|
||||
_postObserver(eventData, typeof(TEvent), Key);
|
||||
EventBus.NotifyDetailedPosted(new ShrinkEventTrace(DateTime.UtcNow, typeof(TEvent), Key,
|
||||
Options, threadId, elapsedTicks, result, true));
|
||||
return result;
|
||||
@@ -367,7 +403,7 @@ namespace ShrinkEventBus
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public override ShrinkPostResult Post<TEvent>(in TEvent eventData)
|
||||
{
|
||||
if (eventData is null)
|
||||
if (!typeof(TEvent).IsValueType && eventData is null)
|
||||
throw new ArgumentNullException(nameof(eventData));
|
||||
if (IsDisposed)
|
||||
return TraceWithoutDispatch(in eventData,
|
||||
@@ -378,7 +414,7 @@ namespace ShrinkEventBus
|
||||
public override UniTask<ShrinkPostResult> PostAsync<TEvent>(TEvent eventData,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (eventData is null)
|
||||
if (!typeof(TEvent).IsValueType && eventData is null)
|
||||
throw new ArgumentNullException(nameof(eventData));
|
||||
if (IsDisposed)
|
||||
return UniTask.FromResult(TraceWithoutDispatch(in eventData,
|
||||
|
||||
@@ -2,25 +2,29 @@
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using ShrinkSDK.Runtime;
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
using MainThreadDispatcherContract = ShrinkEventBus.IShrinkEventBusMainThreadDispatcher;
|
||||
#else
|
||||
using MainThreadDispatcherContract = ShrinkSDK.Runtime.IShrinkMainThreadDispatcher;
|
||||
#endif
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
public static class ShrinkEventBusRuntime
|
||||
{
|
||||
private static IShrinkMainThreadDispatcher _mainThreadDispatcher = CreateDefaultDispatcher();
|
||||
private static MainThreadDispatcherContract _mainThreadDispatcher = CreateDefaultDispatcher();
|
||||
|
||||
public static IShrinkMainThreadDispatcher MainThreadDispatcher =>
|
||||
public static MainThreadDispatcherContract MainThreadDispatcher =>
|
||||
Volatile.Read(ref _mainThreadDispatcher);
|
||||
|
||||
public static void ConfigureMainThreadDispatcher(IShrinkMainThreadDispatcher dispatcher)
|
||||
public static void ConfigureMainThreadDispatcher(MainThreadDispatcherContract dispatcher)
|
||||
{
|
||||
if (dispatcher == null)
|
||||
throw new ArgumentNullException(nameof(dispatcher));
|
||||
Volatile.Write(ref _mainThreadDispatcher, dispatcher);
|
||||
}
|
||||
|
||||
private static IShrinkMainThreadDispatcher CreateDefaultDispatcher()
|
||||
private static MainThreadDispatcherContract CreateDefaultDispatcher()
|
||||
{
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
return new ShrinkUnityMainThreadDispatcher();
|
||||
@@ -33,7 +37,8 @@ namespace ShrinkEventBus
|
||||
}
|
||||
|
||||
#if UNITY_5_3_OR_NEWER
|
||||
internal sealed class ShrinkUnityMainThreadDispatcher : IShrinkMainThreadDispatcher
|
||||
internal sealed class ShrinkUnityMainThreadDispatcher : MainThreadDispatcherContract,
|
||||
ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher
|
||||
{
|
||||
public bool IsMainThread => Cysharp.Threading.Tasks.PlayerLoopHelper.IsMainThread;
|
||||
|
||||
@@ -46,9 +51,20 @@ namespace ShrinkEventBus
|
||||
action);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryPostDeferred(Action action)
|
||||
{
|
||||
if (action == null)
|
||||
throw new ArgumentNullException(nameof(action));
|
||||
Cysharp.Threading.Tasks.PlayerLoopHelper.AddContinuation(
|
||||
Cysharp.Threading.Tasks.PlayerLoopTiming.Update,
|
||||
action);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#else
|
||||
internal sealed class ShrinkSynchronizationContextDispatcher : IShrinkMainThreadDispatcher
|
||||
internal sealed class ShrinkSynchronizationContextDispatcher : MainThreadDispatcherContract,
|
||||
ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher
|
||||
{
|
||||
private readonly SynchronizationContext? _context;
|
||||
private readonly int _threadId;
|
||||
@@ -75,6 +91,16 @@ namespace ShrinkEventBus
|
||||
_context.Post(static state => ((Action)state!).Invoke(), action);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryPostDeferred(Action action)
|
||||
{
|
||||
if (action == null)
|
||||
throw new ArgumentNullException(nameof(action));
|
||||
if (_context == null)
|
||||
return false;
|
||||
_context.Post(static state => ((Action)state!).Invoke(), action);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -61,7 +61,9 @@ namespace ShrinkEventBus
|
||||
QueueFull = 2,
|
||||
Canceled = 3,
|
||||
HandlerException = 4,
|
||||
InvalidEvent = 5
|
||||
InvalidEvent = 5,
|
||||
DeferredUnsupported = 6,
|
||||
SchedulerRejected = 7
|
||||
}
|
||||
|
||||
public readonly struct ShrinkPostResult
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace ShrinkEventBus
|
||||
{
|
||||
public readonly struct ShrinkEventDiagnostic
|
||||
{
|
||||
internal ShrinkEventDiagnostic(DateTime timestampUtc, Type eventType, ShrinkBusKey busKey,
|
||||
ShrinkBusSchedulerKind scheduler, ShrinkDispatchMode dispatchMode, int threadId,
|
||||
long elapsedTimestampTicks, ShrinkPostResult result, bool isAsync)
|
||||
{
|
||||
TimestampUtc = timestampUtc;
|
||||
EventType = eventType;
|
||||
BusKey = busKey;
|
||||
Scheduler = scheduler;
|
||||
DispatchMode = dispatchMode;
|
||||
ThreadId = threadId;
|
||||
ElapsedTimestampTicks = elapsedTimestampTicks;
|
||||
Result = result;
|
||||
IsAsync = isAsync;
|
||||
}
|
||||
|
||||
public DateTime TimestampUtc { get; }
|
||||
public Type EventType { get; }
|
||||
public ShrinkBusKey BusKey { get; }
|
||||
public ShrinkBusSchedulerKind Scheduler { get; }
|
||||
public ShrinkDispatchMode DispatchMode { get; }
|
||||
public int ThreadId { get; }
|
||||
public long ElapsedTimestampTicks { get; }
|
||||
public double ElapsedMilliseconds => ElapsedTimestampTicks * 1000d / Stopwatch.Frequency;
|
||||
public TimeSpan Elapsed => TimeSpan.FromSeconds(ElapsedTimestampTicks / (double)Stopwatch.Frequency);
|
||||
public ShrinkPostResult Result { get; }
|
||||
public bool IsAsync { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0dd120bc74194af29d7cbd1f8c80c141
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,40 @@
|
||||
using ShrinkEventBus;
|
||||
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var bus = host.CreateBus(ShrinkBusKey.Game, ShrinkBusOptions.Inline());
|
||||
var subscriber = new OrderSubscriber();
|
||||
using var binding = host.Attach(subscriber);
|
||||
var diagnostics = 0;
|
||||
using var observation = EventBus.ObserveDiagnostics(_ => diagnostics++);
|
||||
|
||||
bus.Post(new OrderPlaced(2));
|
||||
await bus.PostAsync(new OrderPlaced(3));
|
||||
if (subscriber.Total != 5 || diagnostics != 2)
|
||||
throw new InvalidOperationException("Generated subscription or diagnostics failed.");
|
||||
|
||||
var workerKey = new ShrinkBusKey("worker", "orders");
|
||||
var worker = host.CreateBus(workerKey, ShrinkBusOptions.DedicatedThread());
|
||||
var workerSubscriber = new OrderSubscriber();
|
||||
using var workerBinding = host.Attach(workerSubscriber, workerKey);
|
||||
await worker.PostAsync(new OrderPlaced(7));
|
||||
if (workerSubscriber.Total != 7)
|
||||
throw new InvalidOperationException("Dedicated-thread delivery failed.");
|
||||
|
||||
binding.Dispose();
|
||||
bus.Post(new OrderPlaced(10));
|
||||
if (subscriber.Total != 5)
|
||||
throw new InvalidOperationException("Unsubscribe failed.");
|
||||
|
||||
await host.ShutdownAsync();
|
||||
Console.WriteLine("EVENTBUS_CONSOLE_PASS: sync, async, diagnostics, worker, unsubscribe");
|
||||
|
||||
public readonly record struct OrderPlaced(int Amount) : IShrinkEvent;
|
||||
|
||||
[ShrinkEventSubscriber]
|
||||
public sealed partial class OrderSubscriber
|
||||
{
|
||||
public int Total { get; private set; }
|
||||
|
||||
[ShrinkSubscribe]
|
||||
private void OnOrder(OrderPlaced order) => Total += order.Amount;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
"rootNamespace": "ShrinkEventBus.Tests",
|
||||
"references": [
|
||||
"ShrinkEventBus.Runtime",
|
||||
"ShrinkRuntime.Abstractions",
|
||||
"UniTask",
|
||||
"UnityEngine.TestRunner",
|
||||
"UnityEditor.TestRunner"
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using NUnit.Framework;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
namespace ShrinkEventBus.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class ShrinkEventBusDeferredDiagnosticsTests
|
||||
{
|
||||
private IShrinkEventBusMainThreadDispatcher _originalDispatcher;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_originalDispatcher = ShrinkEventBusRuntime.MainThreadDispatcher;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(_originalDispatcher);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ObserveDiagnostics_ReportsMetadataAndUnsubscribes()
|
||||
{
|
||||
var diagnostics = new List<ShrinkEventDiagnostic>();
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("diagnostics", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, ShrinkBusOptions.Inline());
|
||||
|
||||
var subscription = EventBus.ObserveDiagnostics(diagnostics.Add);
|
||||
bus.Post(new DeferredEvent(1));
|
||||
subscription.Dispose();
|
||||
bus.Post(new DeferredEvent(2));
|
||||
|
||||
Assert.AreEqual(1, diagnostics.Count);
|
||||
Assert.AreEqual(typeof(DeferredEvent), diagnostics[0].EventType);
|
||||
Assert.AreEqual(key, diagnostics[0].BusKey);
|
||||
Assert.IsTrue(diagnostics[0].Result.Accepted);
|
||||
Assert.IsFalse(diagnostics[0].IsAsync);
|
||||
Assert.GreaterOrEqual(diagnostics[0].ElapsedTimestampTicks, 0L);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ObserveDiagnostics_ThrowingObserverDoesNotBlockBusinessOrOtherObservers()
|
||||
{
|
||||
var calls = 0;
|
||||
var secondObserverCalls = 0;
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("diagnostics", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, ShrinkBusOptions.Inline());
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, _ => calls++, ShrinkEventPriority.Normal, 0, false);
|
||||
using var first = EventBus.ObserveDiagnostics(_ =>
|
||||
throw new InvalidOperationException("observer failure"));
|
||||
using var second = EventBus.ObserveDiagnostics(_ => secondObserverCalls++);
|
||||
|
||||
var previous = LogAssert.ignoreFailingMessages;
|
||||
LogAssert.ignoreFailingMessages = true;
|
||||
try
|
||||
{
|
||||
Assert.DoesNotThrow(() => bus.Post(new DeferredEvent(3)));
|
||||
}
|
||||
finally
|
||||
{
|
||||
LogAssert.ignoreFailingMessages = previous;
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, calls);
|
||||
Assert.AreEqual(1, secondObserverCalls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ObserveDiagnostics_MutationsApplyToNextDispatch()
|
||||
{
|
||||
var calls = new List<string>();
|
||||
IDisposable second = null;
|
||||
IDisposable added = null;
|
||||
using var first = EventBus.ObserveDiagnostics(_ =>
|
||||
{
|
||||
calls.Add("first");
|
||||
second.Dispose();
|
||||
if (added == null)
|
||||
added = EventBus.ObserveDiagnostics(__ => calls.Add("added"));
|
||||
});
|
||||
second = EventBus.ObserveDiagnostics(_ => calls.Add("second"));
|
||||
try
|
||||
{
|
||||
EventBus.NotifyDetailedPosted(default);
|
||||
CollectionAssert.AreEqual(new[] { "first", "second" }, calls);
|
||||
calls.Clear();
|
||||
EventBus.NotifyDetailedPosted(default);
|
||||
CollectionAssert.AreEqual(new[] { "first", "added" }, calls);
|
||||
}
|
||||
finally
|
||||
{
|
||||
second.Dispose();
|
||||
added?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_DoesNotDispatchBeforePump()
|
||||
{
|
||||
var dispatcher = new ManualDispatcher();
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(dispatcher);
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, new ShrinkBusOptions
|
||||
{
|
||||
Scheduler = ShrinkBusSchedulerKind.MainThread,
|
||||
QueueCapacity = 8
|
||||
});
|
||||
var calls = 0;
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, _ => calls++, ShrinkEventPriority.Normal, 0, false);
|
||||
|
||||
var result = EventBus.PostDeferred(bus, new DeferredEvent(4));
|
||||
|
||||
Assert.IsTrue(result.Accepted);
|
||||
Assert.IsFalse(result.Handled);
|
||||
Assert.AreEqual(0, calls);
|
||||
Assert.AreEqual(1, dispatcher.Count);
|
||||
|
||||
dispatcher.PumpAll();
|
||||
Assert.AreEqual(1, calls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_ReentrantPostWaitsForNextPump()
|
||||
{
|
||||
var dispatcher = new ManualDispatcher();
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(dispatcher);
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, new ShrinkBusOptions
|
||||
{
|
||||
Scheduler = ShrinkBusSchedulerKind.MainThread,
|
||||
QueueCapacity = 8
|
||||
});
|
||||
var calls = 0;
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, _ =>
|
||||
{
|
||||
calls++;
|
||||
if (calls == 1)
|
||||
EventBus.PostDeferred(bus, new DeferredEvent(5));
|
||||
}, ShrinkEventPriority.Normal, 0, false);
|
||||
|
||||
EventBus.PostDeferred(bus, new DeferredEvent(4));
|
||||
dispatcher.PumpAll();
|
||||
Assert.AreEqual(1, calls);
|
||||
Assert.AreEqual(1, dispatcher.Count);
|
||||
|
||||
dispatcher.PumpAll();
|
||||
Assert.AreEqual(2, calls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_DropOldestKeepsNewest()
|
||||
{
|
||||
var dispatcher = new ManualDispatcher();
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(dispatcher);
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, new ShrinkBusOptions
|
||||
{
|
||||
Scheduler = ShrinkBusSchedulerKind.MainThread,
|
||||
QueueCapacity = 1,
|
||||
OverflowPolicy = ShrinkQueueOverflowPolicy.DropOldest
|
||||
});
|
||||
var values = new List<int>();
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, evt => values.Add(evt.Value), ShrinkEventPriority.Normal, 0, false);
|
||||
|
||||
EventBus.PostDeferred(bus, new DeferredEvent(1));
|
||||
EventBus.PostDeferred(bus, new DeferredEvent(2));
|
||||
dispatcher.PumpAll();
|
||||
|
||||
CollectionAssert.AreEqual(new[] { 2 }, values);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_InlineBusFailsWithoutDispatch()
|
||||
{
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, ShrinkBusOptions.Inline());
|
||||
var calls = 0;
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, _ => calls++, ShrinkEventPriority.Normal, 0, false);
|
||||
|
||||
var result = EventBus.PostDeferred(bus, new DeferredEvent(6));
|
||||
|
||||
Assert.AreEqual(ShrinkPostFailure.DeferredUnsupported, result.Failure);
|
||||
Assert.AreEqual(0, calls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_WithoutDeferredDispatcherFailsWithoutDispatch()
|
||||
{
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(new NonDeferredDispatcher());
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, new ShrinkBusOptions
|
||||
{
|
||||
Scheduler = ShrinkBusSchedulerKind.MainThread
|
||||
});
|
||||
var calls = 0;
|
||||
using var binding = ShrinkGeneratedBinding.Subscribe<DeferredEvent>(host, key, string.Empty,
|
||||
this, _ => calls++, ShrinkEventPriority.Normal, 0, false);
|
||||
|
||||
var result = EventBus.PostDeferred(bus, new DeferredEvent(7));
|
||||
|
||||
Assert.AreEqual(ShrinkPostFailure.DeferredUnsupported, result.Failure);
|
||||
Assert.AreEqual(0, calls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PostDeferred_DisposedBusRejects()
|
||||
{
|
||||
var dispatcher = new ManualDispatcher();
|
||||
ShrinkEventBusRuntime.ConfigureMainThreadDispatcher(dispatcher);
|
||||
using var host = new ShrinkEventBusHost();
|
||||
var key = new ShrinkBusKey("deferred", Guid.NewGuid().ToString("N"));
|
||||
var bus = host.CreateBus(key, new ShrinkBusOptions
|
||||
{
|
||||
Scheduler = ShrinkBusSchedulerKind.MainThread
|
||||
});
|
||||
bus.Dispose();
|
||||
|
||||
var result = EventBus.PostDeferred(bus, new DeferredEvent(8));
|
||||
|
||||
Assert.AreEqual(ShrinkPostFailure.BusStopped, result.Failure);
|
||||
}
|
||||
|
||||
private readonly struct DeferredEvent : IShrinkEvent
|
||||
{
|
||||
public DeferredEvent(int value) => Value = value;
|
||||
public int Value { get; }
|
||||
}
|
||||
|
||||
private sealed class ManualDispatcher : IShrinkEventBusMainThreadDispatcher,
|
||||
ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher
|
||||
{
|
||||
private readonly Queue<Action> _queue = new();
|
||||
|
||||
public bool IsMainThread => true;
|
||||
public int Count => _queue.Count;
|
||||
|
||||
public bool TryPost(Action action)
|
||||
{
|
||||
_queue.Enqueue(action);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryPostDeferred(Action action)
|
||||
{
|
||||
_queue.Enqueue(action);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void PumpAll()
|
||||
{
|
||||
var count = _queue.Count;
|
||||
for (var i = 0; i < count; i++)
|
||||
_queue.Dequeue()();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NonDeferredDispatcher : IShrinkEventBusMainThreadDispatcher
|
||||
{
|
||||
public bool IsMainThread => true;
|
||||
public bool TryPost(Action action) => true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 070c5e5975c64a39badcb0ebb04c2902
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+6
-7
@@ -1,17 +1,16 @@
|
||||
{
|
||||
"name": "com.cneicy.shrink-eventbus",
|
||||
"version": "2.1.0",
|
||||
"version": "2.3.2",
|
||||
"displayName": "ShrinkEventBus",
|
||||
"description": "多 Bus、特性强类型注册、UniTask 调度与低分配发布的 Unity 事件总线。",
|
||||
"unity": "2022.3",
|
||||
"documentationUrl": "https://git.crash.work/ShrinkSDK/ShrinkEventBus",
|
||||
"changelogUrl": "https://git.crash.work/ShrinkSDK/ShrinkEventBus/src/branch/main/CHANGELOG.md",
|
||||
"licensesUrl": "https://git.crash.work/ShrinkSDK/ShrinkEventBus/src/branch/main/LICENSE",
|
||||
"documentationUrl": "https://github.com/cneicy/ShrinkEventBus",
|
||||
"changelogUrl": "https://github.com/cneicy/ShrinkEventBus/blob/main/CHANGELOG.md",
|
||||
"licensesUrl": "https://github.com/cneicy/ShrinkEventBus/blob/main/LICENSE",
|
||||
"dependencies": {
|
||||
"com.cysharp.unitask": "2.5.10",
|
||||
"com.unity.nuget.mono-cecil": "1.11.4",
|
||||
"com.cneicy.shrink-shared-codegen": "0.1.1",
|
||||
"com.cneicy.shrink-runtime-abstractions": "0.1.0"
|
||||
"com.cneicy.shrink-runtime-abstractions": "0.2.0"
|
||||
},
|
||||
"keywords": [
|
||||
"eventbus",
|
||||
@@ -21,6 +20,6 @@
|
||||
],
|
||||
"author": {
|
||||
"name": "cneicy",
|
||||
"url": "https://git.crash.work/ShrinkSDK"
|
||||
"url": "https://github.com/cneicy"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user