registry.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package registry
  2. import (
  3. "github.com/v2fly/v2ray-core/v4/common/protoext"
  4. "google.golang.org/protobuf/proto"
  5. )
  6. type implementationRegistry struct {
  7. implSet map[string]*implementationSet
  8. }
  9. func (i *implementationRegistry) RegisterImplementation(name string, opt *protoext.MessageOpt, loader CustomLoader) {
  10. interfaceType := opt.GetType()[0]
  11. implSet, found := i.implSet[interfaceType]
  12. if !found {
  13. implSet = newImplementationSet()
  14. i.implSet[interfaceType] = implSet
  15. }
  16. implSet.RegisterImplementation(name, opt, loader)
  17. }
  18. func (i *implementationRegistry) FindImplementationByAlias(interfaceType, alias string) (string, CustomLoader, error) {
  19. implSet, found := i.implSet[interfaceType]
  20. if !found {
  21. return "", nil, newError("cannot find implemention unknown interface type")
  22. }
  23. return implSet.FindImplementationByAlias(alias)
  24. }
  25. func newImplementationRegistry() *implementationRegistry {
  26. return &implementationRegistry{implSet: map[string]*implementationSet{}}
  27. }
  28. var globalImplementationRegistry = newImplementationRegistry()
  29. // RegisterImplementation register an implementation of a type of interface
  30. // loader(CustomLoader) is a private API, its interface is subject to breaking changes
  31. func RegisterImplementation(proto proto.Message, loader CustomLoader) error {
  32. msgDesc := proto.ProtoReflect().Type().Descriptor()
  33. fullName := string(msgDesc.FullName())
  34. msgOpts, err := protoext.GetMessageOptions(msgDesc)
  35. if err != nil {
  36. return newError("unable to find message options").Base(err)
  37. }
  38. globalImplementationRegistry.RegisterImplementation(fullName, msgOpts, loader)
  39. return nil
  40. }
  41. func FindImplementationByAlias(interfaceType, alias string) (string, CustomLoader, error) {
  42. return globalImplementationRegistry.FindImplementationByAlias(interfaceType, alias)
  43. }