Debian Codegraph @

common/types/pb/type.go

raw symbols SCIP
1 // Copyright 2018 Google LLC
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 pb
16
17 import (
18 "fmt"
19 "reflect"
20
21 "google.golang.org/protobuf/proto"
22 "google.golang.org/protobuf/reflect/protoreflect"
23
24 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
25 dynamicpb "google.golang.org/protobuf/types/dynamicpb"
26 anypb "google.golang.org/protobuf/types/known/anypb"
27 dpb "google.golang.org/protobuf/types/known/durationpb"
28 structpb "google.golang.org/protobuf/types/known/structpb"
29 tpb "google.golang.org/protobuf/types/known/timestamppb"
30 wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
31 )
32
33 // description is a private interface used to make it convenient to perform type unwrapping at
34 // the TypeDescription or FieldDescription level.
35 type description interface {
36 // Zero returns an empty immutable protobuf message when the description is a protobuf message
37 // type.
38 Zero() proto.Message
39 }
40
41 // newTypeDescription produces a TypeDescription value for the fully-qualified proto type name
42 // with a given descriptor.
43 func newTypeDescription(typeName string, desc protoreflect.MessageDescriptor, extensions extensionMap) *TypeDescription {
44 msgType := dynamicpb.NewMessageType(desc)
45 msgZero := dynamicpb.NewMessage(desc)
46 fieldMap := map[string]*FieldDescription{}
47 fields := desc.Fields()
48 for i := 0; i < fields.Len(); i++ {
49 f := fields.Get(i)
50 fieldMap[string(f.Name())] = newFieldDescription(f)
51 }
52 return &TypeDescription{
53 typeName: typeName,
54 desc: desc,
55 msgType: msgType,
56 fieldMap: fieldMap,
57 extensions: extensions,
58 reflectType: reflectTypeOf(msgZero),
59 zeroMsg: zeroValueOf(msgZero),
60 }
61 }
62
63 // TypeDescription is a collection of type metadata relevant to expression
64 // checking and evaluation.
65 type TypeDescription struct {
66 typeName string
67 desc protoreflect.MessageDescriptor
68 msgType protoreflect.MessageType
69 fieldMap map[string]*FieldDescription
70 extensions extensionMap
71 reflectType reflect.Type
72 zeroMsg proto.Message
73 }
74
75 // Copy copies the type description with updated references to the Db.
76 func (td *TypeDescription) Copy(pbdb *Db) *TypeDescription {
77 return &TypeDescription{
78 typeName: td.typeName,
79 desc: td.desc,
80 msgType: td.msgType,
81 fieldMap: td.fieldMap,
82 extensions: pbdb.extensions,
83 reflectType: td.reflectType,
84 zeroMsg: td.zeroMsg,
85 }
86 }
87
88 // FieldMap returns a string field name to FieldDescription map.
89 func (td *TypeDescription) FieldMap() map[string]*FieldDescription {
90 return td.fieldMap
91 }
92
93 // FieldByName returns (FieldDescription, true) if the field name is declared within the type.
94 func (td *TypeDescription) FieldByName(name string) (*FieldDescription, bool) {
95 fd, found := td.fieldMap[name]
96 if found {
97 return fd, true
98 }
99 extFieldMap, found := td.extensions[td.typeName]
100 if !found {
101 return nil, false
102 }
103 fd, found = extFieldMap[name]
104 return fd, found
105 }
106
107 // MaybeUnwrap accepts a proto message as input and unwraps it to a primitive CEL type if possible.
108 //
109 // This method returns the unwrapped value and 'true', else the original value and 'false'.
110 func (td *TypeDescription) MaybeUnwrap(msg proto.Message) (any, bool, error) {
111 return unwrap(td, msg)
112 }
113
114 // Name returns the fully-qualified name of the type.
115 func (td *TypeDescription) Name() string {
116 return string(td.desc.FullName())
117 }
118
119 // New returns a mutable proto message
120 func (td *TypeDescription) New() protoreflect.Message {
121 return td.msgType.New()
122 }
123
124 // ReflectType returns the Golang reflect.Type for this type.
125 func (td *TypeDescription) ReflectType() reflect.Type {
126 return td.reflectType
127 }
128
129 // Zero returns the zero proto.Message value for this type.
130 func (td *TypeDescription) Zero() proto.Message {
131 return td.zeroMsg
132 }
133
134 // newFieldDescription creates a new field description from a protoreflect.FieldDescriptor.
135 func newFieldDescription(fieldDesc protoreflect.FieldDescriptor) *FieldDescription {
136 var reflectType reflect.Type
137 var zeroMsg proto.Message
138 switch fieldDesc.Kind() {
139 case protoreflect.EnumKind:
140 reflectType = reflectTypeOf(protoreflect.EnumNumber(0))
141 case protoreflect.GroupKind, protoreflect.MessageKind:
142 zeroMsg = dynamicpb.NewMessage(fieldDesc.Message())
143 reflectType = reflectTypeOf(zeroMsg)
144 default:
145 reflectType = reflectTypeOf(fieldDesc.Default().Interface())
146 if fieldDesc.IsList() {
147 var elemValue protoreflect.Value
148 if fieldDesc.IsExtension() {
149 et := dynamicpb.NewExtensionType(fieldDesc)
150 elemValue = et.New().List().NewElement()
151 } else {
152 parentMsgType := fieldDesc.ContainingMessage()
153 parentMsg := dynamicpb.NewMessage(parentMsgType)
154 listField := parentMsg.NewField(fieldDesc).List()
155 elemValue = listField.NewElement()
156 }
157 elem := elemValue.Interface()
158 switch elemType := elem.(type) {
159 case protoreflect.Message:
160 elem = elemType.Interface()
161 }
162 reflectType = reflectTypeOf(elem)
163 }
164 }
165 // Ensure the list type is appropriately reflected as a Go-native list.
166 if fieldDesc.IsList() {
167 reflectType = reflect.SliceOf(reflectType)
168 }
169 var keyType, valType *FieldDescription
170 if fieldDesc.IsMap() {
171 keyType = newFieldDescription(fieldDesc.MapKey())
172 valType = newFieldDescription(fieldDesc.MapValue())
173 }
174 return &FieldDescription{
175 desc: fieldDesc,
176 KeyType: keyType,
177 ValueType: valType,
178 reflectType: reflectType,
179 zeroMsg: zeroValueOf(zeroMsg),
180 }
181 }
182
183 // FieldDescription holds metadata related to fields declared within a type.
184 type FieldDescription struct {
185 // KeyType holds the key FieldDescription for map fields.
186 KeyType *FieldDescription
187 // ValueType holds the value FieldDescription for map fields.
188 ValueType *FieldDescription
189
190 desc protoreflect.FieldDescriptor
191 reflectType reflect.Type
192 zeroMsg proto.Message
193 }
194
195 // CheckedType returns the type-definition used at type-check time.
196 func (fd *FieldDescription) CheckedType() *exprpb.Type {
197 if fd.desc.IsMap() {
198 return &exprpb.Type{
199 TypeKind: &exprpb.Type_MapType_{
200 MapType: &exprpb.Type_MapType{
201 KeyType: fd.KeyType.typeDefToType(),
202 ValueType: fd.ValueType.typeDefToType(),
203 },
204 },
205 }
206 }
207 if fd.desc.IsList() {
208 return &exprpb.Type{
209 TypeKind: &exprpb.Type_ListType_{
210 ListType: &exprpb.Type_ListType{
211 ElemType: fd.typeDefToType()}}}
212 }
213 return fd.typeDefToType()
214 }
215
216 // Descriptor returns the protoreflect.FieldDescriptor for this type.
217 func (fd *FieldDescription) Descriptor() protoreflect.FieldDescriptor {
218 return fd.desc
219 }
220
221 // IsSet returns whether the field is set on the target value, per the proto presence conventions
222 // of proto2 or proto3 accordingly.
223 //
224 // This function implements the FieldType.IsSet function contract which can be used to operate on
225 // more than just protobuf field accesses; however, the target here must be a protobuf.Message.
226 func (fd *FieldDescription) IsSet(target any) bool {
227 switch v := target.(type) {
228 case proto.Message:
229 pbRef := v.ProtoReflect()
230 pbDesc := pbRef.Descriptor()
231 if pbDesc == fd.desc.ContainingMessage() {
232 // When the target protobuf shares the same message descriptor instance as the field
233 // descriptor, use the cached field descriptor value.
234 return pbRef.Has(fd.desc)
235 }
236 // Otherwise, fallback to a dynamic lookup of the field descriptor from the target
237 // instance as an attempt to use the cached field descriptor will result in a panic.
238 return pbRef.Has(pbDesc.Fields().ByName(protoreflect.Name(fd.Name())))
239 default:
240 return false
241 }
242 }
243
244 // GetFrom returns the accessor method associated with the field on the proto generated struct.
245 //
246 // If the field is not set, the proto default value is returned instead.
247 //
248 // This function implements the FieldType.GetFrom function contract which can be used to operate
249 // on more than just protobuf field accesses; however, the target here must be a protobuf.Message.
250 func (fd *FieldDescription) GetFrom(target any) (any, error) {
251 v, ok := target.(proto.Message)
252 if !ok {
253 return nil, fmt.Errorf("unsupported field selection target: (%T)%v", target, target)
254 }
255 pbRef := v.ProtoReflect()
256 pbDesc := pbRef.Descriptor()
257 var fieldVal any
258 if pbDesc == fd.desc.ContainingMessage() {
259 // When the target protobuf shares the same message descriptor instance as the field
260 // descriptor, use the cached field descriptor value.
261 fieldVal = pbRef.Get(fd.desc).Interface()
262 } else {
263 // Otherwise, fallback to a dynamic lookup of the field descriptor from the target
264 // instance as an attempt to use the cached field descriptor will result in a panic.
265 fieldVal = pbRef.Get(pbDesc.Fields().ByName(protoreflect.Name(fd.Name()))).Interface()
266 }
267 switch fv := fieldVal.(type) {
268 // Fast-path return for primitive types.
269 case bool, []byte, float32, float64, int32, int64, string, uint32, uint64, protoreflect.List:
270 return fv, nil
271 case protoreflect.EnumNumber:
272 return int64(fv), nil
273 case protoreflect.Map:
274 // Return a wrapper around the protobuf-reflected Map types which carries additional
275 // information about the key and value definitions of the map.
276 return &Map{Map: fv, KeyType: fd.KeyType, ValueType: fd.ValueType}, nil
277 case protoreflect.Message:
278 // Make sure to unwrap well-known protobuf types before returning.
279 unwrapped, _, err := fd.MaybeUnwrapDynamic(fv)
280 return unwrapped, err
281 default:
282 return fv, nil
283 }
284 }
285
286 // IsEnum returns true if the field type refers to an enum value.
287 func (fd *FieldDescription) IsEnum() bool {
288 return fd.ProtoKind() == protoreflect.EnumKind
289 }
290
291 // IsMap returns true if the field is of map type.
292 func (fd *FieldDescription) IsMap() bool {
293 return fd.desc.IsMap()
294 }
295
296 // IsMessage returns true if the field is of message type.
297 func (fd *FieldDescription) IsMessage() bool {
298 kind := fd.ProtoKind()
299 return kind == protoreflect.MessageKind || kind == protoreflect.GroupKind
300 }
301
302 // IsOneof returns true if the field is declared within a oneof block.
303 func (fd *FieldDescription) IsOneof() bool {
304 return fd.desc.ContainingOneof() != nil
305 }
306
307 // IsList returns true if the field is a repeated value.
308 //
309 // This method will also return true for map values, so check whether the
310 // field is also a map.
311 func (fd *FieldDescription) IsList() bool {
312 return fd.desc.IsList()
313 }
314
315 // MaybeUnwrapDynamic takes the reflected protoreflect.Message and determines whether the
316 // value can be unwrapped to a more primitive CEL type.
317 //
318 // This function returns the unwrapped value and 'true' on success, or the original value
319 // and 'false' otherwise.
320 func (fd *FieldDescription) MaybeUnwrapDynamic(msg protoreflect.Message) (any, bool, error) {
321 return unwrapDynamic(fd, msg)
322 }
323
324 // Name returns the CamelCase name of the field within the proto-based struct.
325 func (fd *FieldDescription) Name() string {
326 return string(fd.desc.Name())
327 }
328
329 // ProtoKind returns the protobuf reflected kind of the field.
330 func (fd *FieldDescription) ProtoKind() protoreflect.Kind {
331 return fd.desc.Kind()
332 }
333
334 // ReflectType returns the Golang reflect.Type for this field.
335 func (fd *FieldDescription) ReflectType() reflect.Type {
336 return fd.reflectType
337 }
338
339 // String returns the fully qualified name of the field within its type as well as whether the
340 // field occurs within a oneof.
341 func (fd *FieldDescription) String() string {
342 return fmt.Sprintf("%v.%s `oneof=%t`", fd.desc.ContainingMessage().FullName(), fd.Name(), fd.IsOneof())
343 }
344
345 // Zero returns the zero value for the protobuf message represented by this field.
346 //
347 // If the field is not a proto.Message type, the zero value is nil.
348 func (fd *FieldDescription) Zero() proto.Message {
349 return fd.zeroMsg
350 }
351
352 func (fd *FieldDescription) typeDefToType() *exprpb.Type {
353 if fd.IsMessage() {
354 msgType := string(fd.desc.Message().FullName())
355 if wk, found := CheckedWellKnowns[msgType]; found {
356 return wk
357 }
358 return checkedMessageType(msgType)
359 }
360 if fd.IsEnum() {
361 return checkedInt
362 }
363 return CheckedPrimitives[fd.ProtoKind()]
364 }
365
366 // Map wraps the protoreflect.Map object with a key and value FieldDescription for use in
367 // retrieving individual elements within CEL value data types.
368 type Map struct {
369 protoreflect.Map
370 KeyType *FieldDescription
371 ValueType *FieldDescription
372 }
373
374 func checkedMessageType(name string) *exprpb.Type {
375 return &exprpb.Type{
376 TypeKind: &exprpb.Type_MessageType{MessageType: name}}
377 }
378
379 func checkedPrimitive(primitive exprpb.Type_PrimitiveType) *exprpb.Type {
380 return &exprpb.Type{
381 TypeKind: &exprpb.Type_Primitive{Primitive: primitive}}
382 }
383
384 func checkedWellKnown(wellKnown exprpb.Type_WellKnownType) *exprpb.Type {
385 return &exprpb.Type{
386 TypeKind: &exprpb.Type_WellKnown{WellKnown: wellKnown}}
387 }
388
389 func checkedWrap(t *exprpb.Type) *exprpb.Type {
390 return &exprpb.Type{
391 TypeKind: &exprpb.Type_Wrapper{Wrapper: t.GetPrimitive()}}
392 }
393
394 // unwrap unwraps the provided proto.Message value, potentially based on the description if the
395 // input message is a *dynamicpb.Message which obscures the typing information from Go.
396 //
397 // Returns the unwrapped value and 'true' if unwrapped, otherwise the input value and 'false'.
398 func unwrap(desc description, msg proto.Message) (any, bool, error) {
399 switch v := msg.(type) {
400 case *anypb.Any:
401 dynMsg, err := v.UnmarshalNew()
402 if err != nil {
403 return v, false, err
404 }
405 return unwrapDynamic(desc, dynMsg.ProtoReflect())
406 case *dynamicpb.Message:
407 return unwrapDynamic(desc, v)
408 case *dpb.Duration:
409 return v.AsDuration(), true, nil
410 case *tpb.Timestamp:
411 return v.AsTime(), true, nil
412 case *structpb.Value:
413 switch v.GetKind().(type) {
414 case *structpb.Value_BoolValue:
415 return v.GetBoolValue(), true, nil
416 case *structpb.Value_ListValue:
417 return v.GetListValue(), true, nil
418 case *structpb.Value_NullValue:
419 return structpb.NullValue_NULL_VALUE, true, nil
420 case *structpb.Value_NumberValue:
421 return v.GetNumberValue(), true, nil
422 case *structpb.Value_StringValue:
423 return v.GetStringValue(), true, nil
424 case *structpb.Value_StructValue:
425 return v.GetStructValue(), true, nil
426 default:
427 return structpb.NullValue_NULL_VALUE, true, nil
428 }
429 case *wrapperspb.BoolValue:
430 if v == nil {
431 return nil, true, nil
432 }
433 return v.GetValue(), true, nil
434 case *wrapperspb.BytesValue:
435 if v == nil {
436 return nil, true, nil
437 }
438 return v.GetValue(), true, nil
439 case *wrapperspb.DoubleValue:
440 if v == nil {
441 return nil, true, nil
442 }
443 return v.GetValue(), true, nil
444 case *wrapperspb.FloatValue:
445 if v == nil {
446 return nil, true, nil
447 }
448 return float64(v.GetValue()), true, nil
449 case *wrapperspb.Int32Value:
450 if v == nil {
451 return nil, true, nil
452 }
453 return int64(v.GetValue()), true, nil
454 case *wrapperspb.Int64Value:
455 if v == nil {
456 return nil, true, nil
457 }
458 return v.GetValue(), true, nil
459 case *wrapperspb.StringValue:
460 if v == nil {
461 return nil, true, nil
462 }
463 return v.GetValue(), true, nil
464 case *wrapperspb.UInt32Value:
465 if v == nil {
466 return nil, true, nil
467 }
468 return uint64(v.GetValue()), true, nil
469 case *wrapperspb.UInt64Value:
470 if v == nil {
471 return nil, true, nil
472 }
473 return v.GetValue(), true, nil
474 }
475 return unwrapDynamic(desc, msg.ProtoReflect())
476 }
477
478 // unwrapDynamic unwraps a reflected protobuf Message value.
479 //
480 // Returns the unwrapped value and 'true' if unwrapped, otherwise the input value and 'false'.
481 func unwrapDynamic(desc description, refMsg protoreflect.Message) (any, bool, error) {
482 msg := refMsg.Interface()
483 if !refMsg.IsValid() {
484 msg = desc.Zero()
485 }
486 // In order to ensure that these wrapped types match the expectations of the CEL type system
487 // the dynamicpb.Message must be merged with an protobuf instance of the well-known type value.
488 typeName := string(refMsg.Descriptor().FullName())
489 switch typeName {
490 case "google.protobuf.Any":
491 // Note, Any values require further unwrapping; however, this unwrapping may or may not
492 // be to a well-known type. If the unwrapped value is a well-known type it will be further
493 // unwrapped before being returned to the caller. Otherwise, the dynamic protobuf object
494 // represented by the Any will be returned.
495 unwrappedAny := &anypb.Any{}
496 err := Merge(unwrappedAny, msg)
497 if err != nil {
498 return nil, false, fmt.Errorf("unwrap dynamic field failed: %v", err)
499 }
500 dynMsg, err := unwrappedAny.UnmarshalNew()
501 if err != nil {
502 // Allow the error to move further up the stack as it should result in an type
503 // conversion error if the caller does not recover it somehow.
504 return nil, false, fmt.Errorf("unmarshal dynamic any failed: %v", err)
505 }
506 // Attempt to unwrap the dynamic type, otherwise return the dynamic message.
507 unwrapped, nested, err := unwrapDynamic(desc, dynMsg.ProtoReflect())
508 if err == nil && nested {
509 return unwrapped, true, nil
510 }
511 return dynMsg, true, err
512 case "google.protobuf.BoolValue",
513 "google.protobuf.BytesValue",
514 "google.protobuf.DoubleValue",
515 "google.protobuf.FloatValue",
516 "google.protobuf.Int32Value",
517 "google.protobuf.Int64Value",
518 "google.protobuf.StringValue",
519 "google.protobuf.UInt32Value",
520 "google.protobuf.UInt64Value":
521 // The msg value is ignored when dealing with wrapper types as they have a null or value
522 // behavior, rather than the standard zero value behavior of other proto message types.
523 if !refMsg.IsValid() {
524 return structpb.NullValue_NULL_VALUE, true, nil
525 }
526 valueField := refMsg.Descriptor().Fields().ByName("value")
527 return refMsg.Get(valueField).Interface(), true, nil
528 case "google.protobuf.Duration":
529 unwrapped := &dpb.Duration{}
530 err := Merge(unwrapped, msg)
531 if err != nil {
532 return nil, false, err
533 }
534 return unwrapped.AsDuration(), true, nil
535 case "google.protobuf.ListValue":
536 unwrapped := &structpb.ListValue{}
537 err := Merge(unwrapped, msg)
538 if err != nil {
539 return nil, false, err
540 }
541 return unwrapped, true, nil
542 case "google.protobuf.NullValue":
543 return structpb.NullValue_NULL_VALUE, true, nil
544 case "google.protobuf.Struct":
545 unwrapped := &structpb.Struct{}
546 err := Merge(unwrapped, msg)
547 if err != nil {
548 return nil, false, err
549 }
550 return unwrapped, true, nil
551 case "google.protobuf.Timestamp":
552 unwrapped := &tpb.Timestamp{}
553 err := Merge(unwrapped, msg)
554 if err != nil {
555 return nil, false, err
556 }
557 return unwrapped.AsTime(), true, nil
558 case "google.protobuf.Value":
559 unwrapped := &structpb.Value{}
560 err := Merge(unwrapped, msg)
561 if err != nil {
562 return nil, false, err
563 }
564 return unwrap(desc, unwrapped)
565 }
566 return msg, false, nil
567 }
568
569 // reflectTypeOf intercepts the reflect.Type call to ensure that dynamicpb.Message types preserve
570 // well-known protobuf reflected types expected by the CEL type system.
571 func reflectTypeOf(val any) reflect.Type {
572 switch v := val.(type) {
573 case proto.Message:
574 return reflect.TypeOf(zeroValueOf(v))
575 default:
576 return reflect.TypeOf(v)
577 }
578 }
579
580 // zeroValueOf will return the strongest possible proto.Message representing the default protobuf
581 // message value of the input msg type.
582 func zeroValueOf(msg proto.Message) proto.Message {
583 if msg == nil {
584 return nil
585 }
586 typeName := string(msg.ProtoReflect().Descriptor().FullName())
587 zeroVal, found := zeroValueMap[typeName]
588 if found {
589 return zeroVal
590 }
591 return msg
592 }
593
594 var (
595 jsonValueTypeURL = "types.googleapis.com/google.protobuf.Value"
596
597 zeroValueMap = map[string]proto.Message{
598 "google.protobuf.Any": &anypb.Any{TypeUrl: jsonValueTypeURL},
599 "google.protobuf.Duration": &dpb.Duration{},
600 "google.protobuf.ListValue": &structpb.ListValue{},
601 "google.protobuf.Struct": &structpb.Struct{},
602 "google.protobuf.Timestamp": &tpb.Timestamp{},
603 "google.protobuf.Value": &structpb.Value{},
604 "google.protobuf.BoolValue": wrapperspb.Bool(false),
605 "google.protobuf.BytesValue": wrapperspb.Bytes([]byte{}),
606 "google.protobuf.DoubleValue": wrapperspb.Double(0.0),
607 "google.protobuf.FloatValue": wrapperspb.Float(0.0),
608 "google.protobuf.Int32Value": wrapperspb.Int32(0),
609 "google.protobuf.Int64Value": wrapperspb.Int64(0),
610 "google.protobuf.StringValue": wrapperspb.String(""),
611 "google.protobuf.UInt32Value": wrapperspb.UInt32(0),
612 "google.protobuf.UInt64Value": wrapperspb.UInt64(0),
613 }
614 )