forked from apple/swift-http-api-proposal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPServerLoggingMiddleware.swift
More file actions
265 lines (239 loc) · 10.4 KB
/
Copy pathHTTPServerLoggingMiddleware.swift
File metadata and controls
265 lines (239 loc) · 10.4 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP API Proposal open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift HTTP API Proposal project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
public import HTTPAPIs
public import Logging
public import Middleware
/// A middleware that logs HTTP server requests and responses.
///
/// ``HTTPServerLoggingMiddleware`` wraps the request reader and response writer with logging
/// decorators that output information about the HTTP request path, method, response status,
/// and the number of bytes read from the request body and written to the response body.
/// This middleware is useful for debugging and monitoring HTTP traffic.
@available(anyAppleOS 26.0, *)
public struct HTTPServerLoggingMiddleware<
RequestConcludingAsyncReader: ConcludingAsyncReader & ~Copyable,
ResponseConcludingAsyncWriter: ConcludingAsyncWriter & ~Copyable
>: Middleware
where
RequestConcludingAsyncReader: ~Copyable & Escapable,
RequestConcludingAsyncReader.Underlying: ~Copyable & Escapable,
RequestConcludingAsyncReader.Underlying.ReadElement == UInt8,
RequestConcludingAsyncReader.FinalElement == HTTPFields?,
ResponseConcludingAsyncWriter: ~Copyable & Escapable,
ResponseConcludingAsyncWriter.Underlying: ~Copyable & Escapable,
ResponseConcludingAsyncWriter.Underlying.WriteElement == UInt8,
ResponseConcludingAsyncWriter.FinalElement == HTTPFields?
{
public typealias Input = HTTPServerMiddlewareInput<RequestConcludingAsyncReader, ResponseConcludingAsyncWriter>
public typealias NextInput = HTTPServerMiddlewareInput<
HTTPRequestLoggingConcludingAsyncReader<RequestConcludingAsyncReader>,
HTTPResponseLoggingConcludingAsyncWriter<ResponseConcludingAsyncWriter>
>
let logger: Logger
/// Creates a new logging middleware.
///
/// - Parameters:
/// - requestConcludingAsyncReaderType: The type of the request reader. Defaults to the inferred type.
/// - responseConcludingAsyncWriterType: The type of the response writer. Defaults to the inferred type.
/// - logger: The logger instance to use for logging HTTP events.
public init(
requestConcludingAsyncReaderType: RequestConcludingAsyncReader.Type = RequestConcludingAsyncReader.self,
responseConcludingAsyncWriterType: ResponseConcludingAsyncWriter.Type = ResponseConcludingAsyncWriter.self,
logger: Logger
) {
self.logger = logger
}
public func intercept<Return: ~Copyable>(
input: consuming Input,
next: (consuming NextInput) async throws -> Return
) async throws -> Return {
try await input.withContents { request, context, requestReader, responseSender in
self.logger.info("Received request \(request.path ?? "unknown" ) \(request.method.rawValue)")
defer {
self.logger.info("Finished request \(request.path ?? "unknown" ) \(request.method.rawValue)")
}
let wrappedReader = HTTPRequestLoggingConcludingAsyncReader(
base: requestReader,
logger: self.logger
)
var maybeSender = Optional(responseSender)
let requestResponseBox = HTTPServerMiddlewareInput(
request: request,
requestContext: context,
requestReader: wrappedReader,
responseSender: HTTPResponseSender { [logger] response in
if let sender = maybeSender.take() {
logger.info("Sending response \(response)")
let writer = try await sender.send(response)
return HTTPResponseLoggingConcludingAsyncWriter(
base: writer,
logger: logger
)
} else {
fatalError("Called closure more than once")
}
} sendInformational: { response in
self.logger.info("Sending informational response \(response)")
try await maybeSender?.sendInformational(response)
}
)
return try await next(requestResponseBox)
}
}
}
@available(anyAppleOS 26.0, *)
extension Middleware where Input: ~Copyable, NextInput: ~Copyable {
/// Creates logging middleware for HTTP servers.
///
/// This middleware logs all incoming requests and outgoing responses, including the request
/// path, method, response status, and the number of bytes read and written in the body.
///
/// - Parameter logger: The logger to use for logging requests and responses.
/// - Returns: A middleware that logs HTTP request and response details.
///
/// ## Example
///
/// ```swift
/// @MiddlewareBuilder
/// func buildMiddleware() -> some Middleware<...> {
/// .logging(logger: Logger(label: "HTTPServer"))
/// .requestHandler()
/// }
/// ```
public func logging<RequestReader, ResponseWriter>(
logger: Logger
) -> HTTPServerLoggingMiddleware<RequestReader, ResponseWriter>
where
Input == HTTPServerMiddlewareInput<RequestReader, ResponseWriter>,
RequestReader: ConcludingAsyncReader & ~Copyable & Escapable,
RequestReader.Underlying: ~Copyable & Escapable,
RequestReader.Underlying.ReadElement == UInt8,
RequestReader.FinalElement == HTTPFields?,
ResponseWriter: ConcludingAsyncWriter & ~Copyable & Escapable,
ResponseWriter.Underlying: ~Copyable & Escapable,
ResponseWriter.Underlying.WriteElement == UInt8,
ResponseWriter.FinalElement == HTTPFields?
{
HTTPServerLoggingMiddleware(logger: logger)
}
}
@available(anyAppleOS 26.0, *)
public struct HTTPRequestLoggingConcludingAsyncReader<
Base: ConcludingAsyncReader & ~Copyable
>: ConcludingAsyncReader, ~Copyable
where
Base.Underlying: ~Copyable,
Base.Underlying: Escapable,
Base.Underlying.ReadElement == UInt8,
Base.FinalElement == HTTPFields?
{
public typealias Underlying = RequestBodyAsyncReader
public typealias FinalElement = HTTPFields?
public struct RequestBodyAsyncReader: AsyncReader, ~Copyable {
public typealias ReadElement = UInt8
public typealias ReadFailure = Base.Underlying.ReadFailure
public typealias Buffer = Base.Underlying.Buffer
private var underlying: Base.Underlying
private let logger: Logger
init(underlying: consuming Base.Underlying, logger: Logger) {
self.underlying = underlying
self.logger = logger
}
public mutating func read<Return: ~Copyable, Failure>(
body: (inout Buffer) async throws(Failure) -> Return
) async throws(EitherError<Base.Underlying.ReadFailure, Failure>) -> Return {
let logger = self.logger
return try await self.underlying.read { (buffer: inout Buffer) async throws(Failure) -> Return in
logger.info("Received next chunk \(buffer.count)")
return try await body(&buffer)
}
}
}
private var base: Base
private let logger: Logger
init(base: consuming Base, logger: Logger) {
self.base = base
self.logger = logger
}
public consuming func consumeAndConclude<Return, Failure>(
body: (consuming sending RequestBodyAsyncReader) async throws(Failure) -> Return
) async throws(Failure) -> (Return, HTTPTypes.HTTPFields?) {
let (result, trailers) = try await self.base.consumeAndConclude { [logger] reader async throws(Failure) -> Return in
let wrappedReader = RequestBodyAsyncReader(
underlying: reader,
logger: logger
)
return try await body(wrappedReader)
}
if let trailers {
self.logger.info("Received request trailers \(trailers)")
} else {
self.logger.info("Received no request trailers")
}
return (result, trailers)
}
}
@available(anyAppleOS 26.0, *)
public struct HTTPResponseLoggingConcludingAsyncWriter<
Base: ConcludingAsyncWriter & ~Copyable
>: ConcludingAsyncWriter, ~Copyable
where
Base.Underlying: ~Copyable,
Base.Underlying: Escapable,
Base.Underlying.WriteElement == UInt8,
Base.FinalElement == HTTPFields?
{
public typealias Underlying = ResponseBodyAsyncWriter
public typealias FinalElement = HTTPFields?
public struct ResponseBodyAsyncWriter: AsyncWriter, ~Copyable {
public typealias WriteElement = UInt8
public typealias WriteFailure = Base.Underlying.WriteFailure
public typealias Buffer = Base.Underlying.Buffer
private var underlying: Base.Underlying
private let logger: Logger
init(underlying: consuming Base.Underlying, logger: Logger) {
self.underlying = underlying
self.logger = logger
}
public mutating func write<Result: ~Copyable, Failure>(
_ body: (inout Buffer) async throws(Failure) -> Result
) async throws(EitherError<Base.Underlying.WriteFailure, Failure>) -> Result {
return try await self.underlying.write { (buffer: inout Buffer) async throws(Failure) -> Result in
let result = try await body(&buffer)
self.logger.info("Wrote response bytes \(buffer.count)")
return result
}
}
}
private var base: Base
private let logger: Logger
init(base: consuming Base, logger: Logger) {
self.base = base
self.logger = logger
}
public consuming func produceAndConclude<Return>(
body: (consuming sending ResponseBodyAsyncWriter) async throws -> (Return, HTTPFields?)
) async throws -> Return {
let logger = self.logger
return try await self.base.produceAndConclude { writer in
let wrappedAsyncWriter = ResponseBodyAsyncWriter(underlying: writer, logger: logger)
let (result, trailers) = try await body(wrappedAsyncWriter)
if let trailers {
logger.info("Wrote response trailers \(trailers)")
} else {
logger.info("Wrote no response trailers")
}
return (result, trailers)
}
}
}