registry.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package protoregistry provides data structures to register and lookup
  5. // protobuf descriptor types.
  6. //
  7. // The Files registry contains file descriptors and provides the ability
  8. // to iterate over the files or lookup a specific descriptor within the files.
  9. // Files only contains protobuf descriptors and has no understanding of Go
  10. // type information that may be associated with each descriptor.
  11. //
  12. // The Types registry contains descriptor types for which there is a known
  13. // Go type associated with that descriptor. It provides the ability to iterate
  14. // over the registered types or lookup a type by name.
  15. package protoregistry
  16. import (
  17. "fmt"
  18. "os"
  19. "strings"
  20. "sync"
  21. "google.golang.org/protobuf/internal/encoding/messageset"
  22. "google.golang.org/protobuf/internal/errors"
  23. "google.golang.org/protobuf/internal/flags"
  24. "google.golang.org/protobuf/reflect/protoreflect"
  25. )
  26. // conflictPolicy configures the policy for handling registration conflicts.
  27. //
  28. // It can be over-written at compile time with a linker-initialized variable:
  29. // go build -ldflags "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn"
  30. //
  31. // It can be over-written at program execution with an environment variable:
  32. // GOLANG_PROTOBUF_REGISTRATION_CONFLICT=warn ./main
  33. //
  34. // Neither of the above are covered by the compatibility promise and
  35. // may be removed in a future release of this module.
  36. var conflictPolicy = "panic" // "panic" | "warn" | "ignore"
  37. // ignoreConflict reports whether to ignore a registration conflict
  38. // given the descriptor being registered and the error.
  39. // It is a variable so that the behavior is easily overridden in another file.
  40. var ignoreConflict = func(d protoreflect.Descriptor, err error) bool {
  41. const env = "GOLANG_PROTOBUF_REGISTRATION_CONFLICT"
  42. const faq = "https://developers.google.com/protocol-buffers/docs/reference/go/faq#namespace-conflict"
  43. policy := conflictPolicy
  44. if v := os.Getenv(env); v != "" {
  45. policy = v
  46. }
  47. switch policy {
  48. case "panic":
  49. panic(fmt.Sprintf("%v\nSee %v\n", err, faq))
  50. case "warn":
  51. fmt.Fprintf(os.Stderr, "WARNING: %v\nSee %v\n\n", err, faq)
  52. return true
  53. case "ignore":
  54. return true
  55. default:
  56. panic("invalid " + env + " value: " + os.Getenv(env))
  57. }
  58. }
  59. var globalMutex sync.RWMutex
  60. // GlobalFiles is a global registry of file descriptors.
  61. var GlobalFiles *Files = new(Files)
  62. // GlobalTypes is the registry used by default for type lookups
  63. // unless a local registry is provided by the user.
  64. var GlobalTypes *Types = new(Types)
  65. // NotFound is a sentinel error value to indicate that the type was not found.
  66. //
  67. // Since registry lookup can happen in the critical performance path, resolvers
  68. // must return this exact error value, not an error wrapping it.
  69. var NotFound = errors.New("not found")
  70. // Files is a registry for looking up or iterating over files and the
  71. // descriptors contained within them.
  72. // The Find and Range methods are safe for concurrent use.
  73. type Files struct {
  74. // The map of descsByName contains:
  75. // EnumDescriptor
  76. // EnumValueDescriptor
  77. // MessageDescriptor
  78. // ExtensionDescriptor
  79. // ServiceDescriptor
  80. // *packageDescriptor
  81. //
  82. // Note that files are stored as a slice, since a package may contain
  83. // multiple files. Only top-level declarations are registered.
  84. // Note that enum values are in the top-level since that are in the same
  85. // scope as the parent enum.
  86. descsByName map[protoreflect.FullName]interface{}
  87. filesByPath map[string][]protoreflect.FileDescriptor
  88. numFiles int
  89. }
  90. type packageDescriptor struct {
  91. files []protoreflect.FileDescriptor
  92. }
  93. // RegisterFile registers the provided file descriptor.
  94. //
  95. // If any descriptor within the file conflicts with the descriptor of any
  96. // previously registered file (e.g., two enums with the same full name),
  97. // then the file is not registered and an error is returned.
  98. //
  99. // It is permitted for multiple files to have the same file path.
  100. func (r *Files) RegisterFile(file protoreflect.FileDescriptor) error {
  101. if r == GlobalFiles {
  102. globalMutex.Lock()
  103. defer globalMutex.Unlock()
  104. }
  105. if r.descsByName == nil {
  106. r.descsByName = map[protoreflect.FullName]interface{}{
  107. "": &packageDescriptor{},
  108. }
  109. r.filesByPath = make(map[string][]protoreflect.FileDescriptor)
  110. }
  111. path := file.Path()
  112. if prev := r.filesByPath[path]; len(prev) > 0 {
  113. r.checkGenProtoConflict(path)
  114. err := errors.New("file %q is already registered", file.Path())
  115. err = amendErrorWithCaller(err, prev[0], file)
  116. if !(r == GlobalFiles && ignoreConflict(file, err)) {
  117. return err
  118. }
  119. }
  120. for name := file.Package(); name != ""; name = name.Parent() {
  121. switch prev := r.descsByName[name]; prev.(type) {
  122. case nil, *packageDescriptor:
  123. default:
  124. err := errors.New("file %q has a package name conflict over %v", file.Path(), name)
  125. err = amendErrorWithCaller(err, prev, file)
  126. if r == GlobalFiles && ignoreConflict(file, err) {
  127. err = nil
  128. }
  129. return err
  130. }
  131. }
  132. var err error
  133. var hasConflict bool
  134. rangeTopLevelDescriptors(file, func(d protoreflect.Descriptor) {
  135. if prev := r.descsByName[d.FullName()]; prev != nil {
  136. hasConflict = true
  137. err = errors.New("file %q has a name conflict over %v", file.Path(), d.FullName())
  138. err = amendErrorWithCaller(err, prev, file)
  139. if r == GlobalFiles && ignoreConflict(d, err) {
  140. err = nil
  141. }
  142. }
  143. })
  144. if hasConflict {
  145. return err
  146. }
  147. for name := file.Package(); name != ""; name = name.Parent() {
  148. if r.descsByName[name] == nil {
  149. r.descsByName[name] = &packageDescriptor{}
  150. }
  151. }
  152. p := r.descsByName[file.Package()].(*packageDescriptor)
  153. p.files = append(p.files, file)
  154. rangeTopLevelDescriptors(file, func(d protoreflect.Descriptor) {
  155. r.descsByName[d.FullName()] = d
  156. })
  157. r.filesByPath[path] = append(r.filesByPath[path], file)
  158. r.numFiles++
  159. return nil
  160. }
  161. // Several well-known types were hosted in the google.golang.org/genproto module
  162. // but were later moved to this module. To avoid a weak dependency on the
  163. // genproto module (and its relatively large set of transitive dependencies),
  164. // we rely on a registration conflict to determine whether the genproto version
  165. // is too old (i.e., does not contain aliases to the new type declarations).
  166. func (r *Files) checkGenProtoConflict(path string) {
  167. if r != GlobalFiles {
  168. return
  169. }
  170. var prevPath string
  171. const prevModule = "google.golang.org/genproto"
  172. const prevVersion = "cb27e3aa (May 26th, 2020)"
  173. switch path {
  174. case "google/protobuf/field_mask.proto":
  175. prevPath = prevModule + "/protobuf/field_mask"
  176. case "google/protobuf/api.proto":
  177. prevPath = prevModule + "/protobuf/api"
  178. case "google/protobuf/type.proto":
  179. prevPath = prevModule + "/protobuf/ptype"
  180. case "google/protobuf/source_context.proto":
  181. prevPath = prevModule + "/protobuf/source_context"
  182. default:
  183. return
  184. }
  185. pkgName := strings.TrimSuffix(strings.TrimPrefix(path, "google/protobuf/"), ".proto")
  186. pkgName = strings.Replace(pkgName, "_", "", -1) + "pb" // e.g., "field_mask" => "fieldmaskpb"
  187. currPath := "google.golang.org/protobuf/types/known/" + pkgName
  188. panic(fmt.Sprintf(""+
  189. "duplicate registration of %q\n"+
  190. "\n"+
  191. "The generated definition for this file has moved:\n"+
  192. "\tfrom: %q\n"+
  193. "\tto: %q\n"+
  194. "A dependency on the %q module must\n"+
  195. "be at version %v or higher.\n"+
  196. "\n"+
  197. "Upgrade the dependency by running:\n"+
  198. "\tgo get -u %v\n",
  199. path, prevPath, currPath, prevModule, prevVersion, prevPath))
  200. }
  201. // FindDescriptorByName looks up a descriptor by the full name.
  202. //
  203. // This returns (nil, NotFound) if not found.
  204. func (r *Files) FindDescriptorByName(name protoreflect.FullName) (protoreflect.Descriptor, error) {
  205. if r == nil {
  206. return nil, NotFound
  207. }
  208. if r == GlobalFiles {
  209. globalMutex.RLock()
  210. defer globalMutex.RUnlock()
  211. }
  212. prefix := name
  213. suffix := nameSuffix("")
  214. for prefix != "" {
  215. if d, ok := r.descsByName[prefix]; ok {
  216. switch d := d.(type) {
  217. case protoreflect.EnumDescriptor:
  218. if d.FullName() == name {
  219. return d, nil
  220. }
  221. case protoreflect.EnumValueDescriptor:
  222. if d.FullName() == name {
  223. return d, nil
  224. }
  225. case protoreflect.MessageDescriptor:
  226. if d.FullName() == name {
  227. return d, nil
  228. }
  229. if d := findDescriptorInMessage(d, suffix); d != nil && d.FullName() == name {
  230. return d, nil
  231. }
  232. case protoreflect.ExtensionDescriptor:
  233. if d.FullName() == name {
  234. return d, nil
  235. }
  236. case protoreflect.ServiceDescriptor:
  237. if d.FullName() == name {
  238. return d, nil
  239. }
  240. if d := d.Methods().ByName(suffix.Pop()); d != nil && d.FullName() == name {
  241. return d, nil
  242. }
  243. }
  244. return nil, NotFound
  245. }
  246. prefix = prefix.Parent()
  247. suffix = nameSuffix(name[len(prefix)+len("."):])
  248. }
  249. return nil, NotFound
  250. }
  251. func findDescriptorInMessage(md protoreflect.MessageDescriptor, suffix nameSuffix) protoreflect.Descriptor {
  252. name := suffix.Pop()
  253. if suffix == "" {
  254. if ed := md.Enums().ByName(name); ed != nil {
  255. return ed
  256. }
  257. for i := md.Enums().Len() - 1; i >= 0; i-- {
  258. if vd := md.Enums().Get(i).Values().ByName(name); vd != nil {
  259. return vd
  260. }
  261. }
  262. if xd := md.Extensions().ByName(name); xd != nil {
  263. return xd
  264. }
  265. if fd := md.Fields().ByName(name); fd != nil {
  266. return fd
  267. }
  268. if od := md.Oneofs().ByName(name); od != nil {
  269. return od
  270. }
  271. }
  272. if md := md.Messages().ByName(name); md != nil {
  273. if suffix == "" {
  274. return md
  275. }
  276. return findDescriptorInMessage(md, suffix)
  277. }
  278. return nil
  279. }
  280. type nameSuffix string
  281. func (s *nameSuffix) Pop() (name protoreflect.Name) {
  282. if i := strings.IndexByte(string(*s), '.'); i >= 0 {
  283. name, *s = protoreflect.Name((*s)[:i]), (*s)[i+1:]
  284. } else {
  285. name, *s = protoreflect.Name((*s)), ""
  286. }
  287. return name
  288. }
  289. // FindFileByPath looks up a file by the path.
  290. //
  291. // This returns (nil, NotFound) if not found.
  292. // This returns an error if multiple files have the same path.
  293. func (r *Files) FindFileByPath(path string) (protoreflect.FileDescriptor, error) {
  294. if r == nil {
  295. return nil, NotFound
  296. }
  297. if r == GlobalFiles {
  298. globalMutex.RLock()
  299. defer globalMutex.RUnlock()
  300. }
  301. fds := r.filesByPath[path]
  302. switch len(fds) {
  303. case 0:
  304. return nil, NotFound
  305. case 1:
  306. return fds[0], nil
  307. default:
  308. return nil, errors.New("multiple files named %q", path)
  309. }
  310. }
  311. // NumFiles reports the number of registered files,
  312. // including duplicate files with the same name.
  313. func (r *Files) NumFiles() int {
  314. if r == nil {
  315. return 0
  316. }
  317. if r == GlobalFiles {
  318. globalMutex.RLock()
  319. defer globalMutex.RUnlock()
  320. }
  321. return r.numFiles
  322. }
  323. // RangeFiles iterates over all registered files while f returns true.
  324. // If multiple files have the same name, RangeFiles iterates over all of them.
  325. // The iteration order is undefined.
  326. func (r *Files) RangeFiles(f func(protoreflect.FileDescriptor) bool) {
  327. if r == nil {
  328. return
  329. }
  330. if r == GlobalFiles {
  331. globalMutex.RLock()
  332. defer globalMutex.RUnlock()
  333. }
  334. for _, files := range r.filesByPath {
  335. for _, file := range files {
  336. if !f(file) {
  337. return
  338. }
  339. }
  340. }
  341. }
  342. // NumFilesByPackage reports the number of registered files in a proto package.
  343. func (r *Files) NumFilesByPackage(name protoreflect.FullName) int {
  344. if r == nil {
  345. return 0
  346. }
  347. if r == GlobalFiles {
  348. globalMutex.RLock()
  349. defer globalMutex.RUnlock()
  350. }
  351. p, ok := r.descsByName[name].(*packageDescriptor)
  352. if !ok {
  353. return 0
  354. }
  355. return len(p.files)
  356. }
  357. // RangeFilesByPackage iterates over all registered files in a given proto package
  358. // while f returns true. The iteration order is undefined.
  359. func (r *Files) RangeFilesByPackage(name protoreflect.FullName, f func(protoreflect.FileDescriptor) bool) {
  360. if r == nil {
  361. return
  362. }
  363. if r == GlobalFiles {
  364. globalMutex.RLock()
  365. defer globalMutex.RUnlock()
  366. }
  367. p, ok := r.descsByName[name].(*packageDescriptor)
  368. if !ok {
  369. return
  370. }
  371. for _, file := range p.files {
  372. if !f(file) {
  373. return
  374. }
  375. }
  376. }
  377. // rangeTopLevelDescriptors iterates over all top-level descriptors in a file
  378. // which will be directly entered into the registry.
  379. func rangeTopLevelDescriptors(fd protoreflect.FileDescriptor, f func(protoreflect.Descriptor)) {
  380. eds := fd.Enums()
  381. for i := eds.Len() - 1; i >= 0; i-- {
  382. f(eds.Get(i))
  383. vds := eds.Get(i).Values()
  384. for i := vds.Len() - 1; i >= 0; i-- {
  385. f(vds.Get(i))
  386. }
  387. }
  388. mds := fd.Messages()
  389. for i := mds.Len() - 1; i >= 0; i-- {
  390. f(mds.Get(i))
  391. }
  392. xds := fd.Extensions()
  393. for i := xds.Len() - 1; i >= 0; i-- {
  394. f(xds.Get(i))
  395. }
  396. sds := fd.Services()
  397. for i := sds.Len() - 1; i >= 0; i-- {
  398. f(sds.Get(i))
  399. }
  400. }
  401. // MessageTypeResolver is an interface for looking up messages.
  402. //
  403. // A compliant implementation must deterministically return the same type
  404. // if no error is encountered.
  405. //
  406. // The Types type implements this interface.
  407. type MessageTypeResolver interface {
  408. // FindMessageByName looks up a message by its full name.
  409. // E.g., "google.protobuf.Any"
  410. //
  411. // This return (nil, NotFound) if not found.
  412. FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error)
  413. // FindMessageByURL looks up a message by a URL identifier.
  414. // See documentation on google.protobuf.Any.type_url for the URL format.
  415. //
  416. // This returns (nil, NotFound) if not found.
  417. FindMessageByURL(url string) (protoreflect.MessageType, error)
  418. }
  419. // ExtensionTypeResolver is an interface for looking up extensions.
  420. //
  421. // A compliant implementation must deterministically return the same type
  422. // if no error is encountered.
  423. //
  424. // The Types type implements this interface.
  425. type ExtensionTypeResolver interface {
  426. // FindExtensionByName looks up a extension field by the field's full name.
  427. // Note that this is the full name of the field as determined by
  428. // where the extension is declared and is unrelated to the full name of the
  429. // message being extended.
  430. //
  431. // This returns (nil, NotFound) if not found.
  432. FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error)
  433. // FindExtensionByNumber looks up a extension field by the field number
  434. // within some parent message, identified by full name.
  435. //
  436. // This returns (nil, NotFound) if not found.
  437. FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error)
  438. }
  439. var (
  440. _ MessageTypeResolver = (*Types)(nil)
  441. _ ExtensionTypeResolver = (*Types)(nil)
  442. )
  443. // Types is a registry for looking up or iterating over descriptor types.
  444. // The Find and Range methods are safe for concurrent use.
  445. type Types struct {
  446. typesByName typesByName
  447. extensionsByMessage extensionsByMessage
  448. numEnums int
  449. numMessages int
  450. numExtensions int
  451. }
  452. type (
  453. typesByName map[protoreflect.FullName]interface{}
  454. extensionsByMessage map[protoreflect.FullName]extensionsByNumber
  455. extensionsByNumber map[protoreflect.FieldNumber]protoreflect.ExtensionType
  456. )
  457. // RegisterMessage registers the provided message type.
  458. //
  459. // If a naming conflict occurs, the type is not registered and an error is returned.
  460. func (r *Types) RegisterMessage(mt protoreflect.MessageType) error {
  461. // Under rare circumstances getting the descriptor might recursively
  462. // examine the registry, so fetch it before locking.
  463. md := mt.Descriptor()
  464. if r == GlobalTypes {
  465. globalMutex.Lock()
  466. defer globalMutex.Unlock()
  467. }
  468. if err := r.register("message", md, mt); err != nil {
  469. return err
  470. }
  471. r.numMessages++
  472. return nil
  473. }
  474. // RegisterEnum registers the provided enum type.
  475. //
  476. // If a naming conflict occurs, the type is not registered and an error is returned.
  477. func (r *Types) RegisterEnum(et protoreflect.EnumType) error {
  478. // Under rare circumstances getting the descriptor might recursively
  479. // examine the registry, so fetch it before locking.
  480. ed := et.Descriptor()
  481. if r == GlobalTypes {
  482. globalMutex.Lock()
  483. defer globalMutex.Unlock()
  484. }
  485. if err := r.register("enum", ed, et); err != nil {
  486. return err
  487. }
  488. r.numEnums++
  489. return nil
  490. }
  491. // RegisterExtension registers the provided extension type.
  492. //
  493. // If a naming conflict occurs, the type is not registered and an error is returned.
  494. func (r *Types) RegisterExtension(xt protoreflect.ExtensionType) error {
  495. // Under rare circumstances getting the descriptor might recursively
  496. // examine the registry, so fetch it before locking.
  497. //
  498. // A known case where this can happen: Fetching the TypeDescriptor for a
  499. // legacy ExtensionDesc can consult the global registry.
  500. xd := xt.TypeDescriptor()
  501. if r == GlobalTypes {
  502. globalMutex.Lock()
  503. defer globalMutex.Unlock()
  504. }
  505. field := xd.Number()
  506. message := xd.ContainingMessage().FullName()
  507. if prev := r.extensionsByMessage[message][field]; prev != nil {
  508. err := errors.New("extension number %d is already registered on message %v", field, message)
  509. err = amendErrorWithCaller(err, prev, xt)
  510. if !(r == GlobalTypes && ignoreConflict(xd, err)) {
  511. return err
  512. }
  513. }
  514. if err := r.register("extension", xd, xt); err != nil {
  515. return err
  516. }
  517. if r.extensionsByMessage == nil {
  518. r.extensionsByMessage = make(extensionsByMessage)
  519. }
  520. if r.extensionsByMessage[message] == nil {
  521. r.extensionsByMessage[message] = make(extensionsByNumber)
  522. }
  523. r.extensionsByMessage[message][field] = xt
  524. r.numExtensions++
  525. return nil
  526. }
  527. func (r *Types) register(kind string, desc protoreflect.Descriptor, typ interface{}) error {
  528. name := desc.FullName()
  529. prev := r.typesByName[name]
  530. if prev != nil {
  531. err := errors.New("%v %v is already registered", kind, name)
  532. err = amendErrorWithCaller(err, prev, typ)
  533. if !(r == GlobalTypes && ignoreConflict(desc, err)) {
  534. return err
  535. }
  536. }
  537. if r.typesByName == nil {
  538. r.typesByName = make(typesByName)
  539. }
  540. r.typesByName[name] = typ
  541. return nil
  542. }
  543. // FindEnumByName looks up an enum by its full name.
  544. // E.g., "google.protobuf.Field.Kind".
  545. //
  546. // This returns (nil, NotFound) if not found.
  547. func (r *Types) FindEnumByName(enum protoreflect.FullName) (protoreflect.EnumType, error) {
  548. if r == nil {
  549. return nil, NotFound
  550. }
  551. if r == GlobalTypes {
  552. globalMutex.RLock()
  553. defer globalMutex.RUnlock()
  554. }
  555. if v := r.typesByName[enum]; v != nil {
  556. if et, _ := v.(protoreflect.EnumType); et != nil {
  557. return et, nil
  558. }
  559. return nil, errors.New("found wrong type: got %v, want enum", typeName(v))
  560. }
  561. return nil, NotFound
  562. }
  563. // FindMessageByName looks up a message by its full name,
  564. // e.g. "google.protobuf.Any".
  565. //
  566. // This returns (nil, NotFound) if not found.
  567. func (r *Types) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) {
  568. if r == nil {
  569. return nil, NotFound
  570. }
  571. if r == GlobalTypes {
  572. globalMutex.RLock()
  573. defer globalMutex.RUnlock()
  574. }
  575. if v := r.typesByName[message]; v != nil {
  576. if mt, _ := v.(protoreflect.MessageType); mt != nil {
  577. return mt, nil
  578. }
  579. return nil, errors.New("found wrong type: got %v, want message", typeName(v))
  580. }
  581. return nil, NotFound
  582. }
  583. // FindMessageByURL looks up a message by a URL identifier.
  584. // See documentation on google.protobuf.Any.type_url for the URL format.
  585. //
  586. // This returns (nil, NotFound) if not found.
  587. func (r *Types) FindMessageByURL(url string) (protoreflect.MessageType, error) {
  588. // This function is similar to FindMessageByName but
  589. // truncates anything before and including '/' in the URL.
  590. if r == nil {
  591. return nil, NotFound
  592. }
  593. if r == GlobalTypes {
  594. globalMutex.RLock()
  595. defer globalMutex.RUnlock()
  596. }
  597. message := protoreflect.FullName(url)
  598. if i := strings.LastIndexByte(url, '/'); i >= 0 {
  599. message = message[i+len("/"):]
  600. }
  601. if v := r.typesByName[message]; v != nil {
  602. if mt, _ := v.(protoreflect.MessageType); mt != nil {
  603. return mt, nil
  604. }
  605. return nil, errors.New("found wrong type: got %v, want message", typeName(v))
  606. }
  607. return nil, NotFound
  608. }
  609. // FindExtensionByName looks up a extension field by the field's full name.
  610. // Note that this is the full name of the field as determined by
  611. // where the extension is declared and is unrelated to the full name of the
  612. // message being extended.
  613. //
  614. // This returns (nil, NotFound) if not found.
  615. func (r *Types) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) {
  616. if r == nil {
  617. return nil, NotFound
  618. }
  619. if r == GlobalTypes {
  620. globalMutex.RLock()
  621. defer globalMutex.RUnlock()
  622. }
  623. if v := r.typesByName[field]; v != nil {
  624. if xt, _ := v.(protoreflect.ExtensionType); xt != nil {
  625. return xt, nil
  626. }
  627. // MessageSet extensions are special in that the name of the extension
  628. // is the name of the message type used to extend the MessageSet.
  629. // This naming scheme is used by text and JSON serialization.
  630. //
  631. // This feature is protected by the ProtoLegacy flag since MessageSets
  632. // are a proto1 feature that is long deprecated.
  633. if flags.ProtoLegacy {
  634. if _, ok := v.(protoreflect.MessageType); ok {
  635. field := field.Append(messageset.ExtensionName)
  636. if v := r.typesByName[field]; v != nil {
  637. if xt, _ := v.(protoreflect.ExtensionType); xt != nil {
  638. if messageset.IsMessageSetExtension(xt.TypeDescriptor()) {
  639. return xt, nil
  640. }
  641. }
  642. }
  643. }
  644. }
  645. return nil, errors.New("found wrong type: got %v, want extension", typeName(v))
  646. }
  647. return nil, NotFound
  648. }
  649. // FindExtensionByNumber looks up a extension field by the field number
  650. // within some parent message, identified by full name.
  651. //
  652. // This returns (nil, NotFound) if not found.
  653. func (r *Types) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) {
  654. if r == nil {
  655. return nil, NotFound
  656. }
  657. if r == GlobalTypes {
  658. globalMutex.RLock()
  659. defer globalMutex.RUnlock()
  660. }
  661. if xt, ok := r.extensionsByMessage[message][field]; ok {
  662. return xt, nil
  663. }
  664. return nil, NotFound
  665. }
  666. // NumEnums reports the number of registered enums.
  667. func (r *Types) NumEnums() int {
  668. if r == nil {
  669. return 0
  670. }
  671. if r == GlobalTypes {
  672. globalMutex.RLock()
  673. defer globalMutex.RUnlock()
  674. }
  675. return r.numEnums
  676. }
  677. // RangeEnums iterates over all registered enums while f returns true.
  678. // Iteration order is undefined.
  679. func (r *Types) RangeEnums(f func(protoreflect.EnumType) bool) {
  680. if r == nil {
  681. return
  682. }
  683. if r == GlobalTypes {
  684. globalMutex.RLock()
  685. defer globalMutex.RUnlock()
  686. }
  687. for _, typ := range r.typesByName {
  688. if et, ok := typ.(protoreflect.EnumType); ok {
  689. if !f(et) {
  690. return
  691. }
  692. }
  693. }
  694. }
  695. // NumMessages reports the number of registered messages.
  696. func (r *Types) NumMessages() int {
  697. if r == nil {
  698. return 0
  699. }
  700. if r == GlobalTypes {
  701. globalMutex.RLock()
  702. defer globalMutex.RUnlock()
  703. }
  704. return r.numMessages
  705. }
  706. // RangeMessages iterates over all registered messages while f returns true.
  707. // Iteration order is undefined.
  708. func (r *Types) RangeMessages(f func(protoreflect.MessageType) bool) {
  709. if r == nil {
  710. return
  711. }
  712. if r == GlobalTypes {
  713. globalMutex.RLock()
  714. defer globalMutex.RUnlock()
  715. }
  716. for _, typ := range r.typesByName {
  717. if mt, ok := typ.(protoreflect.MessageType); ok {
  718. if !f(mt) {
  719. return
  720. }
  721. }
  722. }
  723. }
  724. // NumExtensions reports the number of registered extensions.
  725. func (r *Types) NumExtensions() int {
  726. if r == nil {
  727. return 0
  728. }
  729. if r == GlobalTypes {
  730. globalMutex.RLock()
  731. defer globalMutex.RUnlock()
  732. }
  733. return r.numExtensions
  734. }
  735. // RangeExtensions iterates over all registered extensions while f returns true.
  736. // Iteration order is undefined.
  737. func (r *Types) RangeExtensions(f func(protoreflect.ExtensionType) bool) {
  738. if r == nil {
  739. return
  740. }
  741. if r == GlobalTypes {
  742. globalMutex.RLock()
  743. defer globalMutex.RUnlock()
  744. }
  745. for _, typ := range r.typesByName {
  746. if xt, ok := typ.(protoreflect.ExtensionType); ok {
  747. if !f(xt) {
  748. return
  749. }
  750. }
  751. }
  752. }
  753. // NumExtensionsByMessage reports the number of registered extensions for
  754. // a given message type.
  755. func (r *Types) NumExtensionsByMessage(message protoreflect.FullName) int {
  756. if r == nil {
  757. return 0
  758. }
  759. if r == GlobalTypes {
  760. globalMutex.RLock()
  761. defer globalMutex.RUnlock()
  762. }
  763. return len(r.extensionsByMessage[message])
  764. }
  765. // RangeExtensionsByMessage iterates over all registered extensions filtered
  766. // by a given message type while f returns true. Iteration order is undefined.
  767. func (r *Types) RangeExtensionsByMessage(message protoreflect.FullName, f func(protoreflect.ExtensionType) bool) {
  768. if r == nil {
  769. return
  770. }
  771. if r == GlobalTypes {
  772. globalMutex.RLock()
  773. defer globalMutex.RUnlock()
  774. }
  775. for _, xt := range r.extensionsByMessage[message] {
  776. if !f(xt) {
  777. return
  778. }
  779. }
  780. }
  781. func typeName(t interface{}) string {
  782. switch t.(type) {
  783. case protoreflect.EnumType:
  784. return "enum"
  785. case protoreflect.MessageType:
  786. return "message"
  787. case protoreflect.ExtensionType:
  788. return "extension"
  789. default:
  790. return fmt.Sprintf("%T", t)
  791. }
  792. }
  793. func amendErrorWithCaller(err error, prev, curr interface{}) error {
  794. prevPkg := goPackage(prev)
  795. currPkg := goPackage(curr)
  796. if prevPkg == "" || currPkg == "" || prevPkg == currPkg {
  797. return err
  798. }
  799. return errors.New("%s\n\tpreviously from: %q\n\tcurrently from: %q", err, prevPkg, currPkg)
  800. }
  801. func goPackage(v interface{}) string {
  802. switch d := v.(type) {
  803. case protoreflect.EnumType:
  804. v = d.Descriptor()
  805. case protoreflect.MessageType:
  806. v = d.Descriptor()
  807. case protoreflect.ExtensionType:
  808. v = d.TypeDescriptor()
  809. }
  810. if d, ok := v.(protoreflect.Descriptor); ok {
  811. v = d.ParentFile()
  812. }
  813. if d, ok := v.(interface{ GoPackagePath() string }); ok {
  814. return d.GoPackagePath()
  815. }
  816. return ""
  817. }