Skip to content

[baseserver] Allow zero port to automatically assign port #9396

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 1 commit into from
Apr 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions components/common-go/baseserver/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func WithHostname(hostname string) Option {
func WithHTTPPort(port int) Option {
return func(cfg *config) error {
if port < 0 {
return fmt.Errorf("http port must be greater than 0, got: %d", port)
return fmt.Errorf("http must not be negative, got: %d", port)
}

cfg.httpPort = port
Expand All @@ -62,7 +62,7 @@ func WithHTTPPort(port int) Option {
func WithGRPCPort(port int) Option {
return func(cfg *config) error {
if port < 0 {
return fmt.Errorf("grpc port must be greater than 0, got: %d", port)
return fmt.Errorf("grpc port must not be negative, got: %d", port)
}

cfg.grpcPort = port
Expand Down
26 changes: 20 additions & 6 deletions components/common-go/baseserver/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,28 @@ func TestOptions(t *testing.T) {
}, cfg)
}

func TestWithTTPPort_ErrorsWithNegativePort(t *testing.T) {
_, err := evaluateOptions(defaultConfig(), WithHTTPPort(-1))
require.Error(t, err)
func TestWithTTPPort(t *testing.T) {
t.Run("negative", func(t *testing.T) {
_, err := evaluateOptions(defaultConfig(), WithHTTPPort(-1))
require.Error(t, err)
})

t.Run("zero", func(t *testing.T) {
_, err := evaluateOptions(defaultConfig(), WithHTTPPort(0))
require.NoError(t, err)
})
}

func TestWithGRPCPort_ErrorsWithNegativePort(t *testing.T) {
_, err := evaluateOptions(defaultConfig(), WithGRPCPort(-1))
require.Error(t, err)
func TestWithGRPCPort(t *testing.T) {
t.Run("negative", func(t *testing.T) {
_, err := evaluateOptions(defaultConfig(), WithGRPCPort(-1))
require.Error(t, err)
})

t.Run("zero", func(t *testing.T) {
_, err := evaluateOptions(defaultConfig(), WithGRPCPort(0))
require.NoError(t, err)
})
}

func TestLogger_ErrorsWithNilLogger(t *testing.T) {
Expand Down
17 changes: 14 additions & 3 deletions components/common-go/baseserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,14 +133,25 @@ func (s *Server) Logger() *logrus.Entry {
return s.cfg.logger
}

// HTTPAddress returns address of the HTTP Server
// HTTPAddress() is only available once the server has been started.
func (s *Server) HTTPAddress() string {
if s.httpListener == nil {
return ""
}
protocol := "http"
return fmt.Sprintf("%s://%s:%d", protocol, s.cfg.hostname, s.cfg.httpPort)
addr := s.httpListener.Addr().(*net.TCPAddr)
return fmt.Sprintf("%s://%s:%d", protocol, addr.IP, addr.Port)
}

// GRPCAddress returns address of the gRPC Server
// GRPCAddress() is only available once the server has been started.
func (s *Server) GRPCAddress() string {
protocol := "http"
return fmt.Sprintf("%s://%s:%d", protocol, s.cfg.hostname, s.cfg.grpcPort)
if s.grpcListener == nil {
return ""
}
addr := s.grpcListener.Addr().(*net.TCPAddr)
return fmt.Sprintf("%s:%d", addr.IP, addr.Port)
}

func (s *Server) HTTPMux() *http.ServeMux {
Expand Down
8 changes: 5 additions & 3 deletions components/common-go/baseserver/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@ import (

func TestServer_StartStop(t *testing.T) {
// We don't use the helper NewForTests, because we want to control stopping ourselves.
srv, err := baseserver.New("server_test")
srv, err := baseserver.New("server_test", baseserver.WithHTTPPort(8765), baseserver.WithGRPCPort(8766))
require.NoError(t, err)

go func() {
require.NoError(t, srv.ListenAndServe())
}()

baseserver.WaitForServerToBeReachable(t, srv, 3*time.Second)
require.Equal(t, "http://:::8765", srv.HTTPAddress())
require.Equal(t, ":::8766", srv.GRPCAddress())
require.NoError(t, srv.Close())
}

Expand All @@ -36,8 +38,8 @@ func TestServer_ServesReady(t *testing.T) {

baseserver.WaitForServerToBeReachable(t, srv, 3*time.Second)

readyUR := fmt.Sprintf("%s/ready", srv.HTTPAddress())
resp, err := http.Get(readyUR)
readyURL := fmt.Sprintf("%s/ready", srv.HTTPAddress())
resp, err := http.Get(readyURL)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
}
Expand Down
6 changes: 4 additions & 2 deletions components/common-go/baseserver/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ func NewForTests(t *testing.T, opts ...Option) *Server {
t.Helper()

defaultTestOpts := []Option{
WithGRPCPort(0),
WithHTTPPort(0),
WithCloseTimeout(1 * time.Second),
}

Expand All @@ -44,13 +46,13 @@ func WaitForServerToBeReachable(t *testing.T, srv *Server, timeout time.Duration
Timeout: tick,
}

healthURL := fmt.Sprintf("%s/ready", srv.HTTPAddress())

for {
select {
case <-ctx.Done():
require.Failf(t, "server did not become reachable in %s", timeout.String())
case <-ticker.C:
// We retrieve the URL on each tick, because the HTTPAddress is only available once the server is listening.
healthURL := fmt.Sprintf("%s/ready", srv.HTTPAddress())
_, err := client.Get(healthURL)
if err != nil {
continue
Expand Down