-
-
Notifications
You must be signed in to change notification settings - Fork 59
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
This will also generate unique identifiers across multiple instances of a Humminbird application
- Loading branch information
1 parent
8b6590a
commit 1cafa1d
Showing
3 changed files
with
78 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,42 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// 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 | ||
let high: UInt64 | ||
|
||
init() { | ||
self.low = Self.globalRequestID.loadThenWrappingIncrement(by: 1, ordering: .relaxed) | ||
self.high = Self.instanceIdentifier | ||
} | ||
|
||
var description: String { | ||
self.formatAsHexWithLeadingZeros(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 instanceIdentifier = UInt64.random(in: .min ... .max) | ||
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