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

backward compatible metadata keys #4738

Merged
merged 5 commits into from
Dec 11, 2024
Merged

backward compatible metadata keys #4738

merged 5 commits into from
Dec 11, 2024

Conversation

wdbaruni
Copy link
Member

@wdbaruni wdbaruni commented Dec 11, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new constant for header prefix to improve metadata handling.
  • Improvements

    • Enhanced key retrieval logic for better backward compatibility in metadata access.
    • Improved error logging in message handling to include subscriber name for better traceability.

Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

The changes in this pull request involve modifications to two files within the codebase. In metadata.go, a new constant HeaderPrefix is introduced, and existing constants for message type and payload encoding are updated for brevity. The Get method is revised to enhance key retrieval, ensuring backward compatibility with older headers. In subscriber.go, the error logging in the handleNatsMessage method is improved by including the subscriber's name to provide better context during error occurrences.

Changes

File Change Summary
pkg/lib/envelope/metadata.go - Added constant HeaderPrefix with value "Bacalhau-".
- Updated KeyMessageType from "Bacalhau-Type" to "Type".
- Updated KeyPayloadEncoding from "Bacalhau-PayloadEncoding" to "PayloadEncoding".
- Modified Get method to improve key retrieval and ensure backward compatibility.
pkg/lib/ncl/subscriber.go - Updated error logging in handleNatsMessage to include subscriber's name for better traceability during errors.

Poem

🐰 In the meadow where code does play,
New constants bloom, brightening the day.
With names more concise, and logs that shine,
Our rabbit team hops, all is divine!
Errors now tell tales, clear as can be,
In the world of code, we dance with glee! 🌼


🪧 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. (Experiment)
  • @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.

@wdbaruni wdbaruni self-assigned this Dec 11, 2024
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: 1

🧹 Outside diff range and nitpick comments (3)
pkg/lib/ncl/subscriber.go (1)

Line range hint 1-1: Consider implementing a metadata key migration strategy

The removal of "Bacalhau-" prefix from metadata keys across the codebase requires careful handling to maintain backward compatibility. Consider implementing:

  1. A transition period where both old and new formats are supported
  2. A migration guide for downstream consumers
  3. Version detection in message handling code
  4. Deprecation notices for the old format
pkg/lib/envelope/metadata.go (2)

27-27: Consider adding a safety check for already prefixed keys.

While the current implementation works for the simplified keys, it might cause issues if a key already contains the prefix. Consider adding a check to prevent double-prefixing.

-		headers[HeaderPrefix+k] = []string{v}
+		key := k
+		if !strings.HasPrefix(k, HeaderPrefix) {
+			key = HeaderPrefix + k
+		}
+		headers[key] = []string{v}

Line range hint 10-41: Consider introducing a metadata key management utility.

To improve maintainability and reduce duplication, consider extracting the prefix handling logic into utility functions. This would centralize the logic and make it easier to modify the behavior in the future.

Example approach:

// keyutil/keys.go
package keyutil

func ToHeaderKey(key string) string {
    if strings.HasPrefix(key, HeaderPrefix) {
        return key
    }
    return HeaderPrefix + key
}

func FromHeaderKey(key string) string {
    if strings.HasPrefix(key, HeaderPrefix) {
        return key[len(HeaderPrefix):]
    }
    return key
}

This would:

  • Centralize the prefix handling logic
  • Make it easier to modify the behavior
  • Reduce the chance of inconsistencies
  • Simplify testing
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 83bc0a4 and 72d11ac.

