-
Notifications
You must be signed in to change notification settings - Fork 187
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
Improvement: rename the variables in TCP reconnect function and some default constants #84
Conversation
WalkthroughThe changes made across multiple files in the repository involve enhancements and adjustments to the TCP client connection management, specifically regarding the reconnection logic. This includes renaming and reorganizing constants, updating the reconnection function to use new parameters, adding support for maximum reconnect attempts, refining error handling for setting deadlines, and adjusting configuration and initialization to support these new options. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Client
participant Server as Server
participant Config as Config
participant Logger as Logger
Client->>Config: Load GettySessionParam
Config-->>Client: TcpMaxReconnectAttempts
Client->>Server: Connect
alt Successful Connection
Server-->>Client: Acknowledge
else Connection Fails
Client->>Logger: Log Connection Failed
loop MaxReconnectAttempts
Client->>Server: Reconnect Attempt
alt Connection Successful
Server-->>Client: Acknowledge
break
else Connection Fails
Client->>Logger: Log Failed Attempt
end
end
Server-->>Client: Max Attempts Reached
end
Client->>Logger: Log Final Status
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (invoked as PR comments)
Additionally, you can add CodeRabbit Configration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Outside diff range and nitpick comments (1)
transport/client.go (1)
Line range hint
210-210
: Error return values fromSetWriteDeadline
andSetReadDeadline
are not checked. This can lead to unhandled errors which might affect the stability of the connection handling.- conn.SetWriteDeadline(time.Now().Add(1e9)) + if err := conn.SetWriteDeadline(time.Now().Add(1e9)); err != nil { + log.Warnf("Failed to set write deadline: %+v", err) + continue + } - conn.SetReadDeadline(time.Now().Add(1e9)) + if err := conn.SetReadDeadline(time.Now().Add(1e9)); err != nil { + log.Warnf("Failed to set read deadline: %+v", err) + continue + }Also applies to: 217-217
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (1)
- transport/client.go (2 hunks)
Additional context used
golangci-lint
transport/client.go
210-210: Error return value of
conn.SetWriteDeadline
is not checked (errcheck)
217-217: Error return value of
conn.SetReadDeadline
is not checked (errcheck)
Additional comments not posted (2)
transport/client.go (2)
44-47
: Renaming of constants enhances clarity and sets a clear distinction between default values and potentially modifiable ones. Good job on making these names more descriptive.
426-452
: The renaming of variables in thereConnect
function improves readability and makes the purpose of each variable clearer.
Co-authored-by: AlexStocks <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Outside diff range and nitpick comments (3)
transport/client.go (3)
427-457
: The refactoredreConnect
function now includes more descriptive variable names and a more structured approach to handling reconnection attempts. However, consider adding comments to explain the logic, especially around the calculation ofmaxReconnectInterval
.
Line range hint
211-211
: The error return value ofconn.SetWriteDeadline
is not checked. This could lead to unhandled errors which might affect the stability of the connection.+ if err := conn.SetWriteDeadline(time.Now().Add(1e9)); err != nil { + log.Errorf("SetWriteDeadline failed: %v", err) + return nil + }
Line range hint
218-218
: Similarly, the error return value ofconn.SetReadDeadline
is not checked. It's crucial to handle this to ensure that the connection timeouts are properly managed.+ if err := conn.SetReadDeadline(time.Now().Add(1e9)); err != nil { + log.Errorf("SetReadDeadline failed: %v", err) + return nil + }
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (2)
- transport/client.go (2 hunks)
- transport/options.go (2 hunks)
Additional context used
golangci-lint
transport/client.go
211-211: Error return value of
conn.SetWriteDeadline
is not checked (errcheck)
218-218: Error return value of
conn.SetReadDeadline
is not checked (errcheck)
Additional comments not posted (2)
transport/options.go (1)
103-106
: Renaming the variables enhances clarity and matches the new naming convention.transport/client.go (1)
44-48
: The renaming of constants to include 'default' in their names clarifies that these are default settings, aligning with the PR's objectives.
transport/options.go
Outdated
// WithReconnectInterval @maxReconnectAttempts is max reconnect attempts. | ||
func WithReconnectAttempts(maxReconnectAttempts int) ClientOption { | ||
return func(o *ClientOptions) { | ||
if 0 < maxReconnectAttempts { | ||
o.maxReconnectAttempts = maxReconnectAttempts | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This function allows for setting the maximum number of reconnect attempts, which is a useful addition. However, consider checking for negative values as well to ensure robustness.
- if 0 < maxReconnectAttempts {
+ if maxReconnectAttempts > 0 {
Committable suggestion was skipped due to low confidence.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (1)
- transport/options.go (2 hunks)
Files skipped from review as they are similar to previous changes (1)
- transport/options.go
// WithReconnectAttempts @maxReconnectAttempts is max reconnect attempts. | ||
func WithReconnectAttempts(maxReconnectAttempts int) ClientOption { | ||
return func(o *ClientOptions) { | ||
if 0 < maxReconnectAttempts { | ||
o.maxReconnectAttempts = maxReconnectAttempts | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这段代码并没有被使用,可以先不加或者加注释。否则被人调用之后发现没有效果反而觉得是个问题。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这段代码并没有被使用,可以先不加或者加注释。否则被人调用之后发现没有效果反而觉得是个问题。
这是给上面提供的接口。要不 @No-SilverBullet 你在代码示例里面调用下?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
11
@AlexStocks 雨哥,看着 reconnect 那边的逻辑其实可以加个 issue,太多参数都是临时变量,不利于维护。其实变成 client 里面的参数会更好一点。 |
transport/client.go
Outdated
defaultReconnectInterval = 3e8 // 300ms | ||
connectInterval = 5e8 // 500ms | ||
connectTimeout = 3e9 | ||
defaultMaxReconnectAttempts = 100 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这个要不调小一点,看着是短时间内发起 100次重连请求。
我把里面的一些变量调整为短变量申明的方式,这样看上去可能会好一点。然后除了maxReconnectAttempts(这个参数是client-side需要关心的参数,其他都不需要放到client里) |
…, adjust the defaultMaxReconnectAttempts from 100 to 50, and add the client's specification of the maxReconnectAttempts in the unit test
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Outside diff range and nitpick comments (2)
transport/client.go (1)
Line range hint
211-211
: Error handling forSetWriteDeadline
andSetReadDeadline
.The error return values from
SetWriteDeadline
andSetReadReadline
are not checked. This can lead to unhandled errors that might affect the stability of network operations.- conn.SetWriteDeadline(time.Now().Add(1e9)) + if err := conn.SetWriteDeadline(time.Now().Add(1e9)); err != nil { - log.Warnf("Failed to set write deadline: %+v", err) + } - conn.SetReadDeadline(time.Now().Add(1e9)) + if err := conn.SetReadDeadline(time.Now().Add(1e9)); err != nil { - log.Warnf("Failed to read deadline: %+v", err) + }Also applies to: 218-218
transport/client_test.go (1)
Line range hint
104-104
: Addressing static analysis hints in test file.
- The error from
http.Serve
should be checked to handle potential failures during the setup of a local server.- The error from
WriteControl
should be checked to ensure proper handling of close messages in WebSocket connections.- The unused function
newMessageHandler
should either be removed if it's truly unused or covered by tests if it's intended for future use.- http.Serve(listener, nil) + if err := http.Serve(listener, nil); err != nil { - log.Errorf("Failed to start HTTP server: %+v", err) + } - conn.conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(1e9)) + if err := conn.conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(1e9)); err != nil { - log.Errorf("Failed to send close message: %+v", err) + } - func newMessageHandler() *MessageHandler { + // If used, add tests or usage example here. + // Otherwise, consider removing: + // func newMessageHandler() *MessageHandler {Also applies to: 378-378, 51-51
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (2)
- transport/client.go (2 hunks)
- transport/client_test.go (1 hunks)
Additional context used
golangci-lint
transport/client.go
211-211: Error return value of
conn.SetWriteDeadline
is not checked (errcheck)
218-218: Error return value of
conn.SetReadDeadline
is not checked (errcheck)transport/client_test.go
104-104: Error return value of
http.Serve
is not checked (errcheck)
378-378: Error return value of
conn.conn.WriteControl
is not checked (errcheck)
51-51: func
newMessageHandler
is unused (unused)
Gitleaks
transport/client_test.go
419-433: Identified a Private Key, which may compromise cryptographic security and sensitive data encryption. (private-key)
Additional comments not posted (2)
transport/client.go (1)
44-48
: Renaming of constants improves clarity.The renaming of constants like
reconnectInterval
todefaultReconnectInterval
andmaxTimes
tomaxBackOffTimes
enhances code readability and better reflects their usage. This aligns well with the PR's aim to improve code clarity.transport/client_test.go (1)
118-118
: Addition ofWithReconnectAttempts
in test setup.The introduction of
WithReconnectAttempts
in the test setup is a direct reflection of the new client-side attribute. This ensures that the new functionality is covered by tests, which is crucial for maintaining reliability.
transport/client.go
Outdated
sessionNum, reconnectAttempts int | ||
maxReconnectInterval int64 | ||
) | ||
max = c.number | ||
interval = c.reconnectInterval | ||
if interval == 0 { | ||
interval = reconnectInterval | ||
reconnectInterval := c.reconnectInterval | ||
if reconnectInterval == 0 { | ||
reconnectInterval = defaultReconnectInterval | ||
} | ||
maxReconnectAttempts := c.maxReconnectAttempts | ||
if maxReconnectAttempts == 0 { | ||
maxReconnectAttempts = defaultMaxReconnectAttempts | ||
} | ||
connPoolSize := c.number | ||
for { | ||
if c.IsClosed() { | ||
log.Warnf("client{peer:%s} goroutine exit now.", c.addr) | ||
break | ||
} | ||
|
||
num = c.sessionNum() | ||
if max <= num || max < times { | ||
//Exit when the number of connection pools is sufficient or the reconnection times exceeds the connections numbers. | ||
sessionNum = c.sessionNum() | ||
if connPoolSize <= sessionNum || maxReconnectAttempts < reconnectAttempts { | ||
//exit reconnect when the number of connection pools is sufficient or the current reconnection attempts exceeds the max reconnection attempts. | ||
break | ||
} | ||
c.connect() | ||
times++ | ||
if times > maxTimes { | ||
maxDuration = int64(maxTimes) * int64(interval) | ||
reconnectAttempts++ | ||
if reconnectAttempts > maxBackOffTimes { | ||
maxReconnectInterval = int64(maxBackOffTimes) * int64(reconnectInterval) | ||
} else { | ||
maxDuration = int64(times) * int64(interval) | ||
maxReconnectInterval = int64(reconnectAttempts) * int64(reconnectInterval) | ||
} | ||
<-gxtime.After(time.Duration(maxDuration)) | ||
<-gxtime.After(time.Duration(maxReconnectInterval)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review of reConnect
function modifications.
The renaming of parameters and the restructuring of the reconnect logic are consistent with the PR's objectives. However, the logic for calculating maxReconnectInterval
could be simplified, and there's an inconsistency in the renaming (maxTimes
was supposed to be defaultMaxReconnectAttempts
but is changed to maxBackOffTimes
).
- maxBackOffTimes = 10
+ defaultMaxReconnectAttempts = 10
Additionally, consider simplifying the calculation of maxReconnectInterval
to improve readability.
- if reconnectAttempts > maxBackOffTimes {
- maxReconnectInterval = int64(maxBackOffTimes) * int64(reconnectInterval)
- } else {
- maxReconnectInterval = int64(reconnectAttempts) * int64(reconnectInterval)
- }
+ maxReconnectInterval = int64(min(reconnectAttempts, maxBackOffTimes)) * int64(reconnectInterval)
…d simplify the maxReconnectInterval calculation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (2)
- transport/client.go (4 hunks)
- transport/session.go (1 hunks)
Additional comments not posted (3)
transport/client.go (2)
435-441
: Default Values for Reconnect Interval and Max Reconnect Attempts.The code sets default values for
reconnectInterval
andmaxReconnectAttempts
if they are not provided. This ensures that the function operates with sensible defaults.
450-458
: Reconnection Logic Updated with Renamed Variables.The reconnection logic has been updated to use the renamed variables. The logic appears correct and should function as intended.
transport/session.go (1)
863-868
: Enhanced Error Handling for Setting Deadlines.The function now separately handles setting read and write deadlines, with improved error logging. This change enhances the robustness of the function.
defaultReconnectInterval = 3e8 // 300ms | ||
connectInterval = 5e8 // 500ms | ||
connectTimeout = 3e9 | ||
defaultMaxReconnectAttempts = 50 | ||
maxBackOffTimes = 10 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tip
Codebase Verification
Incomplete Renaming of Constants
The constants have been partially renamed to improve readability. However, occurrences of the old constant name reconnectInterval
still exist in the codebase. Please ensure all references to the old constant names are updated to the new names.
transport/options.go
transport/client.go
transport/options_test.go
Analysis chain
Renamed Constants for Clarity.
The constants have been renamed to improve readability. Ensure that all references to these constants in the codebase are updated accordingly.
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify that all references to the renamed constants are updated in the codebase.
# Test: Search for the old constant names. Expect: No occurrences of old names.
rg --type go 'reconnectInterval|maxTimes'
Length of output: 783
Script:
#!/bin/bash
# Description: Verify that the new constant names are used correctly in the codebase.
# Test: Search for the new constant names in the codebase.
rg --type go 'defaultReconnectInterval|maxBackOffTimes'
Length of output: 384
sessionNum, reconnectAttempts int | ||
maxReconnectInterval int64 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tip
Codebase Verification
Incomplete Variable Renaming
The variables num
, times
, and maxDuration
have not been fully renamed to sessionNum
, reconnectAttempts
, and maxReconnectInterval
respectively in the codebase. The following occurrences in transport/client.go
still need to be updated:
num
:transport/client.go: if c.number <= 0 || c.addr == "" {
transport/client.go: panic(fmt.Sprintf("client type:%s, @connNum:%d, @serverAddr:%s", t, c.number, c.addr))
transport/client.go: c.ssMap = make(map[Session]struct{}, c.number)
transport/client.go: var num int
transport/client.go: num = len(c.ssMap)
transport/client.go: return num
transport/client.go: connPoolSize := c.number
Please ensure that all references to these variables are updated accordingly to maintain consistency.
Analysis chain
Renamed Variables for Clarity.
The variables num
, times
, and maxDuration
have been renamed to sessionNum
, reconnectAttempts
, and maxReconnectInterval
respectively. Ensure that all references to these variables in the codebase are updated accordingly.
The search results indicate that the old variable names num
, times
, and maxDuration
still exist in the codebase. This suggests that not all references have been updated. To verify this, we need to check the specific lines in transport/client.go
and other related files to confirm whether the renaming was applied correctly.
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify that all references to the renamed variables are updated in the codebase.
# Test: Search for the old variable names. Expect: No occurrences of old names.
rg --type go 'num|times|maxDuration'
Length of output: 4177
Script:
#!/bin/bash
# Find the specific lines in transport/client.go where the renaming was done
rg 'sessionNum|reconnectAttempts|maxReconnectInterval' transport/client.go
# Check for the old variable names in the context of transport/client.go to confirm if they were renamed
rg 'num|times|maxDuration' transport/client.go
Length of output: 931
…indicates the max attempts in TCP reconnect behavior
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (2)
- examples/echo/tcp-echo/client/app/config.go (1 hunks)
- examples/echo/tcp-echo/client/app/main.go (1 hunks)
Additional comments not posted (2)
examples/echo/tcp-echo/client/app/main.go (1)
127-127
: Ensure the new client option is correctly integrated.The addition of
getty.WithReconnectAttempts(conf.GettySessionParam.TcpMaxReconnectAttempts)
appears correct. Ensure thatTcpMaxReconnectAttempts
is properly defined and populated in the configuration.examples/echo/tcp-echo/client/app/config.go (1)
61-61
: Ensure the new configuration parameter is correctly integrated.The addition of
TcpMaxReconnectAttempts
to theGettySessionParam
struct appears correct. Ensure that this new parameter is properly documented and populated in the configuration files.
What this PR does:
rename the variables in TCP reconnect function and some default constants.
1.rename constant 'reconnectInterval' to defaultReconnectInterval and 'maxTimes' to defaultMaxReconnectAttempts, indicates that these two constants are the default settings.
2.rename vars in reConnect():
Which issue(s) this PR fixes:
NONE
Special notes for your reviewer:
NONE
Does this PR introduce a user-facing change?:
Summary by CodeRabbit
New Features
Improvements