< Summary

Class:DCL.MessagingControllersManager
Assembly:DCL.Runtime
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/Messaging/MessagingControllersManager.cs
Covered lines:135
Uncovered lines:17
Coverable lines:152
Total lines:356
Line coverage:88.8% (135 of 152)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
MessagingControllersManager(...)0%110100%
Initialize()0%440100%
MarkBusesDirty()0%110100%
PopulateBusesToBeProcessed()0%2020098%
Dispose()0%440100%
ContainsController(...)0%110100%
AddController(...)0%550100%
AddControllerIfNotExists(...)0%220100%
RemoveController(...)0%220100%
DisposeController(...)0%110100%
Enqueue(...)0%2100%
ForceEnqueueToGlobal(...)0%110100%
SetSceneReady(...)0%3.192033.33%
ProcessMessages()0%12.5712084.21%
ProcessBus(...)0%4.024090%
RefreshControllerEnabledState(...)0%8.36060%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/Messaging/MessagingControllersManager.cs

#LineLine coverage
 1using DCL.Controllers;
 2using System.Collections;
 3using System.Collections.Concurrent;
 4using System.Collections.Generic;
 5using MainScripts.DCL.Analytics.PerformanceAnalytics;
 6using UnityEngine;
 7
 8namespace DCL
 9{
 10    public class MessagingControllersManager : IMessagingControllersManager
 11    {
 12        public static bool VERBOSE = false;
 13
 14        private const float MAX_GLOBAL_MSG_BUDGET = 0.02f;
 15        private const float MAX_SYSTEM_MSG_BUDGET_FOR_FAR_SCENES = 0.003f;
 16
 17        private const float GLTF_BUDGET_MAX = 0.033f;
 18        private const float GLTF_BUDGET_MIN = 0.008f;
 19
 20        public const string GLOBAL_MESSAGING_CONTROLLER = "global_messaging_controller";
 21
 408122        public ConcurrentDictionary<string, MessagingController> messagingControllers { get; set; } =
 66723            new ConcurrentDictionary<string, MessagingController>();
 24
 25        private Coroutine mainCoroutine;
 26
 2727        public bool hasPendingMessages => pendingMessagesCount > 0;
 28
 66729        public float timeBudgetCounter = MAX_GLOBAL_MSG_BUDGET;
 5430        public long processedInitMessagesCount { get; set; }
 22531        public int pendingMessagesCount { get; set; }
 3252132        public int pendingInitMessagesCount { get; set; }
 33
 034        public bool isRunning => mainCoroutine != null;
 35
 3245736        public bool paused { get; set; }
 37
 66738        private readonly ConcurrentDictionary<string, MessagingController> globalSceneControllers =
 39            new ConcurrentDictionary<string, MessagingController>();
 40
 66741        private readonly List<MessagingController> sortedControllers = new List<MessagingController>();
 66742        private readonly List<MessagingBus> busesToProcess = new List<MessagingBus>();
 43        private int busesToProcessCount = 0;
 44        private int sortedControllersCount = 0;
 45
 46        private MessagingController globalController = null;
 47        private MessagingController currentSceneController = null;
 48
 49        private IMessageProcessHandler messageHandler;
 50
 66751        public MessagingControllersManager(IMessageProcessHandler messageHandler = null)
 52        {
 66753            this.messageHandler = messageHandler;
 66754        }
 55
 56        public void Initialize()
 57        {
 66058            if (messageHandler == null)
 66059                messageHandler = Environment.i.world.sceneController;
 60
 66061            messagingControllers[GLOBAL_MESSAGING_CONTROLLER] =
 62                new MessagingController(this, messageHandler, GLOBAL_MESSAGING_CONTROLLER);
 63
 66064            if (!string.IsNullOrEmpty(GLOBAL_MESSAGING_CONTROLLER))
 66065                messagingControllers.TryGetValue(GLOBAL_MESSAGING_CONTROLLER, out globalController);
 66
 66067            Environment.i.world.sceneController.OnSortScenes += MarkBusesDirty;
 68
 66069            if (mainCoroutine == null)
 70            {
 66071                mainCoroutine = CoroutineStarter.Start(ProcessMessages());
 72            }
 66073        }
 74
 66775        bool populateBusesDirty = true;
 76
 77        public void MarkBusesDirty()
 78        {
 71179            populateBusesDirty = true;
 71180        }
 81
 82        public void PopulateBusesToBeProcessed()
 83        {
 137184            lock (sortedControllers)
 137185            lock (busesToProcess)
 86            {
 137187                IWorldState worldState = Environment.i.world.state;
 137188                string currentSceneId = worldState.GetCurrentSceneId();
 137189                var scenesSortedByDistance = worldState.GetScenesSortedByDistance();
 90
 137191                int count = scenesSortedByDistance.Count; // we need to retrieve list count everytime because it
 92                // may change after a yield return
 93
 137194                sortedControllers.Clear();
 95
 137196                if (!string.IsNullOrEmpty(currentSceneId) && messagingControllers.ContainsKey(currentSceneId))
 1197                    currentSceneController = messagingControllers[currentSceneId];
 98
 313499                for (int i = 0; i < count; i++)
 100                {
 196101                    string controllerId = scenesSortedByDistance[i].sceneData.id;
 102
 196103                    if (controllerId != currentSceneId)
 104                    {
 147105                        if (!messagingControllers.ContainsKey(controllerId))
 106                            continue;
 107
 145108                        sortedControllers.Add(messagingControllers[controllerId]);
 109                    }
 110                }
 111
 1371112                sortedControllersCount = sortedControllers.Count;
 113
 1371114                bool globalSceneControllerActive = globalSceneControllers.Count > 0;
 1371115                bool globalControllerActive = globalController != null && globalController.enabled;
 1371116                bool currentSceneControllerActive = currentSceneController != null && currentSceneController.enabled;
 117
 1371118                bool atLeastOneControllerShouldBeProcessed = globalSceneControllerActive || globalControllerActive ||
 119                                                             currentSceneControllerActive || sortedControllersCount > 0;
 120
 1371121                if (!atLeastOneControllerShouldBeProcessed)
 0122                    return;
 123
 1371124                busesToProcess.Clear();
 125
 126                //-------------------------------------------------------------------------------------------
 127                // Global scenes
 1371128                using (var globalScenecontrollersIterator = globalSceneControllers.GetEnumerator())
 129                {
 1377130                    while (globalScenecontrollersIterator.MoveNext())
 131                    {
 6132                        busesToProcess.Add(globalScenecontrollersIterator.Current.Value.uiBus);
 6133                        busesToProcess.Add(globalScenecontrollersIterator.Current.Value.initBus);
 6134                        busesToProcess.Add(globalScenecontrollersIterator.Current.Value.systemBus);
 135                    }
 1371136                }
 137
 1371138                if (globalControllerActive)
 139                {
 1367140                    busesToProcess.Add(globalController.initBus);
 141                }
 142
 1371143                if (currentSceneControllerActive)
 144                {
 12145                    busesToProcess.Add(currentSceneController.initBus);
 12146                    busesToProcess.Add(currentSceneController.uiBus);
 12147                    busesToProcess.Add(currentSceneController.systemBus);
 148                }
 149
 3032150                for (int i = 0; i < sortedControllersCount; ++i)
 151                {
 145152                    MessagingController msgController = sortedControllers[i];
 153
 145154                    busesToProcess.Add(msgController.initBus);
 145155                    busesToProcess.Add(msgController.uiBus);
 156                }
 157
 3032158                for (int i = 0; i < sortedControllersCount; ++i)
 159                {
 145160                    MessagingController msgController = sortedControllers[i];
 145161                    busesToProcess.Add(msgController.systemBus);
 162                }
 163
 1371164                busesToProcessCount = busesToProcess.Count;
 1371165            }
 1371166        }
 167
 168        public void Dispose()
 169        {
 660170            if (mainCoroutine != null)
 171            {
 660172                CoroutineStarter.Stop(mainCoroutine);
 660173                mainCoroutine = null;
 174            }
 175
 660176            using (var controllersIterator = messagingControllers.GetEnumerator())
 177            {
 1320178                while (controllersIterator.MoveNext())
 179                {
 660180                    controllersIterator.Current.Value.Stop();
 660181                    DisposeController(controllersIterator.Current.Value);
 182                }
 660183            }
 184
 660185            Environment.i.world.sceneController.OnSortScenes -= PopulateBusesToBeProcessed;
 186
 660187            messagingControllers.Clear();
 660188        }
 189
 190        public bool ContainsController(string sceneId)
 191        {
 31192            return messagingControllers.ContainsKey(sceneId);
 193        }
 194
 195        public void AddController(IMessageProcessHandler messageHandler, string sceneId, bool isGlobal = false)
 196        {
 31197            if (!messagingControllers.ContainsKey(sceneId))
 198            {
 31199                messagingControllers.TryAdd(sceneId, new MessagingController(this, messageHandler, sceneId));
 200            }
 201
 31202            if (isGlobal && !string.IsNullOrEmpty(sceneId))
 203            {
 5204                messagingControllers.TryGetValue(sceneId, out MessagingController newGlobalSceneController);
 205
 5206                if (!globalSceneControllers.ContainsKey(sceneId))
 5207                    globalSceneControllers.TryAdd(sceneId, newGlobalSceneController);
 208            }
 209
 31210            PopulateBusesToBeProcessed();
 31211        }
 212
 213        public void AddControllerIfNotExists(IMessageProcessHandler messageHandler, string sceneId,
 214            bool isGlobal = false)
 215        {
 31216            if (!ContainsController(sceneId))
 31217                AddController(messageHandler, sceneId, isGlobal);
 31218        }
 219
 220        public void RemoveController(string sceneId)
 221        {
 419222            if (messagingControllers.ContainsKey(sceneId))
 223            {
 224                // In case there is any pending message from a scene being unloaded we decrease the count accordingly
 31225                pendingMessagesCount -= messagingControllers[sceneId].messagingBuses[MessagingBusType.INIT]
 226                                            .pendingMessagesCount +
 227                                        messagingControllers[sceneId].messagingBuses[MessagingBusType.UI]
 228                                            .pendingMessagesCount +
 229                                        messagingControllers[sceneId].messagingBuses[MessagingBusType.SYSTEM]
 230                                            .pendingMessagesCount;
 231
 31232                DisposeController(messagingControllers[sceneId]);
 31233                messagingControllers.TryRemove(sceneId, out MessagingController _);
 234            }
 235
 419236            globalSceneControllers.TryRemove(sceneId, out MessagingController _);
 419237        }
 238
 239        void DisposeController(MessagingController controller)
 240        {
 691241            controller.Stop();
 691242            controller.Dispose();
 691243        }
 244
 245        public void Enqueue(bool isUiBus, QueuedSceneMessage_Scene queuedMessage)
 246        {
 0247            PerformanceAnalytics.MessagesEnqueuedTracker.Track();
 0248            messagingControllers[queuedMessage.sceneId].Enqueue(isUiBus, queuedMessage, out MessagingBusType busId);
 0249        }
 250
 251        public void ForceEnqueueToGlobal(MessagingBusType busId, QueuedSceneMessage queuedMessage)
 252        {
 27253            PerformanceAnalytics.MessagesEnqueuedTracker.Track();
 27254            messagingControllers[GLOBAL_MESSAGING_CONTROLLER].ForceEnqueue(busId, queuedMessage);
 27255        }
 256
 257        public void SetSceneReady(string sceneId)
 258        {
 259            // Start processing SYSTEM queue
 390260            if (messagingControllers.ContainsKey(sceneId))
 261            {
 262                // Start processing SYSTEM queue
 0263                MessagingController sceneMessagingController = messagingControllers[sceneId];
 0264                sceneMessagingController.StartBus(MessagingBusType.SYSTEM);
 0265                sceneMessagingController.StartBus(MessagingBusType.UI);
 0266                sceneMessagingController.StopBus(MessagingBusType.INIT);
 267            }
 390268        }
 269
 270        IEnumerator ProcessMessages()
 271        {
 31753272            while (true)
 273            {
 32413274                if (paused)
 275                {
 0276                    yield return null;
 277
 0278                    continue;
 279                }
 280
 32413281                if (populateBusesDirty)
 282                {
 1340283                    PopulateBusesToBeProcessed();
 1340284                    populateBusesDirty = false;
 285                }
 286
 32413287                timeBudgetCounter =
 288                    CommonScriptableObjects.rendererState.Get() ? MAX_GLOBAL_MSG_BUDGET : float.MaxValue;
 289
 130076290                for (int i = 0; i < busesToProcessCount; ++i)
 291                {
 292                    MessagingBus bus;
 293
 32625294                    lock (busesToProcess)
 295                    {
 32625296                        bus = busesToProcess[i];
 32625297                    }
 298
 32625299                    if (ProcessBus(bus))
 300                        break;
 301                }
 302
 32413303                if (pendingInitMessagesCount == 0)
 304                {
 32413305                    AssetPromiseKeeper_GLTF.i.throttlingCounter.budgetPerFrameInMilliseconds =
 306                        Mathf.Clamp(timeBudgetCounter, GLTF_BUDGET_MIN, GLTF_BUDGET_MAX) * 1000f;
 307                }
 308                else
 309                {
 0310                    AssetPromiseKeeper_GLTF.i.throttlingCounter.budgetPerFrameInMilliseconds = 0;
 311                }
 312
 32413313                yield return null;
 314            }
 315        }
 316
 317        bool ProcessBus(MessagingBus bus)
 318        {
 32625319            if (!bus.enabled || bus.pendingMessagesCount <= 0)
 32618320                return false;
 321
 7322            float startTime = Time.realtimeSinceStartup;
 323
 7324            float timeBudget = timeBudgetCounter;
 325
 326            //TODO(Brian): We should use the returning yieldReturn IEnumerator and MoveNext() it manually each frame to
 327            //             account the coroutine processing into the budget. Until we do that we just skip it.
 7328            bus.ProcessQueue(timeBudget, out _);
 7329            RefreshControllerEnabledState(bus.owner);
 330
 7331            timeBudgetCounter -= Time.realtimeSinceStartup - startTime;
 332
 7333            if (timeBudgetCounter <= 0)
 0334                return true;
 335
 7336            return false;
 337        }
 338
 339        private void RefreshControllerEnabledState(MessagingController controller)
 340        {
 7341            if (controller == null || !controller.enabled)
 0342                return;
 343
 7344            if (controller.uiBus.pendingMessagesCount != 0)
 0345                return;
 346
 7347            if (controller.initBus.pendingMessagesCount != 0)
 0348                return;
 349
 7350            if (controller.systemBus.pendingMessagesCount != 0)
 0351                return;
 352
 7353            controller.enabled = false;
 7354        }
 355    }
 356}