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

[udp] make response message cache configurable #590

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

hasheddan
Copy link
Contributor

@hasheddan hasheddan commented Nov 5, 2024

Modifies UDP conn implementation to allow for a custom response message cache to be provided. This change is implemented in such a way that API compatibility with previous v3 releases is preserved. Users may now provide an option to supply their own cache implementation. Structured messages, rather than their serialized representation, are now passed to the cache implementation to allow for caching decisions to be made in the cache implementation. For example, it may be desirable to skip caching blockwise message responses if the entire underlying data being transferred is also cached. The cache implementation is responsible for cloning messages or otherwise ensuring that it is not storing data that may subsequently be modified.

Replaces #589

Summary by CodeRabbit

  • New Features

    • Introduced a caching mechanism for CoAP messages, enhancing message processing efficiency.
    • Added functionality to load, store, and check expirations of cached messages.
  • Improvements

    • Updated message handling to prevent ID collisions during reconnections.
    • Enhanced response management by checking the cache before processing requests.

@hasheddan hasheddan changed the title [udp] make response message cache configurable and update default [udp] make response message cache configurable Nov 5, 2024
Copy link

coderabbitai bot commented Nov 5, 2024

Walkthrough

The changes introduce a new caching mechanism for CoAP messages in the udp/client/conn.go file. A new interface, MessageCache, is defined along with its implementation in the messageCache struct, which uses an in-memory cache. Several methods are added to manage message caching, and the Conn struct is updated to utilize this new interface. Modifications also include updates to the NewConnWithOpts function and enhancements to message ID handling to ensure uniqueness during reconnections.

Changes

File Change Summary
udp/client/conn.go Added MessageCache interface and messageCache struct. Introduced methods: Load, Store, CheckExpirations. Updated responseMsgCache field type in Conn and ConnOptions. Modified NewConnWithOpts to initialize responseMsgCache. Added addResponseToCache and getResponseFromCache methods. Updated checkResponseCache to utilize the new caching mechanism. Enhanced message ID handling.

Poem

In the meadow where messages play,
A cache was born to save the day.
With hops and skips, it stores with glee,
Unique IDs, as bright as can be!
Oh, what joy in the code we find,
A caching tale, so sweet and kind! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b1f7350 and b80b7a8.

