forked from vapor/vapor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DefaultResponder.swift
182 lines (162 loc) · 6.58 KB
/
DefaultResponder.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import Metrics
/// Vapor's main `Responder` type. Combines configured middleware + router to create a responder.
internal struct DefaultResponder: Responder {
private let router: TrieRouter<CachedRoute>
private let notFoundResponder: Responder
private let reportMetrics: Bool
private struct CachedRoute {
let route: Route
let responder: Responder
}
/// Creates a new `ApplicationResponder`
public init(routes: Routes, middleware: [Middleware] = [], reportMetrics: Bool = true) {
let options = routes.caseInsensitive ?
Set(arrayLiteral: TrieRouter<CachedRoute>.ConfigurationOption.caseInsensitive) : []
let router = TrieRouter(CachedRoute.self, options: options)
for route in routes.all {
// Make a copy of the route to cache middleware chaining.
let cached = CachedRoute(
route: route,
responder: middleware.makeResponder(chainingTo: route.responder)
)
// remove any empty path components
let path = route.path.filter { component in
switch component {
case .constant(let string):
return string != ""
default:
return true
}
}
// If the route isn't explicitly a HEAD route,
// and it's made up solely of .constant components,
// register a HEAD route with the same path
if route.method == .GET &&
route.path.allSatisfy({ component in
if case .constant(_) = component { return true }
return false
}) {
let headRoute = Route(
method: .HEAD,
path: cached.route.path,
responder: middleware.makeResponder(chainingTo: HeadResponder()),
requestType: cached.route.requestType,
responseType: cached.route.responseType)
let headCachedRoute = CachedRoute(route: headRoute, responder: middleware.makeResponder(chainingTo: HeadResponder()))
router.register(headCachedRoute, at: [.constant(HTTPMethod.HEAD.string)] + path)
}
router.register(cached, at: [.constant(route.method.string)] + path)
}
self.router = router
self.notFoundResponder = middleware.makeResponder(chainingTo: NotFoundResponder())
self.reportMetrics = reportMetrics
}
/// See `Responder`
public func respond(to request: Request) -> EventLoopFuture<Response> {
let startTime = DispatchTime.now().uptimeNanoseconds
let response: EventLoopFuture<Response>
if let cachedRoute = self.getRoute(for: request) {
request.route = cachedRoute.route
response = cachedRoute.responder.respond(to: request)
} else {
response = self.notFoundResponder.respond(to: request)
}
return response.always { result in
let status: HTTPStatus
switch result {
case .success(let response):
status = response.status
case .failure:
status = .internalServerError
}
if self.reportMetrics {
self.updateMetrics(
for: request,
startTime: startTime,
statusCode: status.code
)
}
}
}
/// Gets a `Route` from the underlying `TrieRouter`.
private func getRoute(for request: Request) -> CachedRoute? {
let pathComponents = request.url.path
.split(separator: "/")
.map(String.init)
// If it's a HEAD request and a HEAD route exists, return that route...
if request.method == .HEAD, let route = self.router.route(
path: [HTTPMethod.HEAD.string] + pathComponents,
parameters: &request.parameters
) {
return route
}
// ...otherwise forward HEAD requests to GET route
let method = (request.method == .HEAD) ? .GET : request.method
return self.router.route(
path: [method.string] + pathComponents,
parameters: &request.parameters
)
}
/// Records the requests metrics.
private func updateMetrics(
for request: Request,
startTime: UInt64,
statusCode: UInt
) {
let pathForMetrics: String
let methodForMetrics: String
if let route = request.route {
// We don't use route.description here to avoid duplicating the method in the path
pathForMetrics = "/\(route.path.map { "\($0)" }.joined(separator: "/"))"
methodForMetrics = request.method.string
} else {
// If the route is undefined (i.e. a 404 and not something like /users/:userID
// We rewrite the path and the method to undefined to avoid DOSing the
// application and any downstream metrics systems. Otherwise an attacker
// could spam the service with unlimited requests and exhaust the system
// with unlimited timers/counters
pathForMetrics = "vapor_route_undefined"
methodForMetrics = "undefined"
}
let dimensions = [
("method", methodForMetrics),
("path", pathForMetrics),
("status", statusCode.description),
]
Counter(label: "http_requests_total", dimensions: dimensions).increment()
if statusCode >= 500 {
Counter(label: "http_request_errors_total", dimensions: dimensions).increment()
}
Timer(
label: "http_request_duration_seconds",
dimensions: dimensions,
preferredDisplayUnit: .seconds
).recordNanoseconds(DispatchTime.now().uptimeNanoseconds - startTime)
}
}
private struct HeadResponder: Responder {
func respond(to request: Request) -> EventLoopFuture<Response> {
request.eventLoop.makeSucceededFuture(.init(status: .ok))
}
}
private struct NotFoundResponder: Responder {
func respond(to request: Request) -> EventLoopFuture<Response> {
request.eventLoop.makeFailedFuture(RouteNotFound())
}
}
struct RouteNotFound: Error {
let stackTrace: StackTrace?
init() {
self.stackTrace = StackTrace.capture(skip: 1)
}
}
extension RouteNotFound: AbortError {
var status: HTTPResponseStatus {
.notFound
}
}
extension RouteNotFound: DebuggableError {
var logLevel: Logger.Level {
.debug
}
}