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

Improvement: rename the variables in TCP reconnect function and some default constants #84

Merged
merged 8 commits into from
Jul 16, 2024

Conversation

No-SilverBullet
Copy link
Collaborator

@No-SilverBullet No-SilverBullet commented Jun 16, 2024

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():

  • num->sessionNum,indicates the number of current sessions.
  • max->maxReconnectAttempts,indicates the maximum attempt times of reconnections.
  • times->reconnectAttempts, indicates the current number of reconnect attempts.
  • interval->reconnectInterval,indicates the interval between each reconnection.
  • maxDuration->maxReconnectInterval, indicates the max interval between each reconnection.

Which issue(s) this PR fixes:
NONE

Special notes for your reviewer:
NONE
Does this PR introduce a user-facing change?:

Add new client-side attribute 'maxReconnectAttempts' to represent the max reconnect attempts in maintaining the tcp connetion pool size, the default value is setted to 100.

Summary by CodeRabbit

  • New Features

    • Introduced a configurable maximum number of TCP reconnect attempts to improve connection reliability.
  • Improvements

    • Enhanced error handling during connection read and write deadline settings for better debugging and stability.

Copy link

coderabbitai bot commented Jun 16, 2024

Walkthrough

The 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

File Path Change Summary
transport/client.go Reorganized constants, updated reconnection logic, and refactored variables for clarity in reconnection attempts.
transport/options.go Added maxReconnectAttempts field in ClientOptions, and introduced the WithReconnectAttempts option.
transport/session.go Improved stop() method to separately handle and log errors for setting connection read and write deadlines.
examples/echo/tcp-echo/client/app/config.go Added TcpMaxReconnectAttempts field to GettySessionParam.
examples/echo/tcp-echo/client/app/main.go Updated initClient function to include getty.WithReconnectAttempts option based on new configuration.

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
Loading

Poem

In circuits of code, we strive and connect,
Reaching out again when paths are wrecked.
With constants anew and errors confined,
TCP whispers, a dance so refined.
Retry, reconnect, with grace we align,
Ensuring the data flows, every time.


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?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a 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 from SetWriteDeadline and SetReadDeadline 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

Commits

Files that changed from the base of the PR and between da9fedf and 38deaf2.

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 the reConnect function improves readability and makes the purpose of each variable clearer.

Copy link

@coderabbitai coderabbitai bot left a 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 refactored reConnect 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 of maxReconnectInterval.


Line range hint 211-211: The error return value of conn.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 of conn.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

Commits

Files that changed from the base of the PR and between 38deaf2 and 8529f81.

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.

Comment on lines 172 to 179
// WithReconnectInterval @maxReconnectAttempts is max reconnect attempts.
func WithReconnectAttempts(maxReconnectAttempts int) ClientOption {
return func(o *ClientOptions) {
if 0 < maxReconnectAttempts {
o.maxReconnectAttempts = maxReconnectAttempts
}
}
}
Copy link

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.

Copy link

@coderabbitai coderabbitai bot left a 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

Commits

Files that changed from the base of the PR and between 8529f81 and 5a06061.

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

Comment on lines +172 to +179
// WithReconnectAttempts @maxReconnectAttempts is max reconnect attempts.
func WithReconnectAttempts(maxReconnectAttempts int) ClientOption {
return func(o *ClientOptions) {
if 0 < maxReconnectAttempts {
o.maxReconnectAttempts = maxReconnectAttempts
}
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

这段代码并没有被使用,可以先不加或者加注释。否则被人调用之后发现没有效果反而觉得是个问题。

Copy link
Owner

Choose a reason for hiding this comment

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

这段代码并没有被使用,可以先不加或者加注释。否则被人调用之后发现没有效果反而觉得是个问题。

这是给上面提供的接口。要不 @No-SilverBullet 你在代码示例里面调用下?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

11

@Lvnszn
Copy link
Collaborator

Lvnszn commented Jun 26, 2024

@AlexStocks 雨哥,看着 reconnect 那边的逻辑其实可以加个 issue,太多参数都是临时变量,不利于维护。其实变成 client 里面的参数会更好一点。

defaultReconnectInterval = 3e8 // 300ms
connectInterval = 5e8 // 500ms
connectTimeout = 3e9
defaultMaxReconnectAttempts = 100
Copy link
Collaborator

Choose a reason for hiding this comment

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

这个要不调小一点,看着是短时间内发起 100次重连请求。

@No-SilverBullet
Copy link
Collaborator Author

@AlexStocks 雨哥,看着 reconnect 那边的逻辑其实可以加个 issue,太多参数都是临时变量,不利于维护。其实变成 client 里面的参数会更好一点。

我把里面的一些变量调整为短变量申明的方式,这样看上去可能会好一点。然后除了maxReconnectAttempts(这个参数是client-side需要关心的参数,其他都不需要放到client里)

…, adjust the defaultMaxReconnectAttempts from 100 to 50, and add the client's specification of the maxReconnectAttempts in the unit test
Copy link

@coderabbitai coderabbitai bot left a 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 for SetWriteDeadline and SetReadDeadline.

The error return values from SetWriteDeadline and SetReadReadline 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.

  1. The error from http.Serve should be checked to handle potential failures during the setup of a local server.
  2. The error from WriteControl should be checked to ensure proper handling of close messages in WebSocket connections.
  3. 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

Commits

Files that changed from the base of the PR and between 5a06061 and 5bd3869.

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 to defaultReconnectInterval and maxTimes to maxBackOffTimes 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 of WithReconnectAttempts 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.

Comment on lines 427 to 457
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))
Copy link

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
Copy link

@coderabbitai coderabbitai bot left a 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

Commits

Files that changed from the base of the PR and between 5bd3869 and 3f88499.

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 and maxReconnectAttempts 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.

Comment on lines +45 to +49
defaultReconnectInterval = 3e8 // 300ms
connectInterval = 5e8 // 500ms
connectTimeout = 3e9
defaultMaxReconnectAttempts = 50
maxBackOffTimes = 10
Copy link

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

Comment on lines +432 to +433
sessionNum, reconnectAttempts int
maxReconnectInterval int64
Copy link

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

Copy link

@coderabbitai coderabbitai bot left a 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

Commits

Files that changed from the base of the PR and between 3f88499 and bace946.

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 that TcpMaxReconnectAttempts 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 the GettySessionParam struct appears correct. Ensure that this new parameter is properly documented and populated in the configuration files.

@AlexStocks AlexStocks merged commit 177fc63 into master Jul 16, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants