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

Feat/params update #11

Merged
merged 5 commits into from
Dec 27, 2024
Merged

Feat/params update #11

merged 5 commits into from
Dec 27, 2024

Conversation

leonz789
Copy link
Collaborator

@leonz789 leonz789 commented Dec 27, 2024

update corresponding fields for existing feeders or setup and start new feeders when a 'updateParams' events is received.

Notable Changes

  1. when a 'updateParams' is received
  • update running feeder's fileds
  • setup and run new feeders if exist
  1. set currency suffix for token name when fetching price from chainlink
  2. refactor methods of feeders
  3. add a buffer for 'updateParams' channel in feeders to get avoid of most of the blockings

Summary by CodeRabbit

  • New Features

    • Enhanced feeder management system with improved setup and lifecycle management.
    • Introduced a new constant for base currency handling in token processing.
  • Bug Fixes

    • Improved error handling in feeder parameter updates.
  • Documentation

    • Updated method and type names for better clarity and visibility.

Copy link

coderabbitai bot commented Dec 27, 2024

Warning

Rate limit exceeded

@leonz789 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 28 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between e578ca9 and a042619.

📒 Files selected for processing (1)
  • cmd/types.go (8 hunks)

Walkthrough

The pull request introduces significant changes to the feeder management system, focusing on refactoring the initialization, configuration, and operational flow of price feeders. The modifications span across multiple files, including cmd/feeder_tool.go, cmd/types.go, and fetcher/chainlink/chainlink.go. The changes enhance error handling, logging mechanisms, and the overall structure of feeder management, with a particular emphasis on making the system more robust and flexible.

Changes

File Change Summary
cmd/feeder_tool.go - Replaced fsMap with feeders using NewFeeders function
- Updated logging to use logger.Error instead of fmt.Printf
- Improved error reporting for oracle parameter fetching
cmd/types.go - Renamed feederInfo to FeederInfo with exported fields
- Introduced Feeders struct with synchronization mechanisms
- Added methods for feeder setup, start, trigger, and price update
- Enhanced error handling in parameter updates
fetcher/chainlink/chainlink.go - Added baseCurrency constant set to "usdt"
- Modified fetch method to append "usdt" to tokens if not present

Sequence Diagram

sequenceDiagram
    participant Main as RunPriceFeeder
    participant Feeders as Feeders
    participant Feeder as Individual Feeder
    participant Chainlink as Chainlink Fetcher
    participant ExoClient as Exo Client

    Main->>Feeders: NewFeeders()
    Feeders->>Feeder: SetupFeeder()
    Feeders->>Feeders: Start()
    loop Event Processing
        ExoClient->>Feeders: Trigger Event
        Feeders->>Feeder: Update Price
        Feeder->>Chainlink: Fetch Price
        Chainlink-->>Feeder: Return Price
        Feeder->>ExoClient: Submit Price
    end
Loading

Poem

🐰 Feeders dance, a crypto ballet,
With USDT's whisper, they find their way.
Logs shine bright, errors take flight,
Synchronized steps, a technological delight.
CodeRabbit's magic, in each price's might! 🚀


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>, 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.

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. (Beta)
  • @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 or @coderabbitai title 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: 2

🧹 Nitpick comments (8)
cmd/types.go (6)

100-113: Consider adding JSON tags or docstrings to exported fields in FeederInfo.
If these fields are exposed outside this package or intended for marshaling, adding json:"..." tags can improve clarity.


130-130: Method visibility suggests internal usage only.
Renaming newFeeder to createFeeder or adding doc comments might improve clarity on its intended usage.


142-143: Late variable initialization is clear enough here.
However, consider grouping fetcher/submitter initialization logic together for readability.


308-319: Synchronization approach in Feeders
Instead of a single mutex for the entire struct, you could explore fine-grained locking for better scalability if the feeder set grows large.


322-335: Buffered channel rationale looks good.
Allowing a buffer prevents blocking the event loop but ensure buffer sizes are sufficient for high-throughput scenarios. Monitor for potential dropped updates if the channel saturates.


442-442: Blocking call for UpdateOracleParams.
While this approach is simple, note that feeding large param sets or frequent updates might slow other operations waiting on the same channel capacity. Consider non-blocking sends or handling partial updates.

fetcher/chainlink/chainlink.go (1)

