github.com/renbou/grpcbridge@v0.0.2-0.20240416012907-bcbd8b12648a/reflection/util.go (about)

     1  package reflection
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"encoding/hex"
     6  	"slices"
     7  	"strings"
     8  
     9  	"google.golang.org/protobuf/reflect/protoreflect"
    10  	"google.golang.org/protobuf/types/descriptorpb"
    11  )
    12  
    13  type namedProtoBundle struct {
    14  	name  string
    15  	proto []byte
    16  }
    17  
    18  func hashNamedProtoBundles(bundles []namedProtoBundle) string {
    19  	slices.SortFunc(bundles, func(a, b namedProtoBundle) int {
    20  		return strings.Compare(a.name, b.name)
    21  	})
    22  
    23  	h := sha256.New()
    24  	for _, bundle := range bundles {
    25  		h.Write(bundle.proto)
    26  	}
    27  
    28  	return hex.EncodeToString(h.Sum(nil))
    29  }
    30  
    31  func hashServiceNames(names []protoreflect.FullName) string {
    32  	slices.Sort(names)
    33  
    34  	h := sha256.New()
    35  	for _, name := range names {
    36  		h.Write([]byte(name))
    37  	}
    38  
    39  	return hex.EncodeToString(h.Sum(nil))
    40  }
    41  
    42  // updatePresentDescriptorSet is used by resolver.retrieveDependencies to update the set of available file descriptors.
    43  func updatePresentDescriptorSet(descriptors *descriptorpb.FileDescriptorSet, present map[string]struct{}) {
    44  	for _, fd := range descriptors.File {
    45  		present[fd.GetName()] = struct{}{}
    46  	}
    47  }
    48  
    49  // growMissingDescriptorSet is used by resolver.retrieveDependencies to update the set of missing file descriptors.
    50  func growMissingDescriptorSet(descriptors *descriptorpb.FileDescriptorSet, present map[string]struct{}, missing map[string]struct{}) {
    51  	for _, fd := range descriptors.File {
    52  		for _, dep := range fd.Dependency {
    53  			if _, ok := present[dep]; !ok {
    54  				missing[dep] = struct{}{}
    55  			}
    56  		}
    57  	}
    58  }
    59  
    60  // shrinkMissingDescriptorSet is used by resolver.retrieveDependencies to remove found file descriptors from the missing set.
    61  func shrinkMissingDescriptorSet(descriptors *descriptorpb.FileDescriptorSet, missing map[string]struct{}) {
    62  	for _, fd := range descriptors.File {
    63  		delete(missing, fd.GetName())
    64  	}
    65  }