-
Notifications
You must be signed in to change notification settings - Fork 171
/
detector.go
93 lines (78 loc) · 2.02 KB
/
detector.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package detector
import (
"context"
"encoding/json"
"github.com/lovoo/goka"
"github.com/lovoo/goka/examples/3-messaging"
"github.com/lovoo/goka/examples/3-messaging/blocker"
"github.com/lovoo/goka/examples/3-messaging/topicinit"
)
const (
minMessages = 200
maxRate = 0.5
)
var (
group goka.Group = "detector"
)
type Counters struct {
Sent int
Received int
}
type CountersCodec struct{}
func (c *CountersCodec) Encode(value interface{}) ([]byte, error) {
return json.Marshal(value)
}
func (c *CountersCodec) Decode(data []byte) (interface{}, error) {
var m Counters
return &m, json.Unmarshal(data, &m)
}
func getValue(ctx goka.Context) *Counters {
if v := ctx.Value(); v != nil {
return v.(*Counters)
}
return &Counters{}
}
func detectSpammer(ctx goka.Context, c *Counters) bool {
var (
total = float64(c.Sent + c.Received)
rate = float64(c.Sent) / total
)
return total >= minMessages && rate >= maxRate
}
func PrepareTopics(brokers []string) {
topicinit.EnsureStreamExists(string(messaging.SentStream), brokers)
}
func Run(ctx context.Context, brokers []string) func() error {
return func() error {
g := goka.DefineGroup(group,
goka.Input(messaging.SentStream, new(messaging.MessageCodec), func(ctx goka.Context, msg interface{}) {
c := getValue(ctx)
c.Sent++
ctx.SetValue(c)
// check if sender is a spammer
if detectSpammer(ctx, c) {
ctx.Emit(blocker.Stream, ctx.Key(), new(blocker.BlockEvent))
}
// Loop to receiver
m := msg.(*messaging.Message)
ctx.Loopback(m.To, m)
}),
goka.Loop(new(messaging.MessageCodec), func(ctx goka.Context, msg interface{}) {
c := getValue(ctx)
c.Received++
ctx.SetValue(c)
// check if receiver is a spammer
if detectSpammer(ctx, c) {
ctx.Emit(blocker.Stream, ctx.Key(), new(blocker.BlockEvent))
}
}),
goka.Output(blocker.Stream, new(blocker.BlockEventCodec)),
goka.Persist(new(CountersCodec)),
)
p, err := goka.NewProcessor(brokers, g)
if err != nil {
return err
}
return p.Run(ctx)
}
}