19-19: Suffix-based approach is straightforward.
However, consider normalizing case or clarifying that “USDT” must always be lowercase or the suffix check could fail.

cmd/feeder_tool.go (1)

35-35: Commented-out loggerTagPrefix is now redundant.
You might safely remove it from here to avoid confusion, given it’s redefined in types.go.

-// loggerTagPrefix = "feed_%s_%d"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c4500c6 and 1704075.

📒 Files selected for processing (3)
  • cmd/feeder_tool.go (4 hunks)
  • cmd/types.go (9 hunks)
  • fetcher/chainlink/chainlink.go (1 hunks)
🔇 Additional comments (10)
cmd/types.go (5)

5-7: Imports seem appropriate and essential for synchronization and string manipulation.


17-18: Good use of a logger prefix constant.
This makes log filtering easier, especially when debugging multiple feeders.


115-126: Potential pointer safety consideration.
The function returns a struct referencing lastPrice and lastSent by value. Any concurrent updates to those fields in another goroutine might not reflect in the returned copy. Confirm whether you need real-time synchronization or an immutable snapshot is sufficient.


259-274: Validate concurrency for updateFeederParams.
Since this updates shared state (f.endBlock, f.startBaseBlock, etc.), verify that the single-threaded approach (goroutine queue) remains intact. If multiple param updates arrive in quick succession, ensure no updates are lost.


Line range hint 353-394: Long-running goroutine with select might cause partial blocking if channels fill.
Monitor channel capacities during peak load to ensure events (trigger, updatePrice, updateParams) do not stall each other. If necessary, implement back-pressure or expand channel buffers.

fetcher/chainlink/chainlink.go (1)

22-24: Appending baseCurrency might cause confusion if token already has a variant of “usdt”.
To avoid potential duplication or mismatch (e.g. “tokenusdtusdt”), confirm tokens are consistently lowercased and validated upstream.

cmd/feeder_tool.go (4)

31-32: Defining these constants is fine.
They’re concise and self-explanatory. Keep them updated if the private file name changes.


70-70: Using NewFeeders clarifies feeder setup.
Good shift from ad-hoc map usage to a structured approach.


85-85: SetupFeeder call is well-placed.
Ensures feeders are configured before starting the main loop. Confirm no concurrency race when reconfiguring feeders after initial start.


95-95: Updated logging approach is consistent.
Using logger.Error is preferred over standard prints for better observability.

cmd/types.go Outdated Show resolved Hide resolved
cmd/types.go Show resolved Hide resolved
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

🧹 Nitpick comments (4)
cmd/types.go (4)

17-17: Consider a more descriptive logger tag format.

The current format feed_%s_%d could be more descriptive. Consider using feeder_token_%s_id_%d for better clarity in logs.

-const loggerTagPrefix = "feed_%s_%d"
+const loggerTagPrefix = "feeder_token_%s_id_%d"

100-113: Add field documentation to exported struct.

Since FeederInfo is now exported, consider adding documentation for each field to help API consumers understand their purpose.

 type FeederInfo struct {
+    // Source represents the price data source (e.g., Chainlink)
     Source   string
+    // Token represents the token symbol
     Token    string
+    // TokenID is the unique identifier for the token
     TokenID  uint64
+    // FeederID is the unique identifier for this feeder
     FeederID int
     // TODO: add check for rouleID, v1 can be skipped
     // ruleID
+    // StartRoundID is the initial round ID for this feeder
     StartRoundID   int64
+    // StartBaseBlock is the starting block height
     StartBaseBlock int64
+    // Interval is the number of blocks between price updates
     Interval       int64
+    // EndBlock is the final block height (0 means no end)
     EndBlock       int64
+    // LastPrice contains the most recent price information
     LastPrice      localPrice
+    // LastSent contains the last sent transaction information
     LastSent       signInfo
 }

260-278: Improve error handling and validation in updateFeederParams.

The error handling could be more specific and the validation more comprehensive:

  1. Use specific error types instead of generic errors
  2. Validate individual field values
  3. Add logging for parameter changes
