Scoop API

scoop:scoop.http.asyncio:0.1.0

src/http1_operation.scoop

Selected production source · src/http1_operation.scoop

1package scoop.http.asyncio
3import scoop.asyncio.*
4import scoop.time.Duration
6internal struct H1Operation<P>(
7 val state: H1State,
8 val reading: Boolean,
9 val prepared: P,
10 val job: Job,
11 val cancellation: Disposable
14internal fun <P> beginH1Operation(
15 state: H1State,
16 reading: Boolean,
17 prepare: () -> P,
18 idle: Duration? = None
19): H1Operation<P> {
20 val job = httpJob(state.loop, true)
21 httpIdleLimit(idle)
22 val prepared =
23 state.lock.withLock {
24 h1Open(state)
25 if (
26 if (reading)
27 state.readBusy
28 else
29 state.writeBusy
30 )
31 throw IllegalStateException(Some("HTTP/1 direction is busy"))
32 val value = prepare()
33 if (present(idle)) {
34 val previous =
35 if (reading)
36 state.readIdle
37 else
38 state.writeIdle
39 if (present(previous))
40 previous!!.limit = idle
41 else {
42 val clock = Some(H1Idle(reading, idle!!))
43 if (reading)
44 state.readIdle = clock
45 else
46 state.writeIdle = clock
47 }
48 }
49 if (reading)
50 state.readBusy = true
51 else
52 state.writeBusy = true
53 value
54 }
55 val listener =
56 job.invokeOnCancellation {
57 error ->
58 state.lock.withLock { terminateH1(state, error) }
59 driveH1Close(state)
60 }
61 return H1Operation(state, reading, prepared, job, listener)
64private fun h1ClosedFailure(error: Throwable, selected: Throwable): Throwable {
65 if (error is IoClosedException)
66 return selected
67 if (error is ResourceUseException) {
68 val primary = h1ClosedFailure(error.primaryFailure, selected)
69 if (primary !== error.primaryFailure)
70 return ResourceUseException(primary, error.cleanupFailure)
71 }
72 return error
75internal fun <P> endH1Operation(operation: H1Operation<P>) {
76 operation.cancellation.dispose()
77 val state = operation.state
78 val reading = operation.reading
79 val closing = state.lock.withLock { finishH1OperationLocked(state, reading) }
80 if (closing)
81 driveH1Close(state)
84private fun finishH1OperationLocked(state: H1State, reading: Boolean): Boolean {
85 if (reading) {
86 state.readBusy = false
87 state.readIdle?.stop()
88 } else {
89 state.writeBusy = false
90 state.writeIdle?.stop()
91 }
92 return state.closing
95internal suspend fun <P> failH1Operation(operation: H1Operation<P>, error: Throwable): Nothing {
96 val state = operation.state
97 val selected = state.lock.withLock { state.primary }
98 val failure =
99 if (present(selected))
100 h1ClosedFailure(error, selected!!)
101 else
102 error
103 endH1Operation(operation)
104 failH1Operation(state, failure)
107internal suspend fun failH1Operation(state: H1State, primary: Throwable): Nothing {
108 val cleanup =
109 try {
110 closeH1(state);
111 state.lock.withLock { state.closeFailure }
112 }
113 catch (error: Throwable) {
114 Some(error)
115 }
116 when (cleanup) {
117 case Some(val error) -> throw ResourceUseException(primary, error)
118 case None -> throw primary
119 }