Scoop API

scoop:scoop.http.server:0.1.0

src/server.scoop

Selected production source · src/server.scoop

1package scoop.http.server
3import scoop.asyncio.*
4import scoop.platform.net.*
5import scoop.time.Duration
7/** Owns an accept loop, its connections and their structured request tasks. */
8public class HttpServer private constructor(private val state: ServerState): AsyncCloseable {
9 /** Explicit listener-ownership construction. */
10 public companion object {
11 /** Binds on the current event loop and starts this application in the supplied scope. */
12 public suspend fun listen(
13 application: HttpApplication,
14 scope: CoroutineScope,
15 port: Int = 8080,
16 host: IpAddress = IpAddress.IPV4_LOOPBACK,
17 options: HttpServerOptions = httpServerOptions()
18 ): HttpServer {
19 val listener = currentEventLoop().listenTcp(SocketAddress(host, port))
20 try {
21 return takeOwnership(listener, application, scope, options)
22 }
23 catch (error: Throwable) {
24 try {
25 nonCancellableScope<Unit> { listener.close() }
26 }
27 catch (cleanup: Throwable) {
28 throw ResourceUseException(error, cleanup)
29 }
30 throw error
31 }
32 }
34 /** Configures and freezes routes before binding, using the same server and lifecycle. */
35 public suspend fun listen(
36 scope: CoroutineScope,
37 port: Int = 8080,
38 host: IpAddress = IpAddress.IPV4_LOOPBACK,
39 options: HttpServerOptions = httpServerOptions(),
40 applicationOptions: HttpApplicationOptions = httpApplicationOptions(),
41 configure: RouterBuilder.() -> Unit
42 ): HttpServer {
43 val application =
44 routing {
45 this.application = applicationOptions
46 this.configure()
47 }
48 return listen(application, scope, port, host, options)
49 }
51 /** Takes the listener after registering the server owner in the supplied active scope. */
52 public suspend fun takeOwnership(
53 listener: AsyncTcpListener,
54 application: HttpApplication,
55 scope: CoroutineScope,
56 options: HttpServerOptions = httpServerOptions()
57 ): HttpServer {
58 val loop = currentEventLoop()
59 val caller =
60 currentJobOrNone() ?:
61 throw IllegalStateException(Some("HTTP server requires a Job"))
62 caller.ensureActive()
63 scope.job.ensureActive()
64 if (scope.job.isCompleted)
65 throw IllegalStateException(Some("HTTP server scope is closed"))
66 val state = ServerState(listener, application, options, loop)
67 val server = HttpServer(state)
68 try {
69 startServerTask(caller, scope) {
70 ready ->
71 val owner = currentJobOrNone()!!
72 state.lock.withLock { state.owner = Some(owner) }
73 ready.ready()
74 runServer(state)
75 }
76 caller.ensureActive()
77 state.reportFailure()
78 return server
79 } catch (error: Throwable) {
80 if (state.lock.withLock { present(state.owner) }) {
81 try {
82 server.close()
83 }
84 catch (cleanup: Throwable) {
85 if (cleanup !== error)
86 throw ResourceUseException(error, cleanup)
87 }
88 }
89 throw error
90 }
91 }
92 }
94 /** The bound address snapshot, including an OS-selected port; remains available after closing. */
95 public val localAddress: SocketAddress = state.listener.localAddress
97 /** Whether the server has stopped accepting new connections. */
98 public val isDraining: Boolean get() =
99 state.lock.withLock { state.phase != ServerPhase.Running }
100 /** Whether all server-owned work and local resource cleanup has ended. */
101 public val isClosed: Boolean get() = state.lock.withLock { state.phase == ServerPhase.Closed }
103 /** Waits without initiating shutdown, then reports any server-owner failure. */
104 public suspend fun awaitTermination() {
105 requireLoop()
106 state.owner!!.join()
107 state.reportFailure()
108 }
110 /** Stops accepting and drains using the configured natural-drain period. */
111 public suspend fun shutdownGracefully() {
112 shutdownGracefully(state.options.gracefulShutdownTimeout)
113 }
115 /** Stops accepting and allows active requests to finish within an explicit natural-drain period. */
116 public suspend fun shutdownGracefully(grace: Duration) {
117 requireServerDuration(Some(grace))
118 requireLoop()
119 var failure: Throwable? = None
120 try {
121 try {
122 serverDeadline<Unit>(
123 Some(grace),
124 "graceful shutdown",
125 suspend {
126 state.stopAccepting()
127 state.listener.close()
128 state.owner!!.join()
129 }
130 )
131 }
132 catch (_: HttpServerTimeoutException) {
133 state.owner!!.cancel()
134 }
135 } catch (error: Throwable) {
136 failure = Some(error);
137 state.owner!!.cancel()
138 }
139 finally {
140 nonCancellableScope<Unit> { this @HttpServer.state.owner!!.join() }
141 }
142 if (present(failure))
143 throw failure!!
144 state.reportFailure()
145 }
147 /** Cancels owned work immediately and waits for actual local cleanup. */
148 public override suspend fun close() {
149 requireLoop()
150 state.stopAccepting(false)
151 state.owner!!.cancel()
152 nonCancellableScope<Unit> { this @HttpServer.state.owner!!.join() }
153 state.reportFailure()
154 }
156 private fun requireLoop() {
157 if (currentEventLoop() !== state.loop || !present(currentJobOrNone()))
158 throw IllegalStateException(
159 Some("HTTP server operation requires its event loop and a Job")
160 )
161 }
164internal suspend fun runServer(state: ServerState) {
165 val connectionExecutor = currentCoroutineExecutorOrNone() ?: state.loop.executor
166 try {
167 withExecutor<Unit>(state.loop.executor) {
168 val scope = this
169 try {
170 while (state.running()) {
171 val transport = state.listener.accept()
172 val connection = ServerConnection(transport)
173 if (!state.register(connection)) {
174 transport.close();
175 continue
176 }
177 try {
178 startServerTask(scope.job, scope) {
179 ready ->
180 val owner = job
181 state.lock.withLock { connection.job = Some(owner) }
182 ready.ready()
183 dispatchServerConnection(state, connection, connectionExecutor)
184 }
185 }
186 catch (error: Throwable) {
187 state.unregister(connection);
188 transport.close();
189 throw error
190 }
191 }
192 } catch (error: Throwable) {
193 if (state.running())
194 throw error
195 }
196 }
197 } catch (error: Throwable) {
198 if (!(error is CancellationException))
199 state.recordFailure(error)
200 } finally {
201 try {
202 state.listener.close()
203 }
204 catch (error: Throwable) {
205 state.recordFailure(error)
206 }
207 state.lock.withLock { state.phase = ServerPhase.Closed }
208 }