Skip to content

Conversation

@swift1337
Copy link
Contributor

@swift1337 swift1337 commented May 1, 2025

This PR refactors all hard-coded time/interval/ttl/duration and resource constants in config/const.go.

This unification makes the code more transparent and simpler. It also reuses values across similar code-paths.

Other improvements

  • Cut stream connect time form 20s to 10s
  • Improve joinPartyMember. Now it skips an unnecessary sleep(500ms)

Closes #56
Related zeta-chain/node#3843

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Centralized configuration of timeouts, intervals, and resource limits for stream and signature operations, allowing for easier adjustment and consistency across the application.
  • Refactor

    • Replaced hardcoded timeout and resource limit values with configurable parameters.
    • Improved logging with structured fields and unified notification constants for signature receipt.
    • Updated retry mechanisms to use ticker-based intervals for better efficiency and clarity.
    • Enhanced cleanup logging and consistent use of configuration values in signature notifier and stream management.
    • Unified error and notification constants for signature events across components.
  • Tests

    • Updated tests to use new configuration-driven timeout values and revised constructor arguments to match refactored functions.

@swift1337 swift1337 requested a review from a team as a code owner May 1, 2025 13:13
@swift1337 swift1337 self-assigned this May 1, 2025
@coderabbitai
Copy link

coderabbitai bot commented May 1, 2025

📝 Walkthrough

Walkthrough

This change introduces a new config package to centralize and manage configuration constants and timeout values across the codebase, replacing numerous hardcoded literals. All relevant durations, buffer sizes, and resource limits related to stream management, signature notification, and party coordination are now sourced from this package. The refactor also unifies string constants and error variables for signature receipt notifications. Associated tests and internal logic are updated to reference the new configuration-driven constants, ensuring consistency and maintainability throughout the project.

Changes

File(s) Change Summary
config/const.go Introduced new package defining centralized constants and configuration functions for timeouts, buffer sizes, and resource scaling.
keygen/ecdsa/tss_keygen.go, keygen/eddsa/tss_keygen.go, keysign/ecdsa/tss_keysign.go, keysign/eddsa/tss_keysign.go Replaced hardcoded 5-second timeouts with config.TSSCommonFinalTimeout for channel operations.
keysign/notifier.go, keysign/signature_notifier.go, keysign/signature_notifier_test.go Replaced hardcoded TTL and timeout values with those from config. Updated notifier and signature notifier logic and tests to use configuration-driven values.
p2p/communication.go, p2p/stream_manager.go Replaced hardcoded stream timeouts, payload sizes, and resource manager limits with values from config. Updated stream manager constructor to accept TTL parameter. Refactored resource manager setup to use config.ScalingLimits.
p2p/party_coordinator.go Replaced hardcoded timeouts and retry intervals with configuration values. Unified string constants for signature notifications. Refactored retry logic and improved structured logging.
p2p/stream_manager_test.go Updated test to use new NewStreamManager signature with TTL argument.
tss/keysign.go Unified error and notification constants for signature receipt, replacing literals and previous error variable with those from p2p.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant Config
    participant StreamMgr
    participant Notifier
    participant PartyCoord

    App->>Config: Retrieve timeout/resource constants
    App->>StreamMgr: Initialize with config values
    App->>Notifier: Initialize with config TTLs and intervals
    App->>PartyCoord: Initialize with config timeouts and retry intervals
    StreamMgr->>Config: Use timeouts for stream operations
    Notifier->>Config: Use TTL and cleanup intervals
    PartyCoord->>Config: Use timeouts and retry intervals
    Note over App,Config: All timing and sizing parameters are centralized
Loading

Assessment against linked issues

