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

ENG-2276: fix for same Item.Start but different Item.Bit access #108

Merged
merged 4 commits into from
Jan 21, 2025

Conversation

led0nk
Copy link
Member

@led0nk led0nk commented Jan 17, 2025

Description:

  • should check also on bit-wise access for duplicates since there are cases where you want to access the same Item.Start but a different Item.Bit
  • if the Item.WordLen isn't set to bit-wise access the field Bit should contain the same value
  • added some tests, we could test everything against each other here, but i guess this should be fine

Testing:

  • had some local tests running with this input.yaml on both devices
input:
  s7comm:
    tcpDevice: <censored>
    rack: 0
    slot: 1
    addresses:
      - DB2.I0
      - DB2.X0.1
      - DB2.X2.0
      - DB2.X4.0
      - DB2.I6
      - MK0.X0.0
      - MK0.X0.1
      - MK0.X0.2
      - MK0.X0.3
      - MK0.X0.4
      - MK0.X0.5
      - MK0.X0.6
      - MK0.X0.7
      - DB2.X8.0
      - DB3.DW0
      - DB3.DW4
      - DB3.DW8
      - DB3.W12

Summary by CodeRabbit

  • New Features

    • Enhanced duplicate address detection with more precise matching criteria.
  • Tests

    • Added comprehensive test suite for parsing duplicate addresses.
    • Improved validation of address parsing logic with new test scenarios for various duplicate conditions.

@led0nk led0nk requested a review from a team January 17, 2025 22:33
Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

Walkthrough

The pull request modifies the duplicate address detection logic in the S7 communication plugin. The changes enhance the specificity of address comparison by utilizing reflect.DeepEqual to compare the entire S7DataItem structure, ensuring accurate detection of duplicates. Additionally, a new test suite is introduced to validate the handling of duplicate addresses under various scenarios, confirming that addresses with different bit values are not incorrectly flagged as duplicates.

Changes

File Change Summary
s7comm_plugin/s7comm.go Updated ParseAddresses function to use reflect.DeepEqual for duplicate address detection
s7comm_plugin/s7comm_test.go Added new structure and test cases for parsing duplicate addresses with various scenarios

Assessment against linked issues

Objective Addressed Explanation
Handle different bit addresses for same byte
Prevent benthos-umh crashing for bit-level inputs

Suggested reviewers

  • Scarjit
  • JeremyTheocharis

Poem

🤖 Bits and bytes, a rabbit's delight! 🐰
In S7's world, addresses shine bright
No more duplicates to cause a fight
With Bit now checked, our logic's tight
Code dancing free, pure and light! 🌟

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 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
Contributor

@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

🧹 Nitpick comments (2)
s7comm_plugin/s7comm_test.go (2)

71-96: Add test cases for additional edge cases.

The current test suite covers basic scenarios well, but consider adding these edge cases:

  1. Addresses with same Start but different WordLen (e.g., "DB2.W0" vs "DB2.DW0")
  2. Addresses with same Start but mixed access types (e.g., "DB2.W0" vs "DB2.X0.0")
 tests := []testCase{
+    {
+        addresses:        []string{"DB2.W0", "DB2.DW0"},
+        expectedErrorMsg: nil,
+    },
+    {
+        addresses:        []string{"DB2.W0", "DB2.X0.0"},
+        expectedErrorMsg: nil,
+    },
     // ... existing test cases ...
 }

98-114: Improve test case descriptions for better readability.

While the test logic is solid, the test description could be more specific about the scenario being tested.

