Skip to content

add grpc-gateway #579

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

Merged
merged 6 commits into from
Mar 11, 2025
Merged

add grpc-gateway #579

merged 6 commits into from
Mar 11, 2025

Conversation

insipx
Copy link
Contributor

@insipx insipx commented Mar 3, 2025

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced support for an additional HTTP endpoint, allowing the server to handle HTTP requests alongside gRPC.
    • Added configuration options and startup flags to specify a dedicated HTTP port.
    • Integrated HTTP-based gateways for API services, enhancing overall API accessibility.
  • Tests

    • Updated test configurations to validate the new HTTP port functionality and registration.

verified with curl (the request parameters are meaningless, but we get back a response)

gateway_curl

Copy link
Contributor

coderabbitai bot commented Mar 3, 2025

Walkthrough

This pull request introduces support for an additional HTTP listener alongside the existing gRPC listener in the API server. The constructor for the server now accepts new parameters for the HTTP address, and new methods such as DialGRPC and HttpAddr are added. Enhanced error handling and proper shutdown logic for the HTTP listener are included. A new HTTP server implementation with CORS support and preflight handling is introduced, and various functions and tests are updated to accommodate the new HTTP configuration.

Changes

File(s) Summary
pkg/api/server.go, pkg/api/http_server.go, pkg/testutils/api/api.go Added HTTP listener support to the API server. Introduced new methods (DialGRPC, HttpAddr, startHTTP), a new type (HttpRegistrationFunc), and helper functions for CORS handling and HTTP preflight. Updated the API server initialization to accept an HTTP listen address and to register HTTP endpoints via httpRegistrationFunc.
cmd/replication/main.go, pkg/server/server.go, pkg/server/server_test.go Updated function signatures to include an additional HTTP address/port parameter during server initialization and tests. Introduced httpRegistrationFunc in the replication server to register HTTP handlers for various APIs, ensuring consistency in handling both gRPC and HTTP requests.
dev/run-2, pkg/config/options.go Modified command-line flags in the run script to include a new HTTP port flag and adjusted the configuration (ApiOptions) to add a new HTTPPort field, enabling the application to listen for HTTP requests on the designated port.

Possibly related PRs

Suggested reviewers

  • fbac
  • richardhuaaa

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

Error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)
Failed executing command with error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)

✨ 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.

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

🧹 Nitpick comments (2)
pkg/server/http_server.go (2)

37-90: Avoid unreachable return statement after log.Fatal.
log.Fatal terminates the program, so the subsequent return nil, err will never be reached:

-if err != nil {
-	log.Fatal("dialing GRPC from HTTP Gateway")
-	return nil, err
-}
+if err != nil {
+	log.Error("dialing GRPC from HTTP Gateway", zap.Error(err))
+	return nil, err
+}

230-239: Allowing all origins could introduce security risks.
Consider configuring a specific origin or domain in production to avoid unintended exposure.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b1a1a6d and 10ed41d.

