From ad20a5f55a1913646584db9e02eacad3d43e56ae Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sun, 19 Nov 2023 15:42:32 +0100 Subject: [PATCH 1/3] Add If and Exists functions to get rid of most of the getters --- config/utils.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 config/utils.go diff --git a/config/utils.go b/config/utils.go new file mode 100644 index 00000000..01871e6a --- /dev/null +++ b/config/utils.go @@ -0,0 +1,15 @@ +package config + +// If returns truthy if predicate is true, falsy otherwise. +func If[T any](predicate bool, truthy, falsy T) T { + if predicate { + return truthy + } + return falsy +} + +// Exists returns true if key exists in map_, false otherwise. +func Exists[T comparable, V any](map_ map[T]V, key T) bool { + _, ok := map_[key] + return ok +} From 4aa91e23b61140037d6ba234a4cd96614814c13d Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sun, 19 Nov 2023 15:43:43 +0100 Subject: [PATCH 2/3] Refactor and replace getters in favor of If and Exists --- cmd/run.go | 169 +++++++++++++++++++++++++++++++---------- config/constants.go | 6 ++ config/getters.go | 178 +++----------------------------------------- network/client.go | 10 +++ network/proxy.go | 12 ++- 5 files changed, 164 insertions(+), 211 deletions(-) diff --git a/cmd/run.go b/cmd/run.go index 7a8c7c61..2edef974 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -210,20 +210,33 @@ var runCmd = &cobra.Command{ // Create and initialize loggers from the config. for name, cfg := range conf.Global.Loggers { loggers[name] = logging.NewLogger(runCtx, logging.LoggerConfig{ - Output: cfg.GetOutput(), - Level: cfg.GetLevel(), - TimeFormat: cfg.GetTimeFormat(), - ConsoleTimeFormat: cfg.GetConsoleTimeFormat(), - NoColor: cfg.NoColor, - FileName: cfg.FileName, - MaxSize: cfg.MaxSize, - MaxBackups: cfg.MaxBackups, - MaxAge: cfg.MaxAge, - Compress: cfg.Compress, - LocalTime: cfg.LocalTime, - SyslogPriority: cfg.GetSyslogPriority(), - RSyslogNetwork: cfg.RSyslogNetwork, - RSyslogAddress: cfg.RSyslogAddress, + Output: cfg.GetOutput(), + Level: config.If[zerolog.Level]( + config.Exists[string, zerolog.Level](config.LogLevels, cfg.Level), + config.LogLevels[cfg.Level], + config.LogLevels[config.DefaultLogLevel], + ), + TimeFormat: config.If[string]( + config.Exists[string, string](config.TimeFormats, cfg.TimeFormat), + config.TimeFormats[cfg.TimeFormat], + config.DefaultTimeFormat, + ), + ConsoleTimeFormat: config.If[string]( + config.Exists[string, string]( + config.ConsoleTimeFormats, cfg.ConsoleTimeFormat), + config.ConsoleTimeFormats[cfg.ConsoleTimeFormat], + config.DefaultConsoleTimeFormat, + ), + NoColor: cfg.NoColor, + FileName: cfg.FileName, + MaxSize: cfg.MaxSize, + MaxBackups: cfg.MaxBackups, + MaxAge: cfg.MaxAge, + Compress: cfg.Compress, + LocalTime: cfg.LocalTime, + SyslogPriority: cfg.GetSyslogPriority(), + RSyslogNetwork: cfg.RSyslogNetwork, + RSyslogAddress: cfg.RSyslogAddress, }) } @@ -239,10 +252,26 @@ var runCmd = &cobra.Command{ // The plugins are loaded and hooks registered before the configuration is loaded. pluginRegistry = plugin.NewRegistry( runCtx, - conf.Plugin.GetPluginCompatibilityPolicy(), - conf.Plugin.GetVerificationPolicy(), - conf.Plugin.GetAcceptancePolicy(), - conf.Plugin.GetTerminationPolicy(), + config.If[config.CompatibilityPolicy]( + config.Exists[string, config.CompatibilityPolicy]( + config.CompatibilityPolicies, conf.Plugin.CompatibilityPolicy), + config.CompatibilityPolicies[conf.Plugin.CompatibilityPolicy], + config.DefaultCompatibilityPolicy), + config.If[config.VerificationPolicy]( + config.Exists[string, config.VerificationPolicy]( + config.VerificationPolicies, conf.Plugin.VerificationPolicy), + config.VerificationPolicies[conf.Plugin.VerificationPolicy], + config.DefaultVerificationPolicy), + config.If[config.AcceptancePolicy]( + config.Exists[string, config.AcceptancePolicy]( + config.AcceptancePolicies, conf.Plugin.AcceptancePolicy), + config.AcceptancePolicies[conf.Plugin.AcceptancePolicy], + config.DefaultAcceptancePolicy), + config.If[config.TerminationPolicy]( + config.Exists[string, config.TerminationPolicy]( + config.TerminationPolicies, conf.Plugin.TerminationPolicy), + config.TerminationPolicies[conf.Plugin.TerminationPolicy], + config.DefaultTerminationPolicy), logger, devMode, ) @@ -413,6 +442,12 @@ var runCmd = &cobra.Command{ handler = mergedMetricsHandler(handler) } + readHeaderTimeout := config.If[time.Duration]( + metricsConfig.ReadHeaderTimeout > 0, + metricsConfig.ReadHeaderTimeout, + config.DefaultReadHeaderTimeout, + ) + // Check if the metrics server is already running before registering the handler. if _, err = http.Get(address); err != nil { //nolint:gosec // The timeout handler limits the nested handlers from running for too long. @@ -420,7 +455,7 @@ var runCmd = &cobra.Command{ metricsConfig.Path, http.TimeoutHandler( gziphandler.GzipHandler(handler), - metricsConfig.GetTimeout(), + readHeaderTimeout, "The request timed out while fetching the metrics", ), ) @@ -430,19 +465,24 @@ var runCmd = &cobra.Command{ } // Create a new metrics server. + timeout := config.If[time.Duration]( + metricsConfig.Timeout > 0, + metricsConfig.Timeout, + config.DefaultMetricsServerTimeout, + ) metricsServer = &http.Server{ Addr: metricsConfig.Address, Handler: mux, - ReadHeaderTimeout: metricsConfig.GetReadHeaderTimeout(), - ReadTimeout: metricsConfig.GetTimeout(), - WriteTimeout: metricsConfig.GetTimeout(), - IdleTimeout: metricsConfig.GetTimeout(), + ReadHeaderTimeout: readHeaderTimeout, + ReadTimeout: timeout, + WriteTimeout: timeout, + IdleTimeout: timeout, } logger.Info().Fields(map[string]interface{}{ "address": address, - "timeout": metricsConfig.GetTimeout().String(), - "readHeaderTimeout": metricsConfig.GetReadHeaderTimeout().String(), + "timeout": timeout.String(), + "readHeaderTimeout": readHeaderTimeout.String(), }).Msg("Metrics are exposed") if metricsConfig.CertFile != "" && metricsConfig.KeyFile != "" { @@ -499,11 +539,22 @@ var runCmd = &cobra.Command{ // Create and initialize pools of connections. for name, cfg := range conf.Global.Pools { logger := loggers[name] - pools[name] = pool.NewPool(runCtx, cfg.GetSize()) + // Check if the pool size is greater than zero. + currentPoolSize := config.If[int]( + cfg.Size > 0, + // Check if the pool size is greater than the minimum pool size. + config.If[int]( + cfg.Size > config.MinimumPoolSize, + cfg.Size, + config.MinimumPoolSize, + ), + config.DefaultPoolSize, + ) + pools[name] = pool.NewPool(runCtx, currentPoolSize) span.AddEvent("Create pool", trace.WithAttributes( attribute.String("name", name), - attribute.Int("size", cfg.GetSize()), + attribute.Int("size", currentPoolSize), )) // Get client config from the config file. @@ -517,21 +568,49 @@ var runCmd = &cobra.Command{ } // Fill the missing and zero values with the default ones. - clients[name].TCPKeepAlivePeriod = clients[name].GetTCPKeepAlivePeriod() - clients[name].ReceiveDeadline = clients[name].GetReceiveDeadline() - clients[name].ReceiveTimeout = clients[name].GetReceiveTimeout() - clients[name].SendDeadline = clients[name].GetSendDeadline() - clients[name].ReceiveChunkSize = clients[name].GetReceiveChunkSize() - clients[name].DialTimeout = clients[name].GetDialTimeout() + clients[name].TCPKeepAlivePeriod = config.If[time.Duration]( + clients[name].TCPKeepAlivePeriod > 0, + clients[name].TCPKeepAlivePeriod, + config.DefaultTCPKeepAlivePeriod, + ) + clients[name].ReceiveDeadline = config.If[time.Duration]( + clients[name].ReceiveDeadline > 0, + clients[name].ReceiveDeadline, + config.DefaultReceiveDeadline, + ) + clients[name].ReceiveTimeout = config.If[time.Duration]( + clients[name].ReceiveTimeout > 0, + clients[name].ReceiveTimeout, + config.DefaultReceiveTimeout, + ) + clients[name].SendDeadline = config.If[time.Duration]( + clients[name].SendDeadline > 0, + clients[name].SendDeadline, + config.DefaultSendDeadline, + ) + clients[name].ReceiveChunkSize = config.If[int]( + clients[name].ReceiveChunkSize > 0, + clients[name].ReceiveChunkSize, + config.DefaultChunkSize, + ) + clients[name].DialTimeout = config.If[time.Duration]( + clients[name].DialTimeout > 0, + clients[name].DialTimeout, + config.DefaultDialTimeout, + ) // Add clients to the pool. - for i := 0; i < cfg.GetSize(); i++ { + for i := 0; i < currentPoolSize; i++ { clientConfig := clients[name] client := network.NewClient( runCtx, clientConfig, logger, network.NewRetry( clientConfig.Retries, - clientConfig.GetBackoff(), + config.If[time.Duration]( + clientConfig.Backoff > 0, + clientConfig.Backoff, + config.DefaultBackoff, + ), clientConfig.BackoffMultiplier, clientConfig.DisableBackoffCaps, loggers[name], @@ -553,7 +632,7 @@ var runCmd = &cobra.Command{ attribute.String("localAddress", client.LocalAddr()), attribute.String("remoteAddress", client.RemoteAddr()), attribute.Int("retries", clientConfig.Retries), - attribute.String("backoff", clientConfig.GetBackoff().String()), + attribute.String("backoff", client.Retry().Backoff.String()), attribute.Float64("backoffMultiplier", clientConfig.BackoffMultiplier), attribute.Bool("disableBackoffCaps", clientConfig.DisableBackoffCaps), ) @@ -583,7 +662,7 @@ var runCmd = &cobra.Command{ "localAddress": client.LocalAddr(), "remoteAddress": client.RemoteAddr(), "retries": clientConfig.Retries, - "backoff": clientConfig.GetBackoff().String(), + "backoff": client.Retry().Backoff.String(), "backoffMultiplier": clientConfig.BackoffMultiplier, "disableBackoffCaps": clientConfig.DisableBackoffCaps, } @@ -611,7 +690,7 @@ var runCmd = &cobra.Command{ "count": strconv.Itoa(pools[name].Size()), }).Msg("There are clients available in the pool") - if pools[name].Size() != cfg.GetSize() { + if pools[name].Size() != currentPoolSize { logger.Error().Msg( "The pool size is incorrect, either because " + "the clients cannot connect due to no network connectivity " + @@ -626,7 +705,7 @@ var runCmd = &cobra.Command{ _, err = pluginRegistry.Run( pluginTimeoutCtx, - map[string]interface{}{"name": name, "size": cfg.GetSize()}, + map[string]interface{}{"name": name, "size": currentPoolSize}, v1.HookName_HOOK_NAME_ON_NEW_POOL) if err != nil { logger.Error().Err(err).Msg("Failed to run OnNewPool hooks") @@ -642,7 +721,11 @@ var runCmd = &cobra.Command{ logger := loggers[name] clientConfig := clients[name] // Fill the missing and zero value with the default one. - cfg.HealthCheckPeriod = cfg.GetHealthCheckPeriod() + cfg.HealthCheckPeriod = config.If[time.Duration]( + cfg.HealthCheckPeriod > 0, + cfg.HealthCheckPeriod, + config.DefaultHealthCheckPeriod, + ) proxies[name] = network.NewProxy( runCtx, @@ -689,7 +772,11 @@ var runCmd = &cobra.Command{ runCtx, cfg.Network, cfg.Address, - cfg.GetTickInterval(), + config.If[time.Duration]( + cfg.TickInterval > 0, + cfg.TickInterval, + config.DefaultTickInterval, + ), network.Option{ // Can be used to send keepalive messages to the client. EnableTicker: cfg.EnableTicker, diff --git a/config/constants.go b/config/constants.go index 224885b9..817a4043 100644 --- a/config/constants.go +++ b/config/constants.go @@ -145,4 +145,10 @@ const ( DefaultHTTPAPIAddress = "localhost:18080" DefaultGRPCAPINetwork = "tcp" DefaultGRPCAPIAddress = "localhost:19090" + + // Policies + DefaultCompatibilityPolicy = Strict + DefaultVerificationPolicy = PassDown + DefaultAcceptancePolicy = Accept + DefaultTerminationPolicy = Stop ) diff --git a/config/getters.go b/config/getters.go index 29dabd65..593ea599 100644 --- a/config/getters.go +++ b/config/getters.go @@ -9,21 +9,21 @@ import ( ) var ( - verificationPolicies = map[string]VerificationPolicy{ + CompatibilityPolicies = map[string]CompatibilityPolicy{ + "strict": Strict, + "loose": Loose, + } + VerificationPolicies = map[string]VerificationPolicy{ "passdown": PassDown, "ignore": Ignore, "abort": Abort, "remove": Remove, } - compatibilityPolicies = map[string]CompatibilityPolicy{ - "strict": Strict, - "loose": Loose, - } - acceptancePolicies = map[string]AcceptancePolicy{ + AcceptancePolicies = map[string]AcceptancePolicy{ "accept": Accept, "reject": Reject, } - terminationPolicies = map[string]TerminationPolicy{ + TerminationPolicies = map[string]TerminationPolicy{ "continue": Continue, "stop": Stop, } @@ -35,14 +35,14 @@ var ( "syslog": Syslog, "rsyslog": RSyslog, } - timeFormats = map[string]string{ + TimeFormats = map[string]string{ "": zerolog.TimeFormatUnix, "unix": zerolog.TimeFormatUnix, "unixms": zerolog.TimeFormatUnixMs, "unixmicro": zerolog.TimeFormatUnixMicro, "unixnano": zerolog.TimeFormatUnixNano, } - consoleTimeFormats = map[string]string{ + ConsoleTimeFormats = map[string]string{ "Layout": time.Layout, "ANSIC": time.ANSIC, "UnixDate": time.UnixDate, @@ -60,7 +60,7 @@ var ( "StampMicro": time.StampMicro, "StampNano": time.StampNano, } - logLevels = map[string]zerolog.Level{ + LogLevels = map[string]zerolog.Level{ "trace": zerolog.TraceLevel, "debug": zerolog.DebugLevel, "info": zerolog.InfoLevel, @@ -72,124 +72,6 @@ var ( } ) -// GetVerificationPolicy returns the hook verification policy from plugin config file. -func (p PluginConfig) GetVerificationPolicy() VerificationPolicy { - if policy, ok := verificationPolicies[p.VerificationPolicy]; ok { - return policy - } - return PassDown -} - -// GetPluginCompatibilityPolicy returns the plugin compatibility policy from plugin config file. -func (p PluginConfig) GetPluginCompatibilityPolicy() CompatibilityPolicy { - if policy, ok := compatibilityPolicies[p.CompatibilityPolicy]; ok { - return policy - } - return Strict -} - -// GetAcceptancePolicy returns the acceptance policy from plugin config file. -func (p PluginConfig) GetAcceptancePolicy() AcceptancePolicy { - if policy, ok := acceptancePolicies[p.AcceptancePolicy]; ok { - return policy - } - return Accept -} - -// GetTerminationPolicy returns the termination policy from plugin config file. -func (p PluginConfig) GetTerminationPolicy() TerminationPolicy { - if policy, ok := terminationPolicies[p.TerminationPolicy]; ok { - return policy - } - return Stop -} - -// GetTCPKeepAlivePeriod returns the TCP keep alive period from config file or default value. -func (c Client) GetTCPKeepAlivePeriod() time.Duration { - if c.TCPKeepAlivePeriod < 0 { - return DefaultTCPKeepAlivePeriod - } - return c.TCPKeepAlivePeriod -} - -// GetReceiveDeadline returns the receive deadline from config file or default value. -func (c Client) GetReceiveDeadline() time.Duration { - if c.ReceiveDeadline < 0 { - return DefaultReceiveDeadline - } - return c.ReceiveDeadline -} - -// GetReceiveTimeout returns the receive timeout from config file or default value. -func (c Client) GetReceiveTimeout() time.Duration { - if c.ReceiveTimeout < 0 { - return DefaultReceiveTimeout - } - return c.ReceiveTimeout -} - -// GetSendDeadline returns the send deadline from config file or default value. -func (c Client) GetSendDeadline() time.Duration { - if c.SendDeadline < 0 { - return DefaultSendDeadline - } - return c.SendDeadline -} - -// GetReceiveChunkSize returns the receive chunk size from config file or default value. -func (c Client) GetReceiveChunkSize() int { - if c.ReceiveChunkSize <= 0 { - return DefaultChunkSize - } - return c.ReceiveChunkSize -} - -// GetDialTimeout returns the dial timeout from config file or default value. -func (c Client) GetDialTimeout() time.Duration { - if c.DialTimeout < 0 { - return DefaultDialTimeout - } - return c.DialTimeout -} - -// GetBackoff returns the backoff from config file or default value. -func (c Client) GetBackoff() time.Duration { - if c.Backoff < 0 { - return DefaultBackoff - } - return c.Backoff -} - -// GetHealthCheckPeriod returns the health check period from config file or default value. -func (pr Proxy) GetHealthCheckPeriod() time.Duration { - if pr.HealthCheckPeriod <= 0 { - return DefaultHealthCheckPeriod - } - return pr.HealthCheckPeriod -} - -// GetTickInterval returns the tick interval from config file or default value. -func (s Server) GetTickInterval() time.Duration { - if s.TickInterval < 0 { - return DefaultTickInterval - } - return s.TickInterval -} - -// GetSize returns the pool size from config file. -func (p Pool) GetSize() int { - if p.Size == 0 { - return DefaultPoolSize - } - - // Minimum pool size is 2. - if p.Size < MinimumPoolSize { - p.Size = MinimumPoolSize - } - - return p.Size -} - // GetOutput returns the logger output from config file. func (l Logger) GetOutput() []LogOutput { var outputs []LogOutput @@ -208,30 +90,6 @@ func (l Logger) GetOutput() []LogOutput { return outputs } -// GetTimeFormat returns the logger time format from config file. -func (l Logger) GetTimeFormat() string { - if format, ok := timeFormats[l.TimeFormat]; ok { - return format - } - return zerolog.TimeFormatUnix -} - -// GetConsoleTimeFormat returns the console logger's time format from config file. -func (l Logger) GetConsoleTimeFormat() string { - if format, ok := consoleTimeFormats[l.ConsoleTimeFormat]; ok { - return format - } - return time.RFC3339 -} - -// GetLevel returns the logger level from config file. -func (l Logger) GetLevel() zerolog.Level { - if level, ok := logLevels[l.Level]; ok { - return level - } - return zerolog.InfoLevel -} - // GetPlugins returns the plugins from config file. func (p PluginConfig) GetPlugins(name ...string) []Plugin { var plugins []Plugin @@ -263,22 +121,6 @@ func GetDefaultConfigFilePath(filename string) string { return filepath.Join("./", filename) } -// GetReadHeaderTimeout returns the read header timeout from config file or default value. -func (m Metrics) GetReadHeaderTimeout() time.Duration { - if m.ReadHeaderTimeout < 0 { - return DefaultReadHeaderTimeout - } - return m.ReadHeaderTimeout -} - -// GetTimeout returns the metrics server timeout from config file or default value. -func (m Metrics) GetTimeout() time.Duration { - if m.Timeout < 0 { - return DefaultMetricsServerTimeout - } - return m.Timeout -} - // Filter returns a filtered global config based on the group name. func (gc GlobalConfig) Filter(groupName string) *GlobalConfig { if _, ok := gc.Servers[groupName]; !ok { diff --git a/network/client.go b/network/client.go index 3f07b10b..e129867e 100644 --- a/network/client.go +++ b/network/client.go @@ -24,6 +24,7 @@ type IClient interface { IsConnected() bool RemoteAddr() string LocalAddr() string + Retry() *Retry } type Client struct { @@ -408,3 +409,12 @@ func (c *Client) LocalAddr() string { return "" } + +// Retry returns the retry object. +func (c *Client) Retry() *Retry { + if _, ok := c.retry.(*Retry); !ok { + return nil + } else { + return c.retry.(*Retry) + } +} diff --git a/network/proxy.go b/network/proxy.go index bec9ac92..4ca07d15 100644 --- a/network/proxy.go +++ b/network/proxy.go @@ -93,7 +93,11 @@ func NewProxy( proxyCtx, proxy.ClientConfig, proxy.logger, NewRetry( proxy.ClientConfig.Retries, - proxy.ClientConfig.GetBackoff(), + config.If[time.Duration]( + proxy.ClientConfig.Backoff > 0, + proxy.ClientConfig.Backoff, + config.DefaultBackoff, + ), proxy.ClientConfig.BackoffMultiplier, proxy.ClientConfig.DisableBackoffCaps, proxy.logger, @@ -159,7 +163,11 @@ func (pr *Proxy) Connect(conn *ConnWrapper) *gerr.GatewayDError { pr.ctx, pr.ClientConfig, pr.logger, NewRetry( pr.ClientConfig.Retries, - pr.ClientConfig.GetBackoff(), + config.If[time.Duration]( + pr.ClientConfig.Backoff > 0, + pr.ClientConfig.Backoff, + config.DefaultBackoff, + ), pr.ClientConfig.BackoffMultiplier, pr.ClientConfig.DisableBackoffCaps, pr.logger, From 91b3fe124a9f76ec862f26f188847547d55d77ae Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sun, 19 Nov 2023 15:43:47 +0100 Subject: [PATCH 3/3] Add basic tests for If and Exists Update tests --- config/constants.go | 2 +- config/getters_test.go | 104 -------------------------------------- config/getters_windows.go | 7 --- config/utils.go | 2 + config/utils_test.go | 22 ++++++++ network/client.go | 6 ++- 6 files changed, 29 insertions(+), 114 deletions(-) create mode 100644 config/utils_test.go diff --git a/config/constants.go b/config/constants.go index 817a4043..49e99bc7 100644 --- a/config/constants.go +++ b/config/constants.go @@ -146,7 +146,7 @@ const ( DefaultGRPCAPINetwork = "tcp" DefaultGRPCAPIAddress = "localhost:19090" - // Policies + // Policies. DefaultCompatibilityPolicy = Strict DefaultVerificationPolicy = PassDown DefaultAcceptancePolicy = Accept diff --git a/config/getters_test.go b/config/getters_test.go index 8812f55f..0d81df36 100644 --- a/config/getters_test.go +++ b/config/getters_test.go @@ -3,108 +3,16 @@ package config import ( "context" "testing" - "time" - "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) -// TestGetVerificationPolicy tests the GetVerificationPolicy function. -func TestGetVerificationPolicy(t *testing.T) { - pluginConfig := PluginConfig{} - assert.Equal(t, PassDown, pluginConfig.GetVerificationPolicy()) -} - -// TestGetPluginCompatibilityPolicy tests the GetPluginCompatibilityPolicy function. -func TestGetPluginCompatibilityPolicy(t *testing.T) { - pluginConfig := PluginConfig{} - assert.Equal(t, Strict, pluginConfig.GetPluginCompatibilityPolicy()) -} - -// TestGetAcceptancePolicy tests the GetAcceptancePolicy function. -func TestGetAcceptancePolicy(t *testing.T) { - pluginConfig := PluginConfig{} - assert.Equal(t, Accept, pluginConfig.GetAcceptancePolicy()) -} - -// TestGetTerminationPolicy tests the GetTerminationPolicy function. -func TestGetTerminationPolicy(t *testing.T) { - pluginConfig := PluginConfig{} - assert.Equal(t, Stop, pluginConfig.GetTerminationPolicy()) -} - -// TestGetTCPKeepAlivePeriod tests the GetTCPKeepAlivePeriod function. -func TestGetTCPKeepAlivePeriod(t *testing.T) { - client := Client{} - assert.Equal(t, client.GetTCPKeepAlivePeriod(), time.Duration(0)) -} - -// TestGetReceiveDeadline tests the GetReceiveDeadline function. -func TestGetReceiveDeadline(t *testing.T) { - client := Client{} - assert.Equal(t, time.Duration(0), client.GetReceiveDeadline()) -} - -// TestGetReceiveTimeout tests the GetReceiveTimeout function. -func TestGetReceiveTimeout(t *testing.T) { - client := Client{} - assert.Equal(t, time.Duration(0), client.GetReceiveTimeout()) -} - -// TestGetSendDeadline tests the GetSendDeadline function. -func TestGetSendDeadline(t *testing.T) { - client := Client{} - assert.Equal(t, time.Duration(0), client.GetSendDeadline()) -} - -// TestGetReceiveChunkSize tests the GetReceiveChunkSize function. -func TestGetReceiveChunkSize(t *testing.T) { - client := Client{} - assert.Equal(t, DefaultChunkSize, client.GetReceiveChunkSize()) -} - -// TestGetHealthCheckPeriod tests the GetHealthCheckPeriod function. -func TestGetHealthCheckPeriod(t *testing.T) { - proxy := Proxy{} - assert.Equal(t, DefaultHealthCheckPeriod, proxy.GetHealthCheckPeriod()) -} - -// TestGetTickInterval tests the GetTickInterval function. -func TestGetTickInterval(t *testing.T) { - server := Server{} - assert.Equal(t, server.GetTickInterval(), time.Duration(0)) -} - -// TestGetSize tests the GetSize function. -func TestGetSize(t *testing.T) { - pool := Pool{} - assert.Equal(t, DefaultPoolSize, pool.GetSize()) -} - // TestGetOutput tests the GetOutput function. func TestGetOutput(t *testing.T) { logger := Logger{} assert.Equal(t, []LogOutput{Console}, logger.GetOutput()) } -// TestGetTimeFormat tests the GetTimeFormat function. -func TestGetTimeFormat(t *testing.T) { - logger := Logger{} - assert.Equal(t, zerolog.TimeFormatUnix, logger.GetTimeFormat()) -} - -// TestGetConsoleTimeFormat tests the GetConsoleTimeFormat function. -func TestGetConsoleTimeFormat(t *testing.T) { - logger := Logger{} - assert.Equal(t, time.RFC3339, logger.GetConsoleTimeFormat()) -} - -// TestGetLevel tests the GetLevel function. -func TestGetLevel(t *testing.T) { - logger := Logger{} - assert.Equal(t, zerolog.InfoLevel, logger.GetLevel()) -} - // TestGetPlugins tests the GetPlugins function. func TestGetPlugins(t *testing.T) { plugin := Plugin{Name: "plugin1"} @@ -117,18 +25,6 @@ func TestGetDefaultConfigFilePath(t *testing.T) { assert.Equal(t, GlobalConfigFilename, GetDefaultConfigFilePath(GlobalConfigFilename)) } -// TestGetReadTimeout tests the GetReadTimeout function. -func TestGetReadHeaderTimeout(t *testing.T) { - metrics := Metrics{} - assert.Equal(t, metrics.GetReadHeaderTimeout(), time.Duration(0)) -} - -// TestGetTimeout tests the GetTimeout function of the metrics server. -func TestGetTimeout(t *testing.T) { - metrics := Metrics{} - assert.Equal(t, metrics.GetTimeout(), time.Duration(0)) -} - // TestFilter tests the Filter function. func TestFilter(t *testing.T) { // Load config from the default config file. diff --git a/config/getters_windows.go b/config/getters_windows.go index 81b5da38..20e96782 100644 --- a/config/getters_windows.go +++ b/config/getters_windows.go @@ -3,14 +3,7 @@ package config -import "github.com/rs/zerolog" - // GetSyslogPriority returns zero value for Windows. func (l Logger) GetSyslogPriority() int { return 0 } - -// GetSystemLimits returns zero values for Windows. -func (s Server) GetRLimits(logger zerolog.Logger) (uint64, uint64) { - return 0, 0 -} diff --git a/config/utils.go b/config/utils.go index 01871e6a..481579ba 100644 --- a/config/utils.go +++ b/config/utils.go @@ -9,6 +9,8 @@ func If[T any](predicate bool, truthy, falsy T) T { } // Exists returns true if key exists in map_, false otherwise. +// +//nolint:revive func Exists[T comparable, V any](map_ map[T]V, key T) bool { _, ok := map_[key] return ok diff --git a/config/utils_test.go b/config/utils_test.go new file mode 100644 index 00000000..3a9ec810 --- /dev/null +++ b/config/utils_test.go @@ -0,0 +1,22 @@ +package config + +import "testing" + +func TestIf(t *testing.T) { + if If(true, 1, 2) != 1 { + t.Error("If(true, 1, 2) != 1") + } + if If(false, 1, 2) != 2 { + t.Error("If(false, 1, 2) != 2") + } +} + +func TestExists(t *testing.T) { + m := map[string]int{"a": 1, "b": 2} + if !Exists(m, "a") { + t.Error("Exists(m, \"a\") != true") + } + if Exists(m, "c") { + t.Error("Exists(m, \"c\") != false") + } +} diff --git a/network/client.go b/network/client.go index e129867e..04e5daee 100644 --- a/network/client.go +++ b/network/client.go @@ -411,10 +411,12 @@ func (c *Client) LocalAddr() string { } // Retry returns the retry object. +// +//nolint:revive func (c *Client) Retry() *Retry { - if _, ok := c.retry.(*Retry); !ok { + if retry, ok := c.retry.(*Retry); !ok { return nil } else { - return c.retry.(*Retry) + return retry } }