Skip to content

Commit

Permalink
fix: mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
cssxsh committed Sep 21, 2021
1 parent 60bbeaf commit 2021cd5
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 7 deletions.
5 changes: 2 additions & 3 deletions src/main/kotlin/xyz/cssxsh/bilibili/BiliClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,10 @@ open class BiliClient(private val timeout: Long = 15_000L) : Closeable {

protected open val mutex = BiliApiMutex(10 * 1000L)

suspend fun <T> useHttpClient(block: suspend (HttpClient) -> T): T = supervisorScope {
suspend fun <T> useHttpClient(block: suspend (HttpClient, BiliApiMutex) -> T): T = supervisorScope {
while (isActive) {
runCatching {
mutex.wait()
block(clients[index])
block(clients[index], mutex)
}.onFailure {
if (isActive && ignore(it)) {
index = (index + 1) % clients.size
Expand Down
3 changes: 2 additions & 1 deletion src/main/kotlin/xyz/cssxsh/bilibili/api/Api.kt
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ const val SUIT_ITEMS = "https://api.bilibili.com/x/garb/mall/item/suit/v2"
internal suspend inline fun <reified T> BiliClient.json(
url: String,
crossinline block: HttpRequestBuilder.() -> Unit
): T = useHttpClient { client ->
): T = useHttpClient { client, mutex ->
mutex.wait()
with(client.get<TempData>(url, block)) {
val temp = data ?: result
BiliClient.Json.decodeFromJsonElement(requireNotNull(temp) { message })
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/xyz/cssxsh/mirai/plugin/BiliBuilder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,8 @@ internal val MediaReplier: MessageReplier = replier@{ result ->
}

private suspend fun Url.location(): String? {
return client.useHttpClient {
it.config {
return client.useHttpClient { http, _ ->
http.config {
followRedirects = false
expectSuccess = false
}.head<HttpMessage>(this@location)
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/xyz/cssxsh/mirai/plugin/BiliUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ private suspend fun Url.cache(type: CacheType, path: String, contact: Contact) =
type.directory.resolve(path).apply {
if (exists().not()) {
parentFile.mkdirs()
writeBytes(client.useHttpClient { it.get(this@cache) })
writeBytes(client.useHttpClient { http, _ -> http.get(this@cache) })
} else {
setLastModified(System.currentTimeMillis())
}
Expand Down

0 comments on commit 2021cd5

Please sign in to comment.