feat: add client name option for user identification in system events

This commit is contained in:
wenzuhuai
2026-02-03 11:12:47 +08:00
parent 9161052033
commit 59800438b3
2 changed files with 14 additions and 3 deletions

View File

@@ -31,9 +31,17 @@ public class NatsClientOptions {
private var clientCertificate: URL? = nil
private var clientKey: URL? = nil
private var inboxPrefix: String = "_INBOX."
private var clientName: String = ""
public init() {}
/// Sets the client name sent to the server during CONNECT.
/// This name appears in system events and can be used to identify the client.
public func name(_ name: String) -> NatsClientOptions {
self.clientName = name
return self
}
/// Sets the prefix for inbox subjects used for request/reply.
/// Defaults to "_INBOX."
public func inboxPrefix(_ prefix: String) -> NatsClientOptions {
@@ -195,7 +203,8 @@ public class NatsClientOptions {
clientCertificate: clientCertificate,
clientKey: clientKey,
rootCertificate: rootCertificate,
retryOnFailedConnect: initialReconnect
retryOnFailedConnect: initialReconnect,
name: clientName
)
return client
}

View File

@@ -46,6 +46,7 @@ class ConnectionHandler: ChannelInboundHandler {
private var rootCertificate: URL?
private var clientCertificate: URL?
private var clientKey: URL?
private let clientName: String
typealias InboundIn = ByteBuffer
private let state = NIOLockedValueBox(NatsState.pending)
@@ -86,7 +87,7 @@ class ConnectionHandler: ChannelInboundHandler {
retainServersOrder: Bool,
pingInterval: TimeInterval, auth: Auth?, requireTls: Bool, tlsFirst: Bool,
clientCertificate: URL?, clientKey: URL?,
rootCertificate: URL?, retryOnFailedConnect: Bool
rootCertificate: URL?, retryOnFailedConnect: Bool, name: String
) {
self.urls = urls
self.group = .singleton
@@ -102,6 +103,7 @@ class ConnectionHandler: ChannelInboundHandler {
self.clientKey = clientKey
self.rootCertificate = rootCertificate
self.retryOnFailedConnect = retryOnFailedConnect
self.clientName = name
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
@@ -485,7 +487,7 @@ class ConnectionHandler: ChannelInboundHandler {
private func sendClientConnectInit() async throws {
var initialConnect = ConnectInfo(
verbose: false, pedantic: false, userJwt: nil, nkey: "", name: "", echo: true,
verbose: false, pedantic: false, userJwt: nil, nkey: "", name: self.clientName, echo: true,
lang: self.lang, version: self.version, natsProtocol: .dynamic, tlsRequired: false,
user: self.auth?.user ?? "", pass: self.auth?.password ?? "",
authToken: self.auth?.token ?? "", headers: true, noResponders: true)