Scoop API

scoop:scoop.http.server:0.1.0

src/application.scoop

Selected production source · src/application.scoop

1package scoop.http.server
3/** Application-level error handling, independent of the server's transport configuration. */
4public class HttpApplicationOptions internal constructor(
5 /** Maps an uncommitted endpoint failure while its middleware Context remains installed. */
6 public val errorMapper: suspend (HttpContext, Throwable) -> HttpResult =
7 suspend { ctx, _ -> text("Internal Server Error\nRequest: " + ctx.requestId, 500U) },
8 /** Observes failures outside internal locks; observer errors do not replace the primary cause. */
9 public val onError: ((HttpContext, Throwable) -> Unit)? = None
12/** An immutable routing table and request pipeline, reusable across server instances. */
13public class HttpApplication internal constructor(
14 internal val routes: RouteNode,
15 private val middleware: Array<HttpMiddleware>,
16 internal val methods: Array<String>,
17 private val options: HttpApplicationOptions
18) {
19 internal suspend fun execute(ctx: HttpContext) {
20 context(ctx) {
21 try {
22 if (middleware.size == 0L)
23 dispatch(ctx)
24 else
25 invokeMiddleware(ctx, middleware, 0L, suspend { dispatch(ctx) })
26 }
27 catch (error: Throwable) {
28 handleFailure(ctx, error)
29 }
30 }
31 }
33 private suspend fun dispatch(ctx: HttpContext) {
34 ctx.request.expectations.requireSupported()
35 val target = ctx.request.target()
36 when (target.kind) {
37 case TargetKind.Connect -> ctx.respond(text("Not Implemented", 501U))
38 case TargetKind.Star -> {
39 if (ctx.request.method == "OPTIONS")
40 ctx.respond(methodResult(204U, methods))
41 else
42 ctx.respond(text("Invalid asterisk target", 400U))
43 }
44 case TargetKind.Path -> {
45 val resource = matchResource(routes, target.segments, 0L, ArrayList<PathSegment>())
46 if (!present(resource)) {
47 val group = matchFallbackGroup(target.segments)
48 ctx.parameters = PathParameters(group.group.names, group.values)
49 invokeEndpoint(ctx, group.group.middleware, group.group.fallback)
50 } else {
51 val match = resource!!
52 val route = selectedMethod(match.node, ctx.request.method)
53 if (present(route)) {
54 val selected = route!!
55 ctx.selectedRoute = Some(selected.info)
56 ctx.parameters = PathParameters(selected.names, match.values)
57 invokeEndpoint(ctx, selected.middleware, selected.handler)
58 } else {
59 val group = matchFallbackGroup(target.segments)
60 ctx.selectedRoute = Some(match.node.endpoints[0L].info)
61 ctx.parameters = PathParameters(group.group.names, group.values)
62 val result =
63 methodResult(
64 if (ctx.request.method == "OPTIONS")
65 204U
66 else
67 405U,
68 resourceMethods(match.node)
69 )
70 invokeEndpoint(ctx, group.group.middleware, suspend { _ -> result })
71 }
72 }
73 }
74 }
75 }
77 private fun matchFallbackGroup(parts: Array<PathSegment>): GroupMatch =
78 matchGroup(routes, parts, 0L, ArrayList<PathSegment>(), GroupMatch(routes.group!!, [], 0L))
80 private suspend fun invokeEndpoint(
81 ctx: HttpContext,
82 chain: Array<HttpMiddleware>,
83 handler: HttpHandler
84 ) {
85 if (chain.size == 0L)
86 endpoint(ctx, handler)
87 else
88 invokeMiddleware(ctx, chain, 0L, suspend { endpoint(ctx, handler) })
89 }
91 private suspend fun endpoint(ctx: HttpContext, handler: HttpHandler) {
92 try {
93 ctx.respond(handler(ctx))
94 }
95 catch (error: Throwable) {
96 handleFailure(ctx, error)
97 }
98 }
100 private suspend fun handleFailure(ctx: HttpContext, failure: Throwable) {
101 val error =
102 if (failure is CommitCallbackFailure)
103 failure.original
104 else
105 failure
106 observeFailure(ctx, error)
107 if (
108 error is
109 CancellationException ||
110 ctx.response.isCommitted ||
111 ctx.response.isAborted ||
112 ctx.mappedFailure
113 ) {
114 try {
115 ctx.abort()
116 }
117 catch (cleanup: Throwable) {
118 throw ResourceUseException(error, cleanup)
119 }
120 throw error
121 }
122 ctx.mappedFailure = true
123 try {
124 if (failure is CommitCallbackFailure) {
125 ctx.sendResult(text("Internal Server Error\nRequest: " + ctx.requestId, 500U), true)
126 } else
127 if (error is HttpRejection) {
128 ctx.respond(error.result)
129 } else {
130 ctx.respond(options.errorMapper(ctx, error))
131 }
132 } catch (secondary: Throwable) {
133 try {
134 ctx.abort()
135 }
136 catch (cleanup: Throwable) {
137 throw ResourceUseException(secondary, cleanup)
138 }
139 throw secondary
140 }
141 }
143 private fun observeFailure(ctx: HttpContext, error: Throwable) {
144 if (present(ctx.observedFailure) && ctx.observedFailure!! === error)
145 return
146 ctx.observedFailure = Some(error)
147 if (present(options.onError)) {
148 try {
149 options.onError!!(ctx, error)
150 }
151 catch (_: Throwable) {
152 return
153 }
154 }
155 }
158private class NextCall {
159 val called: AtomicBoolean = AtomicBoolean(false)
160 val completed: AtomicBoolean = AtomicBoolean(false)
161 val exited: AtomicBoolean = AtomicBoolean(false)
164internal suspend fun invokeMiddleware(
165 ctx: HttpContext,
166 middleware: Array<HttpMiddleware>,
167 index: Long,
168 terminal: HttpNext
169) {
170 if (index == middleware.size) {
171 terminal();
172 return
173 }
174 val next = NextCall()
175 try {
176 middleware[index](
177 ctx,
178 suspend {
179 if (
180 next.exited.load() ||
181 ctx.response.isCommitted ||
182 !next.called.compareAndSet(false, true)
183 )
184 throw IllegalStateException(
185 Some("middleware next may only be awaited once before responding")
186 )
187 try {
188 invokeMiddleware(ctx, middleware, index + 1L, terminal)
189 }
190 finally {
191 next.completed.store(true)
192 }
193 }
194 )
195 if (next.called.load() && !next.completed.load())
196 throw IllegalStateException(Some("middleware did not await next"))
197 if (!ctx.response.isFinished)
198 throw IllegalStateException(Some("middleware returned without completing a response"))
199 } finally {
200 next.exited.store(true)
201 }
204private fun selectedMethod(node: RouteNode, method: String): RoutePlan? {
205 for (route in node.endpoints)
206 if (route.info.method == method)
207 return Some(route)
208 if (method == "HEAD")
209 for (route in node.endpoints)
210 if (route.info.method == "GET")
211 return Some(route)
212 return None
215private fun resourceMethods(node: RouteNode): Array<String> {
216 val methods = ArrayList<String>()
217 for (route in node.endpoints)
218 addMethod(methods, route.info.method)
219 includeImplicitMethods(methods)
220 return methods.toArray()
223private fun methodResult(status: UInt, methods: Array<String>): HttpResult {
224 val allow = StringBuilder()
225 var first = true
226 for (method in methods) {
227 if (!first)
228 allow.append(", ")
229 first = false
230 allow.append(method)
231 }
232 return empty(status, [field("Allow", allow.toString())])