⛔ Files ignored due to path filters (2)
  • go.sum is excluded by !**/*.sum
  • pkg/proto/openapi/openapi.go is excluded by !pkg/proto/**
📒 Files selected for processing (3)
  • go.mod (1 hunks)
  • pkg/api/server.go (2 hunks)
  • pkg/server/http_server.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test (Node)
  • GitHub Check: Lint-Go
  • GitHub Check: Build pre-baked anvil-xmtpd
🔇 Additional comments (5)
go.mod (1)

110-110:

✅ Verification successful

Verify newly introduced indirect dependencies.
Please ensure these pinned versions are secure and free of known vulnerabilities.

Use the following script to check for any GitHub-published advisories:

Also applies to: 114-114


🏁 Script executed:

#!/bin/bash
# Description: Query GitHub Security Advisories for newly added dependencies.

for pkg in "github.com/swaggest/swgui" "github.com/vearutop/statigz"; do
  echo "Checking advisories for $pkg..."
  gh api graphql -f query="query {
    securityVulnerabilities(first: 5, ecosystem: GO, package: \"$(basename "$pkg")\") {
      nodes {
        advisory {
          summary
          severity
          publishedAt
        }
        vulnerableVersionRange
        firstPatchedVersion {
          identifier
        }
      }
    }
  }"
done

Length of output: 1196


No Known Vulnerabilities Found for Pinned Dependencies

The security audit via GitHub advisories indicates that the pinned version of github.com/swaggest/swgui v1.8.2 (as well as github.com/vearutop/statigz if applicable) currently has no known vulnerabilities.

  • File: go.mod, Line 110
    Pinned dependency: github.com/swaggest/swgui v1.8.2 // indirect

  • Also applies to: Line 114
    (If applicable, ensure similar checks for additional indirect dependencies.)

Please continue to monitor these dependencies for any future advisory updates.

pkg/api/server.go (1)

5-5: Import of "fmt" looks fine.
This addition for string formatting is appropriate.

pkg/server/http_server.go (3)

1-23: Package name and imports look appropriate.
No immediate concerns found here.


25-35: Struct definition is clear and well-structured.
No issues identified.


208-229: CORS preflight logic looks consistent.
The specified headers and methods cover common use cases.

@insipx insipx marked this pull request as ready for review March 7, 2025 19:13
@insipx insipx requested a review from a team as a code owner March 7, 2025 19:13
@insipx insipx force-pushed the insipx/grpc-gateway branch from 9f7c614 to 1177c31 Compare March 7, 2025 19:16
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 5

🧹 Nitpick comments (1)
pkg/api/http_server.go (1)

52-54: Add context to error log message

The error log message lacks context about what operation failed, making debugging difficult.

Add more context to the error log:

- s.log.Error("serving http", zap.Error(err))
+ s.log.Error("error while serving http gateway", zap.Error(err), zap.String("address", s.httpListener.Addr().String()))
🛑 Comments failed to post (5)
cmd/replication/main.go (1)

120-120: 💡 Verification agent

🧩 Analysis chain

Fix build error in NewReplicationServer call.

The PR correctly adds the HTTP address parameter to the server initialization, but the build is failing. This suggests there might be a mismatch between the changes in this file and the server constructor implementation.


🏁 Script executed:

#!/bin/bash
# Verify NewReplicationServer function signature
rg -A 5 "func NewReplicationServer\(" pkg/server/

Length of output: 331


Action Required: Fix Build Signature Mismatch in NewReplicationServer Call

  • Issue: The call in cmd/replication/main.go (line 120) is passing an extra parameter generated by

    fmt.Sprintf("0.0.0.0:%d", options.API.HTTPPort),

    which appears to represent the HTTP address. However, the NewReplicationServer function in pkg/server/server.go only accepts the following parameters:

    • ctx context.Context
    • log *zap.Logger
    • options config.ServerOptions
    • nodeRegistry registry.NodeRegistry
    • writerDB *sql.DB

    This mismatch is triggering the build error.

  • Recommendation:
    Please update the call to NewReplicationServer in cmd/replication/main.go to match the constructor's signature. This may involve:

    • Removing the HTTP address parameter if it is not needed; or
    • Modifying the constructor in pkg/server/server.go to accept the new parameter if the HTTP address is required for proper initialization.
pkg/api/http_server.go (2)

46-55: ⚠️ Potential issue

Potential nil pointer dereference risk

The code checks for a nil httpListener only after it has already been used to log the address in line 47. If httpListener is nil, this will cause a panic.

Move the nil check before using the listener:

tracing.GoPanicWrap(s.ctx, &s.wg, "http", func(ctx context.Context) {
-	s.log.Info("serving http", zap.String("address", s.httpListener.Addr().String()))
	if s.httpListener == nil {
		s.log.Fatal("no http listener")
	}
+	s.log.Info("serving http", zap.String("address", s.httpListener.Addr().String()))
	err = gwServer.Serve(s.httpListener)
	if err != nil && err != http.ErrServerClosed && !isErrUseOfClosedConnection(err) {
		s.log.Error("serving http", zap.Error(err))
	}
})
📝 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.

	tracing.GoPanicWrap(s.ctx, &s.wg, "http", func(ctx context.Context) {
		if s.httpListener == nil {
			s.log.Fatal("no http listener")
		}
		s.log.Info("serving http", zap.String("address", s.httpListener.Addr().String()))
		err = gwServer.Serve(s.httpListener)
		if err != nil && err != http.ErrServerClosed && !isErrUseOfClosedConnection(err) {
			s.log.Error("serving http", zap.Error(err))
		}
	})

20-27: ⚠️ Potential issue

Fix unreachable code issue after log.Fatal

The log.Fatal call at line 25 terminates the program immediately, making the return err statement unreachable. This needs to be addressed.

Consider one of these options:

- log.Fatal("dialing GRPC from HTTP Gateway")
- return err
+ log.Error("dialing GRPC from HTTP Gateway", zap.Error(err))
+ return err

Or if you want to keep the Fatal:

- log.Fatal("dialing GRPC from HTTP Gateway")
- return err
+ log.Fatal("dialing GRPC from HTTP Gateway", zap.Error(err))
📝 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.

func (s *ApiServer) startHTTP(ctx context.Context, log *zap.Logger, registrationFunc HttpRegistrationFunc) error {
	var err error

	client, err := s.DialGRPC(ctx)
	if err != nil {
		log.Error("dialing GRPC from HTTP Gateway", zap.Error(err))
		return err
	}
	// ... remaining code ...
}
pkg/testutils/api/api.go (1)

165-186: 🛠️ Refactor suggestion

Initialize the error variable before use

The function uses the err variable without first initializing it in the function scope. It's reusing a variable from a wider scope, which can lead to bugs if the variable has unexpected values.

Explicitly declare and initialize the error variable:

httpRegistrationFunc := func(gwmux *runtime.ServeMux, conn *grpc.ClientConn) error {
+	var err error
	err = metadata_api.RegisterMetadataApiHandler(ctx, gwmux, conn)
	log.Info("Metadata http gateway enabled")

	if err != nil {
		return err
	}

	err = message_api.RegisterReplicationApiHandler(ctx, gwmux, conn)
	log.Info("Replication http gateway enabled")
	if err != nil {
		return err
	}

	err = payer_api.RegisterPayerApiHandler(ctx, gwmux, conn)
	log.Info("Payer http gateway enabled")
	if err != nil {
		return err
	}

	return nil
}
📝 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.

	httpRegistrationFunc := func(gwmux *runtime.ServeMux, conn *grpc.ClientConn) error {
		var err error
		err = metadata_api.RegisterMetadataApiHandler(ctx, gwmux, conn)
		log.Info("Metadata http gateway enabled")

		if err != nil {
			return err
		}

		err = message_api.RegisterReplicationApiHandler(ctx, gwmux, conn)
		log.Info("Replication http gateway enabled")
		if err != nil {
			return err
		}

		err = payer_api.RegisterPayerApiHandler(ctx, gwmux, conn)
		log.Info("Payer http gateway enabled")
		if err != nil {
			return err
		}

		return nil
	}
pkg/server/server.go (1)

275-300: ⚠️ Potential issue

Fix undefined 'log' variable in httpRegistrationFunc

Static analysis and pipeline failures show that the log variable is undefined within the httpRegistrationFunc scope. This will cause compilation errors.

Use the properly scoped logger from the function parameters:

httpRegistrationFunc := func(gwmux *runtime.ServeMux, conn *grpc.ClientConn) error {
+	var err error
	if options.Replication.Enable {
		err = metadata_api.RegisterMetadataApiHandler(ctx, gwmux, conn)
-		log.Info("Metadata http gateway enabled")
+		log.Info("Metadata http gateway enabled")

		if err != nil {
			return err
		}

		err = message_api.RegisterReplicationApiHandler(ctx, gwmux, conn)
-		log.Info("Replication http gateway enabled")
+		log.Info("Replication http gateway enabled")
		if err != nil {
			return err
		}
	}

	if options.Payer.Enable {
		err = payer_api.RegisterPayerApiHandler(ctx, gwmux, conn)
-		log.Info("Payer http gateway enabled")
+		log.Info("Payer http gateway enabled")
		if err != nil {
			return err
		}
	}

	return nil
}

Note: While log is already passed into the outer function and might be accessible here, it's better practice to explicitly reference it to avoid confusion.

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: Lint-Go

[failure] 283-283:
undefined: log


[failure] 290-290:
undefined: log


[failure] 298-298:
undefined: log (typecheck)


[failure] 283-283:
undefined: log


[failure] 290-290:
undefined: log


[failure] 298-298:
undefined: log) (typecheck)


[failure] 283-283:
undefined: log

🪛 GitHub Check: Test (Node)

[failure] 283-283:
undefined: log


[failure] 290-290:
undefined: log


[failure] 298-298:
undefined: log

🪛 GitHub Actions: Test

[error] 283-283: undefined: log

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

♻️ Duplicate comments (1)
pkg/api/server.go (1)

142-145: ⚠️ Potential issue

Fix incorrect gRPC client creation function.

The grpc.NewClient function doesn't exist in the standard gRPC library. This will cause compilation errors.

-func (s *ApiServer) DialGRPC(ctx context.Context) (*grpc.ClientConn, error) {
-	dialAddr := fmt.Sprintf("passthrough://localhost/%s", s.grpcListener.Addr().String())
-	return grpc.NewClient(dialAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
-}
+func (s *ApiServer) DialGRPC(ctx context.Context) (*grpc.ClientConn, error) {
+	dialAddr := fmt.Sprintf("passthrough://localhost/%s", s.grpcListener.Addr().String())
+	return grpc.DialContext(ctx, dialAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+}
🧹 Nitpick comments (1)
pkg/api/server.go (1)

38-40: Remove commented out code.

These commented out fields appear to be leftover from development and should be removed.

-	// gwmux        *runtime.ServeMux
-	// gwServer     *http.Server
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f7c614 and 1177c31.

📒 Files selected for processing (8)
  • cmd/replication/main.go (1 hunks)
  • dev/run-2 (1 hunks)
  • pkg/api/http_server.go (1 hunks)
  • pkg/api/server.go (4 hunks)
  • pkg/config/options.go (1 hunks)
  • pkg/server/server.go (6 hunks)
  • pkg/server/server_test.go (6 hunks)
  • pkg/testutils/api/api.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • pkg/config/options.go
  • dev/run-2
  • cmd/replication/main.go
  • pkg/testutils/api/api.go
🧰 Additional context used
🪛 GitHub Check: Test (Node)
pkg/server/server.go

[failure] 283-283:
undefined: log


[failure] 290-290:
undefined: log


[failure] 298-298:
undefined: log

🪛 GitHub Check: Lint-Go
pkg/server/server.go

[failure] 283-283:
undefined: log


[failure] 290-290:
undefined: log


[failure] 298-298:
undefined: log (typecheck)


[failure] 283-283:
undefined: log


[failure] 290-290:
undefined: log


[failure] 298-298:
undefined: log) (typecheck)


[failure] 283-283:
undefined: log

🪛 GitHub Actions: Test
pkg/server/server.go

[error] 283-283: undefined: log

🔇 Additional comments (25)
pkg/server/server_test.go (7)

46-46: New parameter correctly added.

The addition of the httpPort parameter enhances the test server to support HTTP alongside gRPC. This aligns well with the PR objectives of adding gRPC-gateway functionality.


65-67: Config structure updated correctly.

The API configuration now includes both the gRPC port and HTTP port, which is necessary for the dual-protocol support introduced in this PR.


74-74: Server creation updated with HTTP address.

The NewReplicationServer call has been properly updated to include the HTTP address parameter.


95-98: HTTP port allocation added correctly.

The test now allocates separate ports for both gRPC and HTTP servers, ensuring they don't conflict.


139-140: Test server creation updated consistently.

The test now correctly initializes both servers with their respective gRPC and HTTP ports.


234-236: HTTP port allocation added to second test.

Good consistency - the HTTP port allocation is added to all relevant test functions.


258-258: Test server creation updated consistently.

The update to pass the HTTP port has been consistently applied to all test server instances.

pkg/api/http_server.go (7)

18-18: Good design for HTTP registration.

The HttpRegistrationFunc type is a well-designed function signature that allows for flexible registration of gRPC services with the HTTP gateway.


27-31: Issue with error handling in case of dialing failure.

When DialGRPC fails, you're using log.Fatal which will terminate the program, but also returning the error. The return value becomes redundant since the program would exit.

Consider either:

  1. Use log.Error and return the error, allowing the caller to handle it
  2. Use log.Fatal and don't return (though this is generally not recommended)
-	if err != nil {
-		log.Fatal("dialing GRPC from HTTP Gateway")
-		return err
-	}
+	if err != nil {
+		log.Error("failed dialing GRPC from HTTP Gateway", zap.Error(err))
+		return err
+	}

35-40: Good configuration of HTTP gateway.

The setup includes proper marshaller options, error handling, and health endpoint integration.


45-48: Good server setup with CORS support.

The HTTP server is properly configured with the CORS middleware.


56-58: Comprehensive error handling.

The error handling is thorough, distinguishing between different types of errors (server closed, connection closed, etc.).


64-84: Well-implemented CORS preflight handler.

The preflight handler correctly handles the required headers for a wide range of clients, improving cross-origin compatibility.


86-95: Good CORS middleware implementation.

The middleware properly handles both preflight OPTIONS requests and normal requests by setting the right headers.

pkg/api/server.go (7)

36-36: New field added to support HTTP listener.

This is a good addition to the ApiServer struct to maintain the HTTP listener alongside the gRPC listener.


48-51: Constructor properly updated for HTTP support.

The NewAPIServer function has been correctly updated to accept the new HTTP parameters.


59-62: Good error handling for HTTP listener.

The error handling for the HTTP listener creation follows the same pattern as for the gRPC listener.


70-70: HTTP listener added to ApiServer struct.

The HTTP listener is properly initialized in the struct.


137-137: HTTP server started.

The HTTP server is properly started using the startHTTP method.


151-153: Getter method for HTTP address added.

Adding the HttpAddr method is a good addition that follows the pattern of the existing Addr method.


188-194: HTTP listener cleanup added.

The Close method has been properly updated to clean up the HTTP listener, following the same pattern as the gRPC listener cleanup.

pkg/server/server.go (4)

65-65: Parameter added for HTTP address.

The NewReplicationServer function signature has been updated to include the HTTP address parameter.


143-143: HTTP address passed to API server.

The httpListenAddress is correctly passed to the startAPIServer function.


178-178: API server function updated for HTTP support.

The startAPIServer function signature has been updated to accept the HTTP address.


318-321: API server creation updated for HTTP support.

The NewAPIServer call has been properly updated to include the HTTP address and registration function.

@insipx insipx force-pushed the insipx/grpc-gateway branch from 71f404d to 946d355 Compare March 7, 2025 19:22
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

♻️ Duplicate comments (1)
pkg/api/server.go (1)

144-147: ⚠️ Potential issue

Incorrect usage of grpc.NewClient.

In standard gRPC, there is no NewClient function. You should use grpc.DialContext or grpc.Dial instead:

func (s *ApiServer) DialGRPC(ctx context.Context) (*grpc.ClientConn, error) {
	dialAddr := fmt.Sprintf("passthrough://localhost/%s", s.grpcListener.Addr().String())
-	return grpc.NewClient(dialAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+	return grpc.DialContext(ctx, dialAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
🧹 Nitpick comments (2)
pkg/api/server.go (2)

36-42: Uncomment or remove commented code.

There are commented lines about gwmux and gwServer that appear to be related to the HTTP server implementation. If these are meant to be used, they should be uncommented. Otherwise, consider removing them to avoid confusion.


190-196: Proper HTTP listener cleanup.

The cleanup of the HTTP listener is properly implemented, ensuring resources are released when the server is closed.

Consider handling any potential errors if a HTTP server component exists similar to how the gRPC server's gracefulShutdown is implemented.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 71f404d and 946d355.

📒 Files selected for processing (3)
  • pkg/api/http_server.go (1 hunks)
  • pkg/api/server.go (4 hunks)
  • pkg/testutils/api/api.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/testutils/api/api.go
  • pkg/api/http_server.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build pre-baked anvil-xmtpd
🔇 Additional comments (4)
pkg/api/server.go (4)

59-62: Good error handling for HTTP listener.

The error handling for the HTTP listener creation is properly implemented, ensuring the server won't start if the HTTP listener can't be created.


153-155: Good implementation of HttpAddr method.

This method provides a clean way to access the HTTP listener address, which is a good practice for testing and client configuration.


48-52:

✅ Verification successful

Missing type definition for HttpRegistrationFunc.

The httpRegistrationFunc parameter of type HttpRegistrationFunc is used, but the type definition is not visible in this file. Ensure this type is properly defined and imported, or add the definition alongside the existing RegistrationFunc type.


🏁 Script executed:

#!/bin/bash
# Check if HttpRegistrationFunc is defined somewhere in the codebase
rg "type HttpRegistrationFunc" --type go

Length of output: 150


Verification Update: HttpRegistrationFunc Type Found

The HttpRegistrationFunc type is defined in the codebase (see pkg/api/http_server.go):

type HttpRegistrationFunc func(gwmux *runtime.ServeMux, conn *grpc.ClientConn) error

Please ensure that pkg/api/server.go properly imports or references the package containing this type so that it is visible in the file. If the import is already present and correct, this review concern can be considered resolved.


137-139:

❌ Incorrect review comment

Missing startHTTP implementation.

The startHTTP method is called but its implementation is not visible in this file. Make sure this method is properly implemented and handles the registration of HTTP handlers.


🏁 Script executed:

#!/bin/bash
# Check for the startHTTP implementation in the codebase
rg "func \(\*ApiServer\) startHTTP" --type go

Length of output: 47


🏁 Script executed:

#!/bin/bash
# Re-run search for startHTTP implementation with a flexible regex that accounts for a receiver variable name
rg "func \([^)]+\*ApiServer\)[[:space:]]+startHTTP" --type go

Length of output: 117


Update: startHTTP Implementation Located in pkg/api/http_server.go

Upon verifying the codebase, the startHTTP method is implemented in pkg/api/http_server.go (e.g., see the function starting at the beginning of the file). The call in pkg/api/server.go (lines 137–139) correctly delegates to this implementation. Please disregard the comment regarding the missing implementation or update documentation if a cross-reference to its location would be beneficial.

Likely an incorrect or invalid review comment.

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

♻️ Duplicate comments (1)
pkg/api/server.go (1)

142-145: ⚠️ Potential issue

Incorrect usage of grpc.NewClient.

In standard gRPC, there is no NewClient function. This will cause compiler errors.

Use grpc.DialContext instead:

-func (s *ApiServer) DialGRPC(ctx context.Context) (*grpc.ClientConn, error) {
-	dialAddr := fmt.Sprintf("passthrough://localhost/%s", s.grpcListener.Addr().String())
-	return grpc.NewClient(dialAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
-}
+func (s *ApiServer) DialGRPC(ctx context.Context) (*grpc.ClientConn, error) {
+	dialAddr := fmt.Sprintf("passthrough://localhost/%s", s.grpcListener.Addr().String())
+	return grpc.DialContext(ctx, dialAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dd97a99 and 45d9cef.

📒 Files selected for processing (1)
  • pkg/api/server.go (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd)
  • GitHub Check: Test (Node)
  • GitHub Check: Build pre-baked anvil-xmtpd
🔇 Additional comments (7)
pkg/api/server.go (7)

3-25: The fmt package has been added for string formatting.

The newly added fmt package is used in the DialGRPC method. This is appropriate for the string formatting needed there.


33-40: Good addition of httpListener field to ApiServer struct.

The httpListener field is correctly added to the ApiServer struct to support the new HTTP functionality alongside the existing gRPC functionality.


42-51: Parameters added for HTTP support in constructor.

The constructor now appropriately accepts additional parameters for HTTP support:

  • httpListenAddress for specifying where the HTTP server should listen
  • httpRegistrationFunc for registering HTTP handlers

However, I don't see a definition for the HttpRegistrationFunc type in the provided code.

Is HttpRegistrationFunc defined elsewhere in the codebase? Please ensure it's properly defined before using it.


52-60: Improved error handling for listener creation.

The error handling has been improved by checking and returning errors immediately after creating both the gRPC and HTTP listeners. This is a good practice.


62-71: ApiServer initialization updated with httpListener.

The ApiServer struct initialization has been correctly updated to include the new httpListener field.


151-153: Good addition of HttpAddr method.

The HttpAddr method is correctly implemented to return the address of the HTTP listener, mirroring the existing Addr method for the gRPC listener.


188-194: Proper cleanup of HTTP listener in Close method.

The Close method has been properly updated to clean up the HTTP listener when the server is shut down. The error handling is also appropriate.

@insipx insipx merged commit 20ac657 into main Mar 11, 2025
7 of 8 checks passed
@insipx insipx deleted the insipx/grpc-gateway branch March 11, 2025 15:05
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