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 4 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!

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ 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 plan to trigger planning for file edits and PR creation.
  • @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
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: 0

🧹 Nitpick comments (1)
annotated_test.go (1)

1875-1877: Minor formatting issue

There's a formatting issue in the test file. The indentation for this interface doesn't match the Go standard formatting.

func assertApp(
	t *testing.T,
	app interface {
-	Start(context.Context) error
-	Stop(context.Context) error
-	},
+		Start(context.Context) error
+		Stop(context.Context) error
+	},
	started *bool,
	stopped *bool,
	invoked *bool,
) {
🧰 Tools
🪛 golangci-lint (1.64.8)

1875-1875: File is not properly formatted

(gofumpt)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e64651 and a898732.

📒 Files selected for processing (2)
  • annotated.go (6 hunks)
  • annotated_test.go (7 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
annotated_test.go (2)
provide.go (1)
  • Provide (64-69)
annotated.go (2)
  • Annotate (1933-1945)
  • As (1282-1284)
🪛 golangci-lint (1.64.8)
annotated.go

1241-1241: File is not properly formatted

(gofumpt)


1255-1255: File is not properly formatted

(gofumpt)

annotated_test.go

1875-1875: File is not properly formatted

(gofumpt)

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

1217-1258: Well-documented enhancement to support convertible types

The documentation has been properly updated to include examples for function values and custom convertible types. This clearly explains the new capability of the As annotation to handle not just interfaces but also convertible types, making the API more flexible.

🧰 Tools
🪛 golangci-lint (1.64.8)

1241-1241: File is not properly formatted

(gofumpt)


1255-1255: File is not properly formatted

(gofumpt)


1325-1326: Clear error message improvement

Updated error message to indicate that the argument must be a pointer to an interface or convertible type, which properly explains the expected input format for the enhanced functionality.


1379-1385: Good separation of error checking logic

You've split the condition to separately check for interface implementation and type conversion, which provides more specific error messages. This makes debugging easier for consumers of the API.


1418-1423: Implemented proper conversion handling

The implementation correctly handles both interface assignment and type conversion based on the kind of the target type. The additional check for CanConvert before attempting conversion is a good defensive programming practice to avoid potential panics.

annotated_test.go (6)

447-450: Good addition of test types

These new type definitions are well-structured for testing the enhanced functionality of the fx.As() annotation with convertible types. The function types (myProvideFunc and myInvokeFunc) along with the string type will allow comprehensive testing of the conversion capabilities.


486-497: Comprehensive test for function type conversion

This test case properly validates that a function type can be converted to another compatible function type through the fx.As() annotation. This confirms the core enhancement being made in this PR.


499-521: Good coverage with additional conversion tests

These test cases cover both anonymous function values and primitive type conversions, providing good test coverage for the convertible types enhancement. The anonymous function test is particularly valuable since it represents a common use case.


887-890: Useful negative test types

The addition of myIntType provides a foundation for testing invalid type conversions, which helps ensure proper error handling in the implementation.


904-914: Strong negative testing

These test cases verify that appropriate errors are generated when incompatible types are provided to fx.As(). This is essential for ensuring a robust implementation that fails gracefully when misused.


959-959: Updated error message for clarity

The error message now properly describes that the argument must be a pointer to an interface or convertible type, making it consistent with the implementation changes.

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