-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
59 lines (45 loc) · 1.21 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package codec
import (
"context"
"fmt"
"reflect"
"github.com/botchris/go-pubsub"
lru "github.com/hashicorp/golang-lru"
"github.com/segmentio/fasthash/fnv1a"
)
type handler struct {
pubsub.Handler
cache *lru.Cache
codec Codec
}
func (s *handler) Deliver(ctx context.Context, topic pubsub.Topic, m interface{}) error {
bytes, ok := m.([]byte)
if !ok {
return fmt.Errorf("delivery failure: expecting message to be of type []byte, but got `%T`", m)
}
srf := s.Handler.Reflect()
cacheKey := fmt.Sprintf("%s:%d", srf.MessageType.String(), fnv1a.HashBytes64(bytes))
if found, hit := s.cache.Get(cacheKey); hit {
return s.Handler.Deliver(ctx, topic, found)
}
msg, err := s.decodeFor(bytes, srf.MessageType, srf.MessageKind)
if err != nil {
return nil
}
s.cache.Add(cacheKey, msg)
return s.Handler.Deliver(ctx, topic, msg)
}
func (s *handler) decodeFor(raw []byte, mType reflect.Type, mKind reflect.Kind) (interface{}, error) {
base := mType
if mKind == reflect.Ptr {
base = base.Elem()
}
msg := reflect.New(base).Interface()
if err := s.codec.Decode(raw, msg); err != nil {
return nil, err
}
if mKind == reflect.Ptr {
return msg, nil
}
return reflect.ValueOf(msg).Elem().Interface(), nil
}