Add mutli-tenancy support to the registry

This commit is contained in:
Ben Toogood 2020-05-13 10:40:08 +01:00
parent 762a5bc9e8
commit 346e034d0a
2 changed files with 46 additions and 4 deletions

View File

@ -1,6 +1,8 @@
package service
import (
"strings"
"github.com/micro/go-micro/v2/registry"
pb "github.com/micro/go-micro/v2/registry/service/proto"
)
@ -37,6 +39,10 @@ func toValues(v []*pb.Value) []*registry.Value {
return vs
}
// NameSeperator is the string which is used as a seperator when joinin
// namespace to the service name
const NameSeperator = "/"
func ToProto(s *registry.Service) *pb.Service {
endpoints := make([]*pb.Endpoint, 0, len(s.Endpoints))
for _, ep := range s.Endpoints {
@ -76,8 +82,14 @@ func ToProto(s *registry.Service) *pb.Service {
})
}
// the service name will contain the namespace, e.g.
// 'default/go.micro.service.foo'. Remove the namespace
// using the following:
comps := strings.Split(s.Name, NameSeperator)
name := comps[len(comps)-1]
return &pb.Service{
Name: s.Name,
Name: name,
Version: s.Version,
Metadata: s.Metadata,
Endpoints: endpoints,
@ -86,7 +98,12 @@ func ToProto(s *registry.Service) *pb.Service {
}
}
func ToService(s *pb.Service) *registry.Service {
func ToService(s *pb.Service, opts ...Option) *registry.Service {
var options Options
for _, o := range opts {
o(&options)
}
endpoints := make([]*registry.Endpoint, 0, len(s.Endpoints))
for _, ep := range s.Endpoints {
var request, response *registry.Value
@ -124,11 +141,34 @@ func ToService(s *pb.Service) *registry.Service {
})
}
// add the namespace to the name
var name string
if len(options.Namespace) > 0 {
name = strings.Join([]string{options.Namespace, s.Name}, NameSeperator)
} else {
name = s.Name
}
return &registry.Service{
Name: s.Name,
Name: name,
Version: s.Version,
Metadata: s.Metadata,
Endpoints: endpoints,
Nodes: nodes,
}
}
// Options for marshaling / unmarshaling services
type Options struct {
Namespace string
}
// Option is a function which sets options
type Option func(o *Options)
// WithNamespace sets the namespace option
func WithNamespace(ns string) Option {
return func(o *Options) {
o.Namespace = ns
}
}

View File

@ -276,7 +276,9 @@ func AuthHandler(fn func() auth.Auth) server.HandlerWrapper {
}
// There is an account, set it in the context
ctx = auth.ContextWithAccount(ctx, account)
if len(account.ID) > 0 {
ctx = auth.ContextWithAccount(ctx, account)
}
// The user is authorised, allow the call
return h(ctx, req, rsp)