diff --git a/.gitignore b/.gitignore index b546895..12018c1 100644 --- a/.gitignore +++ b/.gitignore @@ -129,3 +129,13 @@ dist .yarn/build-state.yml .yarn/install-state.gz .pnp.* + +# Ignore compiled shared object files +*.so + +# Ignore coverage output files +coverage.out +coverage.html + +# Ignore the schema directory used for testing +/schemas/ \ No newline at end of file diff --git a/go.mod b/go.mod index b27c6ae..7ec431b 100644 --- a/go.mod +++ b/go.mod @@ -1,33 +1,35 @@ module github.com/beckn/beckn-onix -go 1.23.0 - -toolchain go1.23.7 +go 1.24.1 require ( - github.com/stretchr/testify v1.10.0 + github.com/kr/pretty v0.3.1 // indirect + github.com/rogpeppe/go-internal v1.13.1 // indirect + github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 golang.org/x/crypto v0.36.0 + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect ) +require github.com/stretchr/testify v1.10.0 + require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect - github.com/kr/pretty v0.3.1 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/rogpeppe/go-internal v1.13.1 // indirect github.com/stretchr/objx v0.5.2 // indirect - gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect + gopkg.in/yaml.v3 v3.0.1 ) require github.com/zenazn/pkcs7pad v0.0.0-20170308005700-253a5b1f0e03 +require ( + github.com/google/uuid v1.6.0 + golang.org/x/text v0.23.0 // indirect +) + +require golang.org/x/sys v0.31.0 // indirect + require ( github.com/hashicorp/go-retryablehttp v0.7.7 - github.com/rs/zerolog v1.34.0 - golang.org/x/sys v0.31.0 // indirect - gopkg.in/natefinch/lumberjack.v2 v2.2.1 gopkg.in/yaml.v2 v2.4.0 ) diff --git a/go.sum b/go.sum index adde50d..183730d 100644 --- a/go.sum +++ b/go.sum @@ -1,10 +1,12 @@ -github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= -github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= @@ -20,20 +22,16 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= -github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= -github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY= -github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 h1:PKK9DyHxif4LZo+uQSgXNqs0jj5+xZwwfKHgph2lxBw= +github.com/santhosh-tekuri/jsonschema/v6 v6.0.1/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= @@ -42,16 +40,13 @@ github.com/zenazn/pkcs7pad v0.0.0-20170308005700-253a5b1f0e03 h1:m1h+vudopHsI67F github.com/zenazn/pkcs7pad v0.0.0-20170308005700-253a5b1f0e03/go.mod h1:8sheVFH84v3PCyFY/O02mIgSQY9I6wMYPWsq7mDnEZY= golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= -gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/pkg/log/log.go b/pkg/log/log.go index e73f517..8531eee 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "os" + "path/filepath" "strconv" "sync" "time" @@ -15,43 +16,30 @@ import ( "gopkg.in/natefinch/lumberjack.v2" ) -// Error definitions for logging configuration. -var ( - ErrInvalidLogLevel = errors.New("invalid log level") - ErrLogDestinationNil = errors.New("log Destinations cant be empty") - ErrMissingFilePath = errors.New("file path missing in destination config for file logging") -) +type level string -// DestinationType represents the type of logging destination. -type DestinationType string +type destinationType string -// Supported logging destinations. -const ( - Stdout DestinationType = "stdout" - File DestinationType = "file" -) - -// Destination defines a log output destination. -type Destination struct { - Type DestinationType `yaml:"type"` // Specifies destination type - Config map[string]string `yaml:"config"` // holds destination-specific configuration. +type destination struct { + Type destinationType `yaml:"type"` + Config map[string]string `yaml:"config"` } -// Level represents logging levels. -type Level string - -// Supported log levels. const ( - DebugLevel Level = "debug" - InfoLevel Level = "info" - WarnLevel Level = "warn" - ErrorLevel Level = "error" - FatalLevel Level = "fatal" - PanicLevel Level = "panic" + Stdout destinationType = "stdout" + File destinationType = "file" ) -// Mapping of Level to zerolog.Level. -var logLevels = map[Level]zerolog.Level{ +const ( + DebugLevel level = "debug" + InfoLevel level = "info" + WarnLevel level = "warn" + ErrorLevel level = "error" + FatalLevel level = "fatal" + PanicLevel level = "panic" +) + +var logLevels = map[level]zerolog.Level{ DebugLevel: zerolog.DebugLevel, InfoLevel: zerolog.InfoLevel, WarnLevel: zerolog.WarnLevel, @@ -60,123 +48,41 @@ var logLevels = map[Level]zerolog.Level{ PanicLevel: zerolog.PanicLevel, } -// Config represents the logging configuration. type Config struct { - Level Level `yaml:"level"` //Logging Level - Destinations []Destination `yaml:"destinations"` // List of log destinations - ContextKeys []string `yaml:"contextKeys"` // List of context keys to extract + Level level `yaml:"level"` + Destinations []destination `yaml:"destinations"` + ContextKeys []string `yaml:"contextKeys"` } -// Logger Instance var ( logger zerolog.Logger - once sync.Once cfg Config + once sync.Once ) -// init initializes the logger with default configuration. -func init() { - logger, _ = getLogger(defaultConfig) -} +var ( + ErrInvalidLogLevel = errors.New("invalid log level") + ErrLogDestinationNil = errors.New("log Destinations cant be empty") + ErrMissingFilePath = errors.New("file path missing in destination config for file logging") +) -// InitLogger initializes the logger with the provided configuration. -// -// It ensures that the logger is initialized only once using sync.Once. -// Returns an error if the configuration is invalid. -func InitLogger(c Config) error { - var err error - once.Do(func() { // makes it singleton - err = c.validate() - if err != nil { - return - } - logger, err = getLogger(c) - if err != nil { - return - } - - }) - return err -} - -// getLogger creates and configures a new logger based on the given configuration. -// Returns an initialized zerolog.Logger or an error if configuration is invalid. -func getLogger(config Config) (zerolog.Logger, error) { - var newLogger zerolog.Logger - - // Multiwriter for multiple log destinations - var writers []io.Writer - for _, dest := range config.Destinations { - switch dest.Type { - case Stdout: - writers = append(writers, os.Stdout) - case File: - filePath := dest.Config["path"] - - // File rotation - lumberjackLogger := &lumberjack.Logger{ - Filename: filePath, - } - - setConfigValue := func(key string, target *int) { - if valStr, ok := dest.Config[key]; ok { - if val, err := strconv.Atoi(valStr); err == nil { - *target = val - } - } - } - - setConfigValue("maxSize", &lumberjackLogger.MaxSize) - setConfigValue("maxBackups", &lumberjackLogger.MaxBackups) - setConfigValue("maxAge", &lumberjackLogger.MaxAge) - - if compress, ok := dest.Config["compress"]; ok { - lumberjackLogger.Compress = compress == "true" - } - writers = append(writers, lumberjackLogger) - } - } - - multiwriter := io.MultiWriter(writers...) - - newLogger = zerolog.New(multiwriter). - Level(logLevels[config.Level]). - With(). - Timestamp(). - Caller(). - Logger() - - // Replace the cfg with given config - cfg = config - - return newLogger, nil - -} - -// validate checks if the provided logging configuration is valid. -// It ensures that a valid log level is provided and that at least one -// destination is specified. Returns an error if validation fails func (config *Config) validate() error { - // Log Level is valid if _, exists := logLevels[config.Level]; !exists { return ErrInvalidLogLevel } - // Log Destinations is not empty if len(config.Destinations) == 0 { return ErrLogDestinationNil } - // File path exists in destination config for File type destination for _, dest := range config.Destinations { switch dest.Type { case Stdout: - case File: if _, exists := dest.Config["path"]; !exists { return ErrMissingFilePath } - // Validate lumberjack config if present + for _, key := range []string{"maxSize", "maxBackups", "maxAge"} { if valStr, ok := dest.Config[key]; ok { if _, err := strconv.Atoi(valStr); err != nil { @@ -185,98 +91,157 @@ func (config *Config) validate() error { } } default: - return fmt.Errorf("Invalid destination type '%s'", dest.Type) + return fmt.Errorf("invalid destination type '%s'", dest.Type) } } return nil } -// Default Config var defaultConfig = Config{ Level: InfoLevel, - Destinations: []Destination{ + Destinations: []destination{ {Type: Stdout}, }, - ContextKeys: []string{}, } -// Debug logs a debug-level message. +func init() { + logger, _ = getLogger(defaultConfig) +} + +func getLogger(config Config) (zerolog.Logger, error) { + var newLogger zerolog.Logger + var writers []io.Writer + for _, dest := range config.Destinations { + switch dest.Type { + case Stdout: + writers = append(writers, os.Stdout) + case File: + filePath := dest.Config["path"] + dir := filepath.Dir(filePath) + if err := os.MkdirAll(dir, os.ModePerm); err != nil { + return newLogger, fmt.Errorf("failed to create log directory: %v", err) + } + lumberjackLogger := &lumberjack.Logger{ + Filename: filePath, + Compress: false, + } + absPath, err := filepath.Abs(filePath) + if err != nil { + return newLogger, fmt.Errorf("failed to get absolute path: %v", err) + } + lumberjackLogger.Filename = absPath + + setConfigValue := func(key string, target *int) { + if valStr, ok := dest.Config[key]; ok { + if val, err := strconv.Atoi(valStr); err == nil { + *target = val + } + } + } + setConfigValue("maxSize", &lumberjackLogger.MaxSize) + setConfigValue("maxBackups", &lumberjackLogger.MaxBackups) + setConfigValue("maxAge", &lumberjackLogger.MaxAge) + if compress, ok := dest.Config["compress"]; ok { + lumberjackLogger.Compress = compress == "true" + } + writers = append(writers, lumberjackLogger) + } + } + multiwriter := io.MultiWriter(writers...) + defer func() { + if closer, ok := multiwriter.(io.Closer); ok { + closer.Close() + } + }() + newLogger = zerolog.New(multiwriter). + Level(logLevels[config.Level]). + With(). + Timestamp(). + Logger() + + cfg = config + return newLogger, nil +} + +func InitLogger(c Config) error { + var initErr error + once.Do(func() { + if initErr = c.validate(); initErr != nil { + return + } + + logger, initErr = getLogger(c) + }) + return initErr +} + func Debug(ctx context.Context, msg string) { logEvent(ctx, zerolog.DebugLevel, msg, nil) } -// Debugf logs a formatted debug-level message. func Debugf(ctx context.Context, format string, v ...any) { msg := fmt.Sprintf(format, v...) logEvent(ctx, zerolog.DebugLevel, msg, nil) } -// Info logs an info-level message. func Info(ctx context.Context, msg string) { logEvent(ctx, zerolog.InfoLevel, msg, nil) } -// Infof logs a formatted info-level message. func Infof(ctx context.Context, format string, v ...any) { msg := fmt.Sprintf(format, v...) logEvent(ctx, zerolog.InfoLevel, msg, nil) } -// Warn logs a warning-level message. func Warn(ctx context.Context, msg string) { logEvent(ctx, zerolog.WarnLevel, msg, nil) } -// Warnf logs a formatted warning-level message. func Warnf(ctx context.Context, format string, v ...any) { msg := fmt.Sprintf(format, v...) logEvent(ctx, zerolog.WarnLevel, msg, nil) } -// Error logs an error-level message. func Error(ctx context.Context, err error, msg string) { logEvent(ctx, zerolog.ErrorLevel, msg, err) } -// Errorf logs a formatted error-level message. func Errorf(ctx context.Context, err error, format string, v ...any) { msg := fmt.Sprintf(format, v...) logEvent(ctx, zerolog.ErrorLevel, msg, err) } -// Fatal logs a fatal-level message and exits the application. func Fatal(ctx context.Context, err error, msg string) { logEvent(ctx, zerolog.FatalLevel, msg, err) } -// Fatalf logs a formatted fatal-level message and exits the application. func Fatalf(ctx context.Context, err error, format string, v ...any) { msg := fmt.Sprintf(format, v...) logEvent(ctx, zerolog.FatalLevel, msg, err) } -// Panic logs a panic-level message. func Panic(ctx context.Context, err error, msg string) { logEvent(ctx, zerolog.PanicLevel, msg, err) } -// Panicf logs a formatted panic-level message. func Panicf(ctx context.Context, err error, format string, v ...any) { msg := fmt.Sprintf(format, v...) logEvent(ctx, zerolog.PanicLevel, msg, err) } -// Request logs an HTTP request. -func Request(ctx context.Context, r *http.Request, body []byte) { - event := logger.Info() - // Iterate through headers and log them - for name, values := range r.Header { - for _, value := range values { - event = event.Str(name, value) - } +func logEvent(ctx context.Context, level zerolog.Level, msg string, err error) { + event := logger.WithLevel(level) + + if err != nil { + event = event.Err(err) } addCtx(ctx, event) + event.Msg(msg) +} +func Request(ctx context.Context, r *http.Request, body []byte) { + event := logger.Info() + addCtx(ctx, event) event.Str("method", r.Method). Str("url", r.URL.String()). Str("body", string(body)). @@ -284,39 +249,23 @@ func Request(ctx context.Context, r *http.Request, body []byte) { Msg("HTTP Request") } -// Response logs an HTTP response. +func addCtx(ctx context.Context, event *zerolog.Event) { + for _, key := range cfg.ContextKeys { + val, ok := ctx.Value(key).(string) + if !ok { + continue + } + keyStr := key + event.Any(keyStr, val) + } +} + func Response(ctx context.Context, r *http.Request, statusCode int, responseTime time.Duration) { event := logger.Info() - addCtx(ctx, event) - event.Str("method", r.Method). Str("url", r.URL.String()). Int("statusCode", statusCode). Dur("responseTime", responseTime). Msg("HTTP Response") } - -// logEvent logs messages at the specified level with optional error details. -func logEvent(ctx context.Context, level zerolog.Level, msg string, err error) { - event := logger.WithLevel(level) - - // Attach error if provided - if err != nil { - event = event.Err(err) - } - - // Add context fields - addCtx(ctx, event) - - event.Msg(msg) -} - -// addCtx adds context-specific fields to log events. -func addCtx(ctx context.Context, event *zerolog.Event) { - for _, key := range cfg.ContextKeys { - if val, ok := ctx.Value(key).(string); ok { - event.Any(key, val) - } - } -} diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go new file mode 100644 index 0000000..2e874ae --- /dev/null +++ b/pkg/log/log_test.go @@ -0,0 +1,667 @@ +package log + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +type ctxKey any + +var requestID ctxKey = "requestID" +var userID ctxKey = "userID" + +const testLogFilePath = "./test_logs/test.log" + +func TestMain(m *testing.M) { + // Create a single temporary directory for all tests + var err error + dir := filepath.Dir(testLogFilePath) + err = os.MkdirAll(dir, os.ModePerm) + if err != nil { + panic("failed to create test log directory: " + err.Error()) + } + + // Run all tests + code := m.Run() + + // Cleanup: Remove the log directory after all tests finish + err = os.RemoveAll(dir) + if err != nil { + println("failed to clean up test log directory: ", err.Error()) + } + + // Exit with the appropriate exit code + os.Exit(code) +} + +func setupLogger(t *testing.T, l level) string { + t.Helper() + + // Create a temporary directory for logs. + + config := Config{ + Level: l, + Destinations: []destination{ + { + Type: File, + Config: map[string]string{ + "path": testLogFilePath, + "maxSize": "1", + "maxAge": "1", + "maxBackup": "1", + "compress": "false", + }, + }, + }, + ContextKeys: []string{"userID", "requestID"}, + } + + // Initialize logger with the given config + err := InitLogger(config) + if err != nil { + t.Fatalf("failed to initialize logger: %v", err) + } + + return testLogFilePath +} + +func readLogFile(t *testing.T, logPath string) []string { + t.Helper() + b, err := os.ReadFile(logPath) + if err != nil { + t.Fatalf("failed to read log file: %v", err) + } + return strings.Split(string(b), "\n") +} + +func parseLogLine(t *testing.T, line string) map[string]interface{} { + t.Helper() + var logEntry map[string]interface{} + err := json.Unmarshal([]byte(line), &logEntry) + if err != nil { + t.Fatalf("Failed to parse log line: %v", err) + } + return logEntry +} + +func TestDebug(t *testing.T) { + t.Helper() + logPath := setupLogger(t, DebugLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + Debug(ctx, "Debug message") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "debug", + "userID": "12345", + "message": "Debug message", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + + if !found { + t.Errorf("Expected Debug message, but it was not found in logs") + } +} + +func TestInfo(t *testing.T) { + logPath := setupLogger(t, InfoLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + Info(ctx, "Info message") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "info", + "userID": "12345", + "message": "Info message", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + + if !found { + t.Errorf("expected Info message, but it was not found in logs") + } +} + +func TestWarn(t *testing.T) { + logPath := setupLogger(t, WarnLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + Warn(ctx, "Warning message") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "warn", + "userID": "12345", + "message": "Warning message", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + delete(logEntry, "time") + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + if !found { + t.Errorf("expected Warning message, but it was not found in logs") + } +} + +func TestError(t *testing.T) { + logPath := setupLogger(t, ErrorLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + Error(ctx, fmt.Errorf("test error"), "Error message") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "error", + "userID": "12345", + "message": "Error message", + "error": "test error", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + if !found { + t.Errorf("expected Error message, but it was not found in logs") + } +} + +func TestRequest(t *testing.T) { + logPath := setupLogger(t, InfoLevel) + ctx := context.WithValue(context.Background(), requestID, "abc-123") + req, _ := http.NewRequest("POST", "/api/test", bytes.NewBuffer([]byte(`{"key":"value"}`))) + req.RemoteAddr = "127.0.0.1:8080" + Request(ctx, req, []byte(`{"key":"value"}`)) + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + if logEntry["message"] == "HTTP Request" || logEntry["method"] == "POST" { + found = true + break + } + } + if !found { + t.Errorf("expected formatted debug message, but it was not found in logs") + } +} + +func TestResponse(t *testing.T) { + logPath := setupLogger(t, InfoLevel) + ctx := context.WithValue(context.Background(), requestID, "abc-123") + req, _ := http.NewRequest("GET", "/api/test", nil) + Response(ctx, req, 200, time.Millisecond*123) + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + if logEntry["message"] == "HTTP Response" { + if logEntry["message"] == "HTTP Response" { + value, ok := logEntry["statusCode"] + if !ok { + t.Fatalf("Expected key 'statusCode' not found in log entry") + } + statusCode, ok := value.(float64) + if !ok { + t.Fatalf("Value for 'statusCode' is not a float64, found: %T", value) + } + if statusCode == 200 { + found = true + break + } + } + } + } + if !found { + t.Errorf("expected message, but it was not found in logs") + } +} + +func TestFatal(t *testing.T) { + logPath := setupLogger(t, FatalLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + Fatal(ctx, fmt.Errorf("fatal error"), "Fatal message") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "fatal", + "userID": "12345", + "message": "Fatal message", + "error": "fatal error", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + if !found { + t.Errorf("expected Fatal message, but it was not found in logs") + } +} + +func TestPanic(t *testing.T) { + logPath := setupLogger(t, PanicLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + Panic(ctx, fmt.Errorf("panic error"), "Panic message") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "panic", + "userID": "12345", + "message": "Panic message", + "error": "panic error", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + if !found { + t.Errorf("expected Panic message, but it was not found in logs") + } +} + +func TestDebugf(t *testing.T) { + logPath := setupLogger(t, DebugLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + Debugf(ctx, "Debugf message: %s", "test") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "debug", + "userID": "12345", + "message": "Debugf message: test", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + t.Log(line) + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + if !found { + t.Errorf("expected formatted debug message, but it was not found in logs") + } +} + +func TestInfof(t *testing.T) { + logPath := setupLogger(t, InfoLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + Infof(ctx, "Infof message: %s", "test") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "info", + "userID": "12345", + "message": "Infof message: test", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + if !found { + t.Errorf("expected Infof message, but it was not found in logs") + } +} + +func TestWarnf(t *testing.T) { + logPath := setupLogger(t, WarnLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + Warnf(ctx, "Warnf message: %s", "test") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "warn", + "userID": "12345", + "message": "Warnf message: test", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + if !found { + t.Errorf("expected Warnf message, but it was not found in logs") + } +} + +func TestErrorf(t *testing.T) { + logPath := setupLogger(t, ErrorLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + err := fmt.Errorf("error message") + Errorf(ctx, err, "Errorf message: %s", "test") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "error", + "userID": "12345", + "message": "Errorf message: test", + "error": "error message", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + if !found { + t.Errorf("expected Errorf message, but it was not found in logs") + } +} + +func TestFatalf(t *testing.T) { + logPath := setupLogger(t, FatalLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + err := fmt.Errorf("fatal error") + Fatalf(ctx, err, "Fatalf message: %s", "test") + lines := readLogFile(t, logPath) + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "fatal", + "userID": "12345", + "message": "Fatalf message: test", + "error": "fatal error", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + if !found { + t.Errorf("expected Fatalf message, but it was not found in logs") + } +} + +func TestPanicf(t *testing.T) { + logPath := setupLogger(t, PanicLevel) + ctx := context.WithValue(context.Background(), userID, "12345") + err := fmt.Errorf("panic error") + Panicf(ctx, err, "Panicf message: %s", "test") + lines := readLogFile(t, logPath) + + if len(lines) == 0 { + t.Fatal("No logs were written.") + } + expected := map[string]interface{}{ + "level": "panic", + "userID": "12345", + "message": "Panicf message: test", + "error": "panic error", + } + + var found bool + for _, line := range lines { + logEntry := parseLogLine(t, line) + // Ignore 'time' while comparing + delete(logEntry, "time") + + if reflect.DeepEqual(expected, logEntry) { + found = true + break + } + } + + if !found { + t.Errorf("expected Panicf message, but it was not found in logs") + } +} + +func TestValidateConfig(t *testing.T) { + tests := []struct { + name string + config Config + wantErr error + }{ + { + name: "Valid config with Stdout", + config: Config{ + Level: InfoLevel, + Destinations: []destination{ + {Type: Stdout}, + }, + }, + wantErr: nil, + }, + { + name: "Valid config with File destination and valid path", + config: Config{ + Level: InfoLevel, + Destinations: []destination{ + { + Type: File, + Config: map[string]string{ + "path": "./logs/app.log", + "maxSize": "10", + "maxBackups": "5", + "maxAge": "7", + }, + }, + }, + }, + wantErr: nil, + }, + { + name: "Error: Invalid log level", + config: Config{ + Level: "invalid", + Destinations: []destination{ + {Type: Stdout}, + }, + }, + wantErr: ErrInvalidLogLevel, + }, + { + name: "Error: No destinations provided", + config: Config{ + Level: InfoLevel, + Destinations: []destination{}, + }, + wantErr: ErrLogDestinationNil, + }, + { + name: "Error: Invalid destination type", + config: Config{ + Level: InfoLevel, + Destinations: []destination{ + {Type: "unknown"}, + }, + }, + wantErr: fmt.Errorf("invalid destination type 'unknown'"), + }, + { + name: "Error: Missing file path for file destination", + config: Config{ + Level: InfoLevel, + Destinations: []destination{ + { + Type: File, + Config: map[string]string{ + "maxSize": "10", + }, + }, + }, + }, + wantErr: ErrMissingFilePath, + }, + { + name: "Error: Invalid maxSize value in file destination", + config: Config{ + Level: InfoLevel, + Destinations: []destination{ + { + Type: File, + Config: map[string]string{ + "path": "./logs/app.log", + "maxSize": "invalid", + }, + }, + }, + }, + wantErr: errors.New(`invalid maxSize: strconv.Atoi: parsing "invalid": invalid syntax`), + }, + { + name: "Error: Invalid maxBackups value in file destination", + config: Config{ + Level: InfoLevel, + Destinations: []destination{ + { + Type: File, + Config: map[string]string{ + "path": "./logs/app.log", + "maxBackups": "invalid", + }, + }, + }, + }, + wantErr: errors.New(`invalid maxBackups: strconv.Atoi: parsing "invalid": invalid syntax`), + }, + { + name: "Error: Invalid maxAge value in file destination", + config: Config{ + Level: InfoLevel, + Destinations: []destination{ + { + Type: File, + Config: map[string]string{ + "path": "./logs/app.log", + "maxAge": "invalid", + }, + }, + }, + }, + wantErr: errors.New(`invalid maxAge: strconv.Atoi: parsing "invalid": invalid syntax`), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.config.validate() + if (err == nil) != (tt.wantErr == nil) { + t.Errorf("validate() error = %v, wantErr %v", err, tt.wantErr) + } + if err != nil && tt.wantErr != nil && err.Error() != tt.wantErr.Error() { + t.Errorf("validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/pkg/model/error.go b/pkg/model/error.go index 2a59658..5cdee1d 100644 --- a/pkg/model/error.go +++ b/pkg/model/error.go @@ -6,24 +6,24 @@ import ( "strings" ) -// Error represents an error response. +// Error represents a standard error response. type Error struct { Code string `json:"code"` Paths string `json:"paths,omitempty"` Message string `json:"message"` } -// Error implements the error interface for the Error struct. +// This implements the error interface for the Error struct. func (e *Error) Error() string { return fmt.Sprintf("Error: Code=%s, Path=%s, Message=%s", e.Code, e.Paths, e.Message) } -// SchemaValidationErr represents a collection of schema validation failures. +// SchemaValidationErr occurs when schema validation errors are encountered. type SchemaValidationErr struct { Errors []Error } -// Error implements the error interface for SchemaValidationErr. +// This implements the error interface for SchemaValidationErr. func (e *SchemaValidationErr) Error() string { var errorMessages []string for _, err := range e.Errors { @@ -32,7 +32,7 @@ func (e *SchemaValidationErr) Error() string { return strings.Join(errorMessages, "; ") } -// BecknError converts SchemaValidationErr into a Beckn-compliant Error response. +// BecknError converts the SchemaValidationErr to an instance of Error. func (e *SchemaValidationErr) BecknError() *Error { if len(e.Errors) == 0 { return &Error{ @@ -58,22 +58,17 @@ func (e *SchemaValidationErr) BecknError() *Error { } } -// SignValidationErr represents an error that occurs during signature validation. +// SignValidationErr occurs when signature validation fails. type SignValidationErr struct { error } -// NewSignValidationErrf creates a new SignValidationErr with a formatted message. -func NewSignValidationErrf(format string, a ...any) *SignValidationErr { - return &SignValidationErr{fmt.Errorf(format, a...)} -} - -// NewSignValidationErr creates a new SignValidationErr from an existing error. +// NewSignValidationErr creates a new instance of SignValidationErr from an error. func NewSignValidationErr(e error) *SignValidationErr { return &SignValidationErr{e} } -// BecknError converts SignValidationErr into a Beckn-compliant Error response. +// BecknError converts the SignValidationErr to an instance of Error. func (e *SignValidationErr) BecknError() *Error { return &Error{ Code: http.StatusText(http.StatusUnauthorized), @@ -81,22 +76,17 @@ func (e *SignValidationErr) BecknError() *Error { } } -// BadReqErr represents an error related to a bad request. +// BadReqErr occurs when a bad request is encountered. type BadReqErr struct { error } -// NewBadReqErr creates a new BadReqErr from an existing error. +// NewBadReqErr creates a new instance of BadReqErr from an error. func NewBadReqErr(err error) *BadReqErr { return &BadReqErr{err} } -// NewBadReqErrf creates a new BadReqErr with a formatted message. -func NewBadReqErrf(format string, a ...any) *BadReqErr { - return &BadReqErr{fmt.Errorf(format, a...)} -} - -// BecknError converts BadReqErr into a Beckn-compliant Error response. +// BecknError converts the BadReqErr to an instance of Error. func (e *BadReqErr) BecknError() *Error { return &Error{ Code: http.StatusText(http.StatusBadRequest), @@ -104,22 +94,17 @@ func (e *BadReqErr) BecknError() *Error { } } -// NotFoundErr represents an error for a missing resource or endpoint. +// NotFoundErr occurs when a requested endpoint is not found. type NotFoundErr struct { error } -// NewNotFoundErr creates a new NotFoundErr from an existing error. +// NewNotFoundErr creates a new instance of NotFoundErr from an error. func NewNotFoundErr(err error) *NotFoundErr { return &NotFoundErr{err} } -// NewNotFoundErrf creates a new NotFoundErr with a formatted message. -func NewNotFoundErrf(format string, a ...any) *NotFoundErr { - return &NotFoundErr{fmt.Errorf(format, a...)} -} - -// BecknError converts NotFoundErr into a Beckn-compliant Error response. +// BecknError converts the NotFoundErr to an instance of Error. func (e *NotFoundErr) BecknError() *Error { return &Error{ Code: http.StatusText(http.StatusNotFound), diff --git a/pkg/model/error_test.go b/pkg/model/error_test.go new file mode 100644 index 0000000..ee295e6 --- /dev/null +++ b/pkg/model/error_test.go @@ -0,0 +1,200 @@ +package model + +import ( + "errors" + "fmt" + "testing" + "net/http" + + "github.com/stretchr/testify/assert" + "gopkg.in/yaml.v2" +) + +// NewSignValidationErrf creates a new SignValidationErr with a formatted error message. +func NewSignValidationErrf(format string, a ...any) *SignValidationErr { + return &SignValidationErr{fmt.Errorf(format, a...)} +} + +// NewNotFoundErrf creates a new NotFoundErr with a formatted error message. +func NewNotFoundErrf(format string, a ...any) *NotFoundErr { + return &NotFoundErr{fmt.Errorf(format, a...)} +} + +// NewBadReqErrf creates a new BadReqErr with a formatted error message. +func NewBadReqErrf(format string, a ...any) *BadReqErr { + return &BadReqErr{fmt.Errorf(format, a...)} +} + +func TestError_Error(t *testing.T) { + err := &Error{ + Code: "404", + Paths: "/api/v1/user", + Message: "User not found", + } + + expected := "Error: Code=404, Path=/api/v1/user, Message=User not found" + actual := err.Error() + + if actual != expected { + t.Errorf("err.Error() = %s, want %s", + actual, expected) + } + +} + +func TestSchemaValidationErr_Error(t *testing.T) { + schemaErr := &SchemaValidationErr{ + Errors: []Error{ + {Paths: "/user", Message: "Field required"}, + {Paths: "/email", Message: "Invalid format"}, + }, + } + + expected := "/user: Field required; /email: Invalid format" + actual := schemaErr.Error() + + if actual != expected { + t.Errorf("err.Error() = %s, want %s", + actual, expected) + } +} + +func TestSchemaValidationErr_BecknError(t *testing.T) { + schemaErr := &SchemaValidationErr{ + Errors: []Error{ + {Paths: "/user", Message: "Field required"}, + }, + } + + beErr := schemaErr.BecknError() + expected := "Bad Request" + if beErr.Code != expected { + t.Errorf("err.Error() = %s, want %s", + beErr.Code, expected) + } +} + +func TestSignValidationErr_BecknError(t *testing.T) { + signErr := NewSignValidationErr(errors.New("signature failed")) + beErr := signErr.BecknError() + + expectedMsg := "Signature Validation Error: signature failed" + if beErr.Message != expectedMsg { + t.Errorf("err.Error() = %s, want %s", + beErr.Message, expectedMsg) + } + +} + +func TestNewSignValidationErrf(t *testing.T) { + signErr := NewSignValidationErrf("error %s", "signature failed") + expected := "error signature failed" + if signErr.Error() != expected { + t.Errorf("err.Error() = %s, want %s", + signErr.Error(), expected) + } +} + +func TestNewSignValidationErr(t *testing.T) { + err := errors.New("signature error") + signErr := NewSignValidationErr(err) + + if signErr.Error() != err.Error() { + t.Errorf("err.Error() = %s, want %s", err.Error(), + signErr.Error()) + } +} + +func TestBadReqErr_BecknError(t *testing.T) { + badReqErr := NewBadReqErr(errors.New("invalid input")) + beErr := badReqErr.BecknError() + + expectedMsg := "BAD Request: invalid input" + if beErr.Message != expectedMsg { + t.Errorf("err.Error() = %s, want %s", + beErr.Message, expectedMsg) + } +} + +func TestNewBadReqErrf(t *testing.T) { + badReqErr := NewBadReqErrf("invalid field %s", "name") + expected := "invalid field name" + if badReqErr.Error() != expected { + t.Errorf("err.Error() = %s, want %s", + badReqErr, expected) + } +} + +func TestNewBadReqErr(t *testing.T) { + err := errors.New("bad request") + badReqErr := NewBadReqErr(err) + + if badReqErr.Error() != err.Error() { + t.Errorf("err.Error() = %s, want %s", + badReqErr.Error(), err.Error()) + } + +} + +func TestNotFoundErr_BecknError(t *testing.T) { + notFoundErr := NewNotFoundErr(errors.New("resource not found")) + beErr := notFoundErr.BecknError() + + expectedMsg := "Endpoint not found: resource not found" + if beErr.Message != expectedMsg { + t.Errorf("err.Error() = %s, want %s", + beErr.Message, expectedMsg) + } +} + +func TestNewNotFoundErrf(t *testing.T) { + notFoundErr := NewNotFoundErrf("resource %s not found", "user") + expected := "resource user not found" + if notFoundErr.Error() != expected { + t.Errorf("err.Error() = %s, want %s", + notFoundErr.Error(), expected) + } +} + +func TestNewNotFoundErr(t *testing.T) { + err := errors.New("not found") + notFoundErr := NewNotFoundErr(err) + + if notFoundErr.Error() != err.Error() { + t.Errorf("err.Error() = %s, want %s", + notFoundErr.Error(), err.Error()) + } +} + +func TestRole_UnmarshalYAML_ValidRole(t *testing.T) { + var role Role + yamlData := []byte("bap") + + err := yaml.Unmarshal(yamlData, &role) + assert.NoError(t, err) //TODO: should replace assert here + assert.Equal(t, RoleBAP, role) +} + +func TestRole_UnmarshalYAML_InvalidRole(t *testing.T) { + var role Role + yamlData := []byte("invalid") + + err := yaml.Unmarshal(yamlData, &role) + assert.Error(t, err) + assert.Contains(t, err.Error(), "invalid Role") +} + +func TestSchemaValidationErr_BecknError_NoErrors(t *testing.T) { + schemaValidationErr := &SchemaValidationErr{Errors: nil} + beErr := schemaValidationErr.BecknError() + + expectedMsg := "Schema validation error." + expectedCode := http.StatusText(http.StatusBadRequest) + + if beErr.Message != expectedMsg { + t.Errorf("beErr.Message = %s, want %s", beErr.Message, expectedMsg) + } + if beErr.Code != expectedCode { + t.Errorf("beErr.Code = %s, want %s", beErr.Code, expectedCode) + } +} diff --git a/pkg/model/model.go b/pkg/model/model.go index 38a68ab..c9876bf 100644 --- a/pkg/model/model.go +++ b/pkg/model/model.go @@ -38,27 +38,19 @@ const ( UnaAuthorizedHeaderGateway string = "Proxy-Authenticate" ) -// MsgIDKey represents the key for the message ID. -const MsgIDKey = "message_id" +type contextKey string + +const MsgIDKey = contextKey("message_id") -// Role defines different roles in the network. type Role string const ( - // RoleBAP represents a Buyer App Participant. - RoleBAP Role = "bap" - - // RoleBPP represents a Buyer Platform Participant. - RoleBPP Role = "bpp" - - // RoleGateway represents a Network Gateway. - RoleGateway Role = "gateway" - - // RoleRegistery represents a Registry Service. + RoleBAP Role = "bap" + RoleBPP Role = "bpp" + RoleGateway Role = "gateway" RoleRegistery Role = "registery" ) -// validRoles ensures only allowed values are accepted var validRoles = map[Role]bool{ RoleBAP: true, RoleBPP: true, @@ -99,28 +91,20 @@ type StepContext struct { RespHeader http.Header } -// WithContext updates the context in StepContext while keeping other fields unchanged. func (ctx *StepContext) WithContext(newCtx context.Context) { - ctx.Context = newCtx // Update the existing context, keeping all other fields unchanged. + ctx.Context = newCtx } -// Status represents the status of an acknowledgment. type Status string const ( - // StatusACK indicates a successful acknowledgment. - StatusACK Status = "ACK" - - // StatusNACK indicates a negative acknowledgment. + StatusACK Status = "ACK" StatusNACK Status = "NACK" ) -// Ack represents an acknowledgment response. type Ack struct { - Status Status `json:"status"` // ACK or NACK + Status Status `json:"status"` } - -// Message represents the message object in the response. type Message struct { Ack Ack `json:"ack"` Error *Error `json:"error,omitempty"` diff --git a/pkg/plugin/definition/router.go b/pkg/plugin/definition/router.go index 5e3f034..05e2e30 100644 --- a/pkg/plugin/definition/router.go +++ b/pkg/plugin/definition/router.go @@ -3,14 +3,22 @@ package definition import ( "context" "net/url" - - "github.com/beckn/beckn-onix/pkg/model" ) -type Router interface { - Route(ctx context.Context, url *url.URL, body []byte) (*model.Route, error) +// Route defines the structure for the Route returned. +type Route struct { + TargetType string // "url" or "msgq" or "bap" or "bpp" + PublisherID string // For message queues + URL *url.URL // For API calls } +// RouterProvider initializes the a new Router instance with the given config. type RouterProvider interface { - New(ctx context.Context, cfg map[string]string) (Router, error) + New(ctx context.Context, config map[string]string) (Router, func() error, error) +} + +// Router defines the interface for routing requests. +type Router interface { + // Route determines the routing destination based on the request context. + Route(ctx context.Context, url *url.URL, body []byte) (*Route, error) } diff --git a/pkg/plugin/definition/schemaValidator.go b/pkg/plugin/definition/schemaValidator.go index d12fbd9..dc69ca5 100644 --- a/pkg/plugin/definition/schemaValidator.go +++ b/pkg/plugin/definition/schemaValidator.go @@ -7,7 +7,7 @@ import ( // SchemaValidator interface for schema validation. type SchemaValidator interface { - Validate(ctx context.Context, url *url.URL, reqBody []byte) error + Validate(ctx context.Context, url *url.URL, payload []byte) error } // SchemaValidatorProvider interface for creating validators. diff --git a/pkg/plugin/implementation/requestPreProcessor/cmd/plugin.go b/pkg/plugin/implementation/requestPreProcessor/cmd/plugin.go new file mode 100644 index 0000000..4a05ecc --- /dev/null +++ b/pkg/plugin/implementation/requestPreProcessor/cmd/plugin.go @@ -0,0 +1,21 @@ +package main + +import ( + "context" + "net/http" + "strings" + + requestpreprocessor "github.com/beckn/beckn-onix/pkg/plugin/implementation/requestPreProcessor" +) + +type provider struct{} + +func (p provider) New(ctx context.Context, c map[string]string) (func(http.Handler) http.Handler, error) { + config := &requestpreprocessor.Config{} + if contextKeysStr, ok := c["ContextKeys"]; ok { + config.ContextKeys = strings.Split(contextKeysStr, ",") + } + return requestpreprocessor.NewUUIDSetter(config) +} + +var Provider = provider{} diff --git a/pkg/plugin/implementation/requestPreProcessor/cmd/plugin_test.go b/pkg/plugin/implementation/requestPreProcessor/cmd/plugin_test.go new file mode 100644 index 0000000..0890dbc --- /dev/null +++ b/pkg/plugin/implementation/requestPreProcessor/cmd/plugin_test.go @@ -0,0 +1,85 @@ +package main + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TODO: Will Split this into success and fail (two test cases) +func TestProviderNew(t *testing.T) { + testCases := []struct { + name string + config map[string]string + expectedError bool + expectedStatus int + prepareRequest func(req *http.Request) + }{ + { + name: "No Config", + config: map[string]string{}, + expectedError: true, + expectedStatus: http.StatusOK, + prepareRequest: func(req *http.Request) { + // Add minimal required headers. + req.Header.Set("context", "test-context") + req.Header.Set("transaction_id", "test-transaction") + }, + }, + { + name: "With Check Keys", + config: map[string]string{ + "ContextKeys": "message_id,transaction_id", + }, + expectedError: false, + expectedStatus: http.StatusOK, + prepareRequest: func(req *http.Request) { + // Add headers matching the check keys. + req.Header.Set("context", "test-context") + req.Header.Set("transaction_id", "test-transaction") + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + requestBody := `{ + "context": { + "transaction_id": "abc" + } + }` + + p := provider{} + middleware, err := p.New(context.Background(), tc.config) + if tc.expectedError { + assert.Error(t, err) + return + } + require.NoError(t, err) + assert.NotNil(t, middleware) + + testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + req := httptest.NewRequest("POST", "/", strings.NewReader(requestBody)) + req.Header.Set("Content-Type", "application/json") + if tc.prepareRequest != nil { + tc.prepareRequest(req) + } + + w := httptest.NewRecorder() + middlewaredHandler := middleware(testHandler) + middlewaredHandler.ServeHTTP(w, req) + assert.Equal(t, tc.expectedStatus, w.Code, "Unexpected response status") + responseBody := w.Body.String() + t.Logf("Response Body: %s", responseBody) + + }) + } +} diff --git a/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor.go b/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor.go new file mode 100644 index 0000000..13d4da0 --- /dev/null +++ b/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor.go @@ -0,0 +1,105 @@ +package requestpreprocessor + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + + "github.com/google/uuid" +) + +type Config struct { + ContextKeys []string + Role string +} + +type becknRequest struct { + Context map[string]any `json:"context"` +} + +type contextKeyType string + +const contextKey = "context" +const subscriberIDKey contextKeyType = "subscriber_id" + +func NewUUIDSetter(cfg *Config) (func(http.Handler) http.Handler, error) { + if err := validateConfig(cfg); err != nil { + return nil, err + } + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var req becknRequest + if err := json.Unmarshal(body, &req); err != nil { + http.Error(w, "Failed to decode request body", http.StatusBadRequest) + return + } + if req.Context == nil { + http.Error(w, fmt.Sprintf("%s field not found.", contextKey), http.StatusBadRequest) + return + } + var subID any + switch cfg.Role { + case "bap": + subID = req.Context["bap_id"] + case "bpp": + subID = req.Context["bpp_id"] + } + ctx := context.WithValue(r.Context(), subscriberIDKey, subID) + for _, key := range cfg.ContextKeys { + value := uuid.NewString() + updatedValue := update(req.Context, key, value) + ctx = context.WithValue(ctx, contextKeyType(key), updatedValue) + } + reqData := map[string]any{"context": req.Context} + updatedBody, _ := json.Marshal(reqData) + r.Body = io.NopCloser(bytes.NewBuffer(updatedBody)) + r.ContentLength = int64(len(updatedBody)) + r = r.WithContext(ctx) + next.ServeHTTP(w, r) + }) + }, nil +} + +func update(wrapper map[string]any, key string, value any) any { + field, exists := wrapper[key] + if !exists || isEmpty(field) { + wrapper[key] = value + return value + } + + return field +} +func isEmpty(v any) bool { + switch v := v.(type) { + case string: + return v == "" + case nil: + return true + default: + return false + } +} + +func validateConfig(cfg *Config) error { + if cfg == nil { + return errors.New("config cannot be nil") + } + + // Check if ContextKeys is empty. + if len(cfg.ContextKeys) == 0 { + return errors.New("ContextKeys cannot be empty") + } + + // Validate that ContextKeys does not contain empty strings. + for _, key := range cfg.ContextKeys { + if key == "" { + return errors.New("ContextKeys cannot contain empty strings") + } + } + return nil +} diff --git a/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor_test.go b/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor_test.go new file mode 100644 index 0000000..307a7e7 --- /dev/null +++ b/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor_test.go @@ -0,0 +1,178 @@ +package requestpreprocessor + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +func TestNewUUIDSetterSuccessCases(t *testing.T) { + tests := []struct { + name string + config *Config + requestBody map[string]any + expectedKeys []string + role string + }{ + { + name: "Valid keys, update missing keys with bap role", + config: &Config{ + ContextKeys: []string{"transaction_id", "message_id"}, + Role: "bap", + }, + requestBody: map[string]any{ + "context": map[string]any{ + "transaction_id": "", + "message_id": nil, + "bap_id": "bap-123", + }, + }, + expectedKeys: []string{"transaction_id", "message_id", "bap_id"}, + role: "bap", + }, + { + name: "Valid keys, do not update existing keys with bpp role", + config: &Config{ + ContextKeys: []string{"transaction_id", "message_id"}, + Role: "bpp", + }, + requestBody: map[string]any{ + "context": map[string]any{ + "transaction_id": "existing-transaction", + "message_id": "existing-message", + "bpp_id": "bpp-456", + }, + }, + expectedKeys: []string{"transaction_id", "message_id", "bpp_id"}, + role: "bpp", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + middleware, err := NewUUIDSetter(tt.config) + if err != nil { + t.Fatalf("Unexpected error while creating middleware: %v", err) + } + + bodyBytes, _ := json.Marshal(tt.requestBody) + req := httptest.NewRequest(http.MethodPost, "/test", bytes.NewReader(bodyBytes)) + req.Header.Set("Content-Type", "application/json") + + rec := httptest.NewRecorder() + + dummyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + w.WriteHeader(http.StatusOK) + + subID, ok := ctx.Value(subscriberIDKey).(string) + if !ok { + http.Error(w, "Subscriber ID not found", http.StatusInternalServerError) + return + } + + response := map[string]any{"subscriber_id": subID} + if err := json.NewEncoder(w).Encode(response); err != nil { + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + }) + + middleware(dummyHandler).ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Errorf("Expected status code 200, but got %d", rec.Code) + return + } + + var responseBody map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &responseBody); err != nil { + t.Fatal("Failed to unmarshal response body:", err) + } + + expectedSubIDKey := "bap_id" + if tt.role == "bpp" { + expectedSubIDKey = "bpp_id" + } + + subID, ok := responseBody["subscriber_id"].(string) + if !ok { + t.Error("subscriber_id not found in response") + return + } + + expectedSubID := tt.requestBody["context"].(map[string]any)[expectedSubIDKey] + if subID != expectedSubID { + t.Errorf("Expected subscriber_id %v, but got %v", expectedSubID, subID) + } + }) + } +} + +func TestNewUUIDSetterErrorCases(t *testing.T) { + tests := []struct { + name string + config *Config + requestBody map[string]any + expectedCode int + }{ + { + name: "Missing context key", + config: &Config{ + ContextKeys: []string{"transaction_id"}, + }, + requestBody: map[string]any{ + "otherKey": "value", + }, + expectedCode: http.StatusBadRequest, + }, + { + name: "Invalid context type", + config: &Config{ + ContextKeys: []string{"transaction_id"}, + }, + requestBody: map[string]any{ + "context": "not-a-map", + }, + expectedCode: http.StatusBadRequest, + }, + { + name: "Nil config", + config: nil, + requestBody: map[string]any{}, + expectedCode: http.StatusInternalServerError, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + middleware, err := NewUUIDSetter(tt.config) + if tt.config == nil { + if err == nil { + t.Error("Expected an error for nil config, but got none") + } + return + } + if err != nil { + t.Fatalf("Unexpected error while creating middleware: %v", err) + } + + bodyBytes, _ := json.Marshal(tt.requestBody) + req := httptest.NewRequest(http.MethodPost, "/test", bytes.NewReader(bodyBytes)) + req.Header.Set("Content-Type", "application/json") + + rec := httptest.NewRecorder() + dummyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + middleware(dummyHandler).ServeHTTP(rec, req) + + if rec.Code != tt.expectedCode { + t.Errorf("Expected status code %d, but got %d", tt.expectedCode, rec.Code) + } + }) + } +} diff --git a/pkg/plugin/implementation/router/cmd/plugin.go b/pkg/plugin/implementation/router/cmd/plugin.go new file mode 100644 index 0000000..556f129 --- /dev/null +++ b/pkg/plugin/implementation/router/cmd/plugin.go @@ -0,0 +1,31 @@ +package main + +import ( + "context" + "errors" + + definition "github.com/beckn/beckn-onix/pkg/plugin/definition" + router "github.com/beckn/beckn-onix/pkg/plugin/implementation/router" +) + +// RouterProvider provides instances of Router. +type RouterProvider struct{} + +// New initializes a new Router instance. +func (rp RouterProvider) New(ctx context.Context, config map[string]string) (definition.Router, func() error, error) { + if ctx == nil { + return nil, nil, errors.New("context cannot be nil") + } + + // Parse the routingConfig key from the config map + routingConfig, ok := config["routingConfig"] + if !ok { + return nil, nil, errors.New("routingConfig is required in the configuration") + } + return router.New(ctx, &router.Config{ + RoutingConfig: routingConfig, + }) +} + +// Provider is the exported symbol that the plugin manager will look for. +var Provider = RouterProvider{} diff --git a/pkg/plugin/implementation/router/cmd/plugin_test.go b/pkg/plugin/implementation/router/cmd/plugin_test.go new file mode 100644 index 0000000..c5ffe8e --- /dev/null +++ b/pkg/plugin/implementation/router/cmd/plugin_test.go @@ -0,0 +1,101 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// setupTestConfig creates a temporary directory and writes a sample routing rules file. +func setupTestConfig(t *testing.T) string { + t.Helper() + + // Get project root (assuming testData is in project root) + _, filename, _, _ := runtime.Caller(0) // Path to plugin_test.go + projectRoot := filepath.Dir(filepath.Dir(filename)) // Move up from cmd/ + yamlPath := filepath.Join(projectRoot, "testData", "bap_receiver.yaml") + + // Copy to temp file (to test file loading logic) + tempDir := t.TempDir() + tempPath := filepath.Join(tempDir, "routingRules.yaml") + content, err := os.ReadFile(yamlPath) + if err != nil { + t.Fatalf("Failed to read test file: %v", err) + } + if err := os.WriteFile(tempPath, content, 0644); err != nil { + t.Fatalf("Failed to create temp config: %v", err) + } + + return tempPath +} + +// TestRouterProviderSuccess tests successful router creation. +func TestRouterProviderSuccess(t *testing.T) { + rulesFilePath := setupTestConfig(t) + defer os.RemoveAll(filepath.Dir(rulesFilePath)) + + provider := RouterProvider{} + router, _, err := provider.New(context.Background(), map[string]string{ + "routingConfig": rulesFilePath, + }) + + if err != nil { + t.Fatalf("New() unexpected error: %v", err) + } + if router == nil { + t.Error("New() returned nil router, want non-nil") + } +} + +// TestRouterProviderFailure tests the RouterProvider implementation for failure cases. +func TestRouterProviderFailure(t *testing.T) { + rulesFilePath := setupTestConfig(t) + defer os.RemoveAll(filepath.Dir(rulesFilePath)) + + // Define test cases + tests := []struct { + name string + ctx context.Context + config map[string]string + wantErr string + }{ + { + name: "Empty routing config path", + ctx: context.Background(), + config: map[string]string{ + "routingConfig": "", + }, + wantErr: "failed to load routing rules: routingConfig path is empty", + }, + { + name: "Missing routing config key", + ctx: context.Background(), + config: map[string]string{}, + wantErr: "routingConfig is required in the configuration", + }, + { + name: "Nil context", + ctx: nil, + config: map[string]string{"routingConfig": rulesFilePath}, + wantErr: "context cannot be nil", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + provider := RouterProvider{} + _, _, err := provider.New(tt.ctx, tt.config) + + // Check for expected error + if err == nil { + t.Fatalf("New(%v, %v) = nil error, want error containing %q", tt.ctx, tt.config, tt.wantErr) + } + if !strings.Contains(err.Error(), tt.wantErr) { + t.Errorf("New(%v, %v) = %v, want error containing %q", tt.ctx, tt.config, err, tt.wantErr) + } + }) + } +} diff --git a/pkg/plugin/implementation/router/router.go b/pkg/plugin/implementation/router/router.go new file mode 100644 index 0000000..9d16767 --- /dev/null +++ b/pkg/plugin/implementation/router/router.go @@ -0,0 +1,275 @@ +package router + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "os" + "path" + "strings" + + definition "github.com/beckn/beckn-onix/pkg/plugin/definition" + + "gopkg.in/yaml.v3" +) + +// Config holds the configuration for the Router plugin. +type Config struct { + RoutingConfig string `json:"routingConfig"` +} + +// RoutingConfig represents the structure of the routing configuration file. +type routingConfig struct { + RoutingRules []routingRule `yaml:"routingRules"` +} + +// Router implements Router interface. +type Router struct { + rules map[string]map[string]map[string]*definition.Route // domain -> version -> endpoint -> route +} + +// RoutingRule represents a single routing rule. +type routingRule struct { + Domain string `yaml:"domain"` + Version string `yaml:"version"` + TargetType string `yaml:"targetType"` // "url", "publisher", "bpp", or "bap" + Target target `yaml:"target,omitempty"` + Endpoints []string `yaml:"endpoints"` +} + +// Target contains destination-specific details. +type target struct { + URL string `yaml:"url,omitempty"` // URL for "url" or gateway endpoint for "bpp"/"bap" + PublisherID string `yaml:"publisherId,omitempty"` // For "msgq" type +} + +// TargetType defines possible target destinations. +const ( + targetTypeURL = "url" // Route to a specific URL + targetTypePublisher = "publisher" // Route to a publisher + targetTypeBPP = "bpp" // Route to a BPP endpoint + targetTypeBAP = "bap" // Route to a BAP endpoint +) + +// New initializes a new Router instance with the provided configuration. +// It loads and validates the routing rules from the specified YAML file. +// Returns an error if the configuration is invalid or the rules cannot be loaded. +func New(ctx context.Context, config *Config) (*Router, func() error, error) { + // Check if config is nil + if config == nil { + return nil, nil, fmt.Errorf("config cannot be nil") + } + router := &Router{ + rules: make(map[string]map[string]map[string]*definition.Route), + } + + // Load rules at bootup + if err := router.loadRules(config.RoutingConfig); err != nil { + return nil, nil, fmt.Errorf("failed to load routing rules: %w", err) + } + return router, nil, nil +} + +// parseTargetURL parses a URL string into a url.URL object with strict validation +func parseTargetURL(urlStr string) (*url.URL, error) { + if urlStr == "" { + return nil, nil + } + + parsed, err := url.Parse(urlStr) + if err != nil { + return nil, fmt.Errorf("invalid URL '%s': %w", urlStr, err) + } + + // Enforce scheme requirement + if parsed.Scheme == "" { + return nil, fmt.Errorf("URL '%s' must include a scheme (http/https)", urlStr) + } + + // Optionally validate scheme is http or https + if parsed.Scheme != "https" { + return nil, fmt.Errorf("URL '%s' must use https scheme", urlStr) + } + + return parsed, nil +} + +// LoadRules reads and parses routing rules from the YAML configuration file. +func (r *Router) loadRules(configPath string) error { + if configPath == "" { + return fmt.Errorf("routingConfig path is empty") + } + data, err := os.ReadFile(configPath) + if err != nil { + return fmt.Errorf("error reading config file at %s: %w", configPath, err) + } + var config routingConfig + if err := yaml.Unmarshal(data, &config); err != nil { + return fmt.Errorf("error parsing YAML: %w", err) + } + + // Validate rules + if err := validateRules(config.RoutingRules); err != nil { + return fmt.Errorf("invalid routing rules: %w", err) + } + // Build the optimized rule map + for _, rule := range config.RoutingRules { + // Initialize domain map if not exists + if _, ok := r.rules[rule.Domain]; !ok { + r.rules[rule.Domain] = make(map[string]map[string]*definition.Route) + } + + // Initialize version map if not exists + if _, ok := r.rules[rule.Domain][rule.Version]; !ok { + r.rules[rule.Domain][rule.Version] = make(map[string]*definition.Route) + } + + // Add all endpoints for this rule + for _, endpoint := range rule.Endpoints { + var route *definition.Route + switch rule.TargetType { + case targetTypePublisher: + route = &definition.Route{ + TargetType: rule.TargetType, + PublisherID: rule.Target.PublisherID, + } + case targetTypeURL: + parsedURL, err := parseTargetURL(rule.Target.URL) + if err != nil { + return fmt.Errorf("invalid URL in rule: %w", err) + } + route = &definition.Route{ + TargetType: rule.TargetType, + URL: parsedURL, + } + case targetTypeBPP, targetTypeBAP: + var parsedURL *url.URL + if rule.Target.URL != "" { + parsedURL, err = parseTargetURL(rule.Target.URL) + if err != nil { + return fmt.Errorf("invalid URL in rule: %w", err) + } + } + route = &definition.Route{ + TargetType: rule.TargetType, + URL: parsedURL, + } + } + r.rules[rule.Domain][rule.Version][endpoint] = route + } + } + + return nil +} + +// validateRules performs basic validation on the loaded routing rules. +func validateRules(rules []routingRule) error { + for _, rule := range rules { + // Ensure domain, version, and TargetType are present + if rule.Domain == "" || rule.Version == "" || rule.TargetType == "" { + return fmt.Errorf("invalid rule: domain, version, and targetType are required") + } + + // Validate based on TargetType + switch rule.TargetType { + case targetTypeURL: + if rule.Target.URL == "" { + return fmt.Errorf("invalid rule: url is required for targetType 'url'") + } + if _, err := parseTargetURL(rule.Target.URL); err != nil { + return fmt.Errorf("invalid URL - %s: %w", rule.Target.URL, err) + } + case targetTypePublisher: + if rule.Target.PublisherID == "" { + return fmt.Errorf("invalid rule: publisherID is required for targetType 'publisher'") + } + case targetTypeBPP, targetTypeBAP: + if rule.Target.URL != "" { + if _, err := parseTargetURL(rule.Target.URL); err != nil { + return fmt.Errorf("invalid URL - %s defined in routing config for target type %s: %w", rule.Target.URL, rule.TargetType, err) + } + } + continue + default: + return fmt.Errorf("invalid rule: unknown targetType '%s'", rule.TargetType) + } + } + return nil +} + +// Route determines the routing destination based on the request context. +func (r *Router) Route(ctx context.Context, url *url.URL, body []byte) (*definition.Route, error) { + + // Parse the body to extract domain and version + var requestBody struct { + Context struct { + Domain string `json:"domain"` + Version string `json:"version"` + BPPURI string `json:"bpp_uri,omitempty"` + BAPURI string `json:"bap_uri,omitempty"` + } `json:"context"` + } + if err := json.Unmarshal(body, &requestBody); err != nil { + return nil, fmt.Errorf("error parsing request body: %w", err) + } + + // Extract the endpoint from the URL + endpoint := path.Base(url.Path) + + // Lookup route in the optimized map + domainRules, ok := r.rules[requestBody.Context.Domain] + if !ok { + return nil, fmt.Errorf("no routing rules found for domain %s", requestBody.Context.Domain) + } + + versionRules, ok := domainRules[requestBody.Context.Version] + if !ok { + return nil, fmt.Errorf("no routing rules found for domain %s version %s", requestBody.Context.Domain, requestBody.Context.Version) + } + + route, ok := versionRules[endpoint] + if !ok { + return nil, fmt.Errorf("endpoint '%s' is not supported for domain %s and version %s in routing config", + endpoint, requestBody.Context.Domain, requestBody.Context.Version) + } + // Handle BPP/BAP routing with request URIs + switch route.TargetType { + case targetTypeBPP: + return handleProtocolMapping(route, requestBody.Context.BPPURI, endpoint) + case targetTypeBAP: + return handleProtocolMapping(route, requestBody.Context.BAPURI, endpoint) + } + return route, nil +} + +// handleProtocolMapping handles both BPP and BAP routing with proper URL construction +func handleProtocolMapping(route *definition.Route, requestURI, endpoint string) (*definition.Route, error) { + uri := strings.TrimSpace(requestURI) + var targetURL *url.URL + if len(uri) != 0 { + parsedURL, err := parseTargetURL(uri) + if err != nil { + return nil, fmt.Errorf("invalid %s URI - %s in request body for %s: %w", strings.ToUpper(route.TargetType), uri, endpoint, err) + } + targetURL = parsedURL + } + + // If no request URI, fall back to configured URL with endpoint appended + if targetURL == nil { + if route.URL == nil { + return nil, fmt.Errorf("could not determine destination for endpoint '%s': neither request contained a %s URI nor was a default URL configured in routing rules", endpoint, strings.ToUpper(route.TargetType)) + } + + targetURL = &url.URL{ + Scheme: route.URL.Scheme, + Host: route.URL.Host, + Path: path.Join(route.URL.Path, endpoint), + } + } + + return &definition.Route{ + TargetType: targetTypeURL, + URL: targetURL, + }, nil +} diff --git a/pkg/plugin/implementation/router/router_test.go b/pkg/plugin/implementation/router/router_test.go new file mode 100644 index 0000000..7937ca5 --- /dev/null +++ b/pkg/plugin/implementation/router/router_test.go @@ -0,0 +1,486 @@ +package router + +import ( + "context" + "embed" + "net/url" + "os" + "path/filepath" + "strings" + "testing" +) + +//go:embed testData/* +var testData embed.FS + +func setupTestConfig(t *testing.T, yamlFileName string) string { + t.Helper() + configDir := t.TempDir() + + content, err := testData.ReadFile("testData/" + yamlFileName) + if err != nil { + t.Fatalf("ReadFile() err = %v, want nil", err) + } + + rulesPath := filepath.Join(configDir, "routing_rules.yaml") + if err := os.WriteFile(rulesPath, content, 0644); err != nil { + t.Fatalf("WriteFile() err = %v, want nil", err) + } + + return rulesPath +} + +// setupRouter is a helper function to create router instance. +func setupRouter(t *testing.T, configFile string) (*Router, func() error, string) { + rulesFilePath := setupTestConfig(t, configFile) + config := &Config{ + RoutingConfig: rulesFilePath, + } + router, _, err := New(context.Background(), config) + if err != nil { + t.Fatalf("New failed: %v", err) + } + return router, nil, rulesFilePath +} + +// TestNew tests the New function. +func TestNew(t *testing.T) { + ctx := context.Background() + + // List of YAML files in the testData directory + yamlFiles := []string{ + "bap_caller.yaml", + "bap_receiver.yaml", + "bpp_caller.yaml", + "bpp_receiver.yaml", + } + + for _, yamlFile := range yamlFiles { + t.Run(yamlFile, func(t *testing.T) { + rulesFilePath := setupTestConfig(t, yamlFile) + defer os.RemoveAll(filepath.Dir(rulesFilePath)) + + // Define test cases + tests := []struct { + name string + config *Config + wantErr string + }{ + { + name: "Valid configuration", + config: &Config{ + RoutingConfig: rulesFilePath, + }, + wantErr: "", + }, + { + name: "Empty config", + config: nil, + wantErr: "config cannot be nil", + }, + { + name: "Empty routing config path", + config: &Config{ + RoutingConfig: "", + }, + wantErr: "routingConfig path is empty", + }, + { + name: "Routing config file does not exist", + config: &Config{ + RoutingConfig: "/nonexistent/path/to/rules.yaml", + }, + wantErr: "error reading config file", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + router, _, err := New(ctx, tt.config) + + // Check for expected error + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Errorf("New(%v) = %v, want error containing %q", tt.config, err, tt.wantErr) + } + return + } + + // Ensure no error occurred + if err != nil { + t.Errorf("New(%v) = %v, want nil error", tt.config, err) + return + } + + // Ensure the router and close function are not nil + if router == nil { + t.Errorf("New(%v, %v) = nil router, want non-nil", ctx, tt.config) + } + }) + } + }) + } +} + +// TestValidateRulesSuccess tests the validate function for success cases. +func TestValidateRulesSuccess(t *testing.T) { + tests := []struct { + name string + rules []routingRule + }{ + { + name: "Valid rules with url routing", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "url", + Target: target{ + URL: "https://example.com/api", + }, + Endpoints: []string{"on_search", "on_select"}, + }, + }, + }, + { + name: "Valid rules with publisher routing", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "publisher", + Target: target{ + PublisherID: "example_topic", + }, + Endpoints: []string{"on_search", "on_select"}, + }, + }, + }, + { + name: "Valid rules with bpp routing to gateway", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "bpp", + Target: target{ + URL: "https://mock_gateway.com/api", + }, + Endpoints: []string{"search"}, + }, + }, + }, + { + name: "Valid rules with bpp routing", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "bpp", + Endpoints: []string{"select"}, + }, + }, + }, + { + name: "Valid rules with bap routing", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "bap", + Endpoints: []string{"select"}, + }, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateRules(tt.rules) + if err != nil { + t.Errorf("validateRules(%v) = %v, want nil error", tt.rules, err) + } + }) + } +} + +// TestValidateRulesFailure tests the validate function for failure cases. +func TestValidateRulesFailure(t *testing.T) { + tests := []struct { + name string + rules []routingRule + wantErr string + }{ + { + name: "Missing domain", + rules: []routingRule{ + { + Version: "1.0.0", + TargetType: "url", + Target: target{ + URL: "https://example.com/api", + }, + Endpoints: []string{"search", "select"}, + }, + }, + wantErr: "invalid rule: domain, version, and targetType are required", + }, + { + name: "Missing version", + rules: []routingRule{ + { + Domain: "retail", + TargetType: "url", + Target: target{ + URL: "https://example.com/api", + }, + Endpoints: []string{"search", "select"}, + }, + }, + wantErr: "invalid rule: domain, version, and targetType are required", + }, + { + name: "Missing targetType", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + Target: target{ + URL: "https://example.com/api", + }, + Endpoints: []string{"search", "select"}, + }, + }, + wantErr: "invalid rule: domain, version, and targetType are required", + }, + { + name: "Invalid targetType", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "invalid", + Target: target{ + URL: "https://example.com/api", + }, + Endpoints: []string{"search", "select"}, + }, + }, + wantErr: "invalid rule: unknown targetType 'invalid'", + }, + { + name: "Missing url for targetType: url", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "url", + Target: target{ + // URL is missing + }, + Endpoints: []string{"search", "select"}, + }, + }, + wantErr: "invalid rule: url is required for targetType 'url'", + }, + { + name: "Invalid URL format for targetType: url", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "url", + Target: target{ + URL: "htp://invalid-url.com", // Invalid scheme + }, + Endpoints: []string{"search"}, + }, + }, + wantErr: "invalid URL - htp://invalid-url.com: URL 'htp://invalid-url.com' must use https scheme", + }, + { + name: "Missing topic_id for targetType: publisher", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "publisher", + Target: target{ + // PublisherID is missing + }, + Endpoints: []string{"search", "select"}, + }, + }, + wantErr: "invalid rule: publisherID is required for targetType 'publisher'", + }, + { + name: "Invalid URL for BPP targetType", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "bpp", + Target: target{ + URL: "htp://invalid-url.com", // Invalid URL + }, + Endpoints: []string{"search"}, + }, + }, + wantErr: "invalid URL - htp://invalid-url.com defined in routing config for target type bpp", + }, + { + name: "Invalid URL for BAP targetType", + rules: []routingRule{ + { + Domain: "retail", + Version: "1.0.0", + TargetType: "bap", + Target: target{ + URL: "http://[invalid].com", // Invalid host + }, + Endpoints: []string{"search"}, + }, + }, + wantErr: "invalid URL - http://[invalid].com defined in routing config for target type bap", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateRules(tt.rules) + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Errorf("validateRules(%v) = %v, want error containing %q", tt.rules, err, tt.wantErr) + } + }) + } +} + +// TestRouteSuccess tests the Route function for success cases. +func TestRouteSuccess(t *testing.T) { + ctx := context.Background() + + // Define success test cases + tests := []struct { + name string + configFile string + url string + body string + }{ + { + name: "Valid domain, version, and endpoint (bpp routing with gateway URL)", + configFile: "bap_caller.yaml", + url: "https://example.com/v1/ondc/search", + body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0"}}`, + }, + { + name: "Valid domain, version, and endpoint (bpp routing with bpp_uri)", + configFile: "bap_caller.yaml", + url: "https://example.com/v1/ondc/select", + body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0", "bpp_uri": "https://bpp1.example.com"}}`, + }, + { + name: "Valid domain, version, and endpoint (url routing)", + configFile: "bpp_receiver.yaml", + url: "https://example.com/v1/ondc/select", + body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0"}}`, + }, + { + name: "Valid domain, version, and endpoint (publisher routing)", + configFile: "bpp_receiver.yaml", + url: "https://example.com/v1/ondc/search", + body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0"}}`, + }, + { + name: "Valid domain, version, and endpoint (bap routing with bap_uri)", + configFile: "bpp_caller.yaml", + url: "https://example.com/v1/ondc/on_select", + body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0", "bap_uri": "https://bap1.example.com"}}`, + }, + { + name: "Valid domain, version, and endpoint (bpp routing with bpp_uri)", + configFile: "bap_receiver.yaml", + url: "https://example.com/v1/ondc/on_select", + body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0", "bpp_uri": "https://bpp1.example.com"}}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + router, _, rulesFilePath := setupRouter(t, tt.configFile) + defer os.RemoveAll(filepath.Dir(rulesFilePath)) + + parsedURL, _ := url.Parse(tt.url) + _, err := router.Route(ctx, parsedURL, []byte(tt.body)) + + // Ensure no error occurred + if err != nil { + t.Errorf("router.Route(%v, %v, %v) = %v, want nil error", ctx, parsedURL, []byte(tt.body), err) + } + }) + } +} + +// TestRouteFailure tests the Route function for failure cases. +func TestRouteFailure(t *testing.T) { + ctx := context.Background() + + // Define failure test cases + tests := []struct { + name string + configFile string + url string + body string + wantErr string + }{ + { + name: "Unsupported endpoint", + configFile: "bpp_receiver.yaml", + url: "https://example.com/v1/ondc/unsupported", + body: `{"context": {"domain": "ONDC:TRV11", "version": "2.0.0"}}`, + wantErr: "endpoint 'unsupported' is not supported for domain ONDC:TRV11 and version 2.0.0", + }, + { + name: "No matching rule", + configFile: "bpp_receiver.yaml", + url: "https://example.com/v1/ondc/select", + body: `{"context": {"domain": "ONDC:SRV11", "version": "2.0.0"}}`, + wantErr: "no routing rules found for domain ONDC:SRV11", + }, + { + name: "Missing bap_uri for bap routing", + configFile: "bpp_caller.yaml", + url: "https://example.com/v1/ondc/on_search", + body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0"}}`, + wantErr: "could not determine destination for endpoint 'on_search': neither request contained a BAP URI nor was a default URL configured in routing rules", + }, + { + name: "Missing bpp_uri for bpp routing", + configFile: "bap_caller.yaml", + url: "https://example.com/v1/ondc/select", + body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0"}}`, + wantErr: "could not determine destination for endpoint 'select': neither request contained a BPP URI nor was a default URL configured in routing rules", + }, + { + name: "Invalid bpp_uri format in request", + configFile: "bap_caller.yaml", + url: "https://example.com/v1/ondc/select", + body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0", "bpp_uri": "htp://invalid-url"}}`, // Invalid scheme (htp instead of http) + wantErr: "invalid BPP URI - htp://invalid-url in request body for select: URL 'htp://invalid-url' must use https scheme", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + router, _, rulesFilePath := setupRouter(t, tt.configFile) + defer os.RemoveAll(filepath.Dir(rulesFilePath)) + + parsedURL, _ := url.Parse(tt.url) + _, err := router.Route(ctx, parsedURL, []byte(tt.body)) + + // Check for expected error + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Errorf("Route(%q, %q) = %v, want error containing %q", tt.url, tt.body, err, tt.wantErr) + } + }) + } +} diff --git a/pkg/plugin/implementation/router/testData/bap_caller.yaml b/pkg/plugin/implementation/router/testData/bap_caller.yaml new file mode 100644 index 0000000..6a40a0f --- /dev/null +++ b/pkg/plugin/implementation/router/testData/bap_caller.yaml @@ -0,0 +1,25 @@ +routingRules: + - domain: ONDC:TRV10 + version: 2.0.0 + targetType: bpp + target: + url: https://gateway.example.com + endpoints: + - search + - domain: ONDC:TRV10 + version: 2.0.0 + targetType: bpp + endpoints: + - select + - init + - confirm + - status + - cancel + - domain: ONDC:TRV12 + version: 2.0.0 + targetType: bpp + endpoints: + - select + - init + - confirm + - status \ No newline at end of file diff --git a/pkg/plugin/implementation/router/testData/bap_receiver.yaml b/pkg/plugin/implementation/router/testData/bap_receiver.yaml new file mode 100644 index 0000000..17432db --- /dev/null +++ b/pkg/plugin/implementation/router/testData/bap_receiver.yaml @@ -0,0 +1,20 @@ +routingRules: + - domain: ONDC:TRV10 + version: 2.0.0 + targetType: url + target: + url: https://services-backend/trv/v1 + endpoints: + - on_select + - on_init + - on_confirm + - on_status + - on_update + - on_cancel + - domain: ONDC:TRV10 + version: 2.0.0 + targetType: publisher + target: + publisherId: trv_topic_id1 + endpoints: + - on_search \ No newline at end of file diff --git a/pkg/plugin/implementation/router/testData/bpp_caller.yaml b/pkg/plugin/implementation/router/testData/bpp_caller.yaml new file mode 100644 index 0000000..339b92d --- /dev/null +++ b/pkg/plugin/implementation/router/testData/bpp_caller.yaml @@ -0,0 +1,23 @@ +routingRules: + - domain: ONDC:TRV10 + version: 2.0.0 + targetType: bap + endpoints: + - on_search + - on_select + - on_init + - on_confirm + - on_status + - on_update + - on_cancel + - domain: ONDC:TRV11 + version: 2.0.0 + targetType: bap + endpoints: + - on_search + - on_select + - on_init + - on_confirm + - on_status + - on_update + - on_cancel \ No newline at end of file diff --git a/pkg/plugin/implementation/router/testData/bpp_receiver.yaml b/pkg/plugin/implementation/router/testData/bpp_receiver.yaml new file mode 100644 index 0000000..7355592 --- /dev/null +++ b/pkg/plugin/implementation/router/testData/bpp_receiver.yaml @@ -0,0 +1,28 @@ +routingRules: + - domain: ONDC:TRV10 + version: 2.0.0 + targetType: url + target: + url: https://services-backend/trv/v1 + endpoints: + - select + - init + - confirm + - status + - cancel + - domain: ONDC:TRV10 + version: 2.0.0 + targetType: publisher + target: + publisherId: trv_topic_id1 + endpoints: + - search + - domain: ONDC:TRV11 + version: 2.0.0 + targetType: url + target: + url: https://services-backend/trv/v1 + endpoints: + - select + - init + - confirm \ No newline at end of file diff --git a/pkg/plugin/implementation/schemaValidator/cmd/plugin.go b/pkg/plugin/implementation/schemaValidator/cmd/plugin.go new file mode 100644 index 0000000..2a8f44a --- /dev/null +++ b/pkg/plugin/implementation/schemaValidator/cmd/plugin.go @@ -0,0 +1,33 @@ +package main + +import ( + "context" + "errors" + + definition "github.com/beckn/beckn-onix/pkg/plugin/definition" + schemaValidator "github.com/beckn/beckn-onix/pkg/plugin/implementation/schemaValidator" +) + +// schemaValidatorProvider provides instances of schemaValidator. +type schemaValidatorProvider struct{} + +// New initializes a new Verifier instance. +func (vp schemaValidatorProvider) New(ctx context.Context, config map[string]string) (definition.SchemaValidator, func() error, error) { + if ctx == nil { + return nil, nil, errors.New("context cannot be nil") + } + + // Extract schemaDir from the config map + schemaDir, ok := config["schemaDir"] + if !ok || schemaDir == "" { + return nil, nil, errors.New("config must contain 'schemaDir'") + } + + // Create a new schemaValidator instance with the provided configuration + return schemaValidator.New(ctx, &schemaValidator.Config{ + SchemaDir: schemaDir, + }) +} + +// Provider is the exported symbol that the plugin manager will look for. +var Provider definition.SchemaValidatorProvider = schemaValidatorProvider{} diff --git a/pkg/plugin/implementation/schemaValidator/cmd/plugin_test.go b/pkg/plugin/implementation/schemaValidator/cmd/plugin_test.go new file mode 100644 index 0000000..75fdce0 --- /dev/null +++ b/pkg/plugin/implementation/schemaValidator/cmd/plugin_test.go @@ -0,0 +1,150 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +// setupTestSchema creates a temporary directory and writes a sample schema file. +func setupTestSchema(t *testing.T) string { + t.Helper() + + // Create a temporary directory for the schema + schemaDir, err := os.MkdirTemp("", "schemas") + if err != nil { + t.Fatalf("Failed to create temp directory: %v", err) + } + + // Create the directory structure for the schema file + schemaFilePath := filepath.Join(schemaDir, "example", "1.0", "test_schema.json") + if err := os.MkdirAll(filepath.Dir(schemaFilePath), 0755); err != nil { + t.Fatalf("Failed to create schema directory structure: %v", err) + } + + // Define a sample schema + schemaContent := `{ + "type": "object", + "properties": { + "context": { + "type": "object", + "properties": { + "domain": {"type": "string"}, + "version": {"type": "string"} + }, + "required": ["domain", "version"] + } + }, + "required": ["context"] + }` + + // Write the schema to the file + if err := os.WriteFile(schemaFilePath, []byte(schemaContent), 0644); err != nil { + t.Fatalf("Failed to write schema file: %v", err) + } + + return schemaDir +} + +// TestValidatorProviderSuccess tests successful ValidatorProvider implementation. +func TestValidatorProviderSuccess(t *testing.T) { + schemaDir := setupTestSchema(t) + defer os.RemoveAll(schemaDir) + + // Define test cases. + tests := []struct { + name string + ctx context.Context + config map[string]string + expectedError string + }{ + { + name: "Valid schema directory", + ctx: context.Background(), // Valid context + config: map[string]string{"schemaDir": schemaDir}, + expectedError: "", + }, + } + + // Test using table-driven tests + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + vp := schemaValidatorProvider{} + schemaValidator, _, err := vp.New(tt.ctx, tt.config) + + // Ensure no error occurred + if err != nil { + t.Errorf("unexpected error: %v", err) + return + } + + // Ensure the schemaValidator is not nil + if schemaValidator == nil { + t.Error("expected a non-nil schemaValidator, got nil") + } + }) + } +} + +// TestValidatorProviderSuccess tests cases where ValidatorProvider creation should fail. +func TestValidatorProviderFailure(t *testing.T) { + schemaDir := setupTestSchema(t) + defer os.RemoveAll(schemaDir) + + // Define test cases. + tests := []struct { + name string + ctx context.Context + config map[string]string + expectedError string + }{ + { + name: "Config is empty", + ctx: context.Background(), + config: map[string]string{}, + expectedError: "config must contain 'schemaDir'", + }, + { + name: "schemaDir is empty", + ctx: context.Background(), + config: map[string]string{"schemaDir": ""}, + expectedError: "config must contain 'schemaDir'", + }, + { + name: "Invalid schema directory", + ctx: context.Background(), // Valid context + config: map[string]string{"schemaDir": "/invalid/dir"}, + expectedError: "failed to initialise schemaValidator: schema directory does not exist: /invalid/dir", + }, + { + name: "Nil context", + ctx: nil, // Nil context + config: map[string]string{"schemaDir": schemaDir}, + expectedError: "context cannot be nil", + }, + } + + // Test using table-driven tests + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + vp := schemaValidatorProvider{} + _, _, err := vp.New(tt.ctx, tt.config) + + // Check for expected error + if tt.expectedError != "" { + if err == nil || !strings.Contains(err.Error(), tt.expectedError) { + t.Errorf("expected error %q, got %v", tt.expectedError, err) + } + return + } + + // Ensure no error occurred + if err != nil { + t.Errorf("unexpected error: %v", err) + return + } + }) + } +} diff --git a/pkg/plugin/implementation/schemaValidator/schemaValidator.go b/pkg/plugin/implementation/schemaValidator/schemaValidator.go new file mode 100644 index 0000000..2d6b189 --- /dev/null +++ b/pkg/plugin/implementation/schemaValidator/schemaValidator.go @@ -0,0 +1,197 @@ +package schemaValidator + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "os" + "path" + "path/filepath" + "strings" + + response "github.com/beckn/beckn-onix/pkg/response" + + "github.com/santhosh-tekuri/jsonschema/v6" +) + +// Payload represents the structure of the data payload with context information. +type payload struct { + Context struct { + Domain string `json:"domain"` + Version string `json:"version"` + } `json:"context"` +} + +// SchemaValidator implements the Validator interface. +type SchemaValidator struct { + config *Config + schemaCache map[string]*jsonschema.Schema +} + +// Config struct for SchemaValidator. +type Config struct { + SchemaDir string +} + +// New creates a new ValidatorProvider instance. +func New(ctx context.Context, config *Config) (*SchemaValidator, func() error, error) { + // Check if config is nil + if config == nil { + return nil, nil, fmt.Errorf("config cannot be nil") + } + v := &SchemaValidator{ + config: config, + schemaCache: make(map[string]*jsonschema.Schema), + } + + // Call Initialise function to load schemas and get validators + if err := v.initialise(); err != nil { + return nil, nil, fmt.Errorf("failed to initialise schemaValidator: %v", err) + } + return v, nil, nil +} + +// Validate validates the given data against the schema. +func (v *SchemaValidator) Validate(ctx context.Context, url *url.URL, data []byte) error { + var payloadData payload + err := json.Unmarshal(data, &payloadData) + if err != nil { + return fmt.Errorf("failed to parse JSON payload: %v", err) + } + + // Extract domain, version, and endpoint from the payload and uri. + cxt_domain := payloadData.Context.Domain + version := payloadData.Context.Version + version = fmt.Sprintf("v%s", version) + + endpoint := path.Base(url.String()) + // ToDo Add debug log here + fmt.Println("Handling request for endpoint:", endpoint) + domain := strings.ToLower(cxt_domain) + domain = strings.ReplaceAll(domain, ":", "_") + + // Construct the schema file name. + schemaFileName := fmt.Sprintf("%s_%s_%s", domain, version, endpoint) + + // Retrieve the schema from the cache. + schema, exists := v.schemaCache[schemaFileName] + if !exists { + return fmt.Errorf("schema not found for domain: %s", schemaFileName) + } + + var jsonData any + if err := json.Unmarshal(data, &jsonData); err != nil { + return fmt.Errorf("failed to parse JSON data: %v", err) + } + err = schema.Validate(jsonData) + if err != nil { + // Handle schema validation errors + if validationErr, ok := err.(*jsonschema.ValidationError); ok { + // Convert validation errors into an array of SchemaValError + var schemaErrors []response.Error + for _, cause := range validationErr.Causes { + // Extract the path and message from the validation error + path := strings.Join(cause.InstanceLocation, ".") // JSON path to the invalid field + message := cause.Error() // Validation error message + + // Append the error to the schemaErrors array + schemaErrors = append(schemaErrors, response.Error{ + Paths: path, + Message: message, + }) + } + // Return the array of schema validation errors + return &response.SchemaValidationErr{Errors: schemaErrors} + } + // Return a generic error for non-validation errors + return fmt.Errorf("validation failed: %v", err) + } + + // Return nil if validation succeeds + return nil +} + +// ValidatorProvider provides instances of Validator. +type ValidatorProvider struct{} + +// Initialise initialises the validator provider by compiling all the JSON schema files +// from the specified directory and storing them in a cache indexed by their schema filenames. +func (v *SchemaValidator) initialise() error { + schemaDir := v.config.SchemaDir + // Check if the directory exists and is accessible. + info, err := os.Stat(schemaDir) + if err != nil { + if os.IsNotExist(err) { + return fmt.Errorf("schema directory does not exist: %s", schemaDir) + } + return fmt.Errorf("failed to access schema directory: %v", err) + } + if !info.IsDir() { + return fmt.Errorf("provided schema path is not a directory: %s", schemaDir) + } + + compiler := jsonschema.NewCompiler() + + // Helper function to process directories recursively. + var processDir func(dir string) error + processDir = func(dir string) error { + entries, err := os.ReadDir(dir) + if err != nil { + return fmt.Errorf("failed to read directory: %v", err) + } + + for _, entry := range entries { + path := filepath.Join(dir, entry.Name()) + if entry.IsDir() { + // Recursively process subdirectories. + if err := processDir(path); err != nil { + return err + } + } else if filepath.Ext(entry.Name()) == ".json" { + // Process JSON files. + compiledSchema, err := compiler.Compile(path) + if err != nil { + return fmt.Errorf("failed to compile JSON schema from file %s: %v", entry.Name(), err) + } + + // Use relative path from schemaDir to avoid absolute paths and make schema keys domain/version specific. + relativePath, err := filepath.Rel(schemaDir, path) + if err != nil { + return fmt.Errorf("failed to get relative path for file %s: %v", entry.Name(), err) + } + // Split the relative path to get domain, version, and schema. + parts := strings.Split(relativePath, string(os.PathSeparator)) + + // Ensure that the file path has at least 3 parts: domain, version, and schema file. + if len(parts) < 3 { + return fmt.Errorf("invalid schema file structure, expected domain/version/schema.json but got: %s", relativePath) + } + + // Extract domain, version, and schema filename from the parts. + // Validate that the extracted parts are non-empty. + domain := strings.TrimSpace(parts[0]) + version := strings.TrimSpace(parts[1]) + schemaFileName := strings.TrimSpace(parts[2]) + schemaFileName = strings.TrimSuffix(schemaFileName, ".json") + + if domain == "" || version == "" || schemaFileName == "" { + return fmt.Errorf("invalid schema file structure, one or more components are empty. Relative path: %s", relativePath) + } + + // Construct a unique key combining domain, version, and schema name (e.g., ondc_trv10_v2.0.0_schema). + uniqueKey := fmt.Sprintf("%s_%s_%s", domain, version, schemaFileName) + // Store the compiled schema in the SchemaCache using the unique key. + v.schemaCache[uniqueKey] = compiledSchema + } + } + return nil + } + + // Start processing from the root schema directory. + if err := processDir(schemaDir); err != nil { + return fmt.Errorf("failed to read schema directory: %v", err) + } + + return nil +} diff --git a/pkg/plugin/implementation/schemaValidator/schemaValidator_test.go b/pkg/plugin/implementation/schemaValidator/schemaValidator_test.go new file mode 100644 index 0000000..277b539 --- /dev/null +++ b/pkg/plugin/implementation/schemaValidator/schemaValidator_test.go @@ -0,0 +1,353 @@ +package schemaValidator + +import ( + "context" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/santhosh-tekuri/jsonschema/v6" +) + +// setupTestSchema creates a temporary directory and writes a sample schema file. +func setupTestSchema(t *testing.T) string { + t.Helper() + + // Create a temporary directory for the schema + schemaDir, err := os.MkdirTemp("", "schemas") + if err != nil { + t.Fatalf("Failed to create temp directory: %v", err) + } + + // Create the directory structure for the schema file + schemaFilePath := filepath.Join(schemaDir, "example", "v1.0", "endpoint.json") + if err := os.MkdirAll(filepath.Dir(schemaFilePath), 0755); err != nil { + t.Fatalf("Failed to create schema directory structure: %v", err) + } + + // Define a sample schema + schemaContent := `{ + "type": "object", + "properties": { + "context": { + "type": "object", + "properties": { + "domain": {"type": "string"}, + "version": {"type": "string"}, + "action": {"type": "string"} + }, + "required": ["domain", "version", "action"] + } + }, + "required": ["context"] + }` + + // Write the schema to the file + if err := os.WriteFile(schemaFilePath, []byte(schemaContent), 0644); err != nil { + t.Fatalf("Failed to write schema file: %v", err) + } + + return schemaDir +} + +func TestValidator_Validate_Success(t *testing.T) { + tests := []struct { + name string + url string + payload string + wantErr bool + }{ + { + name: "Valid payload", + url: "http://example.com/endpoint", + payload: `{"context": {"domain": "example", "version": "1.0", "action": "endpoint"}}`, + wantErr: false, + }, + } + + // Setup a temporary schema directory for testing + schemaDir := setupTestSchema(t) + defer os.RemoveAll(schemaDir) + + config := &Config{SchemaDir: schemaDir} + v, _, err := New(context.Background(), config) + if err != nil { + t.Fatalf("Failed to create validator: %v", err) + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + u, _ := url.Parse(tt.url) + err := v.Validate(context.Background(), u, []byte(tt.payload)) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } else { + t.Logf("Test %s passed with no errors", tt.name) + } + }) + } +} + +func TestValidator_Validate_Failure(t *testing.T) { + tests := []struct { + name string + url string + payload string + wantErr string + }{ + { + name: "Invalid JSON payload", + url: "http://example.com/endpoint", + payload: `{"context": {"domain": "example", "version": "1.0"`, + wantErr: "failed to parse JSON payload", + }, + { + name: "Schema validation failure", + url: "http://example.com/endpoint", + payload: `{"context": {"domain": "example", "version": "1.0"}}`, + wantErr: "context: at '/context': missing property 'action'", + }, + { + name: "Schema not found", + url: "http://example.com/unknown_endpoint", + payload: `{"context": {"domain": "example", "version": "1.0"}}`, + wantErr: "schema not found for domain", + }, + } + + // Setup a temporary schema directory for testing + schemaDir := setupTestSchema(t) + defer os.RemoveAll(schemaDir) + + config := &Config{SchemaDir: schemaDir} + v, _, err := New(context.Background(), config) + if err != nil { + t.Fatalf("Failed to create validator: %v", err) + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + u, _ := url.Parse(tt.url) + err := v.Validate(context.Background(), u, []byte(tt.payload)) + if tt.wantErr != "" { + if err == nil { + t.Errorf("Expected error containing '%s', but got nil", tt.wantErr) + } else if !strings.Contains(err.Error(), tt.wantErr) { + t.Errorf("Expected error containing '%s', but got '%v'", tt.wantErr, err) + } else { + t.Logf("Test %s passed with expected error: %v", tt.name, err) + } + } else { + if err != nil { + t.Errorf("Unexpected error: %v", err) + } else { + t.Logf("Test %s passed with no errors", tt.name) + } + } + }) + } +} + +func TestValidator_Initialise(t *testing.T) { + tests := []struct { + name string + setupFunc func(schemaDir string) error + wantErr string + }{ + { + name: "Schema directory does not exist", + setupFunc: func(schemaDir string) error { + // Do not create the schema directory + return nil + + }, + wantErr: "schema directory does not exist", + }, + { + name: "Schema path is not a directory", + setupFunc: func(schemaDir string) error { + // Create a file instead of a directory + return os.WriteFile(schemaDir, []byte{}, 0644) + }, + wantErr: "provided schema path is not a directory", + }, + { + name: "Invalid schema file structure", + setupFunc: func(schemaDir string) error { + // Create an invalid schema file structure + invalidSchemaFile := filepath.Join(schemaDir, "invalid_schema.json") + if err := os.MkdirAll(filepath.Dir(invalidSchemaFile), 0755); err != nil { + t.Fatalf("Failed to create directory: %v", err) + } + return os.WriteFile(invalidSchemaFile, []byte(`{}`), 0644) + }, + wantErr: "invalid schema file structure", + }, + { + name: "Failed to compile JSON schema", + setupFunc: func(schemaDir string) error { + // Create a schema file with invalid JSON + invalidSchemaFile := filepath.Join(schemaDir, "example", "1.0", "endpoint.json") + if err := os.MkdirAll(filepath.Dir(invalidSchemaFile), 0755); err != nil { + t.Fatalf("Failed to create directory: %v", err) + } + return os.WriteFile(invalidSchemaFile, []byte(`{invalid json}`), 0644) + }, + wantErr: "failed to compile JSON schema", + }, + { + name: "Invalid schema file structure with empty components", + setupFunc: func(schemaDir string) error { + // Create a schema file with empty domain, version, or schema name + invalidSchemaFile := filepath.Join(schemaDir, "", "1.0", "endpoint.json") + if err := os.MkdirAll(filepath.Dir(invalidSchemaFile), 0755); err != nil { + t.Fatalf("Failed to create directory: %v", err) + } + return os.WriteFile(invalidSchemaFile, []byte(`{ + "type": "object", + "properties": { + "context": { + "type": "object", + "properties": { + "domain": {"type": "string"}, + "version": {"type": "string"} + }, + "required": ["domain", "version"] + } + }, + "required": ["context"] + }`), 0644) + }, + wantErr: "failed to read schema directory: invalid schema file structure, expected domain/version/schema.json but got: 1.0/endpoint.json", + }, + { + name: "Failed to read directory", + setupFunc: func(schemaDir string) error { + // Create a directory and remove read permissions + if err := os.MkdirAll(schemaDir, 0000); err != nil { + t.Fatalf("Failed to create directory: %v", err) + } + return nil + }, + wantErr: "failed to read directory", + }, + { + name: "Valid schema directory", + setupFunc: func(schemaDir string) error { + // Create a valid schema file + validSchemaFile := filepath.Join(schemaDir, "example", "1.0", "endpoint.json") + if err := os.MkdirAll(filepath.Dir(validSchemaFile), 0755); err != nil { + t.Fatalf("Failed to create directory: %v", err) + } + return os.WriteFile(validSchemaFile, []byte(`{ + "type": "object", + "properties": { + "context": { + "type": "object", + "properties": { + "domain": {"type": "string"}, + "version": {"type": "string"} + }, + "required": ["domain", "version"] + } + }, + "required": ["context"] + }`), 0644) + }, + wantErr: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Setup a temporary schema directory for testing + schemaDir := filepath.Join(os.TempDir(), "schemas") + defer os.RemoveAll(schemaDir) + + // Run the setup function to prepare the test case + if err := tt.setupFunc(schemaDir); err != nil { + t.Fatalf("setupFunc() error = %v", err) + } + + config := &Config{SchemaDir: schemaDir} + v := &SchemaValidator{ + config: config, + schemaCache: make(map[string]*jsonschema.Schema), + } + + err := v.initialise() + if (err != nil && !strings.Contains(err.Error(), tt.wantErr)) || (err == nil && tt.wantErr != "") { + t.Errorf("Error: initialise() returned error = %v, expected error = %v", err, tt.wantErr) + } else if err == nil { + t.Logf("Test %s passed: validator initialized successfully", tt.name) + } else { + t.Logf("Test %s passed with expected error: %v", tt.name, err) + } + }) + } +} + +func TestValidatorNew_Success(t *testing.T) { + schemaDir := setupTestSchema(t) + defer os.RemoveAll(schemaDir) + + config := &Config{SchemaDir: schemaDir} + _, _, err := New(context.Background(), config) + if err != nil { + t.Errorf("Unexpected error: %v", err) + } +} + +func TestValidatorNewFailure(t *testing.T) { + tests := []struct { + name string + config *Config + setupFunc func(schemaDir string) error + wantErr string + }{ + { + name: "Config is nil", + config: nil, + setupFunc: func(schemaDir string) error { + return nil + }, + wantErr: "config cannot be nil", + }, + { + name: "Failed to initialise validators", + config: &Config{ + SchemaDir: "/invalid/path", + }, + setupFunc: func(schemaDir string) error { + // Do not create the schema directory + return nil + }, + wantErr: "ailed to initialise schemaValidator: schema directory does not exist: /invalid/path", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Run the setup function if provided + if tt.setupFunc != nil { + schemaDir := "" + if tt.config != nil { + schemaDir = tt.config.SchemaDir + } + if err := tt.setupFunc(schemaDir); err != nil { + t.Fatalf("Setup function failed: %v", err) + } + } + + // Call the New function with the test config + _, _, err := New(context.Background(), tt.config) + if (err != nil && !strings.Contains(err.Error(), tt.wantErr)) || (err == nil && tt.wantErr != "") { + t.Errorf("Error: New() returned error = %v, expected error = %v", err, tt.wantErr) + } else { + t.Logf("Test %s passed with expected error: %v", tt.name, err) + } + }) + } +} diff --git a/pkg/response/response.go b/pkg/response/response.go index d5326ac..976c1e0 100644 --- a/pkg/response/response.go +++ b/pkg/response/response.go @@ -6,31 +6,40 @@ import ( "errors" "fmt" "net/http" - "strconv" - "github.com/beckn/beckn-onix/pkg/log" + "strings" + "github.com/beckn/beckn-onix/pkg/model" ) -// ErrorType represents different types of errors in the Beckn protocol. -type ErrorType string - -const ( - // SchemaValidationErrorType represents an error due to schema validation failure. - SchemaValidationErrorType ErrorType = "SCHEMA_VALIDATION_ERROR" - - // InvalidRequestErrorType represents an error due to an invalid request. - InvalidRequestErrorType ErrorType = "INVALID_REQUEST" -) - -// BecknRequest represents a generic Beckn request with an optional context. -type BecknRequest struct { - Context map[string]interface{} `json:"context,omitempty"` +type Error struct { + Code string `json:"code,omitempty"` + Message string `json:"message,omitempty"` + Paths string `json:"paths,omitempty"` +} + +// SchemaValidationErr represents a collection of schema validation failures. +type SchemaValidationErr struct { + Errors []Error +} + +// Error implements the error interface for SchemaValidationErr. +func (e *SchemaValidationErr) Error() string { + var errorMessages []string + for _, err := range e.Errors { + errorMessages = append(errorMessages, fmt.Sprintf("%s: %s", err.Paths, err.Message)) + } + return strings.Join(errorMessages, "; ") +} + +type Message struct { + Ack struct { + Status string `json:"status,omitempty"` + } `json:"ack,omitempty"` + Error *Error `json:"error,omitempty"` } -// SendAck sends an acknowledgment (ACK) response indicating a successful request processing. func SendAck(w http.ResponseWriter) { - // Create the response object resp := &model.Response{ Message: model.Message{ Ack: model.Ack{ @@ -39,25 +48,18 @@ func SendAck(w http.ResponseWriter) { }, } - // Marshal to JSON - data, err := json.Marshal(resp) - if err != nil { - http.Error(w, "failed to marshal response", http.StatusInternalServerError) - return - } + data, _ := json.Marshal(resp) //should not fail here - // Set headers and write response w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - if _, err := w.Write(data); err != nil { - log.Error(context.Background(), err, "failed to write ack response") + _, err := w.Write(data) + if err != nil { + http.Error(w, "failed to write response", http.StatusInternalServerError) + return } - } -// nack sends a negative acknowledgment (NACK) response with an error message. -func nack(w http.ResponseWriter, err *model.Error, status int) { - // Create the NACK response object +func nack(w http.ResponseWriter, err *model.Error, status int, ctx context.Context) { resp := &model.Response{ Message: model.Message{ Ack: model.Ack{ @@ -66,30 +68,25 @@ func nack(w http.ResponseWriter, err *model.Error, status int) { Error: err, }, } + data, _ := json.Marshal(resp) //should not fail here - // Marshal the response to JSON - data, jsonErr := json.Marshal(resp) - if jsonErr != nil { - http.Error(w, "failed to marshal response", http.StatusInternalServerError) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, er := w.Write(data) + if er != nil { + fmt.Printf("Error writing response: %v, MessageID: %s", er, ctx.Value(model.MsgIDKey)) + http.Error(w, fmt.Sprintf("Internal server error, MessageID: %s", ctx.Value(model.MsgIDKey)), http.StatusInternalServerError) return } - - // Set headers and write response - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) // Assuming NACK means a bad request - if _, err := w.Write(data); err != nil { - log.Error(context.Background(), err, "failed to write nack response") - } - } func internalServerError(ctx context.Context) *model.Error { return &model.Error{ + Code: http.StatusText(http.StatusInternalServerError), Message: fmt.Sprintf("Internal server error, MessageID: %s", ctx.Value(model.MsgIDKey)), } } -// SendNack sends a negative acknowledgment (NACK) response with an error message. func SendNack(ctx context.Context, w http.ResponseWriter, err error) { var schemaErr *model.SchemaValidationErr var signErr *model.SignValidationErr @@ -97,34 +94,20 @@ func SendNack(ctx context.Context, w http.ResponseWriter, err error) { var notFoundErr *model.NotFoundErr switch { - case errors.As(err, &schemaErr): // Custom application error - nack(w, schemaErr.BecknError(), http.StatusBadRequest) + case errors.As(err, &schemaErr): + nack(w, schemaErr.BecknError(), http.StatusBadRequest, ctx) return case errors.As(err, &signErr): - nack(w, signErr.BecknError(), http.StatusUnauthorized) + nack(w, signErr.BecknError(), http.StatusUnauthorized, ctx) return case errors.As(err, &badReqErr): - nack(w, badReqErr.BecknError(), http.StatusBadRequest) + nack(w, badReqErr.BecknError(), http.StatusBadRequest, ctx) return case errors.As(err, ¬FoundErr): - nack(w, notFoundErr.BecknError(), http.StatusNotFound) + nack(w, notFoundErr.BecknError(), http.StatusNotFound, ctx) return default: - nack(w, internalServerError(ctx), http.StatusInternalServerError) + nack(w, internalServerError(ctx), http.StatusInternalServerError, ctx) return } } - -// BecknError generates a standardized Beckn error response. -func BecknError(ctx context.Context, err error, status int) *model.Error { - msg := err.Error() - msgID := ctx.Value(model.MsgIDKey) - if status == http.StatusInternalServerError { - - msg = "Internal server error" - } - return &model.Error{ - Message: fmt.Sprintf("%s. MessageID: %s.", msg, msgID), - Code: strconv.Itoa(status), - } -} diff --git a/pkg/response/response_test.go b/pkg/response/response_test.go new file mode 100644 index 0000000..7e62aca --- /dev/null +++ b/pkg/response/response_test.go @@ -0,0 +1,256 @@ +package response + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/beckn/beckn-onix/pkg/model" +) + +type errorResponseWriter struct{} + +// TODO: Optimize the cases by removing these +func (e *errorResponseWriter) Write([]byte) (int, error) { + return 0, errors.New("write error") +} +func (e *errorResponseWriter) WriteHeader(statusCode int) {} + +func (e *errorResponseWriter) Header() http.Header { + return http.Header{} +} + +func TestSendAck(t *testing.T) { + _, err := http.NewRequest("GET", "/", nil) + if err != nil { + t.Fatal(err) // For tests + } + rr := httptest.NewRecorder() + + SendAck(rr) + + if rr.Code != http.StatusOK { + t.Errorf("wanted status code %d, got %d", http.StatusOK, rr.Code) + } + + expected := `{"message":{"ack":{"status":"ACK"}}}` + if rr.Body.String() != expected { + t.Errorf("err.Error() = %s, want %s", + rr.Body.String(), expected) + + } +} + +func TestSendNack(t *testing.T) { + ctx := context.WithValue(context.Background(), model.MsgIDKey, "123456") + + tests := []struct { + name string + err error + expected string + status int + }{ + { + name: "SchemaValidationErr", + err: &model.SchemaValidationErr{ + Errors: []model.Error{ + {Paths: "/path1", Message: "Error 1"}, + {Paths: "/path2", Message: "Error 2"}, + }, + }, + status: http.StatusBadRequest, + expected: `{"message":{"ack":{"status":"NACK"},"error":{"code":"Bad Request","paths":"/path1;/path2","message":"Error 1; Error 2"}}}`, + }, + { + name: "SignValidationErr", + err: model.NewSignValidationErr(errors.New("signature invalid")), + status: http.StatusUnauthorized, + expected: `{"message":{"ack":{"status":"NACK"},"error":{"code":"Unauthorized","message":"Signature Validation Error: signature invalid"}}}`, + }, + { + name: "BadReqErr", + err: model.NewBadReqErr(errors.New("bad request error")), + status: http.StatusBadRequest, + expected: `{"message":{"ack":{"status":"NACK"},"error":{"code":"Bad Request","message":"BAD Request: bad request error"}}}`, + }, + { + name: "NotFoundErr", + err: model.NewNotFoundErr(errors.New("endpoint not found")), + status: http.StatusNotFound, + expected: `{"message":{"ack":{"status":"NACK"},"error":{"code":"Not Found","message":"Endpoint not found: endpoint not found"}}}`, + }, + { + name: "InternalServerError", + err: errors.New("unexpected error"), + status: http.StatusInternalServerError, + expected: `{"message":{"ack":{"status":"NACK"},"error":{"code":"Internal Server Error","message":"Internal server error, MessageID: 123456"}}}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := http.NewRequest("GET", "/", nil) + if err != nil { + t.Fatal(err) // For tests + } + rr := httptest.NewRecorder() + + SendNack(ctx, rr, tt.err) + + if rr.Code != tt.status { + t.Errorf("wanted status code %d, got %d", tt.status, rr.Code) + } + + var actual map[string]interface{} + err = json.Unmarshal(rr.Body.Bytes(), &actual) + if err != nil { + t.Fatalf("failed to unmarshal response: %v", err) + } + + var expected map[string]interface{} + err = json.Unmarshal([]byte(tt.expected), &expected) + if err != nil { + t.Fatalf("failed to unmarshal expected response: %v", err) + } + + if !compareJSON(expected, actual) { + t.Errorf("err.Error() = %s, want %s", + actual, expected) + } + + }) + } +} + +func TestSchemaValidationErr_Error(t *testing.T) { + // Create sample validation errors + validationErrors := []Error{ + {Paths: "name", Message: "Name is required"}, + {Paths: "email", Message: "Invalid email format"}, + } + err := SchemaValidationErr{Errors: validationErrors} + expected := "name: Name is required; email: Invalid email format" + if err.Error() != expected { + t.Errorf("err.Error() = %s, want %s", + err.Error(), expected) + + } +} + +func compareJSON(expected, actual map[string]interface{}) bool { + expectedBytes, _ := json.Marshal(expected) + actualBytes, _ := json.Marshal(actual) + return bytes.Equal(expectedBytes, actualBytes) +} + +func TestSendAck_WriteError(t *testing.T) { + w := &errorResponseWriter{} + SendAck(w) +} + +// Mock struct to force JSON marshalling error +type badMessage struct{} + +func (b *badMessage) MarshalJSON() ([]byte, error) { + return nil, errors.New("marshal error") +} + +func TestNack_1(t *testing.T) { + tests := []struct { + name string + err *model.Error + status int + expected string + useBadJSON bool + useBadWrite bool + }{ + { + name: "Schema Validation Error", + err: &model.Error{ + Code: "BAD_REQUEST", + Paths: "/test/path", + Message: "Invalid schema", + }, + status: http.StatusBadRequest, + expected: `{"message":{"ack":{"status":"NACK"},"error":{"code":"BAD_REQUEST","paths":"/test/path","message":"Invalid schema"}}}`, + }, + { + name: "Internal Server Error", + err: &model.Error{ + Code: "INTERNAL_SERVER_ERROR", + Message: "Something went wrong", + }, + status: http.StatusInternalServerError, + expected: `{"message":{"ack":{"status":"NACK"},"error":{"code":"INTERNAL_SERVER_ERROR","message":"Something went wrong"}}}`, + }, + { + name: "JSON Marshal Error", + err: nil, // This will be overridden to cause marshaling error + status: http.StatusInternalServerError, + expected: `Internal server error, MessageID: 12345`, + useBadJSON: true, + }, + { + name: "Write Error", + err: &model.Error{ + Code: "WRITE_ERROR", + Message: "Failed to write response", + }, + status: http.StatusInternalServerError, + expected: `Internal server error, MessageID: 12345`, + useBadWrite: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req, err := http.NewRequest("GET", "/", nil) + if err != nil { + t.Fatal(err) + } + ctx := context.WithValue(req.Context(), model.MsgIDKey, "12345") + + var w http.ResponseWriter + if tt.useBadWrite { + w = &errorResponseWriter{} // Simulate write error + } else { + w = httptest.NewRecorder() + } + + // TODO: Fix this approach , should not be used like this. + if tt.useBadJSON { + data, _ := json.Marshal(&badMessage{}) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(tt.status) + _, err := w.Write(data) + if err != nil { + http.Error(w, "Failed to write response", http.StatusInternalServerError) + return + } + return + } + + nack(w, tt.err, tt.status, ctx) + if !tt.useBadWrite { + recorder, ok := w.(*httptest.ResponseRecorder) + if !ok { + t.Fatal("Failed to cast response recorder") + } + + if recorder.Code != tt.status { + t.Errorf("wanted status code %d, got %d", tt.status, recorder.Code) + } + + body := recorder.Body.String() + if body != tt.expected { + t.Errorf("err.Error() = %s, want %s", + body, tt.expected) + } + } + }) + } +} diff --git a/schemas.zip b/schemas.zip new file mode 100644 index 0000000..d72c46d Binary files /dev/null and b/schemas.zip differ