/
events.go
211 lines (189 loc) · 5.02 KB
/
events.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package server
import (
"context"
"fmt"
"os"
"time"
"github.com/ClickHouse/ch-go"
"github.com/ClickHouse/ch-go/proto"
"github.com/dustin/go-humanize"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/go-faster/sdk/zctx"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"github.com/go-faster/bot/internal/dispatch"
"github.com/go-faster/bot/internal/gh"
)
func formatInt(x int) string {
return formatFloat(float64(x))
}
func formatFloat(num float64) string {
v, u := humanize.ComputeSI(num)
return fmt.Sprintf("%.1f%s", v, u)
}
func (a *App) clickHouse(ctx context.Context) (db *ch.Client, cleanup func(), err error) {
db, err = ch.Dial(ctx, ch.Options{
Address: os.Getenv("CLICKHOUSE_ADDR"),
Compression: ch.CompressionZSTD,
TracerProvider: a.m.TracerProvider(),
MeterProvider: a.m.MeterProvider(),
Database: "faster",
Password: os.Getenv("CLICKHOUSE_PASSWORD"),
User: os.Getenv("CLICKHOUSE_USER"),
OpenTelemetryInstrumentation: true,
})
if err != nil {
return nil, nil, errors.Wrap(err, "connect")
}
cleanup = func() {
if err := db.Close(); err != nil {
a.lg.Error("Close clickhouse", zap.Error(err))
}
}
return db, cleanup, nil
}
func (a *App) HandleEvents(ctx context.Context, e dispatch.MessageEvent) error {
ctx, span := a.tracer.Start(ctx, "HandleEvents")
defer span.End()
db, cleanup, err := a.clickHouse(ctx)
if err != nil {
return errors.Wrap(err, "clickHouse")
}
defer cleanup()
var count, total proto.ColUInt64
if err := db.Do(ctx, ch.Query{
Body: "SELECT COUNT() FROM faster.github_events_raw WHERE ts > now() - toIntervalMinute(30)",
Result: proto.Results{
{Name: "count()", Data: &count},
},
}); err != nil {
return errors.Wrap(err, "do")
}
if len(count) == 0 {
return errors.New("no data")
}
if err := db.Do(ctx, ch.Query{
Body: "SELECT COUNT() FROM faster.github_events_raw",
Result: proto.Results{
{Name: "count()", Data: &total},
},
}); err != nil {
return errors.Wrap(err, "do")
}
if len(total) == 0 {
return errors.New("no data")
}
if _, err := e.Reply().Textf(ctx, "Events in last 30 minutes: %s\nTotal: %s",
formatInt(int(count.Row(0))),
formatInt(int(total.Row(0))),
); err != nil {
return errors.Wrap(err, "reply")
}
return nil
}
func (a *App) FetchEvents(ctx context.Context, start time.Time) error {
begin := time.Now()
ctx, span := a.tracer.Start(ctx, "FetchEvents",
trace.WithSpanKind(trace.SpanKindServer),
)
defer span.End()
trackedRepo := map[string]struct{}{
"ClickHouse/ch-go": {},
}
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
db, cleanup, err := a.clickHouse(ctx)
if err != nil {
return errors.Wrap(err, "clickHouse")
}
defer cleanup()
q := fmt.Sprintf("SELECT id, ts, raw FROM faster.github_events_raw WHERE ts >= toDateTime64(%d, 9) ORDER BY ts DESC, id DESC", start.Unix())
var (
colID proto.ColInt64
colTime proto.ColDateTime
colBody proto.ColStr
d jx.Decoder
e jx.Encoder
total int
skipped int
hit int
processed int
sizeTotal uint64
latest time.Time
)
if err := db.Do(ctx, ch.Query{
Body: q,
Result: proto.Results{
{Name: "id", Data: &colID},
{Name: "ts", Data: &colTime},
{Name: "raw", Data: &colBody},
},
OnResult: func(ctx context.Context, block proto.Block) error {
for i := 0; i < colID.Rows(); i++ {
var (
id = colID.Row(i)
b = colBody.RowBytes(i)
t = colTime.Row(i)
)
if t.After(latest) {
latest = t
}
sizeTotal += uint64(len(b))
d.ResetBytes(b)
e.Reset()
ev, err := gh.Transform(&d, &e)
if err != nil {
return errors.Wrap(err, "transform")
}
d.ResetBytes(e.Bytes())
if err := d.Validate(); err != nil {
return errors.Wrap(err, "validate")
}
total++
if _, ok := trackedRepo[ev.RepoName]; !ok {
skipped++
continue
}
// Protect from duplicates.
k := fmt.Sprintf("v3:event:%x", id)
exists, err := a.cache.Exists(ctx, k).Result()
if err != nil {
return errors.Wrap(err, "exists")
}
if exists != 0 {
hit++
continue
}
if _, err := a.cache.Set(ctx, k, 1, time.Hour).Result(); err != nil {
return errors.Wrap(err, "set")
}
zctx.From(ctx).Info("Got event",
zap.Int64("id", id),
zap.String("type", ev.Type),
zap.Int64("repo_id", ev.RepoID),
zap.String("repo_name", ev.RepoName),
)
ctx = zctx.With(ctx, zap.Bool("from_ch_fetcher", true))
// Handle as event was received from webhook.
if err := a.wh.Handle(ctx, ev.Type, e.Bytes()); err != nil {
return errors.Wrap(err, "handle")
}
processed++
}
return nil
},
}); err != nil {
return errors.Wrap(err, "do")
}
zctx.From(ctx).Info("FetchEvents",
zap.String("duration.human", time.Since(begin).String()),
zap.String("lag.human", time.Since(latest).String()),
zap.Int("total", total),
zap.Int("skipped", skipped),
zap.Int("hit", hit),
zap.Int("processed", processed),
zap.String("parsed", humanize.Bytes(sizeTotal)),
)
return nil
}