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

refactor: Use generics in function of bidirectional stream #2803

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

highpon
Copy link
Contributor

@highpon highpon commented Jan 16, 2025

Description

Use generics of function of bidirectional stream.
This PR intends to refactor current code.

Related Issue

Versions

  • Vald Version: v1.7.15
  • Go Version: v1.23.4
  • Rust Version: v1.83.0
  • Docker Version: v27.4.0
  • Kubernetes Version: v1.32.0
  • Helm Version: v3.16.3
  • NGT Version: v2.3.5
  • Faiss Version: v1.9.0

Checklist

Special notes for your reviewer

Summary by CodeRabbit

  • Refactor

    • Updated function signatures in multiple service files to improve type safety.
    • Modified return types to use pointer-based generics in gRPC stream and load testing utilities.
    • Enhanced type handling for data providers and request generation.
  • Technical Improvements

    • Refined type parameter declarations in gRPC streaming functions.
    • Updated callback and data provider function signatures to use more explicit pointer types.

Copy link
Contributor

coderabbitai bot commented Jan 16, 2025

📝 Walkthrough

Walkthrough

The pull request introduces type-related modifications across multiple files in the gRPC and load testing components. The changes primarily focus on updating function signatures to use more explicit type parameters and return pointers to any type instead of direct any values. These modifications enhance type safety and provide more precise type handling in the data provider and stream-related functions across the internal networking and load testing services.

Changes

File Change Summary
internal/net/grpc/stream.go Updated BidirectionalStream and BidirectionalStreamClient function signatures with more explicit type parameters and renamed callback function.
pkg/tools/cli/loadtest/service/insert.go Modified insertRequestProvider, objectVectorProvider, and objectVectorsProvider to return func() *any instead of func() any.
pkg/tools/cli/loadtest/service/loader.go Replaced dataProvider with sendDataProvider returning *any, updated method signatures to use pointer types.
pkg/tools/cli/loadtest/service/search.go Updated searchRequestProvider to return func() *any and modified internal type handling.

Sequence Diagram

sequenceDiagram
    participant Client
    participant DataProvider
    participant Stream
    
    Client->>DataProvider: Request data
    DataProvider-->>Client: Return *any data
    Client->>Stream: Send data pointer
    Stream->>Stream: Process data
    Stream-->>Client: Return result/error
Loading

The sequence diagram illustrates the updated flow where data providers now return pointers, which are then passed through the stream processing mechanism, maintaining the core logic while introducing more explicit type handling.


📜 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 39c2149 and 6126157.

📒 Files selected for processing (1)
  • pkg/tools/cli/loadtest/service/search.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/tools/cli/loadtest/service/search.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 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: 1

🔭 Outside diff range comments (1)
pkg/tools/cli/loadtest/service/insert.go (1)

Line range hint 12-24: Consider revising the discount and fee structure.

The current implementation has potential issues:

  1. For small purchase amounts, the $20 flat fee on discounted orders can exceed the discount benefit.
  2. A customer with 3-4 years loyalty (10% discount) buying a $100 item would pay $110 ($100 - $10 + $20), which is more than without any discount ($100).

Consider one of these alternatives:

  1. Apply the fee as a percentage instead of a flat amount
  2. Only apply the fee when the discount benefit exceeds the fee
  3. Scale the fee based on the purchase amount
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4c73960 and 2e7be42.

📒 Files selected for processing (4)
  • internal/net/grpc/stream.go (4 hunks)
  • pkg/tools/cli/loadtest/service/insert.go (2 hunks)
  • pkg/tools/cli/loadtest/service/loader.go (7 hunks)
  • pkg/tools/cli/loadtest/service/search.go (1 hunks)
🔇 Additional comments (9)
pkg/tools/cli/loadtest/service/insert.go (1)

Line range hint 4-4: Add unit tests as indicated by the TODO comment.

The TODO comment indicates missing tests for this functionality.

Would you like me to help generate comprehensive unit tests for these functions?

internal/net/grpc/stream.go (1)

170-171: LGTM! Good use of generics for type safety.

The updated function signature using generics (BidirectionalStreamClient[S, R any]) and pointer types improves type safety and makes the API more explicit.

pkg/tools/cli/loadtest/service/loader.go (6)

52-52: LGTM! Improved naming and type safety.

The rename from dataProvider to sendDataProvider better reflects its usage in bidirectional streams, and returning a pointer to any is more memory efficient.


99-101: LGTM! Consistent provider assignment.

The assignments correctly use the renamed sendDataProvider field while maintaining proper error handling.


Line range hint 137-142: LGTM! Consistent pointer usage in callback.

The callback signature now correctly accepts a pointer to any, maintaining consistency with the broader refactor while preserving the atomic counter functionality.


186-186: LGTM! Consistent callback signature.

The method signature correctly uses a pointer type for the callback parameter, maintaining consistency with the broader refactor.


204-204: LGTM! Updated stream client usage.

The BidirectionalStreamClient call correctly uses the renamed sendDataProvider.


Line range hint 213-225: Verify error handling with pointer usage.

While the changes to use pointers are correct, ensure that proper nil checks are in place throughout the error handling path.

✅ Verification successful

Error handling with pointer usage is properly implemented

The error handling chain is complete and pointer usage is safe throughout the error path. The results are properly scoped and initialized before being passed by address to the callback function.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for error handling patterns with pointer usage
rg -U "if\s+.*err\s*!=\s*nil.*\{[\s\S]*?f\(&.*,\s*err\)" .

Length of output: 11178

pkg/tools/cli/loadtest/service/search.go (1)

35-39: Verify type assertion safety.

