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

Add RequestID to generate unique Identifier for each request #326

Merged
merged 4 commits into from
Dec 31, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
7 changes: 2 additions & 5 deletions Sources/Hummingbird/Server/Request.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2022 the Hummingbird authors
// Copyright (c) 2021-2023 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
Expand All @@ -12,7 +12,6 @@
//
//===----------------------------------------------------------------------===//

import Atomics
import HummingbirdCore
import Logging
import NIOConcurrencyHelpers
Expand Down Expand Up @@ -106,7 +105,7 @@ public struct HBRequest: Sendable, HBSendableExtensible {
context: context
)
self.body = body
self.logger = application.logger.with(metadataKey: "hb_id", value: .stringConvertible(Self.globalRequestID.loadThenWrappingIncrement(by: 1, ordering: .relaxed)))
self.logger = application.logger.with(metadataKey: "hb_id", value: .stringConvertible(RequestID()))
self.extensions = .init()
}

Expand Down Expand Up @@ -215,8 +214,6 @@ public struct HBRequest: Sendable, HBSendableExtensible {
}

private var _internal: _Internal

private static let globalRequestID = ManagedAtomic(0)
}

extension Logger {
Expand Down
40 changes: 40 additions & 0 deletions Sources/Hummingbird/Server/RequestID.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2023 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import Atomics

/// Generate Unique ID for each request
struct RequestID: CustomStringConvertible {
let low: UInt64

init() {
self.low = Self.globalRequestID.loadThenWrappingIncrement(by: 1, ordering: .relaxed)
}

var description: String {
String(Self.high, radix: 16) + self.formatAsHexWithLeadingZeros(self.low)
}
Copy link
Contributor

@MahdiBM MahdiBM Dec 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • It's certainly cleaner this way, but it still feels unnecessary to transform high to a String once per RequestID.description call, considering .description will be common due to the logging statement.
  • Doesn't this hex description (partially) defeat the point of having a nice easily-human-readable integer as the request's id? At that point a random UUID could just be the simpler solution although i assume it's somewhat more costly to create.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point about transforming high repeatedly.

I'm not using UUID because one it requires Foundation and two it is slower to generate. I reduced it to hex to shorten the id and the first 16 chars end up being a process id. Anyway not sure a 128bit integer is human readable.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm fair enough. I now think it's fine being a hex 🤔 i was thinking someone might rather read/have it as a decimal number, but I can't come up with enough reasons why that should be important. They can always turn the hex back to an integer trivially if it's that important 🤔


func formatAsHexWithLeadingZeros(_ value: UInt64) -> String {
let string = String(value, radix: 16)
if string.count < 16 {
return String(repeating: "0", count: 16 - string.count) + string

Check warning on line 32 in Sources/Hummingbird/Server/RequestID.swift

View check run for this annotation

Codecov / codecov/patch

Sources/Hummingbird/Server/RequestID.swift#L32

Added line #L32 was not covered by tests
} else {
return string
}
}

private static let high = UInt64.random(in: .min ... .max)
private static let globalRequestID = ManagedAtomic<UInt64>(UInt64.random(in: .min ... .max))
}
39 changes: 34 additions & 5 deletions Tests/HummingbirdTests/RouterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -331,25 +331,54 @@ final class RouterTests: XCTestCase {
}
}

/// Test we have a request id and that it increments with each request
/// Test we have a request id and that it is unique for 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 id = 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)
let id2 = String(buffer: body)
XCTAssertNotEqual(id2, id)
}
}

/// Test we have a request id and that it is unique for each request even across instances
/// of running applications
func testRequestIdAcrossInstances() throws {
let id: String?
do {
let app = HBApplication(testing: .embedded)
app.router.get("id") { $0.id }
try app.XCTStart()
defer { app.XCTStop() }

id = try app.XCTExecute(uri: "/id", method: .GET) { response -> String in
let body = try XCTUnwrap(response.body)
return String(buffer: body)
}
}
let id2: String?
do {
let app = HBApplication(testing: .embedded)
app.router.get("id") { $0.id }
try app.XCTStart()
defer { app.XCTStop() }

id2 = try app.XCTExecute(uri: "/id", method: .GET) { response -> String in
let body = try XCTUnwrap(response.body)
return String(buffer: body)
}
}
XCTAssertNotEqual(id, id2)
}

// Test redirect response
func testRedirect() throws {
let app = HBApplication(testing: .embedded)
Expand Down
Loading