updated code.

1. Resolved merge conflicts.
2. Resolved go linting issues.
This commit is contained in:
MohitKatare-protean
2025-03-28 22:45:58 +05:30
parent 87bc86e1d6
commit 7055c1c0d8
24 changed files with 117 additions and 376 deletions

View File

@@ -25,11 +25,13 @@ type destination struct {
Config map[string]string `yaml:"config"`
}
// Destination types for logging output.
const (
Stdout destinationType = "stdout"
File destinationType = "file"
)
// Log levels define the severity of log messages.
const (
DebugLevel level = "debug"
InfoLevel level = "info"
@@ -48,6 +50,7 @@ var logLevels = map[level]zerolog.Level{
PanicLevel: zerolog.PanicLevel,
}
// Config represents the configuration for logging.
type Config struct {
Level level `yaml:"level"`
Destinations []destination `yaml:"destinations"`
@@ -60,6 +63,7 @@ var (
once sync.Once
)
// Logger instance and configuration.
var (
ErrInvalidLogLevel = errors.New("invalid log level")
ErrLogDestinationNil = errors.New("log Destinations cant be empty")
@@ -163,6 +167,8 @@ func getLogger(config Config) (zerolog.Logger, error) {
return newLogger, nil
}
// InitLogger initializes the logger with the given configuration.
// It ensures that the logger is initialized only once using sync.Once.
func InitLogger(c Config) error {
var initErr error
once.Do(func() {
@@ -175,60 +181,74 @@ func InitLogger(c Config) error {
return initErr
}
// Debug logs a debug-level message with the provided context.
func Debug(ctx context.Context, msg string) {
logEvent(ctx, zerolog.DebugLevel, msg, nil)
}
// Debugf logs a formatted debug-level message with the provided context.
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 with the provided context.
func Info(ctx context.Context, msg string) {
logEvent(ctx, zerolog.InfoLevel, msg, nil)
}
// Infof logs a formatted info-level message with the provided context.
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 with the provided context.
func Warn(ctx context.Context, msg string) {
logEvent(ctx, zerolog.WarnLevel, msg, nil)
}
// Warnf logs a formatted warning-level message with the provided context.
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 along with an error object.
func Error(ctx context.Context, err error, msg string) {
logEvent(ctx, zerolog.ErrorLevel, msg, err)
}
// Errorf logs a formatted error-level message along with an error object.
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 along with an error object 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 along with an error object 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 along with an error object and panics.
func Panic(ctx context.Context, err error, msg string) {
logEvent(ctx, zerolog.PanicLevel, msg, err)
}
// Panicf logs a formatted panic-level message along with an error object and panics.
func Panicf(ctx context.Context, err error, format string, v ...any) {
msg := fmt.Sprintf(format, v...)
logEvent(ctx, zerolog.PanicLevel, msg, err)
}
// logEvent logs an event at the specified log level with an optional error message.
// It adds contextual information before logging the message.
func logEvent(ctx context.Context, level zerolog.Level, msg string, err error) {
event := logger.WithLevel(level)
@@ -239,6 +259,7 @@ func logEvent(ctx context.Context, level zerolog.Level, msg string, err error) {
event.Msg(msg)
}
// Request logs details of an incoming HTTP request, including method, URL, body, and remote address.
func Request(ctx context.Context, r *http.Request, body []byte) {
event := logger.Info()
addCtx(ctx, event)
@@ -249,6 +270,7 @@ func Request(ctx context.Context, r *http.Request, body []byte) {
Msg("HTTP Request")
}
// addCtx adds context values to the log event based on configured context keys.
func addCtx(ctx context.Context, event *zerolog.Event) {
for _, key := range cfg.ContextKeys {
val, ok := ctx.Value(key).(string)
@@ -260,6 +282,7 @@ func addCtx(ctx context.Context, event *zerolog.Event) {
}
}
// Response logs details of an outgoing HTTP response, including method, URL, status code, and response time.
func Response(ctx context.Context, r *http.Request, statusCode int, responseTime time.Duration) {
event := logger.Info()
addCtx(ctx, event)

View File

@@ -40,14 +40,20 @@ const (
type contextKey string
// MsgIDKey is the context key used to store and retrieve the message ID in a request context.
const MsgIDKey = contextKey("message_id")
// Role defines the type of participant in the network.
type Role string
const (
RoleBAP Role = "bap"
RoleBPP Role = "bpp"
RoleGateway Role = "gateway"
// RoleBAP represents a Buyer App Participant (BAP) in the network.
RoleBAP Role = "bap"
// RoleBPP represents a Buyer Platform Participant (BPP) in the network.
RoleBPP Role = "bpp"
// RoleGateway represents a Gateway that facilitates communication in the network.
RoleGateway Role = "gateway"
// RoleRegistery represents the Registry that maintains network participant details.
RoleRegistery Role = "registery"
)
@@ -91,22 +97,32 @@ type StepContext struct {
RespHeader http.Header
}
// WithContext updates the existing StepContext with a new context.
func (ctx *StepContext) WithContext(newCtx context.Context) {
ctx.Context = newCtx
}
// Status represents the acknowledgment status in a response.
type Status string
const (
StatusACK Status = "ACK"
// StatusACK indicates a successful acknowledgment.
StatusACK Status = "ACK"
// StatusNACK indicates a negative acknowledgment or failure.
StatusNACK Status = "NACK"
)
// Ack represents an acknowledgment response.
type Ack struct {
// Status holds the acknowledgment status (ACK/NACK).
Status Status `json:"status"`
}
// Message represents the structure of a response message.
type Message struct {
Ack Ack `json:"ack"`
// Ack contains the acknowledgment status.
Ack Ack `json:"ack"`
// Error holds error details, if any, in the response.
Error *Error `json:"error,omitempty"`
}

View File

@@ -5,7 +5,7 @@ import (
"errors"
definition "github.com/beckn/beckn-onix/pkg/plugin/definition"
schemaValidator "github.com/beckn/beckn-onix/pkg/plugin/implementation/schemaValidator"
schemaValidator "github.com/beckn/beckn-onix/pkg/plugin/implementation/schemavalidator"
)
// schemaValidatorProvider provides instances of schemaValidator.

View File

@@ -1,4 +1,4 @@
package schemaValidator
package schemavalidator
import (
"context"

View File

@@ -1,4 +1,4 @@
package schemaValidator
package schemavalidator
import (
"context"

View File

@@ -149,8 +149,15 @@ func (m *Manager) Router(ctx context.Context, cfg *Config) (definition.Router, e
if err != nil {
return nil, fmt.Errorf("failed to load provider for %s: %w", cfg.ID, err)
}
return rp.New(ctx, cfg.Config)
router, closer, err := rp.New(ctx, cfg.Config)
if closer != nil {
m.addCloser(func() {
if err := closer(); err != nil {
panic(err)
}
})
}
return router, nil
}
func (m *Manager) Middleware(ctx context.Context, cfg *Config) (func(http.Handler) http.Handler, error) {

View File

@@ -12,10 +12,16 @@ import (
"github.com/beckn/beckn-onix/pkg/model"
)
// Error represents a standardized error response used across the system.
type Error struct {
Code string `json:"code,omitempty"`
// Code is a short, machine-readable error code.
Code string `json:"code,omitempty"`
// Message provides a human-readable description of the error.
Message string `json:"message,omitempty"`
Paths string `json:"paths,omitempty"`
// Paths indicates the specific field(s) or endpoint(s) related to the error.
Paths string `json:"paths,omitempty"`
}
// SchemaValidationErr represents a collection of schema validation failures.
@@ -32,13 +38,18 @@ func (e *SchemaValidationErr) Error() string {
return strings.Join(errorMessages, "; ")
}
// Message represents a standard message structure with acknowledgment and error information.
type Message struct {
// Ack contains the acknowledgment status of the response.
Ack struct {
Status string `json:"status,omitempty"`
} `json:"ack,omitempty"`
// Error holds error details if any occurred during processing.
Error *Error `json:"error,omitempty"`
}
// SendAck sends an acknowledgment response (ACK) to the client.
func SendAck(w http.ResponseWriter) {
resp := &model.Response{
Message: model.Message{
@@ -59,7 +70,8 @@ func SendAck(w http.ResponseWriter) {
}
}
func nack(w http.ResponseWriter, err *model.Error, status int, ctx context.Context) {
// nack sends a negative acknowledgment (NACK) response with an error message.
func nack(ctx context.Context, w http.ResponseWriter, err *model.Error, status int) {
resp := &model.Response{
Message: model.Message{
Ack: model.Ack{
@@ -80,6 +92,7 @@ func nack(w http.ResponseWriter, err *model.Error, status int, ctx context.Conte
}
}
// internalServerError generates an internal server error response.
func internalServerError(ctx context.Context) *model.Error {
return &model.Error{
Code: http.StatusText(http.StatusInternalServerError),
@@ -87,6 +100,7 @@ func internalServerError(ctx context.Context) *model.Error {
}
}
// SendNack processes different types of errors and sends an appropriate NACK response.
func SendNack(ctx context.Context, w http.ResponseWriter, err error) {
var schemaErr *model.SchemaValidationErr
var signErr *model.SignValidationErr
@@ -95,19 +109,19 @@ func SendNack(ctx context.Context, w http.ResponseWriter, err error) {
switch {
case errors.As(err, &schemaErr):
nack(w, schemaErr.BecknError(), http.StatusBadRequest, ctx)
nack(ctx, w, schemaErr.BecknError(), http.StatusBadRequest)
return
case errors.As(err, &signErr):
nack(w, signErr.BecknError(), http.StatusUnauthorized, ctx)
nack(ctx, w, signErr.BecknError(), http.StatusUnauthorized)
return
case errors.As(err, &badReqErr):
nack(w, badReqErr.BecknError(), http.StatusBadRequest, ctx)
nack(ctx, w, badReqErr.BecknError(), http.StatusBadRequest)
return
case errors.As(err, &notFoundErr):
nack(w, notFoundErr.BecknError(), http.StatusNotFound, ctx)
nack(ctx, w, notFoundErr.BecknError(), http.StatusNotFound)
return
default:
nack(w, internalServerError(ctx), http.StatusInternalServerError, ctx)
nack(ctx, w, internalServerError(ctx), http.StatusInternalServerError)
return
}
}

View File

@@ -234,7 +234,7 @@ func TestNack_1(t *testing.T) {
return
}
nack(w, tt.err, tt.status, ctx)
nack(ctx, w, tt.err, tt.status)
if !tt.useBadWrite {
recorder, ok := w.(*httptest.ResponseRecorder)
if !ok {