The type assertion v.([]float32) could panic if the dataset returns an unexpected type.

pkg/tools/cli/loadtest/service/search.go Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 16, 2025
Comment on lines 170 to 171
func BidirectionalStreamClient[S, R any](
stream ClientStream, sendDataProvider func() *S, callBack func(*R, error),
Copy link
Collaborator

Choose a reason for hiding this comment

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

@highpon Thank you for your contribution around important libs.

How about an interface that cancels all stream processing in case of false by using a boolean as the return value of the callback function argument of the BidirectionalStreamClient?

It would be very useful to have an interface that can stop all streams when a fatal error is detected in the callback function.

Suggested change
func BidirectionalStreamClient[S, R any](
stream ClientStream, sendDataProvider func() *S, callBack func(*R, error),
func BidirectionalStreamClient[S, R any](
stream ClientStream, sendDataProvider func() *S, callBack func(*R, error) bool,

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for your review!
fix: 39c2149

err = stream.RecvMsg(res)
if err == io.EOF || errors.Is(err, io.EOF) {
cancel()
return nil
}
f(res, err)
callBack(res, err)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Kind of like this.

Suggested change
callBack(res, err)
if !callBack(res, err) {
cancel()
return nil
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for you review!
fix: 39c2149

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 (4)
pkg/tools/cli/loadtest/service/loader.go (4)

52-52: LGTM! Consider adding documentation.

The change to use *any and the renamed field better reflects its purpose. Consider adding a doc comment to explain the purpose of this field and why it returns a pointer.

+// sendDataProvider returns the next data item to be sent in the load test.
+// It returns a pointer to optimize for large data structures and returns nil when no more data is available.
 sendDataProvider func() *any

137-137: Consider whether pointer type is necessary for the callback.

Since this callback is only used for progress tracking and error counting, receiving a pointer to any might be unnecessary overhead. Consider keeping it as func(i any, err error) unless there's a specific need for pointer semantics in the callback.


Line range hint 213-225: Simplify pointer handling in unary requests.

The current implementation unnecessarily dereferences and re-addresses the pointer. Consider simplifying:

-r := l.sendDataProvider()
-if r == nil {
-    break
-}
-// ...
-res, err := l.loaderFunc(egctx, conn, *r)
-f(&res, err)

+req := l.sendDataProvider()
+if req == nil {
+    break
+}
+// ...
+res, err := l.loaderFunc(egctx, conn, *req)
+f(req, err)

This change:

  1. Uses clearer variable naming
  2. Avoids unnecessary pointer operations
  3. Reuses the existing pointer in the callback

Line range hint 52-225: Consider documenting the pointer-based design decision.

The transition to pointer-based types is a significant architectural change that could affect performance and memory usage. Consider:

  1. Adding a comment in the package documentation explaining the rationale behind using pointers to any
  2. Documenting any performance improvements or memory savings observed
  3. Adding benchmarks to validate the benefits of this approach
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2e7be42 and f92db92.

📒 Files selected for processing (1)
  • pkg/tools/cli/loadtest/service/loader.go (7 hunks)
🔇 Additional comments (3)
pkg/tools/cli/loadtest/service/loader.go (3)

99-101: LGTM! Changes align with the new pointer-based approach.

The assignments correctly use the renamed field and maintain the existing logic while adapting to the new pointer type.


186-186: Consistent with previous callback changes.


204-204: LGTM! Appropriate use of pointer-based provider in streaming context.

The change correctly adapts the bidirectional streaming to use the pointer-based provider, which is beneficial for performance in streaming scenarios.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 21, 2025
@highpon highpon requested a review from kpango January 21, 2025 15:25
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: 13

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f92db92 and 39c2149.

📒 Files selected for processing (3)
  • internal/net/grpc/stream.go (5 hunks)
  • pkg/tools/cli/loadtest/service/insert.go (2 hunks)
  • pkg/tools/cli/loadtest/service/loader.go (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/net/grpc/stream.go
🔇 Additional comments (2)
pkg/tools/cli/loadtest/service/loader.go (2)

100-100: 🛠️ Refactor suggestion

Adjust data provider assignment to match function signature

After changing the return type of insertRequestProvider, ensure the assignment matches.

Apply this diff:

-		l.sendDataProvider, l.dataSize, err = insertRequestProvider(dataset, l.batchSize)
+		l.sendDataProvider, l.dataSize, err = insertRequestProvider(dataset, l.batchSize)

Likely invalid or redundant comment.


208-209: 🛠️ Refactor suggestion

Adjust callback function to match updated parameter types

After changing f to accept any, ensure the callback passes the correct type.

Apply this diff:

-						f(nil, err)
+						f(nil, err)

Likely invalid or redundant comment.

pkg/tools/cli/loadtest/service/insert.go Show resolved Hide resolved
pkg/tools/cli/loadtest/service/insert.go Show resolved Hide resolved
pkg/tools/cli/loadtest/service/insert.go Show resolved Hide resolved
pkg/tools/cli/loadtest/service/insert.go Show resolved Hide resolved
pkg/tools/cli/loadtest/service/insert.go Show resolved Hide resolved
pkg/tools/cli/loadtest/service/loader.go Show resolved Hide resolved
pkg/tools/cli/loadtest/service/loader.go Show resolved Hide resolved
pkg/tools/cli/loadtest/service/loader.go Show resolved Hide resolved
pkg/tools/cli/loadtest/service/loader.go Show resolved Hide resolved
pkg/tools/cli/loadtest/service/loader.go Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 21, 2025
@vankichi vankichi requested review from a team and kmrmt and removed request for a team January 23, 2025 04:45
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