📒 Files selected for processing (6)
  • pkg/lib/envelope/metadata.go (2 hunks)
  • pkg/lib/ncl/constants.go (1 hunks)
  • pkg/lib/ncl/error_response.go (1 hunks)
  • pkg/lib/ncl/subscriber.go (1 hunks)
  • pkg/transport/nclprotocol/dispatcher/constants.go (1 hunks)
  • pkg/transport/nclprotocol/types.go (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • pkg/lib/ncl/constants.go
  • pkg/transport/nclprotocol/dispatcher/constants.go
🔇 Additional comments (4)
pkg/lib/ncl/error_response.go (1)

15-15: ⚠️ Potential issue

Ensure backward compatibility for KeyStatusCode changes

The change from "Bacalhau-StatusCode" to "StatusCode" might break existing systems expecting the old format. Consider:

  1. Adding a transition period where both formats are supported
  2. Using the new HeaderPrefix constant mentioned in the summary

Let's verify the impact of this change:

pkg/transport/nclprotocol/types.go (1)

56-56: ⚠️ Potential issue

Verify sequence number backward compatibility

The change from "Bacalhau-SeqNum" to "SeqNum" could affect message ordering and processing in existing systems. Consider:

  1. Adding a transition mechanism to handle both old and new sequence number formats
  2. Documenting the change for downstream consumers

Let's verify the sequence number usage:

pkg/lib/ncl/subscriber.go (1)

78-78: LGTM: Enhanced error logging with handler context

Good improvement to add the handler name in error logs. This will make it easier to identify which subscriber encountered issues during message processing.

pkg/lib/envelope/metadata.go (1)

10-12: LGTM! Clean separation of concerns with the header prefix.

The introduction of HeaderPrefix and simplification of key constants improves code maintainability while preserving backward compatibility through consistent header prefixing.

Let's verify that these are the only metadata keys being used:

✅ Verification successful

No other metadata keys need updating, changes are consistent

Based on the search results, the only metadata-related keys in the codebase that use the "Bacalhau-" prefix are the ones being modified in this PR (Type and PayloadEncoding). The changes are consistent with the codebase:

  • The HeaderPrefix constant is used correctly in the ToHeaders and FromHeaders methods in the same file
  • Other message-related keys in the codebase (like KeySource, KeyEventTime, etc.) follow a similar pattern of not having the prefix in the constant name
  • The prefix is only added when converting to headers, maintaining backward compatibility
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other metadata keys that might need similar updates
rg -g '!vendor/*' '"Bacalhau-[A-Za-z]+"' 

Length of output: 42


Script:

#!/bin/bash
# Let's try a more comprehensive search for metadata keys
# First, let's look for any string constants containing "Type" or "PayloadEncoding"
rg -g '!vendor/*' -i '(Type|PayloadEncoding).*=.*"' 

# Also search for any usage of HeaderPrefix
rg -g '!vendor/*' 'HeaderPrefix'

# And look for any other potential metadata-related constants
rg -g '!vendor/*' 'Key[A-Z][A-Za-z]+\s*='

Length of output: 19519

pkg/lib/envelope/metadata.go Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 72d11ac and 0430fcb.

📒 Files selected for processing (1)
  • pkg/lib/envelope/metadata.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: build / Build Binary (darwin, arm64)
pkg/lib/envelope/metadata.go

[failure] 40-40:
undefined: strings

🪛 GitHub Check: build / Build Binary (darwin, amd64)
pkg/lib/envelope/metadata.go

[failure] 40-40:
undefined: strings

🪛 GitHub Check: build / Build Binary (linux, armv6)
pkg/lib/envelope/metadata.go

[failure] 40-40:
undefined: strings

🪛 GitHub Check: build / Build Binary (linux, armv7)
pkg/lib/envelope/metadata.go

[failure] 40-40:
undefined: strings

🪛 GitHub Check: build / Build Binary (linux, arm64)
pkg/lib/envelope/metadata.go

[failure] 40-40:
undefined: strings

🪛 GitHub Check: build / Build Binary (linux, amd64)
pkg/lib/envelope/metadata.go

[failure] 40-40:
undefined: strings

🪛 GitHub Check: lint / go-lint (ubuntu-latest)
pkg/lib/envelope/metadata.go

[failure] 40-40:
undefined: strings (typecheck)


[failure] 40-40:
undefined: strings) (typecheck)


[failure] 40-40:
undefined: strings) (typecheck)


[failure] 40-40:
undefined: strings) (typecheck)

🔇 Additional comments (3)
pkg/lib/envelope/metadata.go (3)

10-12: LGTM! Good refactoring of constants.

The introduction of HeaderPrefix and simplification of key names improves code maintainability while preserving backward compatibility through the ToHeaders method.


27-27: LGTM! Correct implementation of prefix handling.

The modification correctly applies the HeaderPrefix to maintain backward compatibility with existing header formats.


Line range hint 10-46: Verify backward compatibility across the codebase.

While the changes maintain backward compatibility through proper prefix handling, let's verify the usage across the codebase.

✅ Verification successful

Let me gather more information about the usage of metadata and headers in the codebase to ensure we have a complete picture.


Let me check one final aspect to ensure we have a complete understanding of the header usage in tests.


Based on the comprehensive analysis of the codebase, I can now provide the final response:

Backward compatibility is properly maintained.

The code maintains backward compatibility through:

  1. Consistent usage of HeaderPrefix ("Bacalhau-") across the codebase
  2. Proper handling of both prefixed and unprefixed keys in FromHeaders
  3. Consistent metadata key handling in message types and transport layers
  4. No direct string literals of prefixed headers found that could break
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct usage of the old prefixed constants
rg '"Bacalhau-Type"|"Bacalhau-PayloadEncoding"'

# Search for header key usage to ensure we haven't missed any cases
rg -A 2 'ToHeaders|FromHeaders'

Length of output: 996


Script:

#!/bin/bash
# Search for Metadata type usage and initialization
ast-grep --pattern 'type $_ struct {
  $$$
  Metadata $$$
  $$$
}'

# Search for any direct header manipulation that might bypass ToHeaders/FromHeaders
rg -A 2 'Header.*=.*map\[string\]\[\]string'

# Search for tests involving headers to verify compatibility handling
rg -l 'Test.*Header|Header.*Test' --type go

Length of output: 1474


Script:

#!/bin/bash
# Check the test file content to understand header usage patterns
cat pkg/executor/docker/executor_test.go

# Look for any usage of the specific header keys we're concerned about
rg -A 2 'KeyMessageType|KeyPayloadEncoding'

