|
| 1 | +package validation |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "os" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/pkg/errors" |
| 10 | + "go.uber.org/zap" |
| 11 | + |
| 12 | + "github.com/ChargePi/chargeflow/pkg/ocpp" |
| 13 | + "github.com/ChargePi/chargeflow/pkg/parser" |
| 14 | + "github.com/ChargePi/chargeflow/pkg/report" |
| 15 | + "github.com/ChargePi/chargeflow/pkg/schema_registry" |
| 16 | + "github.com/ChargePi/chargeflow/pkg/validator" |
| 17 | +) |
| 18 | + |
| 19 | +type Service struct { |
| 20 | + logger *zap.Logger |
| 21 | + registry schema_registry.SchemaRegistry |
| 22 | + parser *parser.ParserV2 |
| 23 | + validator *validator.Validator |
| 24 | + aggregator *report.Aggregator |
| 25 | +} |
| 26 | + |
| 27 | +func NewService( |
| 28 | + logger *zap.Logger, |
| 29 | + registry schema_registry.SchemaRegistry, |
| 30 | +) *Service { |
| 31 | + return &Service{ |
| 32 | + logger: logger, |
| 33 | + registry: registry, |
| 34 | + parser: parser.NewParserV2(logger), |
| 35 | + validator: validator.NewValidator(logger, registry), |
| 36 | + aggregator: report.NewAggregator(logger), |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +// ValidateMessage validates a single OCPP message against the schema. |
| 41 | +func (s *Service) ValidateMessage(message string, ocppVersion ocpp.Version) error { |
| 42 | + logger := s.logger.With(zap.String("message", message), zap.String("ocppVersion", ocppVersion.String())) |
| 43 | + logger.Info("Validating message") |
| 44 | + |
| 45 | + validationReport, err := s.parseAndValidate(ocppVersion, []string{message}) |
| 46 | + if err != nil { |
| 47 | + return errors.Wrap(err, "failed to parse message") |
| 48 | + } |
| 49 | + |
| 50 | + s.outputValidationErrorToLogs(validationReport) |
| 51 | + |
| 52 | + return nil |
| 53 | +} |
| 54 | + |
| 55 | +// ValidateFile validates a file containing multiple OCPP messages against the schema. |
| 56 | +func (s *Service) ValidateFile(file string, ocppVersion ocpp.Version) error { |
| 57 | + logger := s.logger.With(zap.String("file", file), zap.String("ocppVersion", ocppVersion.String())) |
| 58 | + logger.Info("Validating file") |
| 59 | + |
| 60 | + messages, err := s.getMessagesFromFile(file) |
| 61 | + if err != nil { |
| 62 | + return errors.Wrap(err, "unable to read messages from file") |
| 63 | + } |
| 64 | + |
| 65 | + logger.Info("✅ Successfully parsed file", zap.Int("messages", len(messages))) |
| 66 | + |
| 67 | + validationReport, err := s.parseAndValidate(ocppVersion, messages) |
| 68 | + if err != nil { |
| 69 | + return errors.Wrap(err, "unable to parse messages") |
| 70 | + } |
| 71 | + |
| 72 | + s.outputValidationErrorToLogs(validationReport) |
| 73 | + |
| 74 | + return nil |
| 75 | +} |
| 76 | + |
| 77 | +// outputValidationErrorToLogs outputs the validation errors to the logs. |
| 78 | +func (s *Service) outputValidationErrorToLogs(validationReport *report.Report) { |
| 79 | + if len(validationReport.InvalidMessages) == 0 && len(validationReport.NonParsableMessages) == 0 { |
| 80 | + s.logger.Info("✅ All messages are valid!") |
| 81 | + return |
| 82 | + } |
| 83 | + |
| 84 | + // Log the non-parsable messages first |
| 85 | + for line, errs := range validationReport.NonParsableMessages { |
| 86 | + logger := s.logger.With(zap.String("line", line)) |
| 87 | + logger.Error(fmt.Sprintf("Message could not be parsed at %s:", line)) |
| 88 | + if len(errs) == 0 { |
| 89 | + continue |
| 90 | + } |
| 91 | + |
| 92 | + for _, parseErr := range errs { |
| 93 | + logger.Error(fmt.Sprintf("👉 %s", parseErr)) |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + // Log any parsing or validation errors for messages |
| 98 | + for messageId, requestResponse := range validationReport.InvalidMessages { |
| 99 | + for k, validationErrors := range requestResponse { |
| 100 | + logger := s.logger.With(zap.String("messageId", messageId)) |
| 101 | + switch k { |
| 102 | + case "request": |
| 103 | + logger.Error(fmt.Sprintf("Request for message %s has the following validation errors:", messageId)) |
| 104 | + case "response": |
| 105 | + logger.Error(fmt.Sprintf("Response for message %s has the following validation errors:", messageId)) |
| 106 | + } |
| 107 | + |
| 108 | + if len(validationErrors) == 0 { |
| 109 | + continue |
| 110 | + } |
| 111 | + |
| 112 | + for _, parseErr := range validationErrors { |
| 113 | + logger.Error(fmt.Sprintf("👉 %s", parseErr)) |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +// parseAndValidate parses and validates a list of OCPP messages. |
| 120 | +func (s *Service) parseAndValidate(ocppVersion ocpp.Version, messages []string) (*report.Report, error) { |
| 121 | + logger := s.logger.With(zap.String("ocppVersion", ocppVersion.String()), zap.Int("messages", len(messages))) |
| 122 | + logger.Info("Parsing and validating messages") |
| 123 | + |
| 124 | + // Parse the messages |
| 125 | + parserResults, nonParsedMessages, err := s.parser.Parse(messages) |
| 126 | + if err != nil { |
| 127 | + return nil, errors.Wrap(err, "failed to parse messages") |
| 128 | + } |
| 129 | + |
| 130 | + // Add non-parsable messages to the aggregator |
| 131 | + for line, result := range nonParsedMessages { |
| 132 | + s.aggregator.AddNonParsableMessage(line, result) |
| 133 | + } |
| 134 | + |
| 135 | + // Add parsed messages to the aggregator |
| 136 | + for messageId, result := range parserResults { |
| 137 | + // Validate the request |
| 138 | + _, found := result.GetRequest() |
| 139 | + if found { |
| 140 | + s.aggregator.AddParserResult(messageId, true, result.Request) |
| 141 | + } |
| 142 | + |
| 143 | + _, found = result.GetResponse() |
| 144 | + if found { |
| 145 | + s.aggregator.AddParserResult(messageId, false, result.Response) |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + // Only valid messages should be validated further |
| 150 | + validMessages := s.filterValidMessages(parserResults) |
| 151 | + invalidMessagesCount := len(parserResults) - len(validMessages) |
| 152 | + logger.Info( |
| 153 | + "✅ OCPP messages parsed. Proceeding with validation.", |
| 154 | + zap.Int("invalid_messages", invalidMessagesCount), |
| 155 | + zap.Int("unparsable_messages", len(nonParsedMessages)), |
| 156 | + ) |
| 157 | + |
| 158 | + for messageId, parserResult := range validMessages { |
| 159 | + // Validate the request |
| 160 | + request, found := parserResult.GetRequest() |
| 161 | + if found { |
| 162 | + result, err := s.validator.ValidateMessage(ocppVersion, request) |
| 163 | + if err != nil { |
| 164 | + return nil, errors.Wrap(err, "failed to validate request message") |
| 165 | + } |
| 166 | + |
| 167 | + // Store the results in the aggregator |
| 168 | + s.aggregator.AddValidationResults(messageId, true, *result) |
| 169 | + } |
| 170 | + |
| 171 | + // Validate the response |
| 172 | + response, found := parserResult.GetResponse() |
| 173 | + if found { |
| 174 | + result, err := s.validator.ValidateMessage(ocppVersion, response) |
| 175 | + if err != nil { |
| 176 | + return nil, errors.Wrap(err, "failed to validate response message") |
| 177 | + } |
| 178 | + |
| 179 | + // Store the results in the aggregator |
| 180 | + s.aggregator.AddValidationResults(messageId, false, *result) |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + validationReport := s.aggregator.CreateReport() |
| 185 | + return &validationReport, nil |
| 186 | +} |
| 187 | + |
| 188 | +// getMessagesFromFile reads messages from a file, where each message is separated by a newline character. |
| 189 | +func (s *Service) getMessagesFromFile(file string) ([]string, error) { |
| 190 | + s.logger.Debug("Reading file", zap.String("file", file)) |
| 191 | + |
| 192 | + openFile, err := os.OpenFile(file, os.O_RDONLY, 0666) |
| 193 | + if err != nil { |
| 194 | + return nil, errors.Wrap(err, "failed to open file") |
| 195 | + } |
| 196 | + |
| 197 | + content, err := io.ReadAll(openFile) |
| 198 | + if err != nil { |
| 199 | + return nil, errors.Wrap(err, "failed to read file content") |
| 200 | + } |
| 201 | + |
| 202 | + messages := strings.Split(string(content), "\n") |
| 203 | + return messages, nil |
| 204 | +} |
| 205 | + |
| 206 | +// filterValidMessages filters out invalid messages from the parser results. |
| 207 | +func (s *Service) filterValidMessages(parserResults map[string]parser.RequestResponseResult) map[string]parser.RequestResponseResult { |
| 208 | + validMessages := make(map[string]parser.RequestResponseResult) |
| 209 | + |
| 210 | + for messageUniqueId, parserResult := range parserResults { |
| 211 | + if !parserResult.IsValid() { |
| 212 | + continue |
| 213 | + } |
| 214 | + validMessages[messageUniqueId] = parserResult |
| 215 | + } |
| 216 | + |
| 217 | + return validMessages |
| 218 | +} |
0 commit comments