< 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:18
Coverable lines:153
Total lines:356
Line coverage:88.2% (135 of 153)
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.4912085%
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
 022        public ConcurrentDictionary<string, MessagingController> messagingControllers { get; set; } =
 67223            new ConcurrentDictionary<string, MessagingController>();
 24
 25        private Coroutine mainCoroutine;
 26
 2727        public bool hasPendingMessages => pendingMessagesCount > 0;
 28
 67229        public float timeBudgetCounter = MAX_GLOBAL_MSG_BUDGET;
 5430        public long processedInitMessagesCount { get; set; }
 13631        public int pendingMessagesCount { get; set; }
 10832        public int pendingInitMessagesCount { get; set; }
 33
 034        public bool isRunning => mainCoroutine != null;
 35
 4436        public bool paused { get; set; }
 37
 67238        private readonly ConcurrentDictionary<string, MessagingController> globalSceneControllers =
 39            new ConcurrentDictionary<string, MessagingController>();
 40
 67241        private readonly List<MessagingController> sortedControllers = new List<MessagingController>();
 67242        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
 67251        public MessagingControllersManager(IMessageProcessHandler messageHandler = null)
 52        {
 67253            this.messageHandler = messageHandler;
 67254        }
 55
 56        public void Initialize()
 57        {
 66558            if (messageHandler == null)
 66559                messageHandler = Environment.i.world.sceneController;
 60
 66561            messagingControllers[GLOBAL_MESSAGING_CONTROLLER] =
 62                new MessagingController(this, messageHandler, GLOBAL_MESSAGING_CONTROLLER);
 63
 66564            if (!string.IsNullOrEmpty(GLOBAL_MESSAGING_CONTROLLER))
 66565                messagingControllers.TryGetValue(GLOBAL_MESSAGING_CONTROLLER, out globalController);
 66
 66567            Environment.i.world.sceneController.OnSortScenes += MarkBusesDirty;
 68
 66569            if (mainCoroutine == null)
 70            {
 66571                mainCoroutine = CoroutineStarter.Start(ProcessMessages());
 72            }
 66573        }
 74
 67275        bool populateBusesDirty = true;
 76
 77        public void MarkBusesDirty()
 78        {
 72179            populateBusesDirty = true;
 72180        }
 81
 82        public void PopulateBusesToBeProcessed()
 83        {
 138684            lock (sortedControllers)
 138685            lock (busesToProcess)
 86            {
 138687                IWorldState worldState = Environment.i.world.state;
 138688                string currentSceneId = worldState.GetCurrentSceneId();
 138689                var scenesSortedByDistance = worldState.GetScenesSortedByDistance();
 90
 138691                int count = scenesSortedByDistance.Count; // we need to retrieve list count everytime because it
 92                // may change after a yield return
 93
 138694                sortedControllers.Clear();
 95
 138696                if (!string.IsNullOrEmpty(currentSceneId) && messagingControllers.ContainsKey(currentSceneId))
 1197                    currentSceneController = messagingControllers[currentSceneId];
 98
 317499                for (int i = 0; i < count; i++)
 100                {
 201101                    string controllerId = scenesSortedByDistance[i].sceneData.id;
 102
 201103                    if (controllerId != currentSceneId)
 104                    {
 147105                        if (!messagingControllers.ContainsKey(controllerId))
 106                            continue;
 107
 145108                        sortedControllers.Add(messagingControllers[controllerId]);
 109                    }
 110                }
 111
 1386112                sortedControllersCount = sortedControllers.Count;
 113
 1386114                bool globalSceneControllerActive = globalSceneControllers.Count > 0;
 1386115                bool globalControllerActive = globalController != null && globalController.enabled;
 1386116                bool currentSceneControllerActive = currentSceneController != null && currentSceneController.enabled;
 117
 1386118                bool atLeastOneControllerShouldBeProcessed = globalSceneControllerActive || globalControllerActive ||
 119                                                             currentSceneControllerActive || sortedControllersCount > 0;
 120
 1386121                if (!atLeastOneControllerShouldBeProcessed)
 0122                    return;
 123
 1386124                busesToProcess.Clear();
 125
 126                //-------------------------------------------------------------------------------------------
 127                // Global scenes
 1386128                using (var globalScenecontrollersIterator = globalSceneControllers.GetEnumerator())
 129                {
 1392130                    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                    }
 1386136                }
 137
 1386138                if (globalControllerActive)
 139                {
 1382140                    busesToProcess.Add(globalController.initBus);
 141                }
 142
 1386143                if (currentSceneControllerActive)
 144                {
 12145                    busesToProcess.Add(currentSceneController.initBus);
 12146                    busesToProcess.Add(currentSceneController.uiBus);
 12147                    busesToProcess.Add(currentSceneController.systemBus);
 148                }
 149
 3062150                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
 3062158                for (int i = 0; i < sortedControllersCount; ++i)
 159                {
 145160                    MessagingController msgController = sortedControllers[i];
 145161                    busesToProcess.Add(msgController.systemBus);
 162                }
 163
 1386164                busesToProcessCount = busesToProcess.Count;
 1386165            }
 1386166        }
 167
 168        public void Dispose()
 169        {
 665170            if (mainCoroutine != null)
 171            {
 665172                CoroutineStarter.Stop(mainCoroutine);
 665173                mainCoroutine = null;
 174            }
 175
 665176            using (var controllersIterator = messagingControllers.GetEnumerator())
 177            {
 1330178                while (controllersIterator.MoveNext())
 179                {
 665180                    controllersIterator.Current.Value.Stop();
 665181                    DisposeController(controllersIterator.Current.Value);
 182                }
 665183            }
 184
 665185            Environment.i.world.sceneController.OnSortScenes -= PopulateBusesToBeProcessed;
 186
 665187            messagingControllers.Clear();
 665188        }
 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        {
 423222            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
 423236            globalSceneControllers.TryRemove(sceneId, out MessagingController _);
 423237        }
 238
 239        void DisposeController(MessagingController controller)
 240        {
 696241            controller.Stop();
 696242            controller.Dispose();
 696243        }
 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
 394260            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            }
 394268        }
 269
 270        IEnumerator ProcessMessages()
 271        {
 7010272            while (true)
 273            {
 7675274                if (paused)
 275                {
 0276                    yield return null;
 277
 0278                    continue;
 279                }
 280
 7675281                if (populateBusesDirty)
 282                {
 1355283                    PopulateBusesToBeProcessed();
 1355284                    populateBusesDirty = false;
 285                }
 286
 7675287                timeBudgetCounter =
 288                    CommonScriptableObjects.rendererState.Get() ? MAX_GLOBAL_MSG_BUDGET : float.MaxValue;
 289
 31124290                for (int i = 0; i < busesToProcessCount; ++i)
 291                {
 292                    MessagingBus bus;
 293
 7887294                    lock (busesToProcess)
 295                    {
 7887296                        bus = busesToProcess[i];
 7887297                    }
 298
 7887299                    if (ProcessBus(bus))
 300                        break;
 301                }
 302
 7675303                if (pendingInitMessagesCount == 0)
 304                {
 7675305                    AssetPromiseKeeper_GLTF.i.throttlingCounter.budgetPerFrameInMilliseconds =
 306                        Mathf.Clamp(timeBudgetCounter, GLTF_BUDGET_MIN, GLTF_BUDGET_MAX) * 1000f;
 7675307                }
 308                else
 309                {
 0310                    AssetPromiseKeeper_GLTF.i.throttlingCounter.budgetPerFrameInMilliseconds = 0;
 311                }
 312
 7675313                yield return null;
 314            }
 315        }
 316
 317        bool ProcessBus(MessagingBus bus)
 318        {
 7887319            if (!bus.enabled || bus.pendingMessagesCount <= 0)
 7880320                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}