< Summary

Class:DCL.Helpers.NFT.Markets.OpenSea_Internal.BatchAssetsRequestHandler
Assembly:OpenSea_Internal
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/ServiceProviders/OpenSea/RequestHandlers/BatchAssetsRequestHandler.cs
Covered lines:0
Uncovered lines:76
Coverable lines:76
Total lines:192
Line coverage:0% (0 of 76)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
get_schedulableRequestHandler()0%2100%
BatchAssetsRequestHandler(...)0%6200%
AddRequest(...)0%6200%
CloseBatch()0%6200%
BatchOpenTimeOut()0%12300%
TryRetrySingleAsset()0%2100%
TryRetryBatchAssets()0%12300%
RetryBatch(...)0%6200%
GetUrl()0%2100%
SetApiResponse(...)0%90900%
CanRetry()0%6200%
Retry()0%12300%
SetApiResponseError(...)0%6200%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/ServiceProviders/OpenSea/RequestHandlers/BatchAssetsRequestHandler.cs

#LineLine coverage
 1using System;
 2using System.Collections;
 3using System.Collections.Generic;
 4using System.Linq;
 5using UnityEngine;
 6
 7namespace DCL.Helpers.NFT.Markets.OpenSea_Internal
 8{
 9    internal class BatchAssetsRequestHandler : IRequestHandler
 10    {
 11        const bool VERBOSE = false;
 12        const float BATCH_OPEN_TIME = 2;
 13        const float QUERY_MAX_LENGTH = 1085; // maxUrl(1279) - apiUrl(37) - longestPossibleRequest (78 tokenId + 42 cont
 14
 015        public bool isOpen { private set; get; }
 16
 017        SchedulableRequestHandler IRequestHandler.schedulableRequestHandler => schedulableHandler;
 18
 019        private readonly List<RequestAssetInBatch> requests = new List<RequestAssetInBatch>();
 20        private readonly RequestController requestController;
 021        private readonly SchedulableRequestHandler schedulableHandler = new SchedulableRequestHandler();
 22
 023        private string query = string.Empty;
 24        private int retryCount = 0;
 25
 026        public BatchAssetsRequestHandler(RequestController requestController, bool autocloseBatch = true)
 27        {
 28            if (VERBOSE)
 29                Debug.Log($"BatchAssetsRequestHandler: ({GetHashCode()}) created");
 30
 031            this.requestController = requestController;
 032            this.isOpen = true;
 33
 034            if (autocloseBatch)
 035                CoroutineStarter.Start(BatchOpenTimeOut(BATCH_OPEN_TIME));
 036        }
 37
 38        public void AddRequest(RequestAssetInBatch request)
 39        {
 040            requests.Add(request);
 041            query += $"asset_contract_addresses={request.contractAddress}&token_ids={request.tokenId}&";
 42
 43            if (VERBOSE)
 44                Debug.Log($"BatchAssetsRequestHandler: ({GetHashCode()}) adding {request.contractAddress}/{request.token
 45
 046            if (query.Length >= QUERY_MAX_LENGTH)
 47            {
 048                CloseBatch();
 49            }
 050        }
 51
 52        void CloseBatch()
 53        {
 54            if (VERBOSE)
 55                Debug.Log($"BatchAssetsRequestHandler: ({GetHashCode()}) closed {query}");
 56
 057            isOpen = false;
 58
 059            if (string.IsNullOrEmpty(query))
 060                return;
 61
 062            schedulableHandler.SetReadyToBeScheduled(this);
 063        }
 64
 65        IEnumerator BatchOpenTimeOut(float openTime)
 66        {
 067            yield return WaitForSecondsCache.Get(openTime);
 068            CloseBatch();
 069        }
 70
 71        void TryRetrySingleAsset()
 72        {
 73            if (VERBOSE)
 74                Debug.Log($"BatchAssetsRequestHandler: ({GetHashCode()}) retry single asset {query}");
 75
 076            requestController.requestScheduler.EnqueueRequest(this);
 077            retryCount ++;
 078        }
 79
 80        void TryRetryBatchAssets()
 81        {
 82            if (VERBOSE)
 83                Debug.Log($"BatchAssetsRequestHandler: ({GetHashCode()}) retry splitting batch {query}");
 84
 85            // Split requests in new batches and retry
 086            int counter = 0;
 087            var batches = requests.GroupBy(x => counter++ % 2);
 88
 089            foreach (var group in batches)
 90            {
 091                RetryBatch(group.ToList());
 92            }
 093        }
 94
 95        void RetryBatch(List<RequestAssetInBatch> batchedRequests)
 96        {
 097            var newHandler = new BatchAssetsRequestHandler(requestController, false);
 098            for (int i = 0; i < batchedRequests.Count; i++)
 99            {
 0100                newHandler.AddRequest(batchedRequests[i]);
 101            }
 102
 0103            requestController.requestScheduler.EnqueueRequest(newHandler);
 0104            newHandler.schedulableHandler.SetReadyToBeScheduled(newHandler);
 0105        }
 106
 0107        string IRequestHandler.GetUrl() { return $"{Constants.MULTIPLE_ASSETS_URL}?{query}"; }
 108
 109        void IRequestHandler.SetApiResponse(string responseJson, Action onSuccess, Action<string> onError)
 110        {
 0111            AssetsResponse response = null;
 112
 113            try
 114            {
 0115                response = Utils.FromJsonWithNulls<AssetsResponse>(responseJson);
 0116            }
 0117            catch (Exception e)
 118            {
 0119                onError?.Invoke(e.Message);
 0120            }
 121
 0122            if (response == null)
 0123                return;
 124
 0125            RequestAssetInBatch request = null;
 0126            AssetResponse asset = null;
 127
 0128            int batchCount = requests.Count;
 0129            for (int i = batchCount - 1; i >= 0; i--)
 130            {
 0131                request = requests[i];
 0132                for (int j = 0; j < response.assets.Length; j++)
 133                {
 0134                    asset = response.assets[j];
 0135                    bool isMatch = asset.token_id == request.tokenId
 136                                   && String.Equals(asset.asset_contract.address, request.contractAddress, StringCompari
 137
 0138                    if (isMatch)
 139                    {
 140                        if (VERBOSE)
 141                            Debug.Log($"BatchAssetsRequestHandler: ({GetHashCode()}) resolved {request.contractAddress}/
 142
 0143                        request.Resolve(asset);
 0144                        requests.RemoveAt(i);
 0145                        break;
 146                    }
 147                }
 148            }
 149
 150            // Retry possible unresolved requests
 0151            if (requests.Count > 0)
 152            {
 0153                RetryBatch(requests);
 154            }
 155
 0156            onSuccess?.Invoke();
 0157        }
 158
 159        bool IRequestHandler.CanRetry()
 160        {
 0161            if (requests.Count == 1)
 0162                return retryCount < Constants.REQUESTS_RETRY_ATTEMPS;
 0163            return true;
 164        }
 165
 166        void IRequestHandler.Retry()
 167        {
 0168            if (requests.Count == 0)
 0169                return;
 170
 0171            if (requests.Count == 1)
 172            {
 0173                TryRetrySingleAsset();
 0174            }
 175            else
 176            {
 0177                TryRetryBatchAssets();
 178            }
 0179        }
 180
 181        void IRequestHandler.SetApiResponseError(string error)
 182        {
 183            if (VERBOSE)
 184                Debug.Log($"BatchAssetsRequestHandler: ({GetHashCode()}) rejecting {error} {query}");
 185
 0186            for (int i = 0; i < requests.Count; i++)
 187            {
 0188                requests[i].Reject(error);
 189            }
 0190        }
 191    }
 192}