scoop:scoop.http.server:0.1.0
src/server_protocol.scoop
Selected production source · src/server_protocol.scoop
1
package scoop.http.server3
import scoop.asyncio.*4
import scoop.bytes.ByteArrayBuilder5
import scoop.http.*6
import scoop.http.asyncio.HttpTransport7
import scoop.platform.memory.NativeByteBuffer8
import scoop.platform.time.MonotonicTimeSource9
import scoop.time.*11
internal fun remainingServerTime(limit: Duration?, started: TimeMark): Duration? {12
if (!present(limit)) return None13
val remaining = limit!! - (MonotonicTimeSource.markNow() - started)14
return Some(if (remaining > Duration.ZERO) remaining else Duration.ZERO)15
}17
internal suspend fun serveCleartextHttp(state: ServerState, entry: ServerConnection, scope: CoroutineScope) {18
val started = MonotonicTimeSource.markNow()19
if (!state.options.allowCleartextHttp2) {20
serveHttp1(state, entry, entry.transport, scope, started)21
return22
}23
val (protocol, prefix) = serverDeadline<(HttpProtocol, Array<Byte>)>(state.options.firstRequestHeadTimeout,24
"cleartext protocol", suspend { probeServerHttp(entry.transport) })25
val transport = HttpTransport.takeOwnershipWithPrefix(entry.transport, prefix)26
var failure: Throwable? = None27
try {28
entry.info = HttpConnectionInfo(entry.transport.localAddress, entry.transport.peerAddress, protocol)29
serveSelectedHttp(state, entry, transport, scope, protocol, started)30
} catch (error: Throwable) { failure = Some(error); throw error }31
finally { closeServerResource(state, transport, failure) }32
}34
internal suspend fun <T> serveSelectedHttp(state: ServerState, entry: ServerConnection, transport: T,35
scope: CoroutineScope, protocol: HttpProtocol, started: TimeMark) where T : AsyncByteStream, T : AsyncCloseable {36
when (protocol) {37
case Http1 -> serveHttp1(state, entry, transport, scope, started)38
case Http2 -> serveHttp2(state, entry, transport, scope, started)39
}40
}42
private suspend fun probeServerHttp(transport: AsyncTcpStream): (HttpProtocol, Array<Byte>) =43
NativeByteBuffer.allocate(1024L).use suspend { input ->44
val probe = HttpCleartextProbe([HttpProtocol.Http1, HttpProtocol.Http2])45
while (!present(probe.protocol)) {46
input.clear()47
if (transport.readInto(input, input.writableBytes) == 0L) probe.endInput()48
else probe.receive(input)49
}50
val prefix = ByteArrayBuilder().append(probe.prefix).append(input.readBytes(input.readableBytes)).toByteArray()51
(probe.protocol!!, prefix)52
}