|
| 1 | +// Copyright 2023 Buf Technologies, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package evaluator |
| 16 | + |
| 17 | +import ( |
| 18 | + "buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate" |
| 19 | + "github.com/bufbuild/protovalidate-go/internal/errors" |
| 20 | + "google.golang.org/protobuf/reflect/protoreflect" |
| 21 | + "google.golang.org/protobuf/types/known/timestamppb" |
| 22 | +) |
| 23 | + |
| 24 | +// timestampPB is a specialized evaluator for applying some validate.TimestampRules (only the |
| 25 | +// `valid` rule currently) to a google.protobuf.Timestamp message. This is handled outside |
| 26 | +// CEL which handles google.protobuf.Timestamp as an abstract type, thus not allowing access |
| 27 | +// to the message fields. |
| 28 | +type timestampPB struct { |
| 29 | + SecondsDescriptor protoreflect.FieldDescriptor |
| 30 | + NanosDescriptor protoreflect.FieldDescriptor |
| 31 | + Valid bool |
| 32 | +} |
| 33 | + |
| 34 | +func (t timestampPB) Evaluate(val protoreflect.Value, failFast bool) error { |
| 35 | + seconds := val.Message().Get(t.SecondsDescriptor).Int() |
| 36 | + nanos := val.Message().Get(t.NanosDescriptor).Int() |
| 37 | + |
| 38 | + timestamp := ×tamppb.Timestamp{Seconds: seconds, Nanos: int32(nanos)} |
| 39 | + |
| 40 | + err := &errors.ValidationError{Violations: []*validate.Violation{}} |
| 41 | + if t.Valid { |
| 42 | + terr := timestamp.CheckValid() |
| 43 | + if terr != nil { |
| 44 | + err.Violations = append(err.Violations, &validate.Violation{ |
| 45 | + ConstraintId: "timestamp.valid", |
| 46 | + Message: terr.Error(), |
| 47 | + }) |
| 48 | + if failFast { |
| 49 | + return err |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if len(err.Violations) > 0 { |
| 55 | + return err |
| 56 | + } |
| 57 | + return nil |
| 58 | +} |
| 59 | + |
| 60 | +func (t timestampPB) Tautology() bool { |
| 61 | + return !t.Valid |
| 62 | +} |
| 63 | + |
| 64 | +var _ evaluator = timestampPB{} |
0 commit comments