scoop:scoop.http.client:0.1.0
src/cache/close.scoop
Selected production source · src/cache/close.scoop
1
package scoop.http.client3
import scoop.asyncio.currentEventLoop4
import scoop.platform.fs.Path5
import scoop.platform.system.PlatformErrorKind6
import scoop.platform.system.PlatformException8
internal class ClientCacheClosure {9
private val lock: ClientLock = ClientLock()10
private var started: Boolean = false11
private var done: Boolean = false12
private var failure: Throwable? = None13
private val waiters: ArrayList<Continuation<Unit>> = ArrayList<Continuation<Unit>>()15
suspend fun close(action: suspend () -> Unit) {16
val first =17
lock.withLock {18
if (started)19
false20
else {21
started = true;22
true23
}24
}25
if (first) {26
var failed: Throwable? = None27
try {28
nonCancellableScope<Unit> { action() }29
}30
catch (error: Throwable) {31
failed = Some(error)32
}33
val result = failed34
val waiting =35
lock.withLock {36
done = true;37
failure = result38
val saved = waiters.toArray();39
waiters.clear();40
saved41
}42
for (waiter in waiting)43
when (failed) {44
case Some(val error) -> waiter.resumeWithException(error)45
case None -> waiter.resume(Unit)46
}47
if (clientPresent(failed))48
throw failed!!49
} else {50
suspendCoroutine<Unit> {51
continuation ->52
val finished =53
lock.withLock {54
if (done)55
true56
else {57
waiters.add(continuation);58
false59
}60
}61
if (finished)62
when (lock.withLock { failure }) {63
case Some(val error) -> continuation.resumeWithException(error)64
case None -> continuation.resume(Unit)65
}66
}67
}68
}69
}71
internal suspend fun deleteClientCacheFile(path: Path) {72
try {73
currentEventLoop().deleteFile(path)74
}75
catch (error: PlatformException) {76
if (error.kind != PlatformErrorKind.NotFound)77
throw error78
}79
}81
internal suspend fun deleteClientCacheFiles(paths: List<Path>) {82
if (paths.size == 0L)83
return84
nonCancellableScope<Unit> {85
var failure: Throwable? = None86
for (path in paths) {87
try {88
deleteClientCacheFile(path)89
}90
catch (error: Throwable) {91
failure = Some(clientCombined(failure, error))92
}93
}94
if (clientPresent(failure))95
throw failure!!96
}97
}