Scoop API

scoop:scoop.http.server:0.1.0

src/server_protocol.scoop

Selected production source · src/server_protocol.scoop

1package scoop.http.server
3import scoop.asyncio.*
4import scoop.bytes.ByteArrayBuilder
5import scoop.http.*
6import scoop.http.asyncio.HttpTransport
7import scoop.platform.memory.NativeByteBuffer
8import scoop.platform.time.MonotonicTimeSource
9import scoop.time.*
11internal fun remainingServerTime(limit: Duration?, started: TimeMark): Duration? {
12 if (!present(limit)) return None
13 val remaining = limit!! - (MonotonicTimeSource.markNow() - started)
14 return Some(if (remaining > Duration.ZERO) remaining else Duration.ZERO)
17internal 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 return
22 }
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? = None
27 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) }
34internal 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 }
42private 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 }