| | 1 | | using System; |
| | 2 | | using System.Collections; |
| | 3 | | using System.Collections.Generic; |
| | 4 | | using UnityEngine; |
| | 5 | |
|
| | 6 | | namespace DCL.Helpers.NFT.Markets.OpenSea_Internal |
| | 7 | | { |
| | 8 | | internal class RequestScheduler |
| | 9 | | { |
| | 10 | | const float REQUEST_DELAY = 0.4f; // max ~2 requests per second |
| | 11 | |
|
| | 12 | | public event Action<IRequestHandler> OnRequestReadyToSend; |
| | 13 | |
|
| 72 | 14 | | private readonly List<IRequestHandler> scheduledRequests = new List<IRequestHandler>(); |
| | 15 | |
|
| | 16 | | private float lastRequestSentTime = 0; |
| | 17 | | private Coroutine scheduleTask = null; |
| | 18 | |
|
| | 19 | | public void EnqueueRequest(IRequestHandler requests) |
| | 20 | | { |
| 0 | 21 | | requests.schedulableRequestHandler.OnReadyToSchedule -= OnRequestReadyToSchedule; |
| | 22 | |
|
| 0 | 23 | | if (requests.schedulableRequestHandler.isReadyToSchedule) |
| | 24 | | { |
| 0 | 25 | | OnRequestReadyToSchedule(requests); |
| 0 | 26 | | } |
| | 27 | | else |
| | 28 | | { |
| 0 | 29 | | requests.schedulableRequestHandler.OnReadyToSchedule += OnRequestReadyToSchedule; |
| | 30 | | } |
| 0 | 31 | | } |
| | 32 | |
|
| | 33 | | private void OnRequestReadyToSchedule(IRequestHandler requestHandler) |
| | 34 | | { |
| 0 | 35 | | if (Time.unscaledTime - lastRequestSentTime >= REQUEST_DELAY) |
| | 36 | | { |
| 0 | 37 | | SendRequest(requestHandler); |
| 0 | 38 | | return; |
| | 39 | | } |
| | 40 | |
|
| 0 | 41 | | scheduledRequests.Add(requestHandler); |
| | 42 | |
|
| 0 | 43 | | if (scheduleTask == null) |
| | 44 | | { |
| 0 | 45 | | scheduleTask = CoroutineStarter.Start(ScheduleTaskRoutine()); |
| | 46 | | } |
| 0 | 47 | | } |
| | 48 | |
|
| | 49 | | private void SendRequest(IRequestHandler requestHandler) |
| | 50 | | { |
| 0 | 51 | | lastRequestSentTime = Time.unscaledTime; |
| 0 | 52 | | OnRequestReadyToSend?.Invoke(requestHandler); |
| 0 | 53 | | } |
| | 54 | |
|
| | 55 | | IEnumerator ScheduleTaskRoutine() |
| | 56 | | { |
| 0 | 57 | | while (scheduledRequests.Count > 0) |
| | 58 | | { |
| 0 | 59 | | float waitTime = Mathf.Clamp(REQUEST_DELAY - (Time.unscaledTime - lastRequestSentTime), 0, REQUEST_DELAY |
| 0 | 60 | | yield return WaitForSecondsCache.Get(waitTime); |
| 0 | 61 | | SendRequest(scheduledRequests[0]); |
| 0 | 62 | | scheduledRequests.RemoveAt(0); |
| | 63 | | } |
| | 64 | |
|
| 0 | 65 | | scheduleTask = null; |
| 0 | 66 | | } |
| | 67 | | } |
| | 68 | | } |