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

Add support for func-types to fx.As() #1249

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

pelmennoteam
Copy link

@pelmennoteam pelmennoteam commented Nov 29, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced annotation functionality for more flexible type conversions, supporting both interface and convertible types with updated documentation and examples.
  • Tests

    • Introduced new test cases to validate successful conversions and proper error handling for unsupported conversion scenarios.

@CLAassistant
Copy link

CLAassistant commented Nov 29, 2024

CLA assistant check
All committers have signed the CLA.

Copy link
Contributor

@JacobOaks JacobOaks left a comment

Choose a reason for hiding this comment

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

Thanks for the PR! I have a couple comments on the implementation.

At a high level, I can't think of any particular reason why this shouldn't be allowed, but can you maybe provide some insight into why this is desired over, say, just providing a struct with a call-able method defined on it and using fx.As(new(someInterface))? Is it just cleaner in some scenarios?

annotated.go Outdated
Comment on lines 1282 to 1286
if !((at.types[i].typ.Kind() == reflect.Interface && t.Implements(at.types[i].typ)) ||
t.ConvertibleTo(at.types[i].typ)) {
return nil,
nil,
fmt.Errorf("invalid fx.As: %v does not implement or is not convertible to %v", t, at.types[i])
Copy link
Contributor

@JacobOaks JacobOaks Dec 4, 2024

Choose a reason for hiding this comment

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

Should we make these two separate checks? This will keep the code cleaner and give better error messages.

if at.types[i].typ.Kind() == reflect.Interface {
    if !t.Implements(at.types[i].typ) {
        return nil, nil, fmt.Errorf("invalid fx.As: %v does not implement %v", t, at.types[i])
    }
} else if !t.ConvertibleTo(at.types[i].typ) {
        return nil, nil, fmt.Errorf("invalid fx.As: %v cannot be converted to %v", t, at.types[i])
}

Copy link
Author

Choose a reason for hiding this comment

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

Thx, I split this condition

annotated.go Outdated
Comment on lines 1320 to 1324
if newOutResult.Field(i).Kind() == reflect.Func {
newOutResult.Field(i).Set(getResult(i, results).Convert(newOutResult.Field(i).Type()))
} else {
newOutResult.Field(i).Set(getResult(i, results))
}
Copy link
Contributor

@JacobOaks JacobOaks Dec 4, 2024

Choose a reason for hiding this comment

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

nit: should we flip these conditions to make the control flow more/appear consistent with the check above?

if newOutResult.Field(i).Kind() == reflect.Interface {
    newOutResult.Field(i).Set(getResult(i, results))
} else {
    newOutResult.Field(i).Set(getResult(i, results).Convert(newOutResult.Field(i).Type()))
}

Copy link
Author

Choose a reason for hiding this comment

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

fixed

@@ -1300,7 +1317,11 @@ func (at *asAnnotation) results(ann *annotated) (

newOutResult := reflect.New(resType).Elem()
for i := 1; i < resType.NumField(); i++ {
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there any reason we would need to check Value.CanConvert first since technically Value.Convert can panic even if Type.ConvertibleTo returns true? I can't think of any reason why a func value wouldn't be convertible if its type is though.

@@ -477,6 +480,32 @@ func TestAnnotatedAs(t *testing.T) {
assert.Equal(t, s.String(), "another stringer")
},
},
{
desc: "value type convertible to target type",
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: consider downscoping the names of these cases since convertible types are locked down to just functions right now

Suggested change
desc: "value type convertible to target type",
desc: "function value convertible to target type",

},
},
{
desc: "anonymous value type convertible to target type",
Copy link
Contributor

Choose a reason for hiding this comment

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

should we add a test case for a function vaoue that is not convertible to the target type?

Copy link
Author

Choose a reason for hiding this comment

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

Thx, I added new test case.

annotated.go Outdated
@@ -1145,6 +1146,19 @@ var _ Annotation = (*asAnnotation)(nil)
// constructor does NOT provide both bytes.Buffer and io.Writer type; it just
// provides io.Writer type.
//
// Example for function-types:
Copy link
Contributor

Choose a reason for hiding this comment

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

Let's update line 1129 as well:

- // constructor) to be provided as another interface.
+ // constructor) to be provided as another type.

Copy link
Author

Choose a reason for hiding this comment

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

Thx, appropriate changes have been made.

Copy link

coderabbitai bot commented Mar 7, 2025

Walkthrough

The changes enhance the As annotation functionality in the fx package to support both interface and convertible type conversions. In annotated.go, comments and error handling have been updated to clarify usage and check for pointer/convertible types. In annotated_test.go, new test cases and types have been added to validate correct conversions and ensure proper error generation when type mismatches occur.

Changes

File(s) Change Summary
annotated.go Enhanced the As annotation to support interfaces and convertible types. Updated comments, improved type-checking (pointer and convertibility), and modified error handling and result processing.
annotated_test.go Added new types (myProvideFunc, myInvokeFunc, myStringType, myIntType) and expanded test coverage with cases for successful type conversion and expected failure scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as fx.Provide
    participant Annotation as As Annotation
    participant Checker as Type Checker
    participant Results as Result Handler

    Caller->>Annotation: Call with function/value
    Annotation->>Checker: Check if value is pointer/interface or convertible
    Checker-->>Annotation: Return conversion status or error
    Annotation->>Results: Update return values accordingly
    Results-->>Caller: Provide converted result / error message
Loading

Poem

I'm a rabbit, hopping through code delight,
Where annotations transform with precision and might.
Interfaces and types dance in a clever array,
Tests and comments lead my merry way.
Carrots of logic fuel each new bright day!


📜 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 8610112 and 7e64651.

📒 Files selected for processing (2)
  • annotated.go (6 hunks)
  • annotated_test.go (7 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
annotated.go

1153-1153: File is not gofumpt-ed

(gofumpt)


1158-1158: File is not gofumpt-ed

(gofumpt)


1167-1167: File is not gofumpt-ed

(gofumpt)

annotated_test.go

1875-1875: File is not gofumpt-ed

(gofumpt)

🔇 Additional comments (10)
annotated.go (5)

1129-1129: Good update to the documentation to match the enhanced functionality

The comment now correctly reflects that fx.As() is used to provide a constructor's return type as another type, not limited to interfaces. This aligns with the expanded functionality.


1149-1169: Well-documented examples for the new functionality

The added examples clearly demonstrate how to use fx.As() with function types and convertible types. The examples follow good Go documentation practices and will help users understand the new capabilities.

🧰 Tools
🪛 golangci-lint (1.62.2)

1153-1153: File is not gofumpt-ed

(gofumpt)


1158-1158: File is not gofumpt-ed

(gofumpt)


1167-1167: File is not gofumpt-ed

(gofumpt)


1237-1239: Improved error message clarity

The error message now correctly reflects that the argument must be a pointer to an interface or convertible type, making it more helpful and accurate.


1291-1297: Good implementation of separate checks for interfaces and convertible types

The implementation now correctly handles both interface implementations and convertible types with separate, clear error messages for each case. This follows the previous reviewer's suggestion and improves code clarity.


1330-1335: Improved control flow for result handling

The code now correctly handles both interfaces and convertible types when setting results. The implementation first checks if the field is an interface, and if not, handles the conversion appropriately. The CanConvert check is a good defensive measure.

annotated_test.go (5)

447-450: Well-defined test types for new functionality

These type definitions provide a good foundation for testing the function type conversion features. They're simple and clearly demonstrate the capability being tested.


486-521: Comprehensive test cases for the new functionality

These test cases cover the key scenarios for the new convertible types support:

  1. Function type conversion
  2. Anonymous function conversion
  3. String to custom string type conversion

The tests are well-structured and verify the correct behavior of the enhanced fx.As() function.


879-890: Good test helper types and functions

These test types and helper functions set up the necessary infrastructure to test both success and failure cases for the enhanced functionality.


904-914: Important failure test cases

These test cases ensure proper error handling when types cannot be converted. Testing both incompatible function types and primitive type conversions is a good approach to validate the error handling logic.


959-959: Updated error message in test

The error message expectation has been updated to match the improved error message in the implementation, ensuring the tests remain in sync with the code.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

@pelmennoteam
Copy link
Author

Thanks for the PR! I have a couple comments on the implementation.

At a high level, I can't think of any particular reason why this shouldn't be allowed, but can you maybe provide some insight into why this is desired over, say, just providing a struct with a call-able method defined on it and using fx.As(new(someInterface))? Is it just cleaner in some scenarios?

gRPC-server implementation:

// interfaces/handlers/grpc/server.go

type Handler[R, V] func(ctx context.Context, request *R) (*V, error) 

type Server struct {
  proto.UnimplementedServer

  listHandler Handler[proto.Request, proto.Response]
}

func (s *Server) List(ctx context.Context, request *proto.Request) (*proto.Response, error) {
  return s.listHandler(ctx, request)
}

func ServerRegistrar(listHandler Handler[proto.Request, proto.Response]) *Server {
  return &Server{listHandler: listHandler}
}

list handler:

// usecases/grpc/list/handler.go

func Handler(deps...) func(ctx context.Context, request *proto.Request) (*proto.Response, error) {
  return func(ctx context.Context, request *proto.Request) (*proto.Response, error) {
    // do some stuff ...
  }
}

I need to do this to register the handler:

// app/main.go

fx.Provide(fx.Annotate(func(deps...) grpc.Handler[proto.Request, proto.Response] {
  return list.Handler(deps...)
}))

What would I like to do:

// app/main.go

fx.Provide(fx.Annotate(list.Handler, fx.As(new(grpc.Handler[proto.Request,proto.Response])))),

@pelmennoteam pelmennoteam requested a review from JacobOaks March 11, 2025 10:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

3 participants