# Check for any direct manipulation of headers in tests
rg -A 2 'Header.*Bacalhau-' --type go

Length of output: 39174

🧰 Tools
🪛 GitHub Check: build / Build Binary (darwin, arm64)

[failure] 40-40:
undefined: strings

🪛 GitHub Check: build / Build Binary (darwin, amd64)

[failure] 40-40:
undefined: strings

🪛 GitHub Check: build / Build Binary (linux, armv6)

[failure] 40-40:
undefined: strings

🪛 GitHub Check: build / Build Binary (linux, armv7)

[failure] 40-40:
undefined: strings

🪛 GitHub Check: build / Build Binary (linux, arm64)

[failure] 40-40:
undefined: strings

🪛 GitHub Check: build / Build Binary (linux, amd64)

[failure] 40-40:
undefined: strings

🪛 GitHub Check: lint / go-lint (ubuntu-latest)

[failure] 40-40:
undefined: strings (typecheck)


[failure] 40-40:
undefined: strings) (typecheck)


[failure] 40-40:
undefined: strings) (typecheck)


[failure] 40-40:
undefined: strings) (typecheck)

pkg/lib/envelope/metadata.go Outdated Show resolved Hide resolved
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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 17f21f5 and 1f094d5.

📒 Files selected for processing (1)
  • pkg/lib/envelope/metadata.go (2 hunks)

Comment on lines +11 to 13
HeaderPrefix = "Bacalhau-"
KeyMessageType = "Bacalhau-Type"
KeyPayloadEncoding = "Bacalhau-PayloadEncoding"
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update message type and encoding constants to use HeaderPrefix

The constants KeyMessageType and KeyPayloadEncoding have the "Bacalhau-" prefix hardcoded, while we now have a HeaderPrefix constant. This creates redundancy and potential maintenance issues.

Consider using the HeaderPrefix constant:

 const (
 	HeaderPrefix       = "Bacalhau-"
-	KeyMessageType     = "Bacalhau-Type"
-	KeyPayloadEncoding = "Bacalhau-PayloadEncoding"
+	KeyMessageType     = "Type"
+	KeyPayloadEncoding = "PayloadEncoding"
 )

This change would:

  1. Reduce redundancy
  2. Make it easier to maintain if the prefix needs to change
  3. Match the backward compatibility logic in the Get method
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
HeaderPrefix = "Bacalhau-"
KeyMessageType = "Bacalhau-Type"
KeyPayloadEncoding = "Bacalhau-PayloadEncoding"
HeaderPrefix = "Bacalhau-"
KeyMessageType = "Type"
KeyPayloadEncoding = "PayloadEncoding"

Comment on lines 54 to +63
func (m Metadata) Get(key string) string {
return m[key]
if v, ok := m[key]; ok {
return v
}
// backward compatible with old headers
if key == KeyMessageType || key == KeyPayloadEncoding {
// return keys excluding header prefix
return m[strings.TrimPrefix(key, HeaderPrefix)]
}
return ""
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance backward compatibility handling in Get method

The current implementation has several limitations:

  1. Only handles backward compatibility for KeyMessageType and KeyPayloadEncoding
  2. Doesn't handle case where both prefixed and unprefixed keys exist
  3. Could be more generic to handle all keys with prefix

Consider this more robust implementation:

 func (m Metadata) Get(key string) string {
 	if v, ok := m[key]; ok {
 		return v
 	}
-	// backward compatible with old headers
-	if key == KeyMessageType || key == KeyPayloadEncoding {
-		// return keys excluding header prefix
-		return m[strings.TrimPrefix(key, HeaderPrefix)]
+	// Check if key has prefix
+	if strings.HasPrefix(key, HeaderPrefix) {
+		// Try without prefix
+		if v, ok := m[strings.TrimPrefix(key, HeaderPrefix)]; ok {
+			return v
+		}
+	} else {
+		// Try with prefix
+		if v, ok := m[HeaderPrefix+key]; ok {
+			return v
+		}
 	}
 	return ""
 }

This implementation:

  1. Handles all keys, not just specific ones
  2. Tries both with and without prefix
  3. Maintains backward compatibility more comprehensively
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (m Metadata) Get(key string) string {
return m[key]
if v, ok := m[key]; ok {
return v
}
// backward compatible with old headers
if key == KeyMessageType || key == KeyPayloadEncoding {
// return keys excluding header prefix
return m[strings.TrimPrefix(key, HeaderPrefix)]
}
return ""
func (m Metadata) Get(key string) string {
if v, ok := m[key]; ok {
return v
}
// Check if key has prefix
if strings.HasPrefix(key, HeaderPrefix) {
// Try without prefix
if v, ok := m[strings.TrimPrefix(key, HeaderPrefix)]; ok {
return v
}
} else {
// Try with prefix
if v, ok := m[HeaderPrefix+key]; ok {
return v
}
}
return ""
}

@wdbaruni wdbaruni merged commit 04ec16c into main Dec 11, 2024
14 checks passed
@wdbaruni wdbaruni deleted the backward-compatible-keys branch December 11, 2024 11:23
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