< Summary

Class:DCL.AssetPromise_AB
Assembly:AssetPromiseKeeper
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/AssetManager/AssetBundles/AB/AssetPromise_AB.cs
Covered lines:81
Uncovered lines:30
Coverable lines:111
Total lines:254
Line coverage:72.9% (81 of 111)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
AssetPromise_AB()0%110100%
AssetPromise_AB(...)0%110100%
AddToLibrary()0%4.123050%
OnCancelLoading()0%550100%
OnBeforeLoadOrReuse()0%110100%
OnAfterLoadOrReuse()0%110100%
LoadAssetBundleWithDeps()0%21.519080.95%
LoadAssetBundle(...)0%4.594066.67%
ToString()0%30500%
OnLoad(...)0%110100%
WaitForConcurrentRequestsSlot()0%4.594066.67%
RegisterConcurrentRequest()0%3.043083.33%
UnregisterConcurrentRequest()0%330100%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/AssetManager/AssetBundles/AB/AssetPromise_AB.cs

#LineLine coverage
 1using System;
 2using System.Collections;
 3using System.Collections.Generic;
 4using UnityEngine;
 5using UnityEngine.Networking;
 6
 7namespace DCL
 8{
 9    public class AssetPromise_AB : AssetPromise_WithUrl<Asset_AB>
 10    {
 111        public static bool VERBOSE = false;
 3012        public static int MAX_CONCURRENT_REQUESTS => CommonScriptableObjects.rendererState.Get() ? 30 : 256;
 13
 114        public static int concurrentRequests = 0;
 15        public static event Action OnDownloadingProgressUpdate;
 16
 17        bool requestRegistered = false;
 18
 019        public static int downloadingCount => concurrentRequests;
 020        public static int queueCount => AssetPromiseKeeper_AB.i.waitingPromisesCount;
 21
 22        Coroutine loadCoroutine;
 123        static HashSet<string> failedRequestUrls = new HashSet<string>();
 24
 4425        List<AssetPromise_AB> dependencyPromises = new List<AssetPromise_AB>();
 26
 127        public static AssetBundlesLoader assetBundlesLoader = new AssetBundlesLoader();
 28        private Transform containerTransform;
 29        private WebRequestAsyncOperation asyncOp;
 30
 31        public AssetPromise_AB(string contentUrl, string hash,
 4432            Transform containerTransform = null) : base(contentUrl,
 33            hash)
 34        {
 4435            this.containerTransform = containerTransform;
 4436            assetBundlesLoader.Start();
 4437        }
 38
 39        protected override bool AddToLibrary()
 40        {
 2241            if (!library.Add(asset))
 42            {
 043                Debug.Log("add to library fail?");
 044                return false;
 45            }
 46
 2247            if (asset == null)
 48            {
 049                Debug.LogWarning($"Asset is null when trying to add it to the library: hash == {this.GetId()}");
 050                return false;
 51            }
 52
 2253            asset = library.Get(asset.id);
 2254            return true;
 55        }
 56
 57        protected override void OnCancelLoading()
 58        {
 859            if (loadCoroutine != null)
 60            {
 861                CoroutineStarter.Stop(loadCoroutine);
 862                loadCoroutine = null;
 63            }
 64
 865            if (asyncOp != null)
 66            {
 867                asyncOp.Dispose();
 68            }
 69
 1870            for (int i = 0; i < dependencyPromises.Count; i++)
 71            {
 172                dependencyPromises[i].Unload();
 73            }
 74
 875            dependencyPromises.Clear();
 76
 877            if (asset != null)
 78            {
 879                asset.CancelShow();
 80            }
 81
 882            UnregisterConcurrentRequest();
 883        }
 84
 85        protected override void OnBeforeLoadOrReuse()
 86        {
 4487        }
 88
 89        protected override void OnAfterLoadOrReuse()
 90        {
 3691        }
 92
 93        protected IEnumerator LoadAssetBundleWithDeps(string baseUrl, string hash, Action OnSuccess, Action<Exception> O
 94        {
 3095            string finalUrl = baseUrl + hash;
 96
 3097            if (failedRequestUrls.Contains(finalUrl))
 98            {
 099                OnFail?.Invoke(new Exception($"The url {finalUrl} has failed"));
 0100                yield break;
 101            }
 102
 30103            yield return WaitForConcurrentRequestsSlot();
 104
 30105            RegisterConcurrentRequest();
 106#if (UNITY_EDITOR || UNITY_STANDALONE)
 30107            asyncOp = Environment.i.platform.webRequest.GetAssetBundle(url: finalUrl, hash: Hash128.Compute(hash),
 108                disposeOnCompleted: false);
 109#else
 110            //NOTE(Brian): Disable in build because using the asset bundle caching uses IDB.
 111            asyncOp = Environment.i.platform.webRequest.GetAssetBundle(url: finalUrl, disposeOnCompleted: false);
 112#endif
 113
 114            // 1. Download asset bundle, but don't load its objects yet
 30115            yield return asyncOp;
 116
 25117            if (asyncOp.isDisposed)
 118            {
 0119                OnFail?.Invoke(new Exception("Operation is disposed"));
 0120                yield break;
 121            }
 122
 25123            if (!asyncOp.isSucceded)
 124            {
 2125                if (VERBOSE)
 0126                    Debug.Log($"Request failed? {asyncOp.webRequest.error} ... {finalUrl}");
 2127                failedRequestUrls.Add(finalUrl);
 2128                OnFail?.Invoke(new Exception($"Request failed? {asyncOp.webRequest.error} ... {finalUrl}"));
 2129                asyncOp.Dispose();
 2130                yield break;
 131            }
 132
 23133            if (!LoadAssetBundle(OnFail, finalUrl))
 0134                yield break;
 135
 136            // 2. Check internal metadata file (dependencies, version, timestamp) and if it doesn't exist, fetch the ext
 23137            TextAsset metadata = asset.GetMetadata();
 138
 23139            if (metadata != null)
 140            {
 0141                AssetBundleDepMapLoadHelper.LoadDepMapFromJSON(metadata.text, hash);
 0142            }
 143            else
 144            {
 23145                if (!AssetBundleDepMapLoadHelper.dependenciesMap.ContainsKey(hash))
 4146                    CoroutineStarter.Start(AssetBundleDepMapLoadHelper.LoadExternalDepMap(baseUrl, hash));
 147
 23148                yield return AssetBundleDepMapLoadHelper.WaitUntilExternalDepMapIsResolved(hash);
 149            }
 150
 151            // 3. Resolve dependencies
 23152            if (AssetBundleDepMapLoadHelper.dependenciesMap.ContainsKey(hash))
 153            {
 21154                using (var it = AssetBundleDepMapLoadHelper.dependenciesMap[hash].GetEnumerator())
 155                {
 35156                    while (it.MoveNext())
 157                    {
 14158                        var dep = it.Current;
 14159                        var promise = new AssetPromise_AB(baseUrl, dep, containerTransform);
 14160                        AssetPromiseKeeper_AB.i.Keep(promise);
 14161                        dependencyPromises.Add(promise);
 162                    }
 21163                }
 164            }
 165
 23166            UnregisterConcurrentRequest();
 167
 74168            foreach (var promise in dependencyPromises)
 169            {
 14170                yield return promise;
 171            }
 172
 23173            assetBundlesLoader.MarkAssetBundleForLoad(asset, containerTransform, OnSuccess, OnFail);
 23174        }
 175        private bool LoadAssetBundle(Action<Exception> OnFail, string finalUrl)
 176        {
 23177            var assetBundle = DownloadHandlerAssetBundle.GetContent(asyncOp.webRequest);
 23178            asyncOp.Dispose();
 179
 23180            if (assetBundle == null || asset == null)
 181            {
 0182                OnFail?.Invoke(new Exception("Asset bundle or asset is null"));
 0183                failedRequestUrls.Add(finalUrl);
 184
 0185                return false;
 186            }
 187
 23188            asset.SetAssetBundle(assetBundle);
 23189            asset.LoadMetrics();
 190
 23191            return true;
 192        }
 193
 194        public override string ToString()
 195        {
 0196            string result = $"AB request... loadCoroutine = {loadCoroutine} ... state = {state}\n";
 197
 0198            if (asyncOp.webRequest != null)
 0199                result +=
 200                    $"url = {asyncOp.webRequest.url} ... code = {asyncOp.webRequest.responseCode} ... progress = {asyncO
 201            else
 0202                result += $"null request for url: {contentUrl + hash}\n";
 203
 204
 0205            if (dependencyPromises != null && dependencyPromises.Count > 0)
 206            {
 0207                result += "Dependencies:\n\n";
 0208                foreach (var p in dependencyPromises)
 209                {
 0210                    result += p.ToString() + "\n\n";
 211                }
 212            }
 213
 0214            result += "Concurrent requests = " + concurrentRequests;
 215
 0216            return result;
 217        }
 218
 219        protected override void OnLoad(Action OnSuccess, Action<Exception> OnFail)
 220        {
 30221            loadCoroutine = CoroutineStarter.Start(DCLCoroutineRunner.Run(
 222                LoadAssetBundleWithDeps(contentUrl, hash, OnSuccess, OnFail),
 0223                exception => OnFail?.Invoke(exception)));
 30224        }
 225
 226        IEnumerator WaitForConcurrentRequestsSlot()
 227        {
 30228            while (concurrentRequests >= MAX_CONCURRENT_REQUESTS)
 229            {
 0230                yield return null;
 231            }
 30232        }
 233
 234        void RegisterConcurrentRequest()
 235        {
 30236            if (requestRegistered)
 0237                return;
 238
 30239            concurrentRequests++;
 30240            OnDownloadingProgressUpdate?.Invoke();
 30241            requestRegistered = true;
 30242        }
 243
 244        void UnregisterConcurrentRequest()
 245        {
 31246            if (!requestRegistered)
 1247                return;
 248
 30249            concurrentRequests--;
 30250            OnDownloadingProgressUpdate?.Invoke();
 30251            requestRegistered = false;
 30252        }
 253    }
 254}