-By("Testing with addresses"+fmt.Sprintf("%v", tc.addresses), func() {
+By(fmt.Sprintf("Testing address combination: %v (expecting %v)", 
+    tc.addresses, 
+    tc.expectedErrorMsg != nil ? "duplicate error" : "no error"
+), func() {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between aa2177b and 6dbe814.

📒 Files selected for processing (2)
  • s7comm_plugin/s7comm.go (1 hunks)
  • s7comm_plugin/s7comm_test.go (2 hunks)
🔇 Additional comments (2)
s7comm_plugin/s7comm.go (1)

182-184: LGTM! The duplicate check now correctly handles bit-wise access.

The modified condition properly identifies duplicates by comparing all relevant fields (Area, DBNumber, Start, and Bit), which aligns with the PR objective of supporting different bit access for the same start address.

Let's verify that this change doesn't break existing functionality:

✅ Verification successful

Verified: The duplicate check modification is safe and doesn't impact existing functionality

The bit-wise access appears to be a new feature, and the modified duplicate check is the only place where Item.Bit is used. This confirms that the change is backward compatible and won't break any existing functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any existing bit-wise address patterns in the codebase
# to ensure we're not breaking existing usage

rg -l 'Item\.Bit.*Item\.Start' --type go

Length of output: 42


Script:

#!/bin/bash
# Search for any usage of Bit field in Item struct
rg "Item\.Bit" --type go -A 2

# Look for test files that might validate address handling
fd ".*_test\.go" --type f --exec grep -l "Item"

# Check the definition of Item struct
ast-grep --pattern 'type Item struct {
  $$$
}'

Length of output: 507

s7comm_plugin/s7comm_test.go (1)

65-68: LGTM! Well-structured test case definition.

The test case structure is clean and appropriately captures both the input addresses and expected error messages for duplicate detection scenarios.

s7comm_plugin/s7comm.go Outdated Show resolved Hide resolved
s7comm_plugin/s7comm_test.go Outdated Show resolved Hide resolved
@led0nk led0nk requested a review from kanapuli January 20, 2025 14:30
Copy link
Contributor

@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 comments (1)
s7comm_plugin/s7comm.go (1)

Line range hint 271-275: Fix buffer handling to prevent data accumulation.

The buffer is never reset between messages, which could lead to memory growth and incorrect data as each message contains all previous messages' data.

Apply this diff to fix the buffer handling:

-buffer := make([]byte, 0)
+for _, item := range b {
+    // Create a new buffer for each message
+    buffer := make([]byte, 0)
 
-for _, item := range b {
     // Execute the converter function to get the converted data
     convertedData := item.ConverterFunc(item.Item.Data)
🧹 Nitpick comments (3)
s7comm_plugin/s7comm_test.go (1)

87-87: Fix typo in test case description.

-		Entry("same DBNumber but differen Item.Bit",
+		Entry("same DBNumber but different Item.Bit",
🧰 Tools
🪛 GitHub Actions: opcua-plc

[warning] 23: Test skipped: environment variables are not set

s7comm_plugin/s7comm.go (2)

183-185: LGTM! The enhanced duplicate detection is more accurate.

The use of reflect.DeepEqual properly handles all fields of S7DataItem, including the Bit field, which fixes the issue with duplicate detection for items having the same Start but different Bit values.

For future optimization, if performance becomes a concern, consider replacing reflect.DeepEqual with direct field comparison:

-if reflect.DeepEqual(a.Item, b.Item) {
+if a.Item.Area == b.Item.Area &&
+   a.Item.WordLen == b.Item.WordLen &&
+   a.Item.Bit == b.Item.Bit &&
+   a.Item.DBNumber == b.Item.DBNumber &&
+   a.Item.Start == b.Item.Start &&
+   a.Item.Amount == b.Item.Amount {

However, this optimization is not critical as:

  1. This code runs during initialization, not in the hot path
  2. The number of addresses is typically small
  3. The current implementation is more maintainable

Line range hint 264-269: Improve error message clarity in ReadBatch.

The error message mentions "Reconnecting..." but the actual reconnection is handled by Benthos's auto-retry mechanism, which could be misleading.

Apply this diff to improve the error message:

-            errMsg := fmt.Sprintf("Failed to read batch %d: %v. Reconnecting...", i+1, err)
+            errMsg := fmt.Sprintf("Failed to read batch %d: %v", i+1, err)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6dbe814 and ae3c03d.

📒 Files selected for processing (2)
  • s7comm_plugin/s7comm.go (2 hunks)
  • s7comm_plugin/s7comm_test.go (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: opcua-plc
s7comm_plugin/s7comm_test.go

[warning] 23: Test skipped: environment variables are not set

🪛 GitHub Actions: tag-processor
s7comm_plugin/s7comm_test.go

[warning] 133-133: Test skipped: environment variables not set

🔇 Additional comments (2)
s7comm_plugin/s7comm_test.go (1)

63-81: Well-structured table-driven tests!

The implementation follows good testing practices and properly addresses the previous review comment about using ginkgo table-driven tests.

🧰 Tools
🪛 GitHub Actions: opcua-plc

[warning] 23: Test skipped: environment variables are not set

s7comm_plugin/s7comm.go (1)

21-21: LGTM!

The addition of the reflect package is necessary for the enhanced duplicate detection logic.

Copy link
Contributor

@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

🧹 Nitpick comments (1)
s7comm_plugin/s7comm_test.go (1)

82-111: Consider adding more edge cases to strengthen test coverage.

The current test entries provide good coverage of common scenarios. Consider adding these additional test cases to make the test suite more robust:

  1. Mixed area types (e.g., DB vs PE with same addresses)
  2. Edge cases with maximum/minimum values
  3. Invalid address formats

Example additions:

+		Entry("same address in different areas",
+			S7Addresses{
+				addresses:      []string{"DB2.W0", "PE2.W0"},
+				expectedErrMsg: nil,
+			}),
+		Entry("invalid address format",
+			S7Addresses{
+				addresses:      []string{"DB2.W0", "DB2.INVALID"},
+				expectedErrMsg: []string{"invalid address format"},
+			}),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ae3c03d and e44bcf7.

📒 Files selected for processing (1)
  • s7comm_plugin/s7comm_test.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-docker (amd64)
  • GitHub Check: go-test-tag-processor
  • GitHub Check: go-test-opcua-plc
  • GitHub Check: go-test-s7-plc
  • GitHub Check: go-test-sensorconnect
  • GitHub Check: go-test-nodered-js
🔇 Additional comments (2)
s7comm_plugin/s7comm_test.go (2)

63-66: LGTM! Well-structured test data type.

The S7Addresses struct is well-defined with clear and descriptive field names.


68-81: LGTM! Well-implemented table-driven tests.

The implementation successfully addresses the previous review feedback by using Ginkgo's table-driven test pattern. The error handling is thorough and well-structured.

@led0nk led0nk merged commit 3115fdf into master Jan 21, 2025
14 checks 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.

2 participants