+var (
+    ErrNilParams = errors.New("oracle params is nil")
+    ErrInvalidFeederID = errors.New("invalid feeder ID in oracle params")
+)

 func (f *feeder) updateFeederParams(p *oracletypes.Params) error {
-    if p == nil || len(p.TokenFeeders) < f.feederID+1 {
-        return errors.New("invalid oracle parmas")
+    if p == nil {
+        return ErrNilParams
+    }
+    if len(p.TokenFeeders) < f.feederID+1 {
+        return fmt.Errorf("%w: feeder ID %d", ErrInvalidFeederID, f.feederID)
     }
-    // TODO: update feeder's params
     tokenFeeder := p.TokenFeeders[f.feederID]
+    
+    // Log parameter changes
     if f.endBlock != int64(tokenFeeder.EndBlock) {
+        f.logger.Info("updating end block", "old", f.endBlock, "new", tokenFeeder.EndBlock)
         f.endBlock = int64(tokenFeeder.EndBlock)
     }
     if f.startBaseBlock != int64(tokenFeeder.StartBaseBlock) {
+        f.logger.Info("updating start base block", "old", f.startBaseBlock, "new", tokenFeeder.StartBaseBlock)
         f.startBaseBlock = int64(tokenFeeder.StartBaseBlock)
     }
     if f.interval != int64(tokenFeeder.Interval) {
+        f.logger.Info("updating interval", "old", f.interval, "new", tokenFeeder.Interval)
         f.interval = int64(tokenFeeder.Interval)
     }
-    if p.MaxNonce > 0 {
+    if p.MaxNonce > 0 && f.lastSent.maxNonce != p.MaxNonce {
+        f.logger.Info("updating max nonce", "old", f.lastSent.maxNonce, "new", p.MaxNonce)
         f.lastSent.maxNonce = p.MaxNonce
     }
     return nil
 }

383-398: Extract new feeder creation logic to a separate method.

The feeder creation logic in the Start method is complex and could be extracted to improve readability and maintainability.

+func (fs *Feeders) createNewFeeder(tfID int, tf *oracletypes.TokenFeeder, params *oracletypes.Params) {
+    tokenName := strings.ToLower(params.Tokens[tf.TokenID].Name)
+    source := fetchertypes.Chainlink
+    
+    if fetchertypes.IsNSTToken(tokenName) {
+        nstToken := fetchertypes.NSTToken(tokenName)
+        if source = fetchertypes.GetNSTSource(nstToken); len(source) == 0 {
+            fs.logger.Error("failed to add new feeder, source of nst token is not set", "token", tokenName)
+            return
+        }
+    }
+    
+    feeder := newFeeder(tf, tfID, fs.fetcher, fs.submitter, source, tokenName, params.MaxNonce, fs.logger)
+    fs.feederMap[tfID] = feeder
+    feeder.start()
+}

 // In the Start method:
 for tfID, tf := range params.TokenFeeders {
     if _, ok := existingFeederIDs[int64(tfID)]; !ok {
-        // create and start a new feeder
-        tokenName := strings.ToLower(params.Tokens[tf.TokenID].Name)
-        source := fetchertypes.Chainlink
-        if fetchertypes.IsNSTToken(tokenName) {
-            nstToken := fetchertypes.NSTToken(tokenName)
-            if source = fetchertypes.GetNSTSource(nstToken); len(source) == 0 {
-                fs.logger.Error("failed to add new feeder, source of nst token is not set", "token", tokenName)
-            }
-        }
-        feeder := newFeeder(tf, tfID, fs.fetcher, fs.submitter, source, tokenName, params.MaxNonce, fs.logger)
-        fs.feederMap[tfID] = feeder
-        feeder.start()
+        fs.createNewFeeder(tfID, tf, params)
     }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1704075 and e578ca9.

📒 Files selected for processing (1)
  • cmd/types.go (9 hunks)
🧰 Additional context used
📓 Learnings (1)
cmd/types.go (1)
Learnt from: leonz789
PR: ExocoreNetwork/price-feeder#11
File: cmd/types.go:340-347
Timestamp: 2024-12-27T08:13:34.691Z
Learning: The 'locker' field in the 'Feeders' struct ensures concurrency safety. When 'SetupFeeder' is called after 'Start' has been invoked, it logs an error and refuses to proceed, effectively preventing concurrency problems.

cmd/types.go Outdated Show resolved Hide resolved
cmd/types.go Outdated Show resolved Hide resolved
@leonz789 leonz789 merged commit a8c8db2 into develop Dec 27, 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.

1 participant