Scoop API

scoop:scoop.http.asyncio:0.1.0

src/message_io/state.scoop

Selected production source · src/message_io/state.scoop

1package scoop.http.asyncio
3import scoop.Result
4import scoop.getOrThrow
5import scoop.asyncio.*
7internal class MessageIo<T>(
8 endpoint: T,
9 var owner: AsyncCloseable?,
10 val loop: EventLoop,
11 cleanup: () -> Unit
12) {
13 var endpoint: T? = Some(endpoint)
14 var cleanup: (() -> Unit)? = Some(cleanup)
15 val lock: HttpLock = HttpLock()
16 var running: Boolean = false
17 var active: Job? = None
18 var closing: Boolean = false
19 var closed: Boolean = false
20 var cleanupStarted: Boolean = false
21 var closeJob: Job? = None
22 val closeWaiters: ArrayList<Continuation<Unit>> = ArrayList<Continuation<Unit>>()
23 private var operationFailure: Throwable? = None
24 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 = true
39 endpoint!!
40 }
41 try {
42 val result =
43 coroutineScope<Result<R, Throwable>> {
44 val scope = this
46 val stop =
47 this @MessageIo.lock.withLock {
48 this @MessageIo.active = Some(scope.job)
49 this @MessageIo.closing
50 }
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 error
64 } finally {
65 lock.withLock {
66 running = false;
67 active = None
68 }
69 startMessageClose(this)
70 }
71 }
73 suspend fun close() {
74 closeMessageIo(this)
75 }