📒 Files selected for processing (1)
  • udp/client/conn.go (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • udp/client/conn.go

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 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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 91a04ea and b1f7350.

📒 Files selected for processing (1)
  • udp/client/conn.go (8 hunks)

udp/client/conn.go Outdated Show resolved Hide resolved
Comment on lines +691 to +694
// getResponseFromCache gets a message from the response message cache.
func (cc *Conn) getResponseFromCache(mid int32, resp *pool.Message) (bool, error) {
return cc.responseMsgCache.Load(strconv.Itoa(int(mid)), resp)
}

// addResponseToCache adds a message to the response message cache.
func (cc *Conn) addResponseToCache(resp *pool.Message) error {
marshaledResp, err := resp.MarshalWithEncoder(coder.DefaultCoder)
if err != nil {
return err
}
cacheMsg := make([]byte, len(marshaledResp))
copy(cacheMsg, marshaledResp)
cc.responseMsgCache.LoadOrStore(cc.responseMsgCacheID(resp.MessageID()), cache.NewElement(cacheMsg, time.Now().Add(ExchangeLifetime), nil))
return nil
}

func (cc *Conn) getResponseFromCache(mid int32, resp *pool.Message) (bool, error) {
cachedResp := cc.responseMsgCache.Load(cc.responseMsgCacheID(mid))
if cachedResp == nil {
return false, nil
}
if rawMsg := cachedResp.Data(); len(rawMsg) > 0 {
_, err := resp.UnmarshalWithDecoder(coder.DefaultCoder, rawMsg)
if err != nil {
return false, err
}
return true, nil
}
return false, nil
return cc.responseMsgCache.Store(strconv.Itoa(int(resp.MessageID())), resp)
Copy link

@coderabbitai coderabbitai bot Nov 5, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential cache key collision due to Message ID reuse across different remote addresses

Using only the Message ID (MID) as the cache key may lead to collisions when the same MID is used by different remote endpoints. According to the CoAP specification, MIDs are unique per endpoint but can be reused over time and across different clients. To prevent cache key collisions and ensure correct message handling, consider incorporating the remote address (e.g., IP address and port) into the cache key.

Apply this diff to modify the cache key to include the remote address:

 func (cc *Conn) getResponseFromCache(mid int32, resp *pool.Message) (bool, error) {
+	key := cc.RemoteAddr().String() + ":" + strconv.Itoa(int(mid))
-	return cc.responseMsgCache.Load(strconv.Itoa(int(mid)), resp)
+	return cc.responseMsgCache.Load(key, resp)
 }

 func (cc *Conn) addResponseToCache(resp *pool.Message) error {
+	key := cc.RemoteAddr().String() + ":" + strconv.Itoa(int(resp.MessageID()))
-	return cc.responseMsgCache.Store(strconv.Itoa(int(resp.MessageID())), resp)
+	return cc.responseMsgCache.Store(key, resp)
 }

You'll also need to update calls to these functions to ensure the remote address is available when constructing the cache key.

📝 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
// getResponseFromCache gets a message from the response message cache.
func (cc *Conn) getResponseFromCache(mid int32, resp *pool.Message) (bool, error) {
return cc.responseMsgCache.Load(strconv.Itoa(int(mid)), resp)
}
// addResponseToCache adds a message to the response message cache.
func (cc *Conn) addResponseToCache(resp *pool.Message) error {
marshaledResp, err := resp.MarshalWithEncoder(coder.DefaultCoder)
if err != nil {
return err
}
cacheMsg := make([]byte, len(marshaledResp))
copy(cacheMsg, marshaledResp)
cc.responseMsgCache.LoadOrStore(cc.responseMsgCacheID(resp.MessageID()), cache.NewElement(cacheMsg, time.Now().Add(ExchangeLifetime), nil))
return nil
}
func (cc *Conn) getResponseFromCache(mid int32, resp *pool.Message) (bool, error) {
cachedResp := cc.responseMsgCache.Load(cc.responseMsgCacheID(mid))
if cachedResp == nil {
return false, nil
}
if rawMsg := cachedResp.Data(); len(rawMsg) > 0 {
_, err := resp.UnmarshalWithDecoder(coder.DefaultCoder, rawMsg)
if err != nil {
return false, err
}
return true, nil
}
return false, nil
return cc.responseMsgCache.Store(strconv.Itoa(int(resp.MessageID())), resp)
// getResponseFromCache gets a message from the response message cache.
func (cc *Conn) getResponseFromCache(mid int32, resp *pool.Message) (bool, error) {
key := cc.RemoteAddr().String() + ":" + strconv.Itoa(int(mid))
return cc.responseMsgCache.Load(key, resp)
}
// addResponseToCache adds a message to the response message cache.
func (cc *Conn) addResponseToCache(resp *pool.Message) error {
key := cc.RemoteAddr().String() + ":" + strconv.Itoa(int(resp.MessageID()))
return cc.responseMsgCache.Store(key, resp)
}

Copy link
Member

Choose a reason for hiding this comment

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

I agree. Collisions could occur – could you please use responseMsgCacheID(resp.MessageID()) as the key?

Copy link

Choose a reason for hiding this comment

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

@jkralik, certainly! We can reintroduce the responseMsgCacheID function and use it as the key to prevent collisions. Here are the necessary changes:

First, add the responseMsgCacheID function back into your code:

func (cc *Conn) responseMsgCacheID(msgID int32) string {
    return fmt.Sprintf("resp-%v-%d", cc.RemoteAddr(), msgID)
}

Then, update the getResponseFromCache and addResponseToCache functions to use this key:

// getResponseFromCache gets a message from the response message cache.
func (cc *Conn) getResponseFromCache(mid int32, resp *pool.Message) (bool, error) {
    return cc.responseMsgCache.Load(cc.responseMsgCacheID(mid), resp)
}

// addResponseToCache adds a message to the response message cache.
func (cc *Conn) addResponseToCache(resp *pool.Message) error {
    return cc.responseMsgCache.Store(cc.responseMsgCacheID(resp.MessageID()), resp)
}

This change ensures that the cache key includes both the remote address and the message ID, preventing collisions across different remote addresses.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@jkralik I intentionally made this update because, if using DTLS 1.2 Connection IDs, the underlying remote IP address / port can change and the connection can continue. Items in the cache would then no longer be accessible because we would attempt to access with a different key. In the event that we are not using DTLS, or using DTLS without Connection IDs, I don't believe that Conns should be used across multiple endpoints, and I believe there are issues other than just the cache keys here if they are. Is there a scenario in which a Conn is being used across endpoints, thus meaning that a responseMsgCache would not be local to a single endpoint?

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Modifies UDP conn implementation to allow for a custom response message
cache to be provided. This change is implemented in such a way that API
compatibility with previous v3 releases is preserved. Users may now
provide an option to supply their own cache implementation. Structured
messages, rather than their serialized representation, are now passed to
the cache implementation to allow for caching decisions to be made in
the cache implementation. For example, it may be desirable to skip
caching blockwise message responses if the entire underlying data being
transferred is also cached. The cache implementation is responsible for
cloning messages or otherwise ensuring that it is not storing data that
may subsequently be modified.

Signed-off-by: Daniel Mangum <[email protected]>
Copy link
Contributor Author

@hasheddan hasheddan left a comment

Choose a reason for hiding this comment

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

@jkralik any thoughts here? 🙂

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