diff --git a/src/main/kotlin/com/github/insanusmokrassar/SauceNaoAPI/SauceNaoAPI.kt b/src/main/kotlin/com/github/insanusmokrassar/SauceNaoAPI/SauceNaoAPI.kt index e8e6dd6..b414b13 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/SauceNaoAPI/SauceNaoAPI.kt +++ b/src/main/kotlin/com/github/insanusmokrassar/SauceNaoAPI/SauceNaoAPI.kt @@ -2,6 +2,7 @@ package com.github.insanusmokrassar.SauceNaoAPI import com.github.insanusmokrassar.SauceNaoAPI.additional.LONG_TIME_RECALCULATING_MILLIS import com.github.insanusmokrassar.SauceNaoAPI.additional.SHORT_TIME_RECALCULATING_MILLIS +import com.github.insanusmokrassar.SauceNaoAPI.exceptions.TooManyRequestsException import com.github.insanusmokrassar.SauceNaoAPI.exceptions.sauceNaoAPIException import com.github.insanusmokrassar.SauceNaoAPI.models.SauceNaoAnswer import com.github.insanusmokrassar.SauceNaoAPI.utils.* @@ -52,6 +53,9 @@ data class SauceNaoAPI( callback.resumeWith(Result.success(answer)) quotaManager.updateQuota(answer.header, timeManager) + } catch (e: TooManyRequestsException) { + quotaManager.happenTooManyRequests(timeManager) + requestsChannel.send(callback to requestBuilder) } catch (e: Exception) { try { callback.resumeWith(Result.failure(e)) diff --git a/src/main/kotlin/com/github/insanusmokrassar/SauceNaoAPI/utils/RequestQuotaManager.kt b/src/main/kotlin/com/github/insanusmokrassar/SauceNaoAPI/utils/RequestQuotaManager.kt index a94740b..43fca38 100644 --- a/src/main/kotlin/com/github/insanusmokrassar/SauceNaoAPI/utils/RequestQuotaManager.kt +++ b/src/main/kotlin/com/github/insanusmokrassar/SauceNaoAPI/utils/RequestQuotaManager.kt @@ -26,14 +26,20 @@ class RequestQuotaManager ( } } - suspend fun updateQuota(header: Header, timeManager: TimeManager) { + private suspend fun updateQuota( + newLongQuota: Int, + newShortQuota: Int, + newMaxLongQuota: Int?, + newMaxShortQuota: Int?, + timeManager: TimeManager + ) { quotaActions.send( suspend { - longMaxQuota = header.longLimit - shortMaxQuota = header.shortLimit + longMaxQuota = newMaxLongQuota ?: longMaxQuota + shortMaxQuota = newMaxShortQuota ?: shortMaxQuota - longQuota = min(header.longLimit, header.longRemaining) - shortQuota = min(header.shortLimit, header.shortRemaining) + longQuota = min(newLongQuota, longMaxQuota) + shortQuota = min(newShortQuota, shortMaxQuota) when { shortQuota < 1 -> timeManager.getMostOldestInShortPeriod() ?.millis ?.plus(SHORT_TIME_RECALCULATING_MILLIS) ?: let { @@ -53,6 +59,22 @@ class RequestQuotaManager ( ) } + suspend fun updateQuota(header: Header, timeManager: TimeManager) = updateQuota( + header.longRemaining, + header.shortRemaining, + header.longLimit, + header.shortLimit, + timeManager + ) + + suspend fun happenTooManyRequests(timeManager: TimeManager) = updateQuota( + 1, + 0, + null, + null, + timeManager + ) + suspend fun getQuota() { return suspendCoroutine { lateinit var callback: suspend () -> Unit