-
-
Notifications
You must be signed in to change notification settings - Fork 56
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add RequestID to generate unique Identifier for each request (#326)
* Add RequestID to generate unique Identifier for each request This will also generate unique identifiers across multiple instances of a Humminbird application * Don't bother with leading zeros for high value in request id * Don't need to store high in RequestID as it is the same for all ids * Don't keep rebuilding high string
- Loading branch information
1 parent
8b6590a
commit 02ab651
Showing
3 changed files
with
76 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | ||
Self.high + self.formatAsHexWithLeadingZeros(self.low) | ||
} | ||
|
||
func formatAsHexWithLeadingZeros(_ value: UInt64) -> String { | ||
let string = String(value, radix: 16) | ||
if string.count < 16 { | ||
return String(repeating: "0", count: 16 - string.count) + string | ||
} else { | ||
return string | ||
} | ||
} | ||
|
||
private static let high = String(UInt64.random(in: .min ... .max), radix: 16) | ||
private static let globalRequestID = ManagedAtomic<UInt64>(UInt64.random(in: .min ... .max)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters