scoop:scoop.http.server:0.1.0
src/server_state.scoop
Selected production source · src/server_state.scoop
1
package scoop.http.server3
import scoop.asyncio.*4
import scoop.http.HttpProtocol6
internal enum ServerPhase { Running, Draining, Closed }8
internal class ServerConnection(val transport: AsyncTcpStream) {9
var job: Job? = None10
var active: Long = 0L11
var http2: ServerHttp2? = None12
var webSocket: ServerWebSocket? = None13
var info: HttpConnectionInfo = HttpConnectionInfo(transport.localAddress, transport.peerAddress, HttpProtocol.Http1)14
}16
internal class ServerState(val listener: AsyncTcpListener, val application: HttpApplication,17
val options: HttpServerOptions, val loop: EventLoop) {18
val lock: ServerLock = ServerLock()19
var phase: ServerPhase = ServerPhase.Running20
var owner: Job? = None21
var failure: Throwable? = None22
val connections: ArrayList<ServerConnection> = ArrayList<ServerConnection>()23
var requests: Long = 0L24
var webSockets: Long = 0L25
private var nextId: ULong = 0UL27
fun running(): Boolean = lock.withLock { phase == ServerPhase.Running }29
fun register(connection: ServerConnection): Boolean = lock.withLock {30
if (phase != ServerPhase.Running || connections.size >= options.maxConnections) return@withLock false31
connections.add(connection)32
true33
}35
fun unregister(connection: ServerConnection) {36
lock.withLock {37
var index = 0L38
while (index < connections.size) {39
if (connections[index] === connection) { connections.removeAt(index); break }40
index += 1L41
}42
}43
}45
fun beginRequest(connection: ServerConnection, queuedHttp2: Boolean = false): String? = lock.withLock {46
if ((phase != ServerPhase.Running && !queuedHttp2) || phase == ServerPhase.Closed ||47
requests >= options.maxActiveRequests) return@withLock None48
if (nextId == ULong.MAX_VALUE) throw ArithmeticException()49
nextId += 1UL50
requests += 1L51
connection.active += 1L52
Some(nextId.toString())53
}55
fun endRequest(connection: ServerConnection) {56
lock.withLock { connection.active -= 1L; requests -= 1L }57
}59
fun stopAccepting(graceful: Boolean = true) {60
val actions = lock.withLock {61
if (phase == ServerPhase.Running) phase = ServerPhase.Draining62
val pending = ArrayList<() -> Unit>()63
if (graceful) for (connection in connections) {64
val http2 = connection.http265
val job = connection.job66
val webSocket = connection.webSocket67
if (present(webSocket)) pending.add { webSocket!!.requestDrain() }68
else if (present(http2)) pending.add { http2!!.requestDrain() }69
else if (connection.active == 0L && present(job)) pending.add { job!!.cancel() }70
}71
pending.toArray()72
}73
for (action in actions) action()74
}76
fun recordFailure(error: Throwable) {77
lock.withLock {78
failure = Some(if (present(failure)) ResourceUseException(failure!!, error) else error)79
}80
}82
fun reportFailure() {83
val error = lock.withLock { failure }84
if (present(error)) throw error!!85
}86
}