scoop:scoop.http.asyncio:0.1.0
src/message_io/state.scoop
Selected production source · src/message_io/state.scoop
1
package scoop.http.asyncio3
import scoop.Result4
import scoop.getOrThrow5
import scoop.asyncio.*7
internal class MessageIo<T>(8
endpoint: T,9
var owner: AsyncCloseable?,10
val loop: EventLoop,11
cleanup: () -> Unit12
) {13
var endpoint: T? = Some(endpoint)14
var cleanup: (() -> Unit)? = Some(cleanup)15
val lock: HttpLock = HttpLock()16
var running: Boolean = false17
var active: Job? = None18
var closing: Boolean = false19
var closed: Boolean = false20
var cleanupStarted: Boolean = false21
var closeJob: Job? = None22
val closeWaiters: ArrayList<Continuation<Unit>> = ArrayList<Continuation<Unit>>()23
private var operationFailure: Throwable? = None24
val isClosed: Boolean get() = lock.withLock { closed }25
val failure: Throwable? get() = lock.withLock { operationFailure }27
suspend fun <R> run(validate: () -> Unit, block: suspend (T) -> R): R {28
httpJob(loop, true)29
val source =30
lock.withLock {31
if (closing || closed)32
throw IoClosedException()33
if (present(operationFailure))34
throw IllegalStateException(Some("HTTP message stream has failed"))35
if (running)36
throw IllegalStateException(Some("HTTP message stream is already in use"))37
validate()38
running = true39
endpoint!!40
}41
try {42
val result =43
coroutineScope<Result<R, Throwable>> {44
val scope = this46
val stop =47
this @MessageIo.lock.withLock {48
this @MessageIo.active = Some(scope.job)49
this @MessageIo.closing50
}51
if (stop)52
scope.job.cancel()53
try {54
ensureActive()55
Result.Success<R, Throwable>(block(source))56
} catch (error: Throwable) {57
Result.Failure<R, Throwable>(error)58
}59
}60
return result.getOrThrow()61
} catch (error: Throwable) {62
lock.withLock { operationFailure = Some(error) }63
throw error64
} finally {65
lock.withLock {66
running = false;67
active = None68
}69
startMessageClose(this)70
}71
}73
suspend fun close() {74
closeMessageIo(this)75
}76
}