scoop:scoop.http.asyncio:0.1.0
src/http1_operation.scoop
Selected production source · src/http1_operation.scoop
1
package scoop.http.asyncio3
import scoop.asyncio.*4
import scoop.time.Duration6
internal struct H1Operation<P>(7
val state: H1State,8
val reading: Boolean,9
val prepared: P,10
val job: Job,11
val cancellation: Disposable12
)14
internal fun <P> beginH1Operation(15
state: H1State,16
reading: Boolean,17
prepare: () -> P,18
idle: Duration? = None19
): 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.readBusy28
else29
state.writeBusy30
)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.readIdle37
else38
state.writeIdle39
if (present(previous))40
previous!!.limit = idle41
else {42
val clock = Some(H1Idle(reading, idle!!))43
if (reading)44
state.readIdle = clock45
else46
state.writeIdle = clock47
}48
}49
if (reading)50
state.readBusy = true51
else52
state.writeBusy = true53
value54
}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)62
}64
private fun h1ClosedFailure(error: Throwable, selected: Throwable): Throwable {65
if (error is IoClosedException)66
return selected67
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 error73
}75
internal fun <P> endH1Operation(operation: H1Operation<P>) {76
operation.cancellation.dispose()77
val state = operation.state78
val reading = operation.reading79
val closing = state.lock.withLock { finishH1OperationLocked(state, reading) }80
if (closing)81
driveH1Close(state)82
}84
private fun finishH1OperationLocked(state: H1State, reading: Boolean): Boolean {85
if (reading) {86
state.readBusy = false87
state.readIdle?.stop()88
} else {89
state.writeBusy = false90
state.writeIdle?.stop()91
}92
return state.closing93
}95
internal suspend fun <P> failH1Operation(operation: H1Operation<P>, error: Throwable): Nothing {96
val state = operation.state97
val selected = state.lock.withLock { state.primary }98
val failure =99
if (present(selected))100
h1ClosedFailure(error, selected!!)101
else102
error103
endH1Operation(operation)104
failH1Operation(state, failure)105
}107
internal 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 primary119
}120
}