Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace RequestContext initialization parameters with associatedtype #469

Merged
merged 4 commits into from
Jun 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions Sources/Hummingbird/Application.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ public enum EventLoopGroupProvider {
}
}

public protocol ApplicationProtocol: Service where Context: RequestContext {
/// Protocol for an Application. Brings together all the components of Hummingbird together
public protocol ApplicationProtocol: Service where Context: InstantiableRequestContext, Context.Source == ServerRequestContextSource {
/// Responder that generates a response from a requests and context
associatedtype Responder: HTTPResponder
/// Context passed with Request to responder
Expand Down Expand Up @@ -100,9 +101,12 @@ extension ApplicationProtocol {
eventLoopGroup: self.eventLoopGroup,
logger: self.logger
) { request, channel in
let logger = self.logger.with(metadataKey: "hb_id", value: .stringConvertible(RequestID()))
let context = Self.Responder.Context(
channel: channel,
logger: self.logger.with(metadataKey: "hb_id", value: .stringConvertible(RequestID()))
source: .init(
channel: channel,
logger: logger
)
)
// respond to request
var response: Response
Expand All @@ -115,7 +119,7 @@ extension ApplicationProtocol {
response = httpError.response(allocator: channel.allocator)
default:
// this error has not been recognised
context.logger.debug("Unrecognised Error", metadata: ["error": "\(error)"])
logger.debug("Unrecognised Error", metadata: ["error": "\(error)"])
response = Response(
status: .internalServerError,
body: .init()
Expand Down Expand Up @@ -169,10 +173,7 @@ extension ApplicationProtocol {
/// try await app.runService()
/// ```
/// Editing the application setup after calling `runService` will produce undefined behaviour.
public struct Application<Responder: HTTPResponder>: ApplicationProtocol where Responder.Context: RequestContext {
public typealias Context = Responder.Context
public typealias Responder = Responder

public struct Application<Responder: HTTPResponder>: ApplicationProtocol where Responder.Context: InstantiableRequestContext, Responder.Context.Source == ServerRequestContextSource {
// MARK: Member variables

/// event loop group used by application
Expand Down
4 changes: 2 additions & 2 deletions Sources/Hummingbird/Codable/CodableProtocols.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public protocol ResponseEncoder {
/// - Parameters:
/// - value: value to encode
/// - request: request that generated this value
func encode(_ value: some Encodable, from request: Request, context: some BaseRequestContext) throws -> Response
func encode(_ value: some Encodable, from request: Request, context: some RequestContext) throws -> Response
}

/// protocol for decoder deserializing from a Request body
Expand All @@ -30,5 +30,5 @@ public protocol RequestDecoder {
/// - Parameters:
/// - type: type to decode to
/// - request: request
func decode<T: Decodable>(_ type: T.Type, from request: Request, context: some BaseRequestContext) async throws -> T
func decode<T: Decodable>(_ type: T.Type, from request: Request, context: some RequestContext) async throws -> T
}
4 changes: 2 additions & 2 deletions Sources/Hummingbird/Codable/JSON/JSONCoding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ extension JSONEncoder: ResponseEncoder {
/// - Parameters:
/// - value: Value to encode
/// - request: Request used to generate response
public func encode(_ value: some Encodable, from request: Request, context: some BaseRequestContext) throws -> Response {
public func encode(_ value: some Encodable, from request: Request, context: some RequestContext) throws -> Response {
let data = try self.encode(value)
let buffer = context.allocator.buffer(data: data)
return Response(
Expand All @@ -41,7 +41,7 @@ extension JSONDecoder: RequestDecoder {
/// - Parameters:
/// - type: Type to decode
/// - request: Request to decode from
public func decode<T: Decodable>(_ type: T.Type, from request: Request, context: some BaseRequestContext) async throws -> T {
public func decode<T: Decodable>(_ type: T.Type, from request: Request, context: some RequestContext) async throws -> T {
let buffer = try await request.body.collect(upTo: context.maxUploadSize)
return try self.decode(T.self, from: buffer)
}
Expand Down
6 changes: 3 additions & 3 deletions Sources/Hummingbird/Codable/ResponseEncodable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public protocol ResponseCodable: ResponseEncodable, Decodable {}

/// Extend ResponseEncodable to conform to ResponseGenerator
extension ResponseEncodable {
public func response(from request: Request, context: some BaseRequestContext) throws -> Response {
public func response(from request: Request, context: some RequestContext) throws -> Response {
return try context.responseEncoder.encode(self, from: request, context: context)
}
}
Expand All @@ -33,7 +33,7 @@ extension Array: ResponseGenerator where Element: Encodable {}

/// Extend Array to conform to ResponseEncodable
extension Array: ResponseEncodable where Element: Encodable {
public func response(from request: Request, context: some BaseRequestContext) throws -> Response {
public func response(from request: Request, context: some RequestContext) throws -> Response {
return try context.responseEncoder.encode(self, from: request, context: context)
}
}
Expand All @@ -43,7 +43,7 @@ extension Dictionary: ResponseGenerator where Key: Encodable, Value: Encodable {

/// Extend Array to conform to ResponseEncodable
extension Dictionary: ResponseEncodable where Key: Encodable, Value: Encodable {
public func response(from request: Request, context: some BaseRequestContext) throws -> Response {
public func response(from request: Request, context: some RequestContext) throws -> Response {
return try context.responseEncoder.encode(self, from: request, context: context)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ extension URLEncodedFormEncoder: ResponseEncoder {
/// - Parameters:
/// - value: Value to encode
/// - request: Request used to generate response
public func encode(_ value: some Encodable, from request: Request, context: some BaseRequestContext) throws -> Response {
public func encode(_ value: some Encodable, from request: Request, context: some RequestContext) throws -> Response {
let string = try self.encode(value)
let buffer = context.allocator.buffer(string: string)
return Response(
Expand All @@ -36,7 +36,7 @@ extension URLEncodedFormDecoder: RequestDecoder {
/// - Parameters:
/// - type: Type to decode
/// - request: Request to decode from
public func decode<T: Decodable>(_ type: T.Type, from request: Request, context: some BaseRequestContext) async throws -> T {
public func decode<T: Decodable>(_ type: T.Type, from request: Request, context: some RequestContext) async throws -> T {
let buffer = try await request.body.collect(upTo: context.maxUploadSize)
let string = String(buffer: buffer)
return try self.decode(T.self, from: string)
Expand Down
10 changes: 6 additions & 4 deletions Sources/Hummingbird/Deprecations.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@ public typealias HBEnvironment = Environment
@_documentation(visibility: internal) @available(*, deprecated, renamed: "FileIO")
public typealias HBFileIO = FileIO

@_documentation(visibility: internal) @available(*, deprecated, renamed: "BaseRequestContext")
public typealias HBBaseRequestContext = BaseRequestContext
@_documentation(visibility: internal) @available(*, deprecated, renamed: "RequestContext")
public typealias HBBaseRequestContext = RequestContext
@_documentation(visibility: internal) @available(*, deprecated, renamed: "BasicRequestContext")
public typealias HBBasicRequestContext = BasicRequestContext
@_documentation(visibility: internal) @available(*, deprecated, renamed: "CoreRequestContext")
public typealias HBCoreRequestContext = CoreRequestContext
@_documentation(visibility: internal) @available(*, deprecated, renamed: "CoreRequestContextStorage")
public typealias HBCoreRequestContext = CoreRequestContextStorage
@_documentation(visibility: internal) @available(*, deprecated, renamed: "CoreRequestContextStorage")
public typealias CoreRequestContext = CoreRequestContextStorage
@_documentation(visibility: internal) @available(*, deprecated, renamed: "RequestContext")
public typealias HBRequestContext = RequestContext
@_documentation(visibility: internal) @available(*, deprecated, renamed: "RequestDecoder")
Expand Down
10 changes: 5 additions & 5 deletions Sources/Hummingbird/Files/FileIO.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public struct FileIO: Sendable {
/// - context: Context this request is being called in
/// - chunkLength: Size of the chunks read from disk and loaded into memory (in bytes). Defaults to the value suggested by `swift-nio`.
/// - Returns: Response body
public func loadFile(path: String, context: some BaseRequestContext, chunkLength: Int = NonBlockingFileIO.defaultChunkSize) async throws -> ResponseBody {
public func loadFile(path: String, context: some RequestContext, chunkLength: Int = NonBlockingFileIO.defaultChunkSize) async throws -> ResponseBody {
do {
let stat = try await fileIO.lstat(path: path)
return self.readFile(path: path, range: 0...numericCast(stat.st_size - 1), context: context, chunkLength: chunkLength)
Expand All @@ -55,7 +55,7 @@ public struct FileIO: Sendable {
/// - context: Context this request is being called in
/// - chunkLength: Size of the chunks read from disk and loaded into memory (in bytes). Defaults to the value suggested by `swift-nio`.
/// - Returns: Response body plus file size
public func loadFile(path: String, range: ClosedRange<Int>, context: some BaseRequestContext, chunkLength: Int = NonBlockingFileIO.defaultChunkSize) async throws -> ResponseBody {
public func loadFile(path: String, range: ClosedRange<Int>, context: some RequestContext, chunkLength: Int = NonBlockingFileIO.defaultChunkSize) async throws -> ResponseBody {
do {
let stat = try await fileIO.lstat(path: path)
let fileRange: ClosedRange<Int> = 0...numericCast(stat.st_size - 1)
Expand All @@ -75,7 +75,7 @@ public struct FileIO: Sendable {
public func writeFile<AS: AsyncSequence>(
contents: AS,
path: String,
context: some BaseRequestContext
context: some RequestContext
) async throws where AS.Element == ByteBuffer {
context.logger.debug("[FileIO] PUT", metadata: ["file": .string(path)])
try await self.fileIO.withFileHandle(path: path, mode: .write, flags: .allowFileCreation()) { handle in
Expand All @@ -94,7 +94,7 @@ public struct FileIO: Sendable {
public func writeFile(
buffer: ByteBuffer,
path: String,
context: some BaseRequestContext
context: some RequestContext
) async throws {
context.logger.debug("[FileIO] PUT", metadata: ["file": .string(path)])
try await self.fileIO.withFileHandle(path: path, mode: .write, flags: .allowFileCreation()) { handle in
Expand All @@ -103,7 +103,7 @@ public struct FileIO: Sendable {
}

/// Return response body that will read file
func readFile(path: String, range: ClosedRange<Int>, context: some BaseRequestContext, chunkLength: Int = NonBlockingFileIO.defaultChunkSize) -> ResponseBody {
func readFile(path: String, range: ClosedRange<Int>, context: some RequestContext, chunkLength: Int = NonBlockingFileIO.defaultChunkSize) -> ResponseBody {
return ResponseBody(contentLength: range.count) { writer in
try await self.fileIO.withFileHandle(path: path, mode: .read) { handle in
let endOffset = range.endIndex
Expand Down
4 changes: 2 additions & 2 deletions Sources/Hummingbird/Files/FileProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@ public protocol FileProvider: Sendable {
/// - path: Full path to file
/// - context: Request context
/// - Returns: Response body
func loadFile(path: String, context: some BaseRequestContext) async throws -> ResponseBody
func loadFile(path: String, context: some RequestContext) async throws -> ResponseBody

/// Return a reponse body that will write a partial file body
/// - Parameters:
/// - path: Full path to file
/// - range: Part of file to return
/// - context: Request context
/// - Returns: Response body
func loadFile(path: String, range: ClosedRange<Int>, context: some BaseRequestContext) async throws -> ResponseBody
func loadFile(path: String, range: ClosedRange<Int>, context: some RequestContext) async throws -> ResponseBody
}
4 changes: 2 additions & 2 deletions Sources/Hummingbird/Files/LocalFileSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public struct LocalFileSystem: FileProvider {
/// - path: Full path to file
/// - context: Request context
/// - Returns: Response body
public func loadFile(path: String, context: some BaseRequestContext) async throws -> ResponseBody {
public func loadFile(path: String, context: some RequestContext) async throws -> ResponseBody {
try await self.fileIO.loadFile(path: path, context: context)
}

Expand All @@ -113,7 +113,7 @@ public struct LocalFileSystem: FileProvider {
/// - range: Part of file to return
/// - context: Request context
/// - Returns: Response body
public func loadFile(path: String, range: ClosedRange<Int>, context: some BaseRequestContext) async throws -> ResponseBody {
public func loadFile(path: String, range: ClosedRange<Int>, context: some RequestContext) async throws -> ResponseBody {
try await self.fileIO.loadFile(path: path, range: range, context: context)
}
}
2 changes: 1 addition & 1 deletion Sources/Hummingbird/Middleware/CORSMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import NIOCore
/// then return an empty body with all the standard CORS headers otherwise send
/// request onto the next handler and when you receive the response add a
/// "access-control-allow-origin" header
public struct CORSMiddleware<Context: BaseRequestContext>: RouterMiddleware {
public struct CORSMiddleware<Context: RequestContext>: RouterMiddleware {
/// Defines what origins are allowed
public enum AllowOrigin: Sendable {
case none
Expand Down
2 changes: 1 addition & 1 deletion Sources/Hummingbird/Middleware/FileMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public protocol FileMiddlewareFileAttributes {
/// "if-modified-since", "if-none-match", "if-range" and 'range" headers. It will output "content-length",
/// "modified-date", "eTag", "content-type", "cache-control" and "content-range" headers where
/// they are relevant.
public struct FileMiddleware<Context: BaseRequestContext, Provider: FileProvider>: RouterMiddleware where Provider.FileAttributes: FileMiddlewareFileAttributes {
public struct FileMiddleware<Context: RequestContext, Provider: FileProvider>: RouterMiddleware where Provider.FileAttributes: FileMiddlewareFileAttributes {
let cacheControl: CacheControl
let searchForIndexHtml: Bool
let fileProvider: Provider
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import HTTPTypes
import Logging

/// Middleware outputting to log for every call to server
public struct LogRequestsMiddleware<Context: BaseRequestContext>: RouterMiddleware {
public struct LogRequestsMiddleware<Context: RequestContext>: RouterMiddleware {
/// Header filter
public struct HeaderFilter: Sendable, ExpressibleByArrayLiteral {
fileprivate enum _Internal: Sendable {
Expand Down
2 changes: 1 addition & 1 deletion Sources/Hummingbird/Middleware/MetricsMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import Metrics
///
/// Records the number of requests, the request duration and how many errors were thrown. Each metric has additional
/// dimensions URI and method.
public struct MetricsMiddleware<Context: BaseRequestContext>: RouterMiddleware {
public struct MetricsMiddleware<Context: RequestContext>: RouterMiddleware {
public init() {}

public func handle(_ request: Request, context: Context, next: (Request, Context) async throws -> Response) async throws -> Response {
Expand Down
4 changes: 2 additions & 2 deletions Sources/Hummingbird/Middleware/TracingMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import Tracing
/// You may opt in to recording a specific subset of HTTP request/response header values by passing
/// a set of header names.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct TracingMiddleware<Context: BaseRequestContext>: RouterMiddleware {
public struct TracingMiddleware<Context: RequestContext>: RouterMiddleware {
private let headerNamesToRecord: Set<RecordingHeader>
private let attributes: SpanAttributes?

Expand Down Expand Up @@ -164,7 +164,7 @@ extension UnsafeTransfer: @unchecked Sendable {}
///
/// If you want the TracingMiddleware to record the remote address of requests
/// then your request context will need to conform to this protocol
public protocol RemoteAddressRequestContext: BaseRequestContext {
public protocol RemoteAddressRequestContext: RequestContext {
/// Connected host address
var remoteAddress: SocketAddress? { get }
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Hummingbird/Router/EndpointResponder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import HTTPTypes

/// Stores endpoint responders for each HTTP method
@usableFromInline
struct EndpointResponders<Context: BaseRequestContext>: Sendable {
struct EndpointResponders<Context>: Sendable {
init(path: String) {
self.path = path
self.methods = [:]
Expand Down
Loading
Loading