backend.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package backend
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "strings"
  7. )
  8. var factoryMap map[string]Factory
  9. func init() {
  10. factoryMap = make(map[string]Factory)
  11. }
  12. // Factory backend factory
  13. type Factory func(map[string]interface{}) (Backend, error)
  14. // Registry registry backdend
  15. func Registry(name string, factory Factory) {
  16. if _, ok := factoryMap[name]; ok {
  17. panic(fmt.Sprintf("backend %s already exists", name))
  18. }
  19. factoryMap[name] = factory
  20. }
  21. // New backend
  22. func New(name string, conf map[string]interface{}) (Backend, error) {
  23. if factory, ok := factoryMap[name]; ok {
  24. return factory(conf)
  25. }
  26. return nil, fmt.Errorf("backend %s not exists", name)
  27. }
  28. // Selector selector
  29. type Selector struct {
  30. Env string
  31. Region string
  32. Zone string
  33. Hostname string
  34. }
  35. func (s Selector) String() string {
  36. strs := make([]string, 0, 4)
  37. if s.Env != "" {
  38. strs = append(strs, s.Env)
  39. }
  40. if s.Region != "" {
  41. strs = append(strs, s.Region)
  42. }
  43. if s.Zone != "" {
  44. strs = append(strs, s.Zone)
  45. }
  46. if s.Hostname != "" {
  47. strs = append(strs, s.Hostname)
  48. }
  49. return strings.Join(strs, "-")
  50. }
  51. // Target global unique application identifier
  52. type Target struct {
  53. Name string
  54. }
  55. func (t Target) String() string {
  56. return t.Name
  57. }
  58. // ParseName parse qname get name and selector
  59. func ParseName(name string, defaultSel Selector) (target Target, sel Selector, err error) {
  60. // TODO: support selector
  61. return Target{Name: name}, defaultSel, nil
  62. }
  63. // Metadata metadata contain env, zone, region e.g.
  64. type Metadata struct {
  65. ClientHost string
  66. LatestTimestamps string
  67. }
  68. // Instance service instance struct
  69. type Instance struct {
  70. Region string `json:"region"`
  71. Zone string `json:"zone"`
  72. Env string `json:"env"`
  73. Hostname string `json:"hostname"`
  74. DiscoveryID string `json:"discovery_id"`
  75. TreeID int64 `json:"tree_id"`
  76. IPAddr net.IP `json:"ip_addr,omitempty"` // hacked field
  77. }
  78. // Backend provide service query
  79. type Backend interface {
  80. Ping(ctx context.Context) error
  81. Query(ctx context.Context, target Target, sel Selector, md Metadata) ([]*Instance, error)
  82. Close(ctx context.Context) error
  83. }