forked from fabpot/mercure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bolt_transport.go
291 lines (239 loc) · 6.85 KB
/
bolt_transport.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package mercure
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"math/rand"
"net/url"
"strconv"
"sync"
bolt "go.etcd.io/bbolt"
"go.uber.org/zap"
)
func init() { //nolint:gochecknoinits
RegisterTransportFactory("bolt", newBoltTransport)
}
const defaultBoltBucketName = "updates"
// boltTransport implements the TransportInterface using the Bolt database.
type boltTransport struct {
sync.RWMutex
logger Logger
db *bolt.DB
bucketName string
size uint64
cleanupFrequency float64
subscribers map[*Subscriber]struct{}
closed chan struct{}
closedOnce sync.Once
lastSeq uint64
lastEventID string
}
// newBoltTransport create a new boltTransport.
func newBoltTransport(u *url.URL, l Logger) (Transport, error) {
var err error
q := u.Query()
bucketName := defaultBoltBucketName
if q.Get("bucket_name") != "" {
bucketName = q.Get("bucket_name")
}
size := uint64(0)
sizeParameter := q.Get("size")
if sizeParameter != "" {
size, err = strconv.ParseUint(sizeParameter, 10, 64)
if err != nil {
return nil, &ErrInvalidTransportDSN{u.String(), fmt.Sprintf(`invalid "size" parameter %q`, sizeParameter), err}
}
}
cleanupFrequency := 0.3
cleanupFrequencyParameter := q.Get("cleanup_frequency")
if cleanupFrequencyParameter != "" {
cleanupFrequency, err = strconv.ParseFloat(cleanupFrequencyParameter, 64)
if err != nil {
return nil, &ErrInvalidTransportDSN{u.String(), fmt.Sprintf(`invalid "cleanup_frequency" parameter %q`, cleanupFrequencyParameter), err}
}
}
path := u.Path // absolute path (bolt:///path.db)
if path == "" {
path = u.Host // relative path (bolt://path.db)
}
if path == "" {
return nil, &ErrInvalidTransportDSN{u.String(), "missing path", err}
}
db, err := bolt.Open(path, 0o600, nil)
if err != nil {
return nil, &ErrInvalidTransportDSN{dsn: u.String(), err: err}
}
return &boltTransport{
logger: l,
db: db,
bucketName: bucketName,
size: size,
cleanupFrequency: cleanupFrequency,
subscribers: make(map[*Subscriber]struct{}),
closed: make(chan struct{}),
lastEventID: getDBLastEventID(db, bucketName),
}, nil
}
func getDBLastEventID(db *bolt.DB, bucketName string) string {
lastEventID := EarliestLastEventID
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucketName))
if b == nil {
return nil // No data
}
if k, _ := b.Cursor().Last(); k != nil {
lastEventID = string(k[8:])
}
return nil
})
return lastEventID
}
// Dispatch dispatches an update to all subscribers and persists it in Bolt DB.
func (t *boltTransport) Dispatch(update *Update) error {
select {
case <-t.closed:
return ErrClosedTransport
default:
}
AssignUUID(update)
updateJSON, err := json.Marshal(*update)
if err != nil {
return fmt.Errorf("error when marshaling update: %w", err)
}
// We cannot use RLock() because Bolt allows only one read-write transaction at a time
t.Lock()
defer t.Unlock()
if err := t.persist(update.ID, updateJSON); err != nil {
return err
}
for subscriber := range t.subscribers {
if !subscriber.Dispatch(update, false) {
delete(t.subscribers, subscriber)
}
}
return nil
}
// persist stores update in the database.
func (t *boltTransport) persist(updateID string, updateJSON []byte) error {
return t.db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(t.bucketName))
if err != nil {
return fmt.Errorf("error when creating Bolt DB bucket: %w", err)
}
seq, err := bucket.NextSequence()
if err != nil {
return fmt.Errorf("error when generating Bolt DB sequence: %w", err)
}
prefix := make([]byte, 8)
binary.BigEndian.PutUint64(prefix, seq)
// The sequence value is prepended to the update id to create an ordered list
key := bytes.Join([][]byte{prefix, []byte(updateID)}, []byte{})
// The DB is append only
bucket.FillPercent = 1
t.lastSeq = seq
t.lastEventID = updateID
if err := bucket.Put(key, updateJSON); err != nil {
return fmt.Errorf("unable to put value in Bolt DB: %w", err)
}
return t.cleanup(bucket, seq)
})
}
// AddSubscriber adds a new subscriber to the transport.
func (t *boltTransport) AddSubscriber(s *Subscriber) error {
select {
case <-t.closed:
return ErrClosedTransport
default:
}
t.Lock()
t.subscribers[s] = struct{}{}
toSeq := t.lastSeq
t.Unlock()
if s.RequestLastEventID != "" {
t.dispatchHistory(s, toSeq)
}
return nil
}
// GetSubscribers get the list of active subscribers.
func (t *boltTransport) GetSubscribers() (lastEventID string, subscribers []*Subscriber) {
t.RLock()
defer t.RUnlock()
subscribers = make([]*Subscriber, len(t.subscribers))
i := 0
for subscriber := range t.subscribers {
subscribers[i] = subscriber
i++
}
return t.lastEventID, subscribers
}
func (t *boltTransport) dispatchHistory(s *Subscriber, toSeq uint64) {
t.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(t.bucketName))
if b == nil {
s.HistoryDispatched(EarliestLastEventID)
return nil // No data
}
c := b.Cursor()
responseLastEventID := EarliestLastEventID
afterFromID := s.RequestLastEventID == EarliestLastEventID
for k, v := c.First(); k != nil; k, v = c.Next() {
if !afterFromID {
responseLastEventID = string(k[8:])
if responseLastEventID == s.RequestLastEventID {
afterFromID = true
}
continue
}
var update *Update
if err := json.Unmarshal(v, &update); err != nil {
s.HistoryDispatched(responseLastEventID)
t.logger.Error("Unable to unmarshal update coming from the Bolt DB", zap.Error(err))
return fmt.Errorf("unable to unmarshal update: %w", err)
}
if !s.Dispatch(update, true) || (toSeq > 0 && binary.BigEndian.Uint64(k[:8]) >= toSeq) {
s.HistoryDispatched(responseLastEventID)
return nil
}
}
s.HistoryDispatched(responseLastEventID)
return nil
})
}
// Close closes the Transport.
func (t *boltTransport) Close() (err error) {
t.closedOnce.Do(func() {
close(t.closed)
t.Lock()
for subscriber := range t.subscribers {
subscriber.Disconnect()
delete(t.subscribers, subscriber)
}
t.Unlock()
err = t.db.Close()
})
if err == nil {
return nil
}
return fmt.Errorf("unable to close Bolt DB: %w", err)
}
// cleanup removes entries in the history above the size limit, triggered probabilistically.
func (t *boltTransport) cleanup(bucket *bolt.Bucket, lastID uint64) error {
if t.size == 0 ||
t.cleanupFrequency == 0 ||
t.size >= lastID ||
(t.cleanupFrequency != 1 && rand.Float64() < t.cleanupFrequency) { //nolint:gosec
return nil
}
removeUntil := lastID - t.size
c := bucket.Cursor()
for k, _ := c.First(); k != nil; k, _ = c.Next() {
if binary.BigEndian.Uint64(k[:8]) > removeUntil {
break
}
if err := bucket.Delete(k); err != nil {
return fmt.Errorf("unable to delete value in Bolt DB: %w", err)
}
}
return nil
}