micro-server-grpc/subscriber.go

233 lines
5.0 KiB
Go
Raw Permalink Normal View History

2019-06-03 20:44:43 +03:00
package grpc
import (
"context"
"fmt"
"reflect"
"runtime/debug"
"strings"
2019-06-03 20:44:43 +03:00
"github.com/unistack-org/micro/v3/broker"
"github.com/unistack-org/micro/v3/errors"
"github.com/unistack-org/micro/v3/logger"
"github.com/unistack-org/micro/v3/metadata"
"github.com/unistack-org/micro/v3/register"
"github.com/unistack-org/micro/v3/server"
2019-06-03 20:44:43 +03:00
)
type handler struct {
reqType reflect.Type
ctxType reflect.Type
method reflect.Value
2019-06-03 20:44:43 +03:00
}
type subscriber struct {
topic string
rcvr reflect.Value
typ reflect.Type
subscriber interface{}
handlers []*handler
endpoints []*register.Endpoint
2019-06-03 20:44:43 +03:00
opts server.SubscriberOptions
}
func newSubscriber(topic string, sub interface{}, opts ...server.SubscriberOption) server.Subscriber {
options := server.NewSubscriberOptions(opts...)
2019-06-03 20:44:43 +03:00
var endpoints []*register.Endpoint
2019-06-03 20:44:43 +03:00
var handlers []*handler
if typ := reflect.TypeOf(sub); typ.Kind() == reflect.Func {
h := &handler{
method: reflect.ValueOf(sub),
}
switch typ.NumIn() {
case 1:
h.reqType = typ.In(0)
case 2:
h.ctxType = typ.In(0)
h.reqType = typ.In(1)
}
handlers = append(handlers, h)
endpoints = append(endpoints, &register.Endpoint{
2019-06-03 20:44:43 +03:00
Name: "Func",
Request: register.ExtractSubValue(typ),
2019-06-03 20:44:43 +03:00
Metadata: map[string]string{
"topic": topic,
"subscriber": "true",
},
})
} else {
hdlr := reflect.ValueOf(sub)
name := reflect.Indirect(hdlr).Type().Name()
for m := 0; m < typ.NumMethod(); m++ {
method := typ.Method(m)
h := &handler{
method: method.Func,
}
switch method.Type.NumIn() {
case 2:
h.reqType = method.Type.In(1)
case 3:
h.ctxType = method.Type.In(1)
h.reqType = method.Type.In(2)
}
handlers = append(handlers, h)
endpoints = append(endpoints, &register.Endpoint{
2019-06-03 20:44:43 +03:00
Name: name + "." + method.Name,
Request: register.ExtractSubValue(method.Type),
2019-06-03 20:44:43 +03:00
Metadata: map[string]string{
"topic": topic,
"subscriber": "true",
},
})
}
}
return &subscriber{
rcvr: reflect.ValueOf(sub),
typ: reflect.TypeOf(sub),
topic: topic,
subscriber: sub,
handlers: handlers,
endpoints: endpoints,
opts: options,
}
}
func (g *grpcServer) createSubHandler(sb *subscriber, opts server.Options) broker.Handler {
return func(p broker.Event) (err error) {
defer func() {
if r := recover(); r != nil {
if g.opts.Logger.V(logger.ErrorLevel) {
g.opts.Logger.Error(g.opts.Context, "panic recovered: ", r)
g.opts.Logger.Error(g.opts.Context, string(debug.Stack()))
}
2020-08-08 11:21:13 +03:00
err = errors.InternalServerError(g.opts.Name+".subscriber", "panic recovered: %v", r)
}
}()
msg := p.Message()
// if we don't have headers, create empty map
if msg.Header == nil {
msg.Header = make(map[string]string)
}
2019-06-03 20:44:43 +03:00
ct := msg.Header["Content-Type"]
if len(ct) == 0 {
msg.Header["Content-Type"] = defaultContentType
ct = defaultContentType
}
cf, err := g.newCodec(ct)
2019-06-03 20:44:43 +03:00
if err != nil {
return err
}
hdr := make(map[string]string, len(msg.Header))
2019-06-03 20:44:43 +03:00
for k, v := range msg.Header {
if k == "Content-Type" {
continue
}
2019-06-03 20:44:43 +03:00
hdr[k] = v
}
ctx := metadata.NewIncomingContext(sb.opts.Context, hdr)
2019-06-03 20:44:43 +03:00
results := make(chan error, len(sb.handlers))
2019-06-03 20:44:43 +03:00
for i := 0; i < len(sb.handlers); i++ {
handler := sb.handlers[i]
var isVal bool
var req reflect.Value
if handler.reqType.Kind() == reflect.Ptr {
req = reflect.New(handler.reqType.Elem())
} else {
req = reflect.New(handler.reqType)
isVal = true
}
if isVal {
req = req.Elem()
}
if err = cf.Unmarshal(msg.Body, req.Interface()); err != nil {
2019-06-03 20:44:43 +03:00
return err
}
fn := func(ctx context.Context, msg server.Message) error {
var vals []reflect.Value
if sb.typ.Kind() != reflect.Func {
vals = append(vals, sb.rcvr)
}
if handler.ctxType != nil {
vals = append(vals, reflect.ValueOf(ctx))
}
vals = append(vals, reflect.ValueOf(msg.Payload()))
returnValues := handler.method.Call(vals)
if rerr := returnValues[0].Interface(); rerr != nil {
return rerr.(error)
2019-06-03 20:44:43 +03:00
}
return nil
}
for i := len(opts.SubWrappers); i > 0; i-- {
fn = opts.SubWrappers[i-1](fn)
}
2019-06-17 12:07:55 +03:00
if g.wg != nil {
g.wg.Add(1)
}
2019-06-03 20:44:43 +03:00
go func() {
2019-06-17 12:07:55 +03:00
if g.wg != nil {
defer g.wg.Done()
}
cerr := fn(ctx, &rpcMessage{
2019-06-03 20:44:43 +03:00
topic: sb.topic,
contentType: ct,
payload: req.Interface(),
header: msg.Header,
body: msg.Body,
2019-06-03 20:44:43 +03:00
})
results <- cerr
2019-06-03 20:44:43 +03:00
}()
}
var errors []string
for i := 0; i < len(sb.handlers); i++ {
if rerr := <-results; rerr != nil {
errors = append(errors, rerr.Error())
}
}
if len(errors) > 0 {
err = fmt.Errorf("subscriber error: %s", strings.Join(errors, "\n"))
}
return err
2019-06-03 20:44:43 +03:00
}
}
func (s *subscriber) Topic() string {
return s.topic
}
func (s *subscriber) Subscriber() interface{} {
return s.subscriber
}
func (s *subscriber) Endpoints() []*register.Endpoint {
2019-06-03 20:44:43 +03:00
return s.endpoints
}
func (s *subscriber) Options() server.SubscriberOptions {
return s.opts
}