forked from lovoo/goka
/
blocker.go
70 lines (57 loc) · 1.31 KB
/
blocker.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
70
package blocker
import (
"encoding/json"
"github.com/lovoo/goka"
)
var (
group goka.Group = "blocker"
Table goka.Table = goka.GroupTable(group)
Stream goka.Stream = "block_user"
)
type BlockEvent struct {
Unblock bool
}
type BlockEventCodec struct{}
func (c *BlockEventCodec) Encode(value interface{}) ([]byte, error) {
return json.Marshal(value)
}
func (c *BlockEventCodec) Decode(data []byte) (interface{}, error) {
var m BlockEvent
return &m, json.Unmarshal(data, &m)
}
type BlockValue struct {
Blocked bool
}
type BlockValueCodec struct{}
func (c *BlockValueCodec) Encode(value interface{}) ([]byte, error) {
return json.Marshal(value)
}
func (c *BlockValueCodec) Decode(data []byte) (interface{}, error) {
var m BlockValue
return &m, json.Unmarshal(data, &m)
}
func block(ctx goka.Context, msg interface{}) {
var s *BlockValue
if v := ctx.Value(); v == nil {
s = new(BlockValue)
} else {
s = v.(*BlockValue)
}
if msg.(*BlockEvent).Unblock {
s.Blocked = false
} else {
s.Blocked = true
}
ctx.SetValue(s)
}
func Run(brokers []string) {
g := goka.DefineGroup(group,
goka.Input(Stream, new(BlockEventCodec), block),
goka.Persist(new(BlockValueCodec)),
)
if p, err := goka.NewProcessor(brokers, g); err != nil {
panic(err)
} else if err = p.Start(); err != nil {
panic(err)
}
}