< 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; } =
 67523            new ConcurrentDictionary<string, MessagingController>();
 24
 25        private Coroutine mainCoroutine;
 26
 3327        public bool hasPendingMessages => pendingMessagesCount > 0;
 28
 67529        public float timeBudgetCounter = MAX_GLOBAL_MSG_BUDGET;
 6030        public long processedInitMessagesCount { get; set; }
 14831        public int pendingMessagesCount { get; set; }
 12032        public int pendingInitMessagesCount { get; set; }
 33
 034        public bool isRunning => mainCoroutine != null;
 35
 4436        public bool paused { get; set; }
 37
 67538        private readonly ConcurrentDictionary<string, MessagingController> globalSceneControllers =
 39            new ConcurrentDictionary<string, MessagingController>();
 40
 67541        private readonly List<MessagingController> sortedControllers = new List<MessagingController>();
 67542        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
 67551        public MessagingControllersManager(IMessageProcessHandler messageHandler = null)
 52        {
 67553            this.messageHandler = messageHandler;
 67554        }
 55
 56        public void Initialize()
 57        {
 66858            if (messageHandler == null)
 66859                messageHandler = Environment.i.world.sceneController;
 60
 66861            messagingControllers[GLOBAL_MESSAGING_CONTROLLER] =
 62                new MessagingController(this, messageHandler, GLOBAL_MESSAGING_CONTROLLER);
 63
 66864            if (!string.IsNullOrEmpty(GLOBAL_MESSAGING_CONTROLLER))
 66865                messagingControllers.TryGetValue(GLOBAL_MESSAGING_CONTROLLER, out globalController);
 66
 66867            Environment.i.world.sceneController.OnSortScenes += MarkBusesDirty;
 68
 66869            if (mainCoroutine == null)
 70            {
 66871                mainCoroutine = CoroutineStarter.Start(ProcessMessages());
 72            }
 66873        }
 74
 67575        bool populateBusesDirty = true;
 76
 77        public void MarkBusesDirty()
 78        {
 72979            populateBusesDirty = true;
 72980        }
 81
 82        public void PopulateBusesToBeProcessed()
 83        {
 139884            lock (sortedControllers)
 139885            lock (busesToProcess)
 86            {
 139887                IWorldState worldState = Environment.i.world.state;
 139888                string currentSceneId = worldState.GetCurrentSceneId();
 139889                var scenesSortedByDistance = worldState.GetScenesSortedByDistance();
 90
 139891                int count = scenesSortedByDistance.Count; // we need to retrieve list count everytime because it
 92                // may change after a yield return
 93
 139894                sortedControllers.Clear();
 95
 139896                if (!string.IsNullOrEmpty(currentSceneId) && messagingControllers.ContainsKey(currentSceneId))
 1197                    currentSceneController = messagingControllers[currentSceneId];
 98
 321899                for (int i = 0; i < count; i++)
 100                {
 211101                    string controllerId = scenesSortedByDistance[i].sceneData.id;
 102
 211103                    if (controllerId != currentSceneId)
 104                    {
 151105                        if (!messagingControllers.ContainsKey(controllerId))
 106                            continue;
 107
 148108                        sortedControllers.Add(messagingControllers[controllerId]);
 109                    }
 110                }
 111
 1398112                sortedControllersCount = sortedControllers.Count;
 113
 1398114                bool globalSceneControllerActive = globalSceneControllers.Count > 0;
 1398115                bool globalControllerActive = globalController != null && globalController.enabled;
 1398116                bool currentSceneControllerActive = currentSceneController != null && currentSceneController.enabled;
 117
 1398118                bool atLeastOneControllerShouldBeProcessed = globalSceneControllerActive || globalControllerActive ||
 119                                                             currentSceneControllerActive || sortedControllersCount > 0;
 120
 1398121                if (!atLeastOneControllerShouldBeProcessed)
 0122                    return;
 123
 1398124                busesToProcess.Clear();
 125
 126                //-------------------------------------------------------------------------------------------
 127                // Global scenes
 1398128                using (var globalScenecontrollersIterator = globalSceneControllers.GetEnumerator())
 129                {
 1404130                    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                    }
 1398136                }
 137
 1398138                if (globalControllerActive)
 139                {
 1393140                    busesToProcess.Add(globalController.initBus);
 141                }
 142
 1398143                if (currentSceneControllerActive)
 144                {
 12145                    busesToProcess.Add(currentSceneController.initBus);
 12146                    busesToProcess.Add(currentSceneController.uiBus);
 12147                    busesToProcess.Add(currentSceneController.systemBus);
 148                }
 149
 3092150                for (int i = 0; i < sortedControllersCount; ++i)
 151                {
 148152                    MessagingController msgController = sortedControllers[i];
 153
 148154                    busesToProcess.Add(msgController.initBus);
 148155                    busesToProcess.Add(msgController.uiBus);
 156                }
 157
 3092158                for (int i = 0; i < sortedControllersCount; ++i)
 159                {
 148160                    MessagingController msgController = sortedControllers[i];
 148161                    busesToProcess.Add(msgController.systemBus);
 162                }
 163
 1398164                busesToProcessCount = busesToProcess.Count;
 1398165            }
 1398166        }
 167
 168        public void Dispose()
 169        {
 668170            if (mainCoroutine != null)
 171            {
 668172                CoroutineStarter.Stop(mainCoroutine);
 668173                mainCoroutine = null;
 174            }
 175
 668176            using (var controllersIterator = messagingControllers.GetEnumerator())
 177            {
 1336178                while (controllersIterator.MoveNext())
 179                {
 668180                    controllersIterator.Current.Value.Stop();
 668181                    DisposeController(controllersIterator.Current.Value);
 182                }
 668183            }
 184
 668185            Environment.i.world.sceneController.OnSortScenes -= PopulateBusesToBeProcessed;
 186
 668187            messagingControllers.Clear();
 668188        }
 189
 190        public bool ContainsController(string sceneId)
 191        {
 33192            return messagingControllers.ContainsKey(sceneId);
 193        }
 194
 195        public void AddController(IMessageProcessHandler messageHandler, string sceneId, bool isGlobal = false)
 196        {
 33197            if (!messagingControllers.ContainsKey(sceneId))
 198            {
 33199                messagingControllers.TryAdd(sceneId, new MessagingController(this, messageHandler, sceneId));
 200            }
 201
 33202            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
 33210            PopulateBusesToBeProcessed();
 33211        }
 212
 213        public void AddControllerIfNotExists(IMessageProcessHandler messageHandler, string sceneId,
 214            bool isGlobal = false)
 215        {
 33216            if (!ContainsController(sceneId))
 33217                AddController(messageHandler, sceneId, isGlobal);
 33218        }
 219
 220        public void RemoveController(string sceneId)
 221        {
 427222            if (messagingControllers.ContainsKey(sceneId))
 223            {
 224                // In case there is any pending message from a scene being unloaded we decrease the count accordingly
 33225                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
 33232                DisposeController(messagingControllers[sceneId]);
 33233                messagingControllers.TryRemove(sceneId, out MessagingController _);
 234            }
 235
 427236            globalSceneControllers.TryRemove(sceneId, out MessagingController _);
 427237        }
 238
 239        void DisposeController(MessagingController controller)
 240        {
 701241            controller.Stop();
 701242            controller.Dispose();
 701243        }
 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        {
 30253            PerformanceAnalytics.MessagesEnqueuedTracker.Track();
 30254            messagingControllers[GLOBAL_MESSAGING_CONTROLLER].ForceEnqueue(busId, queuedMessage);
 30255        }
 256
 257        public void SetSceneReady(string sceneId)
 258        {
 259            // Start processing SYSTEM queue
 395260            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            }
 395268        }
 269
 270        IEnumerator ProcessMessages()
 271        {
 7063272            while (true)
 273            {
 7731274                if (paused)
 275                {
 0276                    yield return null;
 277
 0278                    continue;
 279                }
 280
 7731281                if (populateBusesDirty)
 282                {
 1365283                    PopulateBusesToBeProcessed();
 1365284                    populateBusesDirty = false;
 285                }
 286
 7731287                timeBudgetCounter =
 288                    CommonScriptableObjects.rendererState.Get() ? MAX_GLOBAL_MSG_BUDGET : float.MaxValue;
 289
 31372290                for (int i = 0; i < busesToProcessCount; ++i)
 291                {
 292                    MessagingBus bus;
 293
 7955294                    lock (busesToProcess)
 295                    {
 7955296                        bus = busesToProcess[i];
 7955297                    }
 298
 7955299                    if (ProcessBus(bus))
 300                        break;
 301                }
 302
 7731303                if (pendingInitMessagesCount == 0)
 304                {
 7731305                    AssetPromiseKeeper_GLTF.i.throttlingCounter.budgetPerFrameInMilliseconds =
 306                        Mathf.Clamp(timeBudgetCounter, GLTF_BUDGET_MIN, GLTF_BUDGET_MAX) * 1000f;
 7731307                }
 308                else
 309                {
 0310                    AssetPromiseKeeper_GLTF.i.throttlingCounter.budgetPerFrameInMilliseconds = 0;
 311                }
 312
 7731313                yield return null;
 314            }
 315        }
 316
 317        bool ProcessBus(MessagingBus bus)
 318        {
 7955319            if (!bus.enabled || bus.pendingMessagesCount <= 0)
 7945320                return false;
 321
 10322            float startTime = Time.realtimeSinceStartup;
 323
 10324            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.
 10328            bus.ProcessQueue(timeBudget, out _);
 10329            RefreshControllerEnabledState(bus.owner);
 330
 10331            timeBudgetCounter -= Time.realtimeSinceStartup - startTime;
 332
 10333            if (timeBudgetCounter <= 0)
 0334                return true;
 335
 10336            return false;
 337        }
 338
 339        private void RefreshControllerEnabledState(MessagingController controller)
 340        {
 10341            if (controller == null || !controller.enabled)
 0342                return;
 343
 10344            if (controller.uiBus.pendingMessagesCount != 0)
 0345                return;
 346
 10347            if (controller.initBus.pendingMessagesCount != 0)
 0348                return;
 349
 10350            if (controller.systemBus.pendingMessagesCount != 0)
 0351                return;
 352
 10353            controller.enabled = false;
 10354        }
 355    }
 356}