-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageHandler.cs
More file actions
6840 lines (6375 loc) · 278 KB
/
Copy pathMessageHandler.cs
File metadata and controls
6840 lines (6375 loc) · 278 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace DxMessaging.Core
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using DxMessaging.Core.Internal;
using Helper;
using MessageBus;
using Messages;
using Pooling;
/// <summary>
/// Per-owner handler that executes registered message callbacks.
/// </summary>
/// <remarks>
/// A <see cref="MessageHandler"/> is typically created and managed by <see cref="Unity.MessagingComponent"/> in Unity.
/// Most user code interacts with the handler through <see cref="MessageRegistrationToken"/>, which stages
/// registrations and ensures correct enable/disable lifecycles.
/// </remarks>
/// <example>
/// <code>
/// // Plain .NET usage without Unity
/// var owner = new DxMessaging.Core.InstanceId(1);
/// var handler = new DxMessaging.Core.MessageHandler(owner) { active = true };
/// var token = DxMessaging.Core.MessageRegistrationToken.Create(handler);
/// _ = token.RegisterUntargeted<WorldRegenerated>((ref WorldRegenerated m) => Console.WriteLine(m.seed));
/// token.Enable();
///
/// var bus = DxMessaging.Core.MessageHandler.MessageBus;
/// var msg = new WorldRegenerated(42);
/// bus.UntargetedBroadcast(ref msg);
/// </code>
/// </example>
public sealed class MessageHandler
: IEquatable<MessageHandler>,
IComparable,
IComparable<MessageHandler>
{
/// <summary>
/// High-performance handler that receives the message by reference (no boxing/copies).
/// </summary>
public delegate void FastHandler<TMessage>(ref TMessage message)
where TMessage : IMessage;
/// <summary>
/// High-performance handler with an additional context value (e.g., target/source) by reference.
/// </summary>
public delegate void FastHandlerWithContext<TMessage>(
ref InstanceId context,
ref TMessage message
)
where TMessage : IMessage;
private static readonly object GlobalResetLock = new object();
/// <summary>
/// Global message bus used when no explicit bus is provided.
/// </summary>
private static IMessageBus _globalMessageBus;
private static MessageBus.MessageBus _defaultGlobalMessageBus = new MessageBus.MessageBus();
/// <summary>
/// Gets the process-wide <see cref="IMessageBus"/> used when no explicit bus is supplied.
/// </summary>
/// <remarks>
/// This mirrors the legacy singleton so existing code continues to function. Use
/// <see cref="SetGlobalMessageBus(Core.MessageBus.MessageBus)"/> to replace the instance (for example from a DI container) and
/// <see cref="ResetGlobalMessageBus"/> to restore the stock configuration afterwards.
/// </remarks>
public static IMessageBus MessageBus => _globalMessageBus;
/// <summary>
/// Gets the baseline global <see cref="IMessageBus"/> instance used when no custom bus is configured.
/// </summary>
/// <remarks>
/// The instance is recreated when <see cref="DxMessagingStaticState.Reset"/> runs so that domain-reload-disabled
/// environments can obtain a clean slate.
/// </remarks>
public static IMessageBus InitialGlobalMessageBus => _defaultGlobalMessageBus;
static MessageHandler()
{
ResetStatics();
}
/// <summary>
/// Reclaims empty slots and pooled collections owned by the current global message bus.
/// </summary>
/// <param name="force">
/// When true, ignores idle-age thresholds and drains shared pools to zero.
/// When false, only slots past the configured idle threshold are eligible.
/// </param>
/// <returns>Counts describing what was reclaimed.</returns>
public static IMessageBus.TrimResult TrimAll(bool force = false)
{
return MessageBus.Trim(force);
}
/// <summary>
/// Replaces the global <see cref="Core.MessageBus.MessageBus"/> instance returned by <see cref="MessageBus"/>.
/// </summary>
/// <param name="messageBus">Instance to expose globally.</param>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="messageBus"/> is <see langword="null"/>.
/// </exception>
/// <remarks>
/// This is primarily intended for integration tests or dependency injection bootstrap code. Invoke
/// <see cref="ResetGlobalMessageBus"/> when the customisation is no longer required.
/// </remarks>
public static void SetGlobalMessageBus(MessageBus.MessageBus messageBus)
{
if (messageBus == null)
{
throw new ArgumentNullException(nameof(messageBus));
}
_globalMessageBus = messageBus;
}
/// <summary>
/// Replaces the global message bus with an arbitrary <see cref="IMessageBus"/> implementation.
/// </summary>
/// <param name="messageBus">Instance to expose globally.</param>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="messageBus"/> is <see langword="null"/>.
/// </exception>
public static void SetGlobalMessageBus(IMessageBus messageBus)
{
if (messageBus == null)
{
throw new ArgumentNullException(nameof(messageBus));
}
_globalMessageBus = messageBus;
}
/// <summary>
/// Restores the global <see cref="Core.MessageBus.MessageBus"/> to the built-in default instance.
/// </summary>
/// <remarks>
/// The default instance is recreated by <see cref="ResetStatics"/> when the static state reset utility runs.
/// </remarks>
public static void ResetGlobalMessageBus()
{
lock (GlobalResetLock)
{
_globalMessageBus = _defaultGlobalMessageBus;
}
}
/// <summary>
/// Temporarily overrides the global message bus until the returned scope is disposed.
/// </summary>
/// <param name="messageBus">Message bus to expose for the duration of the scope.</param>
/// <returns>An <see cref="IDisposable"/> scope that restores the previous bus on dispose.</returns>
public static GlobalMessageBusScope OverrideGlobalMessageBus(IMessageBus messageBus)
{
return new GlobalMessageBusScope(messageBus);
}
/// <summary>
/// Recreates the built-in global <see cref="Core.MessageBus.MessageBus"/> and assigns it as the active global bus.
/// </summary>
/// <remarks>
/// Invoked by <see cref="DxMessagingStaticState.Reset"/> to provide a clean slate when domain reloads are disabled.
/// </remarks>
internal static void ResetStatics()
{
lock (GlobalResetLock)
{
_defaultGlobalMessageBus.ResetState();
_globalMessageBus = _defaultGlobalMessageBus;
}
}
/// <summary>
/// Represents a disposable override scope for the global message bus.
/// </summary>
public struct GlobalMessageBusScope : IDisposable
{
private readonly IMessageBus _previous;
private bool _disposed;
internal GlobalMessageBusScope(IMessageBus messageBus)
{
if (messageBus == null)
{
throw new ArgumentNullException(nameof(messageBus));
}
_previous = MessageBus;
_disposed = false;
if (messageBus is MessageBus.MessageBus concrete)
{
SetGlobalMessageBus(concrete);
}
else
{
SetGlobalMessageBus(messageBus);
}
}
/// <summary>
/// Restores the previously active global message bus when the scope ends.
/// </summary>
public void Dispose()
{
if (_disposed)
{
return;
}
if (_previous is MessageBus.MessageBus concrete)
{
SetGlobalMessageBus(concrete);
}
else if (_previous != null)
{
SetGlobalMessageBus(_previous);
}
else
{
ResetGlobalMessageBus();
}
_disposed = true;
}
}
/// <summary>
/// Whether this MessageHandler will process messages.
/// </summary>
public bool active;
/// <summary>
/// The Id of the GameObject that owns us.
/// </summary>
public readonly InstanceId owner;
/// <summary>
/// Maps Types to the corresponding Handler of that type.
/// </summary>
/// <note>
/// Ideally, this would be something like a Dictionary[T, Handler[T]], but that can't be done with C#s type system.
/// </note>
internal readonly List<MessageCache<object>> _handlersByTypeByMessageBus;
private IMessageBus _defaultMessageBus;
/// <summary>
/// Gets the <see cref="IMessageBus"/> that will be used when a registration does not specify one explicitly.
/// </summary>
/// <remarks>
/// When no override has been provided via <see cref="SetDefaultMessageBus"/>, this value defers to the global
/// <see cref="MessageBus"/> singleton.
/// </remarks>
public IMessageBus DefaultMessageBus => _defaultMessageBus ?? MessageBus;
/// <summary>
/// Initializes a message handler bound to the specified owner and optional default bus.
/// </summary>
/// <param name="owner">Identity of the object that owns this handler.</param>
/// <param name="defaultMessageBus">
/// Preferred bus to use when registrations do not specify one. Falls back to
/// <see cref="MessageBus"/> if omitted.
/// </param>
public MessageHandler(InstanceId owner, IMessageBus defaultMessageBus = null)
{
this.owner = owner;
_handlersByTypeByMessageBus = new List<MessageCache<object>>();
_defaultMessageBus = defaultMessageBus;
}
/// <summary>
/// Assigns an <see cref="IMessageBus"/> for registrations that omit an explicit bus parameter.
/// </summary>
/// <param name="messageBus">
/// Bus to use; pass <see langword="null"/> to revert to the global <see cref="MessageBus"/> singleton.
/// </param>
/// <remarks>
/// This allows a handler to participate in dependency injection scenarios without forcing every caller to supply
/// a bus manually.
/// </remarks>
public void SetDefaultMessageBus(IMessageBus messageBus)
{
_defaultMessageBus = messageBus;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private IMessageBus ResolveMessageBus(IMessageBus messageBus)
{
return messageBus ?? _defaultMessageBus ?? MessageBus;
}
/// <summary>
/// Callback from the MessageBus for handling Messages when this MessageHandler has subscribed to GlobalAcceptAll - user code should generally never use this.
/// </summary>
/// <param name="message">Message to handle.</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
internal void HandleGlobalUntargetedMessage(
ref IUntargetedMessage message,
IMessageBus messageBus
)
{
if (!active)
{
return;
}
// Use the "IMessage" explicitly to indicate global messages, allowing us to multipurpose a single dictionary
if (GetHandlerForType(messageBus, out TypedHandler<IMessage> handler))
{
long emissionId = messageBus.EmissionId;
handler.HandleGlobalUntargeted(ref message, emissionId);
}
}
/// <summary>
/// Pre-freezes this handler's GlobalAcceptAll untargeted caches for this emission.
/// </summary>
internal void PrefreezeGlobalUntargetedForEmission(long emissionId, IMessageBus messageBus)
{
if (!GetHandlerForType(messageBus, out TypedHandler<IMessage> handler))
{
return;
}
HandlerActionCache<FastHandler<IUntargetedMessage>> fastCache = handler.GetGlobalCache<
FastHandler<IUntargetedMessage>
>(TypedGlobalSlotIndex.UntargetedFast);
if (fastCache != null)
{
_ = TypedHandler<IMessage>.GetOrAddNewHandlerStack(fastCache, emissionId);
}
HandlerActionCache<Action<IUntargetedMessage>> cache = handler.GetGlobalCache<
Action<IUntargetedMessage>
>(TypedGlobalSlotIndex.UntargetedDefault);
if (cache != null)
{
_ = TypedHandler<IMessage>.GetOrAddNewHandlerStack(cache, emissionId);
}
}
/// <summary>
/// Pre-freezes this handler's GlobalAcceptAll targeted caches for this emission.
/// </summary>
internal void PrefreezeGlobalTargetedForEmission(long emissionId, IMessageBus messageBus)
{
if (!GetHandlerForType(messageBus, out TypedHandler<IMessage> handler))
{
return;
}
HandlerActionCache<FastHandlerWithContext<ITargetedMessage>> fastCache =
handler.GetGlobalCache<FastHandlerWithContext<ITargetedMessage>>(
TypedGlobalSlotIndex.TargetedFast
);
if (fastCache != null)
{
_ = TypedHandler<IMessage>.GetOrAddNewHandlerStack(fastCache, emissionId);
}
HandlerActionCache<Action<InstanceId, ITargetedMessage>> cache = handler.GetGlobalCache<
Action<InstanceId, ITargetedMessage>
>(TypedGlobalSlotIndex.TargetedDefault);
if (cache != null)
{
_ = TypedHandler<IMessage>.GetOrAddNewHandlerStack(cache, emissionId);
}
}
/// <summary>
/// Pre-freezes this handler's GlobalAcceptAll broadcast caches for this emission.
/// </summary>
internal void PrefreezeGlobalBroadcastForEmission(long emissionId, IMessageBus messageBus)
{
if (!GetHandlerForType(messageBus, out TypedHandler<IMessage> handler))
{
return;
}
HandlerActionCache<FastHandlerWithContext<IBroadcastMessage>> fastCache =
handler.GetGlobalCache<FastHandlerWithContext<IBroadcastMessage>>(
TypedGlobalSlotIndex.BroadcastFast
);
if (fastCache != null)
{
_ = TypedHandler<IMessage>.GetOrAddNewHandlerStack(fastCache, emissionId);
}
HandlerActionCache<Action<InstanceId, IBroadcastMessage>> cache =
handler.GetGlobalCache<Action<InstanceId, IBroadcastMessage>>(
TypedGlobalSlotIndex.BroadcastDefault
);
if (cache != null)
{
_ = TypedHandler<IMessage>.GetOrAddNewHandlerStack(cache, emissionId);
}
}
/// <summary>
/// Callback from the MessageBus for handling Messages when this MessageHandler has subscribed to GlobalAcceptAll - user code should generally never use this.
/// </summary>
/// <param name="target">Target of the message.</param>
/// <param name="message">Message to handle.</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
internal void HandleGlobalTargetedMessage(
ref InstanceId target,
ref ITargetedMessage message,
IMessageBus messageBus
)
{
if (!active)
{
return;
}
// Use the "IMessage" explicitly to indicate global messages, allowing us to multipurpose a single dictionary
if (GetHandlerForType(messageBus, out TypedHandler<IMessage> handler))
{
long emissionId = messageBus.EmissionId;
handler.HandleGlobalTargeted(ref target, ref message, emissionId);
}
}
/// <summary>
/// Callback from the MessageBus for handling Messages when this MessageHandler has subscribed to GlobalAcceptAll - user code should generally never use this.
/// </summary>
/// <param name="source">Source that this message is from.</param>
/// <param name="message">Message to handle.</param>
/// <param name="messageBus">The specific MessageBus to use.</param>
internal void HandleGlobalSourcedBroadcastMessage(
ref InstanceId source,
ref IBroadcastMessage message,
IMessageBus messageBus
)
{
if (!active)
{
return;
}
// Use the "IMessage" explicitly to indicate global messages, allowing us to multipurpose a single dictionary
if (GetHandlerForType(messageBus, out TypedHandler<IMessage> handler))
{
long emissionId = messageBus.EmissionId;
handler.HandleGlobalBroadcast(ref source, ref message, emissionId);
}
}
/// <summary>
/// Reference-identity teardown base used by token lifecycle queues. The common
/// token path is implemented by the token's existing Registration object with
/// value-type state returned from MessageHandler; concrete wrappers below are
/// reserved for direct handler compatibility and overlapping retry spills.
/// </summary>
/// <remarks>
/// The implicit conversion to <see cref="Action"/> exists so the
/// handful of internal callers (contract tests through the
/// bus<->handler boundary) that stored the old <see cref="Action"/>
/// continue to compile unchanged; it allocates a single delegate ONLY
/// when a caller explicitly requests the <see cref="Action"/> form, and
/// is never used on the token's common storage path.
/// </remarks>
internal abstract class HandlerDeregistration
{
internal abstract void Deregister();
public static implicit operator Action(HandlerDeregistration deregistration)
{
return deregistration == null ? null : deregistration.Deregister;
}
}
/// <summary>
/// Teardown for the interceptor facades: the bus-side registration is
/// the only thing to undo (there is no typed-handler cache entry).
/// Mirrors the old <c>() => messageBus.Deregister<T>(in registration)</c>.
/// </summary>
internal readonly struct InterceptorDeregistrationState<T>
where T : IMessage
{
private readonly IMessageBus _messageBus;
private readonly MessageBusRegistration _registration;
internal InterceptorDeregistrationState(
IMessageBus messageBus,
in MessageBusRegistration registration
)
{
_messageBus = messageBus;
_registration = registration;
}
internal void Deregister()
{
_messageBus.Deregister<T>(in _registration);
}
public static implicit operator HandlerDeregistration(
InterceptorDeregistrationState<T> state
)
{
return new InterceptorDeregistration<T>(state);
}
public static implicit operator Action(InterceptorDeregistrationState<T> state)
{
InterceptorDeregistration<T> deregistration = new(state);
return deregistration.Deregister;
}
}
internal sealed class InterceptorDeregistration<T> : HandlerDeregistration
where T : IMessage
{
private readonly InterceptorDeregistrationState<T> _state;
internal InterceptorDeregistration(InterceptorDeregistrationState<T> state)
{
_state = state;
}
internal override void Deregister()
{
_state.Deregister();
}
}
/// <summary>
/// Value teardown for one typed global handler slot. Captures the old closure's
/// reset/slot guards, erased cache identity, refcount key, and touch/live-count state.
/// </summary>
internal readonly struct GlobalHandlerDeregistrationState
{
private readonly IMessageBus _messageBus;
private readonly long _resetGeneration;
private readonly TypedGlobalSlot _slot;
private readonly long _slotVersion;
private readonly IHandlerActionCache _cache;
private readonly object _originalHandler;
internal GlobalHandlerDeregistrationState(
IMessageBus messageBus,
long resetGeneration,
TypedGlobalSlot slot,
long slotVersion,
IHandlerActionCache cache,
object originalHandler
)
{
_messageBus = messageBus;
_resetGeneration = resetGeneration;
_slot = slot;
_slotVersion = slotVersion;
_cache = cache;
_originalHandler = originalHandler;
}
internal void Deregister()
{
if (
!global::DxMessaging.Core.MessageBus.MessageBus.IsResetGenerationCurrent(
_messageBus,
_resetGeneration
)
|| _slot.version != _slotVersion
|| !_cache.ContainsEntry(_originalHandler)
)
{
return;
}
_cache.BumpVersion();
_slot.lastTouchTicks =
global::DxMessaging.Core.MessageBus.MessageBus.GetCurrentTouchTick(_messageBus);
_ = _cache.DeregisterEntry(_originalHandler, out bool wasLastForEntry);
if (wasLastForEntry)
{
_slot.liveCount--;
}
}
}
/// <summary>
/// Composite teardown for the global accept-all registration: undoes the
/// bus-side global registration then the three typed sub-handler
/// deregistrations, preserving the exact order of the old closure
/// (<c>messageBus.Deregister<IMessage>(...); untargeted(); targeted(); broadcast();</c>).
/// </summary>
internal readonly struct GlobalAcceptAllDeregistrationState
{
private readonly IMessageBus _messageBus;
private readonly MessageBusRegistration _messageBusRegistration;
private readonly GlobalHandlerDeregistrationState _untargetedDeregistration;
private readonly GlobalHandlerDeregistrationState _targetedDeregistration;
private readonly GlobalHandlerDeregistrationState _broadcastDeregistration;
internal GlobalAcceptAllDeregistrationState(
IMessageBus messageBus,
in MessageBusRegistration messageBusRegistration,
GlobalHandlerDeregistrationState untargetedDeregistration,
GlobalHandlerDeregistrationState targetedDeregistration,
GlobalHandlerDeregistrationState broadcastDeregistration
)
{
_messageBus = messageBus;
_messageBusRegistration = messageBusRegistration;
_untargetedDeregistration = untargetedDeregistration;
_targetedDeregistration = targetedDeregistration;
_broadcastDeregistration = broadcastDeregistration;
}
internal void Deregister()
{
_messageBus.Deregister<IMessage>(in _messageBusRegistration);
_untargetedDeregistration.Deregister();
_targetedDeregistration.Deregister();
_broadcastDeregistration.Deregister();
}
public static implicit operator HandlerDeregistration(
GlobalAcceptAllDeregistrationState state
)
{
return new GlobalAcceptAllDeregistration(state);
}
public static implicit operator Action(GlobalAcceptAllDeregistrationState state)
{
GlobalAcceptAllDeregistration deregistration = new(state);
return deregistration.Deregister;
}
}
internal sealed class GlobalAcceptAllDeregistration : HandlerDeregistration
{
private readonly GlobalAcceptAllDeregistrationState _state;
internal GlobalAcceptAllDeregistration(GlobalAcceptAllDeregistrationState state)
{
_state = state;
}
internal override void Deregister()
{
_state.Deregister();
}
}
/// <summary>
/// Registers this MessageHandler to Globally Accept All Messages via the MessageBus, properly handling deregistration.
/// </summary>
/// <param name="untargetedMessageHandler">MessageHandler to accept all UntargetedMessages.</param>
/// <param name="broadcastMessageHandler">MessageHandler to accept all TargetedMessages for all entities.</param>
/// <param name="targetedMessageHandler">MessageHandler to accept all BroadcastMessages for all entities.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
internal GlobalAcceptAllDeregistrationState RegisterGlobalAcceptAll(
Action<IUntargetedMessage> originalUntargetedMessageHandler,
Action<IUntargetedMessage> untargetedMessageHandler,
Action<InstanceId, ITargetedMessage> originalTargetedMessageHandler,
Action<InstanceId, ITargetedMessage> targetedMessageHandler,
Action<InstanceId, IBroadcastMessage> originalBroadcastMessageHandler,
Action<InstanceId, IBroadcastMessage> broadcastMessageHandler,
IMessageBus messageBus = null
)
{
messageBus = ResolveMessageBus(messageBus);
MessageBusRegistration messageBusDeregistration = messageBus.RegisterGlobalAcceptAll(
this
);
TypedHandler<IMessage> typedHandler = GetOrCreateHandlerForType<IMessage>(messageBus);
GlobalHandlerDeregistrationState untargetedDeregistration =
typedHandler.AddGlobalUntargetedHandler(
originalUntargetedMessageHandler,
untargetedMessageHandler,
messageBus
);
GlobalHandlerDeregistrationState targetedDeregistration =
typedHandler.AddGlobalTargetedHandler(
originalTargetedMessageHandler,
targetedMessageHandler,
messageBus
);
GlobalHandlerDeregistrationState broadcastDeregistration =
typedHandler.AddGlobalBroadcastHandler(
originalBroadcastMessageHandler,
broadcastMessageHandler,
messageBus
);
return new GlobalAcceptAllDeregistrationState(
messageBus,
in messageBusDeregistration,
untargetedDeregistration,
targetedDeregistration,
broadcastDeregistration
);
}
/// <summary>
/// Registers this MessageHandler to Globally Accept All Messages via the MessageBus, properly handling deregistration.
/// </summary>
/// <param name="untargetedMessageHandler">MessageHandler to accept all UntargetedMessages.</param>
/// <param name="broadcastMessageHandler">MessageHandler to accept all TargetedMessages for all entities.</param>
/// <param name="targetedMessageHandler">MessageHandler to accept all BroadcastMessages for all entities.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
internal GlobalAcceptAllDeregistrationState RegisterGlobalAcceptAll(
FastHandler<IUntargetedMessage> originalUntargetedMessageHandler,
FastHandler<IUntargetedMessage> untargetedMessageHandler,
FastHandlerWithContext<ITargetedMessage> originalTargetedMessageHandler,
FastHandlerWithContext<ITargetedMessage> targetedMessageHandler,
FastHandlerWithContext<IBroadcastMessage> originalBroadcastMessageHandler,
FastHandlerWithContext<IBroadcastMessage> broadcastMessageHandler,
IMessageBus messageBus = null
)
{
messageBus = ResolveMessageBus(messageBus);
MessageBusRegistration messageBusDeregistration = messageBus.RegisterGlobalAcceptAll(
this
);
TypedHandler<IMessage> typedHandler = GetOrCreateHandlerForType<IMessage>(messageBus);
GlobalHandlerDeregistrationState untargetedDeregistration =
typedHandler.AddGlobalUntargetedHandler(
originalUntargetedMessageHandler,
untargetedMessageHandler,
messageBus
);
GlobalHandlerDeregistrationState targetedDeregistration =
typedHandler.AddGlobalTargetedHandler(
originalTargetedMessageHandler,
targetedMessageHandler,
messageBus
);
GlobalHandlerDeregistrationState broadcastDeregistration =
typedHandler.AddGlobalBroadcastHandler(
originalBroadcastMessageHandler,
broadcastMessageHandler,
messageBus
);
return new GlobalAcceptAllDeregistrationState(
messageBus,
in messageBusDeregistration,
untargetedDeregistration,
targetedDeregistration,
broadcastDeregistration
);
}
/// <summary>
/// Registers this MessageHandler to accept TargetedMessages via the MessageBus, properly handling deregistration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="target">Target Id of TargetedMessages to listen for.</param>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="priority">Priority at which to run the handler, lower runs earlier than higher.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
internal TypedHandler<T>.TypedHandlerDeregistrationState RegisterTargetedMessageHandler<T>(
InstanceId target,
Action<T> originalHandler,
Action<T> messageHandler,
int priority = 0,
IMessageBus messageBus = null
)
where T : ITargetedMessage
{
messageBus = ResolveMessageBus(messageBus);
MessageBusRegistration messageBusDeregistration = messageBus.RegisterTargeted<T>(
target,
this,
priority: priority
);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddTargetedHandler(
target,
originalHandler,
messageHandler,
messageBusDeregistration,
priority,
messageBus
);
}
/// <summary>
/// Registers a targeted handler whose diagnostics-augmented by-ref flat
/// invoker was already built by the caller (the registration token), so the
/// default slot stores a single closure instead of an <see cref="Action{T}"/>
/// wrapper plus a separately allocated FastHandler adapter.
/// <paramref name="originalHandler"/> stays the dedup/identity key.
/// </summary>
internal TypedHandler<T>.TypedHandlerDeregistrationState RegisterTargetedMessageHandler<T>(
InstanceId target,
Action<T> originalHandler,
FastHandler<T> flatInvoker,
int priority = 0,
IMessageBus messageBus = null
)
where T : ITargetedMessage
{
messageBus = ResolveMessageBus(messageBus);
MessageBusRegistration messageBusDeregistration = messageBus.RegisterTargeted<T>(
target,
this,
priority: priority
);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddTargetedHandler(
target,
originalHandler,
flatInvoker,
messageBusDeregistration,
priority,
messageBus
);
}
/// <summary>
/// Registers this MessageHandler to accept fast TargetedMessages via the MessageBus, properly handling deregistration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="target">Target Id of TargetedMessages to listen for.</param>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="priority">Priority at which to run the handler, lower runs earlier than higher.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
internal TypedHandler<T>.TypedHandlerDeregistrationState RegisterTargetedMessageHandler<T>(
InstanceId target,
FastHandler<T> originalHandler,
FastHandler<T> messageHandler,
int priority = 0,
IMessageBus messageBus = null
)
where T : ITargetedMessage
{
messageBus = ResolveMessageBus(messageBus);
MessageBusRegistration messageBusDeregistration = messageBus.RegisterTargeted<T>(
target,
this,
priority: priority
);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddTargetedHandler(
target,
originalHandler,
messageHandler,
messageBusDeregistration,
priority,
messageBus
);
}
/// <summary>
/// Registers this MessageHandler to post process TargetedMessages via the MessageBus, properly handling deregistration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="target">Target Id of TargetedMessages to listen for.</param>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="priority">Priority at which to run the handler, lower runs earlier than higher.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
internal TypedHandler<T>.TypedHandlerDeregistrationState RegisterTargetedPostProcessor<T>(
InstanceId target,
Action<T> originalHandler,
Action<T> messageHandler,
int priority = 0,
IMessageBus messageBus = null
)
where T : ITargetedMessage
{
messageBus = ResolveMessageBus(messageBus);
MessageBusRegistration messageBusDeregistration =
messageBus.RegisterTargetedPostProcessor<T>(target, this, priority);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddTargetedPostProcessor(
target,
originalHandler,
messageHandler,
messageBusDeregistration,
priority,
messageBus
);
}
/// <summary>
/// Registers this MessageHandler to post process fast TargetedMessages via the MessageBus, properly handling deregistration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="target">Target Id of TargetedMessages to listen for.</param>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="priority">Priority at which to run the handler, lower runs earlier than higher.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
internal TypedHandler<T>.TypedHandlerDeregistrationState RegisterTargetedPostProcessor<T>(
InstanceId target,
FastHandler<T> originalHandler,
FastHandler<T> messageHandler,
int priority = 0,
IMessageBus messageBus = null
)
where T : ITargetedMessage
{
messageBus = ResolveMessageBus(messageBus);
MessageBusRegistration messageBusDeregistration =
messageBus.RegisterTargetedPostProcessor<T>(target, this, priority: priority);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddTargetedPostProcessor(
target,
originalHandler,
messageHandler,
messageBusDeregistration,
priority,
messageBus
);
}
/// <summary>
/// Registers a targeted post-processor whose diagnostics-augmented by-ref flat
/// invoker was already built by the caller (the registration token), so the
/// default slot stores a single closure instead of an <see cref="Action{T}"/>
/// wrapper plus a separately allocated FastHandler adapter.
/// <paramref name="originalHandler"/> stays the dedup/identity key.
/// </summary>
internal TypedHandler<T>.TypedHandlerDeregistrationState RegisterTargetedPostProcessor<T>(
InstanceId target,
Action<T> originalHandler,
FastHandler<T> flatInvoker,
int priority = 0,
IMessageBus messageBus = null
)
where T : ITargetedMessage
{
messageBus = ResolveMessageBus(messageBus);
MessageBusRegistration messageBusDeregistration =
messageBus.RegisterTargetedPostProcessor<T>(target, this, priority);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddTargetedPostProcessor(
target,
originalHandler,
flatInvoker,
messageBusDeregistration,
priority,
messageBus
);
}
/// <summary>
/// Registers this MessageHandler to post-process TargetedMessages for all messages of the provided type via the MessageBus, properly handling deregistration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="priority">Priority at which to run the handler, lower runs earlier than higher.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
internal TypedHandler<T>.TypedHandlerDeregistrationState RegisterTargetedWithoutTargetingPostProcessor<T>(
Action<InstanceId, T> originalHandler,
Action<InstanceId, T> messageHandler,
int priority = 0,
IMessageBus messageBus = null
)
where T : ITargetedMessage
{
messageBus = ResolveMessageBus(messageBus);
MessageBusRegistration messageBusDeregistration =
messageBus.RegisterTargetedWithoutTargetingPostProcessor<T>(
priority: priority,
messageHandler: this
);
TypedHandler<T> typedHandler = GetOrCreateHandlerForType<T>(messageBus);
return typedHandler.AddTargetedWithoutTargetingPostProcessor(
originalHandler,
messageHandler,
messageBusDeregistration,
priority,
messageBus
);
}
/// <summary>
/// Registers this MessageHandler to post process fast TargetedMessages for all messages of the provided type via the MessageBus, properly handling deregistration.
/// </summary>
/// <typeparam name="T">Type of Message to be handled.</typeparam>
/// <param name="messageHandler">Function that actually handles the message.</param>
/// <param name="priority">Priority at which to run the handler, lower runs earlier than higher.</param>
/// <param name="messageBus">IMessageBus override to register with, if any. Null/not provided defaults to the GlobalMessageBus.</param>
/// <returns>The de-registration action.</returns>
internal TypedHandler<T>.TypedHandlerDeregistrationState RegisterTargetedWithoutTargetingPostProcessor<T>(
FastHandlerWithContext<T> originalHandler,
FastHandlerWithContext<T> messageHandler,
int priority = 0,
IMessageBus messageBus = null
)
where T : ITargetedMessage
{
messageBus = ResolveMessageBus(messageBus);