Objective Addressed Explanation
Consolidate and tweak constants (timeouts, deadlines, buffer sizes, etc.) (#56)

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f79dbf4 and 58c4573.

📒 Files selected for processing (1)
  • config/const.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • config/const.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test go 1.22
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 using 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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: 1

🧹 Nitpick comments (4)
p2p/party_coordinator.go (4)

47-50: Good defensive defaulting – nit: consider lifting the magic number.

The fallback to 10 * time.Second is sensible, but putting the value in config (e.g. config.DefaultPartyTimeout) would keep all time-related knobs in one place, matching the PR goal.


58-59: Double-default overlap.

NewStreamManager already assigns time.Minute when maxAgeBeforeCleanup == 0.
Because config.StreamExcessTTL is exactly one minute, passing that constant buys no functional gain while coupling two defaults. Either:

  1. Remove the defaulting inside NewStreamManager, or
  2. Omit the argument here (0) and rely on the constructor default.

Keeping a single source of truth avoids accidental drift.


323-337: Retry loop: consider context cancellation for clarity.

The done channel plus ticker works, but Go’s idiomatic pattern is a context.Context with WithTimeout/WithCancel.
Doing so removes the explicit done choreography and integrates naturally with pc.stopChan via context.AfterFunc.

Not blocking this PR, but worth a follow-up refactor.


380-389: Control-flow rewritten – retain explicit else-branches for readability.

The new switch is neat, yet combining error conditions and success in a single block can make future maintenance harder.
A small restructure keeps intent crystal clear:

if err != nil {
    return nil, errors.Wrap(err, "failed to parse peer ids")
}
if len(pIDs) < peerGroup.threshold {
    return pIDs, errors.New("not enough peers")
}
if peerGroup.getLeaderResponse().Type == messages.JoinPartyLeaderComm_Success {
    return pIDs, nil
}
return pIDs, ErrJoinPartyTimeout

Not mandatory, but marginally more readable.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 14f84bf and 70bd876.

📒 Files selected for processing (13)
  • config/const.go (1 hunks)
  • keygen/ecdsa/tss_keygen.go (2 hunks)
  • keygen/eddsa/tss_keygen.go (2 hunks)
  • keysign/ecdsa/tss_keysign.go (2 hunks)
  • keysign/eddsa/tss_keysign.go (2 hunks)
  • keysign/notifier.go (2 hunks)
  • keysign/signature_notifier.go (5 hunks)
  • keysign/signature_notifier_test.go (2 hunks)
  • p2p/communication.go (8 hunks)
  • p2p/party_coordinator.go (8 hunks)
  • p2p/stream_manager.go (7 hunks)
  • p2p/stream_manager_test.go (1 hunks)
  • tss/keysign.go (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (10)
keygen/ecdsa/tss_keygen.go (1)
config/const.go (1)
  • TSSCommonFinalTimeout (40-40)
keysign/signature_notifier_test.go (1)
config/const.go (1)
  • SigNotifierTTL (36-36)
keygen/eddsa/tss_keygen.go (1)
config/const.go (1)
  • TSSCommonFinalTimeout (40-40)
keysign/eddsa/tss_keysign.go (1)
config/const.go (1)
  • TSSCommonFinalTimeout (40-40)
keysign/notifier.go (1)
config/const.go (1)
  • SigNotifierTTL (36-36)
keysign/ecdsa/tss_keysign.go (1)
config/const.go (1)
  • TSSCommonFinalTimeout (40-40)
keysign/signature_notifier.go (2)
p2p/stream_manager.go (1)
  • NewStreamManager (42-66)
config/const.go (5)
  • StreamExcessTTL (24-24)
  • SigNotifierCleanupInterval (37-37)
  • SigNotifierTTL (36-36)
  • StreamTimeoutConnect (15-15)
  • SigNotifierAckTimeout (33-33)
tss/keysign.go (1)
p2p/party_coordinator.go (3)
  • ErrSigReceived (27-27)
  • NotificationSigReceived (22-22)
  • ErrNotActiveSigner (28-28)
p2p/stream_manager.go (2)
config/const.go (3)
  • StreamTimeoutRead (18-18)
  • StreamMaxPayload (27-27)
  • StreamTimeoutWrite (21-21)
p2p/protocol.go (1)
  • PayloadHeaderLen (36-36)
p2p/party_coordinator.go (5)
p2p/stream_manager.go (1)
  • NewStreamManager (42-66)
config/const.go (3)
  • StreamExcessTTL (24-24)
  • StreamTimeoutConnect (15-15)
  • PartyJoinMemberRetryInterval (42-42)
logs/fields.go (2)
  • MsgID (8-8)
  • Leader (11-11)
conversion/key_provider.go (1)
  • GetPubKeyFromPeerID (78-97)
messages/join_party.pb.go (1)
  • JoinPartyLeaderComm_Success (27-27)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test go 1.22
🔇 Additional comments (49)
keygen/ecdsa/tss_keygen.go (2)

18-18: Appropriate import addition.

The import of the config package is correctly added to support the centralized timeout constants refactoring.


155-155: Good refactor: Hardcoded timeout replaced with configurable constant.

Replacing the hardcoded timeout with config.TSSCommonFinalTimeout improves maintainability by centralizing timeout configuration. This change maintains the same timeout value (5 seconds) while making it configurable from a single location.

p2p/stream_manager_test.go (1)

152-152: Test updated to match new constructor signature.

The test has been correctly updated to accommodate the additional maxAgeBeforeCleanup parameter now required by the NewStreamManager constructor. The value of 0 is used for the duration in this test context.

Verify that using 0 as the duration value is the intended behavior for testing. While this will pass the test, consider if a more realistic value would provide better test coverage for stream cleanup functionality.

keysign/notifier.go (2)

17-18: Import block properly organized.

The import for the config package has been correctly added and the trailing closing parenthesis has been properly fixed, resolving a syntax issue in the import block.


51-51: Good refactor: Hardcoded TTL replaced with configurable constant.

Replacing the hardcoded TTL value with config.SigNotifierTTL improves maintainability and consistency. This change centralizes the configuration while maintaining the same functional behavior (30 seconds TTL).

keygen/eddsa/tss_keygen.go (2)

17-17: Appropriate import addition.

The import of the config package is correctly added to support the centralized timeout constants refactoring.


146-146: Good refactor: Hardcoded timeout replaced with configurable constant.

Replacing the hardcoded timeout with config.TSSCommonFinalTimeout improves maintainability by centralizing timeout configuration. This change maintains the same timeout value (5 seconds) while making it configurable from a single location. The change is consistent with similar refactoring in the ECDSA keygen implementation.

keysign/ecdsa/tss_keysign.go (2)

22-23: Appropriate config package addition.

Clean addition of the config package import to support the use of centralized timeout constants.


210-215: Good replacement of hardcoded timeout with configurable constant.

This change improves maintainability by replacing the hardcoded 5-second timeout with a centralized constant. The config.TSSCommonFinalTimeout value matches the previous behavior while providing a single point of configuration for future adjustments.

keysign/eddsa/tss_keysign.go (2)

22-23: Appropriate config package addition.

Good addition of the config package import to support centralized timeout constants.


197-202: Good replacement of hardcoded timeout with configurable constant.

This change properly replaces the hardcoded 5-second timeout with the centralized config.TSSCommonFinalTimeout constant, ensuring consistent timeout behavior across the codebase.

keysign/signature_notifier_test.go (2)

18-19: Appropriate config package addition.

The config package import is correctly added to access the centralized TTL constant.


167-168: Good test adaptation to use centralized TTL constant.

This change correctly updates the test to validate against config.SigNotifierTTL instead of a hardcoded value, ensuring tests remain aligned with implementation.

tss/keysign.go (3)

99-101: Corrected error constant usage.

The error constant has been properly standardized to use p2p.ErrSigReceived instead of p2p.ErrSignReceived, ensuring consistency across the codebase.


330-336: Good standardization of notification constant.

The string literal "signature received" has been appropriately replaced with the constant p2p.NotificationSigReceived, improving maintainability and consistency.


363-366: Corrected error constant in conditional check.

The error check has been properly updated to use the standardized p2p.ErrSigReceived constant instead of p2p.ErrSignReceived, ensuring consistent error handling.

p2p/stream_manager.go (9)

17-17: Good addition of the config package

Adding the config package import enables the use of centralized time-related constants, aligning with the refactoring goal.


21-21: Improved variable naming

Renaming the constant from unknown to unknownMsgID enhances code readability by making the intent clearer and more descriptive.


42-47: Well-designed constructor enhancement

The constructor now accepts a configurable TTL parameter with a sensible default fallback. This increases flexibility while maintaining backward compatibility.


93-93: Consistent use of the renamed constant

Properly updated the usage of unknownMsgID in the StashUnknown method, ensuring consistency throughout the codebase.


172-172: Consistent usage in cleanup method

Properly updated the usage of unknownMsgID in the cleanup method, maintaining code consistency.


207-207: Improved timeout configuration

Replaced hardcoded read timeout with the centralized configuration constant, improving maintainability.


220-222: Improved payload size validation

Replaced hardcoded maximum payload size with a centralized configuration constant, providing better consistency across the codebase.


236-238: Consistent payload limit application

The maximum payload size constraint is consistently applied using the same configuration constant as in the read path, ensuring uniform behavior.


240-240: Standardized write timeout

Replaced hardcoded write timeout with the centralized configuration constant, completing the standardization of all stream timeouts.

p2p/communication.go (7)

24-24: Good addition of the config package

Adding the config package import enables the use of centralized time-related constants, aligning with the refactoring goal.


90-90: Proper integration with the StreamManager

Updated the constructor call to include the new TTL parameter from config, ensuring consistent stream lifecycle management.


145-146: Standardized connection timeout

Replaced hardcoded connection timeout with the centralized configuration constant, improving consistency across the codebase.


192-202: Enhanced stream reading timeout

Improved the timeout handling for stream reading using the centralized configuration constant, including properly referencing the timeout value in the log message.


274-274: Simplified resource limits configuration

Replaced manual resource limit construction with the centralized ScalingLimits function, reducing code complexity and improving maintainability.


294-296: Cleaner host initialization

Simplified the libp2p.New call by using a more concise parameter style, improving code readability.


356-357: Consistent connection timeout application

Used the same configuration constant for timeout in peer connections, ensuring uniform behavior across the codebase.

config/const.go (6)

1-11: Well-structured new configuration package

The new config package is properly organized with clear imports and a descriptive package comment.


13-28: Comprehensive stream-related constants

Well-organized stream constants with descriptive comments. The timeout values are reasonable, and the max payload size is defined using bit shifting for clarity.


31-38: Well-defined signature notifier constants

Clear organization of signature notifier constants with descriptive comments explaining their purpose.


40-42: Properly defined general timeout constants

Added important general timeout constants with appropriate values for TSS operations and party join retry intervals.


45-76: Excellent resource limits function

The ScalingLimits function is well-designed, providing a centralized and configurable way to define resource constraints for libp2p. The implementation properly handles protocol-specific limits and automatically scales based on system memory.


79-81: Useful utility function

The mb helper function provides a clean way to convert megabytes to bytes, enhancing code readability when defining memory limits.

keysign/signature_notifier.go (7)

16-16: Good addition of the config package

Adding the config package import enables the use of centralized time-related constants, aligning with the refactoring goal.


56-56: Proper integration with the StreamManager

Updated the StreamManager initialization to use the standardized TTL from config, ensuring consistent stream lifecycle management.


81-97: Improved cleanup function structure

Enhanced the cleanup logic with:

  1. Better function organization using a local function
  2. Proper deferred mutex unlocking
  3. Added deletion counter for better observability
  4. Improved conditional logging that only reports when actions were taken

These changes improve code maintainability and operational visibility.


99-99: Standardized cleanup interval

Replaced hardcoded cleanup interval with the centralized configuration constant, ensuring consistency across the codebase.


162-162: Standardized notifier TTL

Updated the notifier TTL to use the centralized configuration constant, maintaining consistent timeout behavior.


169-169: Standardized connection timeout

Replaced hardcoded connection timeout with the centralized configuration constant, ensuring consistency with other parts of the system.


211-213: Improved ACK timeout handling

Enhanced the ACK timeout implementation by:

  1. Using the standardized configuration constant
  2. Updating the comment to clearly explain the purpose
  3. Maintaining consistent code style with the rest of the codebase

This change improves code clarity and maintainability.

p2p/party_coordinator.go (4)

260-263: 👍 Config-driven connect timeout.

Replacing the hard-coded 4 s with config.StreamTimeoutConnect aligns with the refactor goal and makes tuning easier.


358-360: Error semantics are now clear – good use of sentinel error.

Return-early on ErrSigReceived simplifies upstream handling.


411-413: Consistent signalling path confirmed.

Leader side mirrors the member side and correctly propagates ErrSigReceived.


16-23:

✅ Verification successful

Rename introduces breaking-change risk; scan the repo for stale usages.

ErrSigReceived and NotificationSigReceived replace the previous ErrSignReceived / literal.
Compilation will break wherever the old identifiers remain. Please verify the entire repo (tests, other packages, mocks).


🏁 Script executed:

#!/bin/bash
# Find remaining references to the old identifiers / literal
rg -n --hidden --glob '!.git' $'\bErrSignReceived\b|\"signature received\"'

Length of output: 153


No stale references to ErrSignReceived remain

I ran a repository-wide search and confirmed there are no occurrences of ErrSignReceived or the literal "signature received" beyond its updated definition in p2p/party_coordinator.go. All references have been updated accordingly.

Copy link
Collaborator

@brewmaster012 brewmaster012 left a comment

Choose a reason for hiding this comment

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

LGTM!

@swift1337 swift1337 merged commit 2d9bfc8 into master May 9, 2025
7 checks passed
@swift1337 swift1337 deleted the refactor/organize-consts branch May 9, 2025 15:39
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.

Consolidate & tweak consts

4 participants