11//
2- // Copyright 2024-2025 The Chainloop Authors.
2+ // Copyright 2024-2026 The Chainloop Authors.
33//
44// Licensed under the Apache License, Version 2.0 (the "License");
55// you may not use this file except in compliance with the License.
@@ -56,17 +56,11 @@ func (v *validatorAdapter) Validate(msg proto.Message) error {
5656 return v .validator .Validate (msg )
5757}
5858
59- func FromRaw (body []byte , format RawFormat , out proto.Message , doValidate bool ) error {
60- var validator protovalidate.Validator
61- var err error
62-
63- if doValidate {
64- validator , err = protovalidate .New ()
65- if err != nil {
66- return fmt .Errorf ("could not create validator: %w" , err )
67- }
68- }
59+ // yamlValidator wraps the protovalidate global Validator for use with protoyaml,
60+ // initialised once and reused across calls.
61+ var yamlValidator = & validatorAdapter {validator : protovalidate .GlobalValidator }
6962
63+ func FromRaw (body []byte , format RawFormat , out proto.Message , doValidate bool ) error {
7064 switch format {
7165 case RawFormatJSON :
7266 if err := protojson .Unmarshal (body , out ); err != nil {
@@ -76,7 +70,7 @@ func FromRaw(body []byte, format RawFormat, out proto.Message, doValidate bool)
7670 // protoyaml allows validating the contract while unmarshalling
7771 yamlOpts := protoyaml.UnmarshalOptions {}
7872 if doValidate {
79- yamlOpts .Validator = & validatorAdapter { validator : validator }
73+ yamlOpts .Validator = yamlValidator
8074 }
8175
8276 if err := yamlOpts .Unmarshal (body , out ); err != nil {
@@ -97,9 +91,8 @@ func FromRaw(body []byte, format RawFormat, out proto.Message, doValidate bool)
9791 return fmt .Errorf ("unsupported format: %s" , format )
9892 }
9993
100- if validator != nil {
101- err = validator .Validate (out )
102- if err != nil {
94+ if doValidate {
95+ if err := protovalidate .Validate (out ); err != nil {
10396 return fmt .Errorf ("error validating raw message: %w" , err )
10497 }
10598 }
0 commit comments