浏览代码

Add retry for cuiCloudUpload

Him188 5 年之前
父节点
当前提交
7ed5dd1631
共有 1 个文件被更改,包括 38 次插入6 次删除
  1. 38 6
      buildSrc/src/main/kotlin/upload/CuiCloud.kt

+ 38 - 6
buildSrc/src/main/kotlin/upload/CuiCloud.kt

@@ -21,6 +21,9 @@ import org.gradle.api.Project
 import org.gradle.kotlin.dsl.provideDelegate
 import java.io.File
 import java.util.*
+import kotlin.contracts.ExperimentalContracts
+import kotlin.contracts.InvocationKind
+import kotlin.contracts.contract
 
 @Suppress("DEPRECATION")
 object CuiCloud {
@@ -77,13 +80,18 @@ object CuiCloud {
         val cuiCloudUrl = getUrl(project)
         val key = getKey(project)
 
+
+        val bytes = file.readBytes()
+
         runBlocking {
-            uploadToCuiCloud(
-                cuiCloudUrl,
-                key,
-                "/mirai/${project.name}/${file.nameWithoutExtension}.mp4",
-                file.readBytes()
-            )
+            retryCatching(5) {
+                uploadToCuiCloud(
+                    cuiCloudUrl,
+                    key,
+                    "/mirai/${project.name}/${file.nameWithoutExtension}.mp4",
+                    bytes
+                )
+            }
         }
     }
 
@@ -129,6 +137,30 @@ object CuiCloud {
     }
 }
 
+
+@OptIn(ExperimentalContracts::class)
+@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "RESULT_CLASS_IN_RETURN_TYPE")
[email protected]
+internal inline fun <R> retryCatching(n: Int, block: () -> R): Result<R> {
+    contract {
+        callsInPlace(block, InvocationKind.AT_LEAST_ONCE)
+    }
+    require(n >= 0) { "param n for retryCatching must not be negative" }
+    var exception: Throwable? = null
+    repeat(n) {
+        try {
+            return Result.success(block())
+        } catch (e: Throwable) {
+            try {
+                exception?.addSuppressed(e)
+            } catch (e: Throwable) {
+            }
+            exception = e
+        }
+    }
+    return Result.failure(exception!!)
+}
+
 inline fun <E> buildList(builderAction: MutableList<E>.() -> Unit): List<E> {
     return ArrayList<E>().apply(builderAction)
 }