github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/registry/memory/util.go (about) 1 package memory 2 3 import ( 4 "context" 5 "time" 6 7 "github.com/volts-dev/volts/registry" 8 ) 9 10 type servicesKey struct{} 11 12 func getServiceRecords(ctx context.Context) map[string]map[string]*record { 13 memServices, ok := ctx.Value(servicesKey{}).(map[string][]*registry.Service) 14 if !ok { 15 return nil 16 } 17 18 services := make(map[string]map[string]*record) 19 20 for name, svc := range memServices { 21 if _, ok := services[name]; !ok { 22 services[name] = make(map[string]*record) 23 } 24 // go through every version of the service 25 for _, s := range svc { 26 services[s.Name][s.Version] = serviceToRecord(s, 0) 27 } 28 } 29 30 return services 31 } 32 33 func serviceToRecord(s *registry.Service, ttl time.Duration) *record { 34 metadata := make(map[string]string, len(s.Metadata)) 35 for k, v := range s.Metadata { 36 metadata[k] = v 37 } 38 39 nodes := make(map[string]*node, len(s.Nodes)) 40 for _, n := range s.Nodes { 41 nodes[n.Id] = &node{ 42 Node: n, 43 TTL: ttl, 44 LastSeen: time.Now(), 45 } 46 } 47 48 endpoints := make([]*registry.Endpoint, len(s.Endpoints)) 49 for i, e := range s.Endpoints { 50 endpoints[i] = e 51 } 52 53 return &record{ 54 Name: s.Name, 55 Version: s.Version, 56 Metadata: metadata, 57 Nodes: nodes, 58 Endpoints: endpoints, 59 } 60 } 61 62 func recordToService(r *record) *registry.Service { 63 metadata := make(map[string]string, len(r.Metadata)) 64 for k, v := range r.Metadata { 65 metadata[k] = v 66 } 67 68 endpoints := make([]*registry.Endpoint, len(r.Endpoints)) 69 for i, e := range r.Endpoints { 70 request := new(registry.Value) 71 if e.Request != nil { 72 *request = *e.Request 73 } 74 response := new(registry.Value) 75 if e.Response != nil { 76 *response = *e.Response 77 } 78 79 metadata := make(map[string]string, len(e.Metadata)) 80 for k, v := range e.Metadata { 81 metadata[k] = v 82 } 83 84 endpoints[i] = ®istry.Endpoint{ 85 Name: e.Name, 86 Host: e.Host, 87 Method: e.Method, 88 Path: e.Path, 89 Description: e.Description, 90 Stream: e.Stream, 91 Handler: e.Handler, 92 Body: e.Body, 93 Request: request, 94 Response: response, 95 Metadata: metadata, 96 } 97 } 98 99 nodes := make([]*registry.Node, len(r.Nodes)) 100 i := 0 101 for _, n := range r.Nodes { 102 metadata := make(map[string]string, len(n.Metadata)) 103 for k, v := range n.Metadata { 104 metadata[k] = v 105 } 106 107 nodes[i] = ®istry.Node{ 108 Id: n.Id, 109 Address: n.Address, 110 Metadata: metadata, 111 } 112 i++ 113 } 114 115 return ®istry.Service{ 116 Name: r.Name, 117 Version: r.Version, 118 Metadata: metadata, 119 Endpoints: endpoints, 120 Nodes: nodes, 121 } 122 }