forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shard.go
69 lines (57 loc) · 1.51 KB
/
shard.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
60
61
62
63
64
65
66
67
68
69
// Package shard implements the sharding call strategy
package shard
import (
"hash/crc32"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/metadata"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/selector"
"context"
)
type shard struct {
key string
client.Client
}
func (s *shard) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
// get headers
md, ok := metadata.FromContext(ctx)
if !ok {
// noop, defer to client
return s.Client.Call(ctx, req, rsp, opts...)
}
// get key val
val := md[s.key]
// noop on nil value
if len(val) == 0 {
return s.Client.Call(ctx, req, rsp, opts...)
}
// checksum it
cs := crc32.ChecksumIEEE([]byte(val))
nOpts := append(opts, client.WithSelectOption(
// create a selector strategy
selector.WithStrategy(func(services []*registry.Service) selector.Next {
// flatten
var nodes []*registry.Node
for _, service := range services {
nodes = append(nodes, service.Nodes...)
}
// create the next func that always returns our node
return func() (*registry.Node, error) {
if len(nodes) == 0 {
return nil, selector.ErrNoneAvailable
}
return nodes[cs%uint32(len(nodes))], nil
}
}),
))
return s.Client.Call(ctx, req, rsp, nOpts...)
}
// NewClientWrapper is a wrapper which shards based on a header key value
func NewClientWrapper(key string) client.Wrapper {
return func(c client.Client) client.Client {
return &shard{
key: key,
Client: c,
}
}
}