feat: update Godot integration and coordinated package dependencies
Publish UPM package / publish (push) Successful in 3s
Publish NuGet packages / publish (push) Successful in 3m43s

This commit is contained in:
cneicy committed 2026-11-06 19:13:18 +08:00
1 parent 95844e11ff
commit 901ad18453
15 files changed
+576 -55

No files matched your search

+52 -7
View File
@@ -133,6 +133,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)
@@ -191,17 +215,38 @@ namespace ShrinkEventBus
var observers = Volatile.Read(ref _detailedPosted);
if (observers == null)
return;
try
{
observers(trace);
}
catch (Exception exception)
var invocationList = observers.GetInvocationList();
for (var i = 0; i < invocationList.Length; i++)
{
try
{
((Action<ShrinkEventTrace>)invocationList[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;
}
}
}
+109 -32
View File
@@ -1,6 +1,7 @@
#nullable enable
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
@@ -17,11 +18,22 @@ 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)
@@ -81,6 +93,7 @@ namespace ShrinkEventBus
}
public bool IsEmpty => _queue.IsEmpty;
public int Count => _queue.Count;
public bool TryEnqueue(ShrinkSchedulerWorkItem item)
{
@@ -192,6 +205,7 @@ namespace ShrinkEventBus
internal sealed class ShrinkInlineScheduler : IShrinkBusScheduler
{
public bool IsOnSchedulerThread => true;
public bool SupportsDeferred => false;
public bool TryPost(Action action)
{
@@ -199,6 +213,9 @@ namespace ShrinkEventBus
return true;
}
public ShrinkDeferredPostStatus TryPostDeferred(Action action) =>
ShrinkDeferredPostStatus.Unsupported;
public UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -213,36 +230,53 @@ namespace ShrinkEventBus
{
private readonly ShrinkSchedulerQueue _queue;
private readonly MainThreadDispatcherContract _dispatcher;
private readonly ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher? _deferredDispatcher;
private readonly object _gate = new();
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;
}
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();
return UniTask.CompletedTask;
}, awaitable: false);
if (!_queue.TryEnqueue(item)) return ShrinkDeferredPostStatus.QueueFull;
return SchedulePump() ? ShrinkDeferredPostStatus.Accepted : ShrinkDeferredPostStatus.SchedulerRejected;
}
}
public async UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
@@ -255,19 +289,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();
@@ -275,34 +314,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(() => PumpAsync().Forget())
: _dispatcher.TryPost(() => PumpAsync().Forget());
}
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();
}
}
}
}
@@ -321,6 +392,7 @@ namespace ShrinkEventBus
}
public bool IsOnSchedulerThread => false;
public bool SupportsDeferred => false;
public bool TryPost(Action action)
{
@@ -337,6 +409,8 @@ namespace ShrinkEventBus
return true;
}
public ShrinkDeferredPostStatus TryPostDeferred(Action action) => ShrinkDeferredPostStatus.Unsupported;
public async UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
{
if (Volatile.Read(ref _disposed) != 0)
@@ -417,6 +491,7 @@ namespace ShrinkEventBus
}
public bool IsOnSchedulerThread => Thread.CurrentThread.ManagedThreadId == Volatile.Read(ref _threadId);
public bool SupportsDeferred => false;
public bool TryPost(Action action)
{
@@ -439,6 +514,8 @@ namespace ShrinkEventBus
return true;
}
public ShrinkDeferredPostStatus TryPostDeferred(Action action) => ShrinkDeferredPostStatus.Unsupported;
public async UniTask PostAsync(Func<UniTask> action, CancellationToken cancellationToken)
{
if (Volatile.Read(ref _disposed) != 0)
+2 -1
View File
@@ -2,7 +2,8 @@
"name": "ShrinkEventBus.Runtime",
"rootNamespace": "ShrinkEventBus",
"references": [
"UniTask"
"UniTask",
"ShrinkRuntime.Abstractions"
],
"includePlatforms": [],
"excludePlatforms": [],
+31 -7
View File
@@ -87,6 +87,30 @@ namespace ShrinkEventBus
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;
@@ -207,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);
@@ -222,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);
@@ -258,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;
@@ -269,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));
@@ -309,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;
+24 -2
View File
@@ -37,7 +37,8 @@ namespace ShrinkEventBus
}
#if UNITY_5_3_OR_NEWER
internal sealed class ShrinkUnityMainThreadDispatcher : MainThreadDispatcherContract
internal sealed class ShrinkUnityMainThreadDispatcher : MainThreadDispatcherContract,
ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher
{
public bool IsMainThread => Cysharp.Threading.Tasks.PlayerLoopHelper.IsMainThread;
@@ -50,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 : MainThreadDispatcherContract
internal sealed class ShrinkSynchronizationContextDispatcher : MainThreadDispatcherContract,
ShrinkSDK.Runtime.IShrinkDeferredMainThreadDispatcher
{
private readonly SynchronizationContext? _context;
private readonly int _threadId;
@@ -79,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
}
+3 -1
View File
@@ -61,7 +61,9 @@ namespace ShrinkEventBus
QueueFull = 2,
Canceled = 3,
HandlerException = 4,
InvalidEvent = 5
InvalidEvent = 5,
DeferredUnsupported = 6,
SchedulerRejected = 7
}
public readonly struct ShrinkPostResult
+37
View File
@@ -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; }
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0dd120bc74194af29d7cbd1f8c80c141
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: