-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
254 lines (221 loc) · 5.72 KB
/
database.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/gocql/gocql"
"github.com/hammertrack/tracker/errors"
)
var (
ErrDBConnTimeout = errors.New("test connection with database timed out")
)
type SubscribedStatus int
func (s SubscribedStatus) MarshalCQL(info gocql.TypeInfo) ([]byte, error) {
return gocql.Marshal(info, int(s))
}
func (s *SubscribedStatus) UnmarshalCQL(info gocql.TypeInfo, data []byte) error {
var n int
if err := gocql.Unmarshal(info, data, &n); err != nil {
return err
}
*s = SubscribedStatus(n)
return nil
}
const (
SubscribedStatusFalse SubscribedStatus = iota
SubscribedStatusTrue
SubscribedStatusUnknown
)
type Ban struct {
Channel string `json:"c,omitempty"`
Username string `json:"u,omitempty"`
At int64 `json:"t,omitempty"`
Recent []string `json:"m,omitempty"`
Subscribed SubscribedStatus `json:"s,omitempty"`
}
type Pagination struct {
After string `json:"after,omitempty"`
}
type ManyBan struct {
Data []Ban `json:"data"`
Pagination *Pagination `json:"pagination"`
}
type Channel string
type Driver interface {
Channels() ([]Channel, error)
BansByUser(username string, after Cursor) (*ManyBan, error)
BansByChannel(username string, after Cursor) (*ManyBan, error)
Close() error
}
type Storage struct {
driver Driver
}
func (s *Storage) Channels() ([]Channel, error) {
return s.driver.Channels()
}
func (s *Storage) BansByUser(username string, cursor Cursor) (*ManyBan, error) {
return s.driver.BansByUser(username, cursor)
}
func (s *Storage) BansByChannel(username string, after Cursor) (*ManyBan, error) {
return s.driver.BansByChannel(username, after)
}
func (s *Storage) Shutdown() error {
return s.driver.Close()
}
func NewStorage(d Driver) *Storage {
return &Storage{
driver: d,
}
}
type CassandraDriver struct {
s *gocql.Session
ctx context.Context
cancel context.CancelFunc
}
func (d *CassandraDriver) Channels() ([]Channel, error) {
iter := d.s.Query(`SELECT user_name FROM tracked_channels WHERE shard_id=1`).
WithContext(d.ctx).
Iter()
var (
scanner = iter.Scanner()
all = make([]Channel, 0, iter.NumRows())
err error
ch string
)
for scanner.Next() {
if err = scanner.Scan(&ch); err != nil {
return nil, errors.Wrap(err)
}
all = append(all, Channel(ch))
}
if err = scanner.Err(); err != nil {
return nil, errors.Wrap(err)
}
return all, nil
}
func (d *CassandraDriver) BansByUser(username string, after Cursor) (*ManyBan, error) {
iter := d.s.Query(`SELECT channel_name, user_name, at, messages, sub
FROM hammertrack.mod_messages_by_user_name WHERE user_name=?`, username).
WithContext(d.ctx).
PageState(after).
Iter()
var (
scanner = iter.Scanner()
all = make([]Ban, 0, iter.NumRows())
err error
b Ban
)
for scanner.Next() {
if err = scanner.Scan(&b.Channel, &b.Username, &b.At, &b.Recent, &b.Subscribed); err != nil {
return nil, errors.Wrap(err)
}
all = append(all, b)
}
if err = scanner.Err(); err != nil {
return nil, errors.Wrap(err)
}
var nextAfter string
if nextState := iter.PageState(); len(nextState) > 0 {
nextAfter, err = Cursor(iter.PageState()).Obscure()
if err != nil {
return nil, errors.Wrap(err)
}
}
return &ManyBan{
Data: all,
Pagination: &Pagination{
After: nextAfter,
},
}, nil
}
func (d *CassandraDriver) BansByChannel(username string, after Cursor) (*ManyBan, error) {
iter := d.s.Query(`SELECT channel_name, user_name, at, messages, sub
FROM hammertrack.mod_messages_by_channel_name
WHERE channel_name=? AND month = ?`, username, time.Now().Month()).
WithContext(d.ctx).
PageState(after).
Iter()
var (
scanner = iter.Scanner()
all = make([]Ban, 0, iter.NumRows())
err error
b Ban
)
for scanner.Next() {
if err = scanner.Scan(&b.Channel, &b.Username, &b.At, &b.Recent, &b.Subscribed); err != nil {
return nil, errors.Wrap(err)
}
all = append(all, b)
}
if err = scanner.Err(); err != nil {
return nil, errors.Wrap(err)
}
var nextAfter string
if nextState := iter.PageState(); len(nextState) > 0 {
nextAfter, err = Cursor(iter.PageState()).Obscure()
if err != nil {
return nil, errors.Wrap(err)
}
}
return &ManyBan{
Data: all,
Pagination: &Pagination{
After: nextAfter,
},
}, nil
}
func (d *CassandraDriver) Close() error {
// Cancel queries
d.cancel()
// Close all connections
d.s.Close()
return nil
}
// pingUntil tries to connect to the database. If the database is not ready it will
// try again until the given context is canceled
func pingUntil(ctx context.Context, c *gocql.ClusterConfig) (s *gocql.Session, err error) {
timer := time.NewTicker(time.Second)
for {
select {
case <-timer.C:
if s, err = c.CreateSession(); err == nil {
var t string
if err = s.Query("SELECT now() FROM system.local").
WithContext(ctx).
Consistency(gocql.One).
Scan(&t); err == nil {
return
}
} else {
errors.Wrap(err)
}
case <-ctx.Done():
return
}
}
}
func src() string {
return fmt.Sprintf("%s:%s", DBHost, DBPort)
}
func Cassandra() *CassandraDriver {
cluster := gocql.NewCluster(src())
cluster.Keyspace = DBKeyspace
cluster.ProtoVersion = 4
cluster.Consistency = gocql.Quorum
cluster.PageSize = DBPageSize
ctx, cancel := context.WithCancel(context.Background())
ctxPing, cancelPing := context.WithTimeout(ctx, time.Duration(DBConnTimeoutSeconds)*time.Second)
defer cancelPing()
log.Print("testing database connection...")
s, err := pingUntil(ctxPing, cluster)
if err != nil {
errors.WrapFatalWithContext(ErrDBConnTimeout, struct {
Cause string
}{err.Error()})
}
log.Print(" ✓ database connection")
return &CassandraDriver{
s: s, ctx: ctx, cancel: cancel,
}
}