Skip to content

Commit 68f55b7

Browse files
committed
Remove unused default configuration constants
1 parent 3f705d7 commit 68f55b7

File tree

2 files changed

+261
-17
lines changed

2 files changed

+261
-17
lines changed
Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
package httpclient
2+
3+
import (
4+
"bufio"
5+
"encoding/json"
6+
"io"
7+
"os"
8+
"strconv"
9+
"strings"
10+
"time"
11+
12+
"github.com/deploymenttheory/go-api-http-client/logger"
13+
"go.uber.org/zap"
14+
)
15+
16+
const (
17+
DefaultLogLevel = logger.LogLevelInfo
18+
DefaultMaxRetryAttempts = 3
19+
DefaultEnableDynamicRateLimiting = true
20+
DefaultMaxConcurrentRequests = 5
21+
DefaultTokenBufferPeriod = 5 * time.Minute
22+
DefaultTotalRetryDuration = 5 * time.Minute
23+
DefaultTimeout = 10 * time.Second
24+
)
25+
26+
func SetClientConfiguration(log *zap.Logger, configFilePath string) (*ClientConfig, error) {
27+
config := &ClientConfig{}
28+
29+
// Load config values from environment variables
30+
loadConfigFromEnv(config)
31+
32+
// Load config values from file if necessary
33+
if validateConfigCompletion(config) && configFilePath != "" {
34+
if err := config.loadConfigFromFile(configFilePath, log); err != nil { // Updated to the correct function name
35+
log.Error("Failed to load configuration from file", zap.String("path", configFilePath), zap.Error(err))
36+
return nil, err
37+
}
38+
}
39+
40+
// Validate the configuration
41+
if err := validateClientConfig(config, log); err != nil {
42+
log.Error("Configuration validation failed", zap.Error(err))
43+
return nil, err
44+
}
45+
46+
// Set default values where necessary
47+
setClientDefaultValues(config, log)
48+
49+
return config, nil
50+
}
51+
52+
func loadConfigFromEnv(config *ClientConfig) {
53+
// AuthConfig
54+
config.Auth.ClientID = getEnvOrDefault("CLIENT_ID", config.Auth.ClientID)
55+
config.Auth.ClientSecret = getEnvOrDefault("CLIENT_SECRET", config.Auth.ClientSecret)
56+
57+
// EnvironmentConfig
58+
config.Environment.InstanceName = getEnvOrDefault("INSTANCE_NAME", config.Environment.InstanceName)
59+
config.Environment.OverrideBaseDomain = getEnvOrDefault("OVERRIDE_BASE_DOMAIN", config.Environment.OverrideBaseDomain)
60+
config.Environment.APIType = getEnvOrDefault("API_TYPE", config.Environment.APIType)
61+
62+
// ClientOptions
63+
config.ClientOptions.LogLevel = getEnvOrDefault("LOG_LEVEL", config.ClientOptions.LogLevel)
64+
config.ClientOptions.LogOutputFormat = getEnvOrDefault("LOG_OUTPUT_FORMAT", config.ClientOptions.LogOutputFormat)
65+
config.ClientOptions.LogConsoleSeparator = getEnvOrDefault("LOG_CONSOLE_SEPARATOR", config.ClientOptions.LogConsoleSeparator)
66+
config.ClientOptions.HideSensitiveData = parseBool(getEnvOrDefault("HIDE_SENSITIVE_DATA", strconv.FormatBool(config.ClientOptions.HideSensitiveData)))
67+
config.ClientOptions.MaxRetryAttempts = parseInt(getEnvOrDefault("MAX_RETRY_ATTEMPTS", strconv.Itoa(config.ClientOptions.MaxRetryAttempts)), DefaultMaxRetryAttempts)
68+
config.ClientOptions.EnableDynamicRateLimiting = parseBool(getEnvOrDefault("ENABLE_DYNAMIC_RATE_LIMITING", strconv.FormatBool(config.ClientOptions.EnableDynamicRateLimiting)))
69+
config.ClientOptions.MaxConcurrentRequests = parseInt(getEnvOrDefault("MAX_CONCURRENT_REQUESTS", strconv.Itoa(config.ClientOptions.MaxConcurrentRequests)), DefaultMaxConcurrentRequests)
70+
config.ClientOptions.TokenRefreshBufferPeriod = parseDuration(getEnvOrDefault("TOKEN_REFRESH_BUFFER_PERIOD", config.ClientOptions.TokenRefreshBufferPeriod.String()), DefaultTokenBufferPeriod)
71+
config.ClientOptions.TotalRetryDuration = parseDuration(getEnvOrDefault("TOTAL_RETRY_DURATION", config.ClientOptions.TotalRetryDuration.String()), DefaultTotalRetryDuration)
72+
config.ClientOptions.CustomTimeout = parseDuration(getEnvOrDefault("CUSTOM_TIMEOUT", config.ClientOptions.CustomTimeout.String()), DefaultTimeout)
73+
}
74+
75+
// Helper function to get environment variable or default value
76+
func getEnvOrDefault(envKey string, defaultValue string) string {
77+
if value, exists := os.LookupEnv(envKey); exists {
78+
return value
79+
}
80+
return defaultValue
81+
}
82+
83+
// Helper function to parse boolean from environment variable
84+
func parseBool(value string) bool {
85+
result, err := strconv.ParseBool(value)
86+
if err != nil {
87+
return false
88+
}
89+
return result
90+
}
91+
92+
// Helper function to parse int from environment variable
93+
func parseInt(value string, defaultVal int) int {
94+
result, err := strconv.Atoi(value)
95+
if err != nil {
96+
return defaultVal
97+
}
98+
return result
99+
}
100+
101+
// Helper function to parse duration from environment variable
102+
func parseDuration(value string, defaultVal time.Duration) time.Duration {
103+
result, err := time.ParseDuration(value)
104+
if err != nil {
105+
return defaultVal
106+
}
107+
return result
108+
}
109+
110+
// validateConfigCompletion checks if any essential configuration fields are missing,
111+
// indicating the configuration might be incomplete and may require loading from additional sources.
112+
func validateConfigCompletion(config *ClientConfig) bool {
113+
// Check if essential fields are missing; additional fields can be checked as needed
114+
return config.Auth.ClientID == "" || config.Auth.ClientSecret == "" ||
115+
config.Environment.InstanceName == "" || config.Environment.APIType == "" ||
116+
config.ClientOptions.LogLevel == "" || config.ClientOptions.LogOutputFormat == "" ||
117+
config.ClientOptions.LogConsoleSeparator == ""
118+
}
119+
120+
func setClientDefaultValues(config *ClientConfig, log *zap.Logger) {
121+
if config.ClientOptions.MaxRetryAttempts < 0 {
122+
config.ClientOptions.MaxRetryAttempts = DefaultMaxRetryAttempts
123+
log.Info("MaxRetryAttempts was negative, set to default value", zap.Int("MaxRetryAttempts", DefaultMaxRetryAttempts))
124+
}
125+
126+
if config.ClientOptions.MaxConcurrentRequests <= 0 {
127+
config.ClientOptions.MaxConcurrentRequests = DefaultMaxConcurrentRequests
128+
log.Info("MaxConcurrentRequests was negative or zero, set to default value", zap.Int("MaxConcurrentRequests", DefaultMaxConcurrentRequests))
129+
}
130+
131+
if config.ClientOptions.TokenRefreshBufferPeriod < 0 {
132+
config.ClientOptions.TokenRefreshBufferPeriod = DefaultTokenBufferPeriod
133+
log.Info("TokenRefreshBufferPeriod was negative, set to default value", zap.Duration("TokenRefreshBufferPeriod", DefaultTokenBufferPeriod))
134+
}
135+
136+
if config.ClientOptions.TotalRetryDuration <= 0 {
137+
config.ClientOptions.TotalRetryDuration = DefaultTotalRetryDuration
138+
log.Info("TotalRetryDuration was negative or zero, set to default value", zap.Duration("TotalRetryDuration", DefaultTotalRetryDuration))
139+
}
140+
141+
if config.ClientOptions.TokenRefreshBufferPeriod == 0 {
142+
config.ClientOptions.TokenRefreshBufferPeriod = DefaultTokenBufferPeriod
143+
log.Info("TokenRefreshBufferPeriod not set, set to default value", zap.Duration("TokenRefreshBufferPeriod", DefaultTokenBufferPeriod))
144+
}
145+
146+
if config.ClientOptions.TotalRetryDuration == 0 {
147+
config.ClientOptions.TotalRetryDuration = DefaultTotalRetryDuration
148+
log.Info("TotalRetryDuration not set, set to default value", zap.Duration("TotalRetryDuration", DefaultTotalRetryDuration))
149+
}
150+
151+
if config.ClientOptions.CustomTimeout == 0 {
152+
config.ClientOptions.CustomTimeout = DefaultTimeout
153+
log.Info("CustomTimeout not set, set to default value", zap.Duration("CustomTimeout", DefaultTimeout))
154+
}
155+
156+
// Log completion of setting default values
157+
log.Info("Default values set for client configuration")
158+
}
159+
160+
// loadFromFile loads configuration values from a JSON file into the ClientConfig struct.
161+
func (config *ClientConfig) loadConfigFromFile(filePath string, log *zap.Logger) error {
162+
// Open the configuration file
163+
file, err := os.Open(filePath)
164+
if err != nil {
165+
log.Error("Failed to open the configuration file", zap.String("filePath", filePath), zap.Error(err))
166+
return err
167+
}
168+
defer file.Close()
169+
170+
reader := bufio.NewReader(file)
171+
var builder strings.Builder
172+
173+
// Read the file content
174+
for {
175+
part, _, err := reader.ReadLine()
176+
if err == io.EOF {
177+
break
178+
}
179+
if err != nil {
180+
log.Error("Failed to read the configuration file", zap.String("filePath", filePath), zap.Error(err))
181+
return err
182+
}
183+
builder.Write(part)
184+
}
185+
186+
// Unmarshal JSON content into the ClientConfig struct
187+
err = json.Unmarshal([]byte(builder.String()), config)
188+
if err != nil {
189+
log.Error("Failed to unmarshal the configuration file", zap.String("filePath", filePath), zap.Error(err))
190+
return err
191+
}
192+
193+
log.Info("Configuration successfully loaded from file", zap.String("filePath", filePath))
194+
return nil
195+
}
196+
197+
// validateClientConfig checks the client configuration and logs any issues using zap logger.
198+
func validateClientConfig(config *ClientConfig, log *zap.Logger) {
199+
// Helper function to log validation errors
200+
logValidationError := func(msg string) {
201+
log.Error(msg)
202+
}
203+
204+
// Flag to track if any validation errors were found
205+
var hasErrors bool
206+
207+
// Validate AuthConfig
208+
if config.Auth.ClientID == "" {
209+
logValidationError("Validation error: ClientID in AuthConfig is required")
210+
hasErrors = true
211+
}
212+
if config.Auth.ClientSecret == "" {
213+
logValidationError("Validation error: ClientSecret in AuthConfig is required")
214+
hasErrors = true
215+
}
216+
217+
// Validate EnvironmentConfig
218+
if config.Environment.InstanceName == "" {
219+
logValidationError("Validation error: InstanceName in EnvironmentConfig is required")
220+
hasErrors = true
221+
}
222+
if config.Environment.APIType == "" {
223+
logValidationError("Validation error: APIType in EnvironmentConfig is required")
224+
hasErrors = true
225+
}
226+
227+
// Validate ClientOptions
228+
if config.ClientOptions.LogLevel == "" {
229+
logValidationError("Validation error: LogLevel in ClientOptions is required")
230+
hasErrors = true
231+
}
232+
if config.ClientOptions.LogOutputFormat == "" {
233+
logValidationError("Validation error: LogOutputFormat in ClientOptions is required")
234+
hasErrors = true
235+
}
236+
if config.ClientOptions.MaxRetryAttempts < 0 {
237+
logValidationError("Validation error: MaxRetryAttempts in ClientOptions must not be negative")
238+
hasErrors = true
239+
}
240+
if config.ClientOptions.MaxConcurrentRequests <= 0 {
241+
logValidationError("Validation error: MaxConcurrentRequests in ClientOptions must be greater than 0")
242+
hasErrors = true
243+
}
244+
if config.ClientOptions.TokenRefreshBufferPeriod < 0 {
245+
logValidationError("Validation error: TokenRefreshBufferPeriod in ClientOptions must not be negative")
246+
hasErrors = true
247+
}
248+
if config.ClientOptions.TotalRetryDuration < 0 {
249+
logValidationError("Validation error: TotalRetryDuration in ClientOptions must not be negative")
250+
hasErrors = true
251+
}
252+
if config.ClientOptions.CustomTimeout <= 0 {
253+
logValidationError("Validation error: CustomTimeout in ClientOptions must be greater than 0")
254+
hasErrors = true
255+
}
256+
257+
// Log a summary error if any validation errors were found
258+
if hasErrors {
259+
log.Error("Configuration validation failed with one or more errors")
260+
}
261+
}

httpclient/httpclient_defaultconfig.go

Lines changed: 0 additions & 17 deletions
This file was deleted.

0 commit comments

Comments
 (0)