| 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 reflects over protocol buffer descriptors to generate objects |
| 16 | // that simplify type, enum, and field lookup. |
| 17 | package pb |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | |
| 22 | "google.golang.org/protobuf/proto" |
| 23 | "google.golang.org/protobuf/reflect/protoreflect" |
| 24 | "google.golang.org/protobuf/reflect/protoregistry" |
| 25 | |
| 26 | anypb "google.golang.org/protobuf/types/known/anypb" |
| 27 | durpb "google.golang.org/protobuf/types/known/durationpb" |
| 28 | emptypb "google.golang.org/protobuf/types/known/emptypb" |
| 29 | structpb "google.golang.org/protobuf/types/known/structpb" |
| 30 | tspb "google.golang.org/protobuf/types/known/timestamppb" |
| 31 | wrapperspb "google.golang.org/protobuf/types/known/wrapperspb" |
| 32 | ) |
| 33 | |
| 34 | // Db maps from file / message / enum name to file description. |
| 35 | // |
| 36 | // Each Db is isolated from each other, and while information about protobuf descriptors may be |
| 37 | // fetched from the global protobuf registry, no descriptors are added to this registry, else |
| 38 | // the isolation guarantees of the Db object would be violated. |
| 39 | type Db struct { |
| 40 | revFileDescriptorMap map[string]*FileDescription |
| 41 | // files contains the deduped set of FileDescriptions whose types are contained in the pb.Db. |
| 42 | files []*FileDescription |
| 43 | // extensions contains the mapping between a given type name, extension name and its FieldDescription |
| 44 | extensions map[string]map[string]*FieldDescription |
| 45 | } |
| 46 | |
| 47 | // extensionsMap is a type alias to a map[typeName]map[extensionName]*FieldDescription |
| 48 | type extensionMap = map[string]map[string]*FieldDescription |
| 49 | |
| 50 | var ( |
| 51 | // DefaultDb used at evaluation time or unless overridden at check time. |
| 52 | DefaultDb = &Db{ |
| 53 | revFileDescriptorMap: make(map[string]*FileDescription), |
| 54 | files: []*FileDescription{}, |
| 55 | extensions: make(extensionMap), |
| 56 | } |
| 57 | ) |
| 58 | |
| 59 | // Merge will copy the source proto message into the destination, or error if the merge cannot be completed. |
| 60 | // |
| 61 | // Unlike the proto.Merge, this method will fallback to proto.Marshal/Unmarshal of the two proto messages do not |
| 62 | // share the same instance of their type descriptor. |
| 63 | func Merge(dstPB, srcPB proto.Message) error { |
| 64 | src, dst := srcPB.ProtoReflect(), dstPB.ProtoReflect() |
| 65 | if src.Descriptor() == dst.Descriptor() { |
| 66 | proto.Merge(dstPB, srcPB) |
| 67 | return nil |
| 68 | } |
| 69 | if src.Descriptor().FullName() != dst.Descriptor().FullName() { |
| 70 | return fmt.Errorf("pb.Merge() arguments must be the same type. got: %v, %v", |
| 71 | dst.Descriptor().FullName(), src.Descriptor().FullName()) |
| 72 | } |
| 73 | bytes, err := proto.Marshal(srcPB) |
| 74 | if err != nil { |
| 75 | return fmt.Errorf("pb.Merge(dstPB, srcPB) failed to marshal source proto: %v", err) |
| 76 | } |
| 77 | err = proto.Unmarshal(bytes, dstPB) |
| 78 | if err != nil { |
| 79 | return fmt.Errorf("pb.Merge(dstPB, srcPB) failed to unmarshal to dest proto: %v", err) |
| 80 | } |
| 81 | return nil |
| 82 | } |
| 83 | |
| 84 | // NewDb creates a new `pb.Db` with an empty type name to file description map. |
| 85 | func NewDb() *Db { |
| 86 | pbdb := &Db{ |
| 87 | revFileDescriptorMap: make(map[string]*FileDescription), |
| 88 | files: []*FileDescription{}, |
| 89 | extensions: make(extensionMap), |
| 90 | } |
| 91 | // The FileDescription objects in the default db contain lazily initialized TypeDescription |
| 92 | // values which may point to the state contained in the DefaultDb irrespective of this shallow |
| 93 | // copy; however, the type graph for a field is idempotently computed, and is guaranteed to |
| 94 | // only be initialized once thanks to atomic values within the TypeDescription objects, so it |
| 95 | // is safe to share these values across instances. |
| 96 | for k, v := range DefaultDb.revFileDescriptorMap { |
| 97 | pbdb.revFileDescriptorMap[k] = v |
| 98 | } |
| 99 | pbdb.files = append(pbdb.files, DefaultDb.files...) |
| 100 | return pbdb |
| 101 | } |
| 102 | |
| 103 | // Copy creates a copy of the current database with its own internal descriptor mapping. |
| 104 | func (pbdb *Db) Copy() *Db { |
| 105 | copy := NewDb() |
| 106 | for _, fd := range pbdb.files { |
| 107 | hasFile := false |
| 108 | for _, fd2 := range copy.files { |
| 109 | if fd2 == fd { |
| 110 | hasFile = true |
| 111 | } |
| 112 | } |
| 113 | if !hasFile { |
| 114 | fd = fd.Copy(copy) |
| 115 | copy.files = append(copy.files, fd) |
| 116 | } |
| 117 | for _, enumValName := range fd.GetEnumNames() { |
| 118 | copy.revFileDescriptorMap[enumValName] = fd |
| 119 | } |
| 120 | for _, msgTypeName := range fd.GetTypeNames() { |
| 121 | copy.revFileDescriptorMap[msgTypeName] = fd |
| 122 | } |
| 123 | copy.revFileDescriptorMap[fd.GetName()] = fd |
| 124 | } |
| 125 | for typeName, extFieldMap := range pbdb.extensions { |
| 126 | copyExtFieldMap, found := copy.extensions[typeName] |
| 127 | if !found { |
| 128 | copyExtFieldMap = make(map[string]*FieldDescription, len(extFieldMap)) |
| 129 | } |
| 130 | for extFieldName, fd := range extFieldMap { |
| 131 | copyExtFieldMap[extFieldName] = fd |
| 132 | } |
| 133 | copy.extensions[typeName] = copyExtFieldMap |
| 134 | } |
| 135 | return copy |
| 136 | } |
| 137 | |
| 138 | // FileDescriptions returns the set of file descriptions associated with this db. |
| 139 | func (pbdb *Db) FileDescriptions() []*FileDescription { |
| 140 | return pbdb.files |
| 141 | } |
| 142 | |
| 143 | // RegisterDescriptor produces a `FileDescription` from a `FileDescriptor` and registers the |
| 144 | // message and enum types into the `pb.Db`. |
| 145 | func (pbdb *Db) RegisterDescriptor(fileDesc protoreflect.FileDescriptor) (*FileDescription, error) { |
| 146 | fd, found := pbdb.revFileDescriptorMap[fileDesc.Path()] |
| 147 | if found { |
| 148 | return fd, nil |
| 149 | } |
| 150 | // Make sure to search the global registry to see if a protoreflect.FileDescriptor for |
| 151 | // the file specified has been linked into the binary. If so, use the copy of the descriptor |
| 152 | // from the global cache. |
| 153 | // |
| 154 | // Note: Proto reflection relies on descriptor values being object equal rather than object |
| 155 | // equivalence. This choice means that a FieldDescriptor generated from a FileDescriptorProto |
| 156 | // will be incompatible with the FieldDescriptor in the global registry and any message created |
| 157 | // from that global registry. |
| 158 | globalFD, err := protoregistry.GlobalFiles.FindFileByPath(fileDesc.Path()) |
| 159 | if err == nil { |
| 160 | fileDesc = globalFD |
| 161 | } |
| 162 | var fileExtMap extensionMap |
| 163 | fd, fileExtMap = newFileDescription(fileDesc, pbdb) |
| 164 | for _, enumValName := range fd.GetEnumNames() { |
| 165 | pbdb.revFileDescriptorMap[enumValName] = fd |
| 166 | } |
| 167 | for _, msgTypeName := range fd.GetTypeNames() { |
| 168 | pbdb.revFileDescriptorMap[msgTypeName] = fd |
| 169 | } |
| 170 | pbdb.revFileDescriptorMap[fd.GetName()] = fd |
| 171 | |
| 172 | // Return the specific file descriptor registered. |
| 173 | pbdb.files = append(pbdb.files, fd) |
| 174 | |
| 175 | // Index the protobuf message extensions from the file into the pbdb |
| 176 | for typeName, extMap := range fileExtMap { |
| 177 | typeExtMap, found := pbdb.extensions[typeName] |
| 178 | if !found { |
| 179 | pbdb.extensions[typeName] = extMap |
| 180 | continue |
| 181 | } |
| 182 | for extName, field := range extMap { |
| 183 | typeExtMap[extName] = field |
| 184 | } |
| 185 | } |
| 186 | return fd, nil |
| 187 | } |
| 188 | |
| 189 | // RegisterMessage produces a `FileDescription` from a `message` and registers the message and all |
| 190 | // other definitions within the message file into the `pb.Db`. |
| 191 | func (pbdb *Db) RegisterMessage(message proto.Message) (*FileDescription, error) { |
| 192 | msgDesc := message.ProtoReflect().Descriptor() |
| 193 | msgName := msgDesc.FullName() |
| 194 | typeName := sanitizeProtoName(string(msgName)) |
| 195 | if fd, found := pbdb.revFileDescriptorMap[typeName]; found { |
| 196 | return fd, nil |
| 197 | } |
| 198 | return pbdb.RegisterDescriptor(msgDesc.ParentFile()) |
| 199 | } |
| 200 | |
| 201 | // DescribeEnum takes a qualified enum name and returns an `EnumDescription` if it exists in the |
| 202 | // `pb.Db`. |
| 203 | func (pbdb *Db) DescribeEnum(enumName string) (*EnumValueDescription, bool) { |
| 204 | enumName = sanitizeProtoName(enumName) |
| 205 | if fd, found := pbdb.revFileDescriptorMap[enumName]; found { |
| 206 | return fd.GetEnumDescription(enumName) |
| 207 | } |
| 208 | return nil, false |
| 209 | } |
| 210 | |
| 211 | // DescribeType returns a `TypeDescription` for the `typeName` if it exists in the `pb.Db`. |
| 212 | func (pbdb *Db) DescribeType(typeName string) (*TypeDescription, bool) { |
| 213 | typeName = sanitizeProtoName(typeName) |
| 214 | if fd, found := pbdb.revFileDescriptorMap[typeName]; found { |
| 215 | return fd.GetTypeDescription(typeName) |
| 216 | } |
| 217 | return nil, false |
| 218 | } |
| 219 | |
| 220 | // CollectFileDescriptorSet builds a file descriptor set associated with the file where the input |
| 221 | // message is declared. |
| 222 | func CollectFileDescriptorSet(message proto.Message) map[string]protoreflect.FileDescriptor { |
| 223 | fdMap := map[string]protoreflect.FileDescriptor{} |
| 224 | parentFile := message.ProtoReflect().Descriptor().ParentFile() |
| 225 | fdMap[parentFile.Path()] = parentFile |
| 226 | // Initialize list of dependencies |
| 227 | deps := make([]protoreflect.FileImport, parentFile.Imports().Len()) |
| 228 | for i := 0; i < parentFile.Imports().Len(); i++ { |
| 229 | deps[i] = parentFile.Imports().Get(i) |
| 230 | } |
| 231 | // Expand list for new dependencies |
| 232 | for i := 0; i < len(deps); i++ { |
| 233 | dep := deps[i] |
| 234 | if _, found := fdMap[dep.Path()]; found { |
| 235 | continue |
| 236 | } |
| 237 | fdMap[dep.Path()] = dep.FileDescriptor |
| 238 | for j := 0; j < dep.FileDescriptor.Imports().Len(); j++ { |
| 239 | deps = append(deps, dep.FileDescriptor.Imports().Get(j)) |
| 240 | } |
| 241 | } |
| 242 | return fdMap |
| 243 | } |
| 244 | |
| 245 | func init() { |
| 246 | // Describe well-known types to ensure they can always be resolved by the check and interpret |
| 247 | // execution phases. |
| 248 | // |
| 249 | // The following subset of message types is enough to ensure that all well-known types can |
| 250 | // resolved in the runtime, since describing the value results in describing the whole file |
| 251 | // where the message is declared. |
| 252 | DefaultDb.RegisterMessage(&anypb.Any{}) |
| 253 | DefaultDb.RegisterMessage(&durpb.Duration{}) |
| 254 | DefaultDb.RegisterMessage(&emptypb.Empty{}) |
| 255 | DefaultDb.RegisterMessage(&tspb.Timestamp{}) |
| 256 | DefaultDb.RegisterMessage(&structpb.Value{}) |
| 257 | DefaultDb.RegisterMessage(&wrapperspb.BoolValue{}) |
| 258 | } |