Repository: hummingbird-project/hummingbird (swift)

Issue:
Feature: Associate a unique ID with each request
Vapor keeps a unique ID for each request which, although not publicly exposed yet, allows us to track logs related to a specific request. I think that this kind of information could also be useful for logs originating from a handled Hummingbird Request.

Related: https://github.com/vapor/vapor/pull/2964

Pull request description:

Patch:
diff --git a/Sources/Hummingbird/Server/Request.swift b/Sources/Hummingbird/Server/Request.swift
index e888b50e9..c7e6e25ad 100644
--- a/Sources/Hummingbird/Server/Request.swift
+++ b/Sources/Hummingbird/Server/Request.swift
@@ -48,6 +48,9 @@ public struct HBRequest: HBSendableExtensible {
     /// IP request came from
     public var remoteAddress: SocketAddress? { self._internal.context.remoteAddress }
 
+    /// Request ID (Uses ID attached to loggger to avoid replication)
+    public var id: String { self.logger[metadataKey: "hb_id"]!.description }
+
     /// Parameters extracted during processing of request URI. These are available to you inside the route handler
     public var parameters: HBParameters {
         get {


Test patch:
diff --git a/Tests/HummingbirdTests/RouterTests.swift b/Tests/HummingbirdTests/RouterTests.swift
index 0a70d1309..3530446d2 100644
--- a/Tests/HummingbirdTests/RouterTests.swift
+++ b/Tests/HummingbirdTests/RouterTests.swift
@@ -295,6 +295,25 @@ final class RouterTests: XCTestCase {
             XCTAssertEqual(String(buffer: body), "1234")
         }
     }
+
+    /// Test we have a request id and that it increments with each request
+    func testRequestId() throws {
+        let app = HBApplication(testing: .embedded)
+        app.router.get("id") { $0.id }
+        try app.XCTStart()
+        defer { app.XCTStop() }
+
+        let idString = try app.XCTExecute(uri: "/id", method: .GET) { response -> String in
+            let body = try XCTUnwrap(response.body)
+            return String(buffer: body)
+        }
+        let id = try XCTUnwrap(Int(idString))
+        try app.XCTExecute(uri: "/id", method: .GET) { response in
+            let body = try XCTUnwrap(response.body)
+            let id2 = Int(String(buffer: body))
+            XCTAssertEqual(id2, id + 1)
+        }
+    }
 }
 
 extension HBRequest {