-
Notifications
You must be signed in to change notification settings - Fork 117
/
queuer.go
329 lines (265 loc) · 9.53 KB
/
queuer.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package utils
import (
"encoding/binary"
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
gogoprototypes "github.com/gogo/protobuf/types"
"github.com/tendermint/tendermint/libs/log"
db "github.com/tendermint/tm-db"
)
//go:generate moq -out ./mock/queuer.go -pkg mock . KVQueue
// KVQueue represents a queue built with the KVStore
type KVQueue interface {
// Enqueue pushes the given value into the queue with the given key
Enqueue(key Key, value codec.ProtoMarshaler)
// Dequeue pops the first item in queue and stores it in the given value
Dequeue(value codec.ProtoMarshaler) bool
// DequeueIf pops the first item in queue iff it matches the given filter and stores it in the given value
DequeueIf(value codec.ProtoMarshaler, filter func(value codec.ProtoMarshaler) bool) bool
// DequeueUntil pops the first item in queue that matches the given filter and stores it in the given value
DequeueUntil(value codec.ProtoMarshaler, filter func(value codec.ProtoMarshaler) bool) bool
// IsEmpty returns true if the queue is empty; false otherwise
IsEmpty() bool
//TODO: convert to iterator
Keys() []Key
}
var _ KVQueue = GeneralKVQueue{}
var _ KVQueue = BlockHeightKVQueue{}
// GeneralKVQueue is a queue that orders items based on the given prioritizer function
type GeneralKVQueue struct {
name StringKey
store KVStore
logger log.Logger
prioritizer func(value codec.ProtoMarshaler) Key
}
// NewGeneralKVQueue is the contructor for GeneralKVQueue
func NewGeneralKVQueue(name string, store KVStore, logger log.Logger, prioritizer func(value codec.ProtoMarshaler) Key) GeneralKVQueue {
return GeneralKVQueue{
name: KeyFromStr(name),
store: store,
logger: logger,
prioritizer: prioritizer,
}
}
// Enqueue pushes the given value onto the top of the queue and stores the value at given key
func (q GeneralKVQueue) Enqueue(key Key, value codec.ProtoMarshaler) {
q.store.Set(q.name.Append(q.prioritizer(value)).Append(key), &gogoprototypes.BytesValue{Value: key.AsKey()})
q.store.Set(key, value)
}
func noopFilter(_ codec.ProtoMarshaler) bool {
return true
}
// Dequeue pops the first item in queue and stores it in the given value
func (q GeneralKVQueue) Dequeue(value codec.ProtoMarshaler) bool {
iter := sdk.KVStorePrefixIterator(q.store.KVStore, q.name.AsKey())
defer CloseLogError(iter, q.logger)
return q.dequeue(value, iter, noopFilter, false)
}
// DequeueIf pops the first item in queue iff it matches the given filter and stores it in the given value
func (q GeneralKVQueue) DequeueIf(value codec.ProtoMarshaler, filter func(value codec.ProtoMarshaler) bool) bool {
iter := sdk.KVStorePrefixIterator(q.store.KVStore, q.name.AsKey())
defer CloseLogError(iter, q.logger)
return q.dequeue(value, iter, filter, false)
}
// DequeueUntil pops the first item in queue that matches the given filter and stores it in the given value
func (q GeneralKVQueue) DequeueUntil(value codec.ProtoMarshaler, filter func(value codec.ProtoMarshaler) bool) bool {
iter := sdk.KVStorePrefixIterator(q.store.KVStore, q.name.AsKey())
defer CloseLogError(iter, q.logger)
return q.dequeue(value, iter, filter, true)
}
func (q GeneralKVQueue) dequeue(value codec.ProtoMarshaler, iter db.Iterator, filter func(value codec.ProtoMarshaler) bool, continueIfNotQualified bool) bool {
for ; iter.Valid(); iter.Next() {
var key gogoprototypes.BytesValue
q.store.cdc.MustUnmarshalLengthPrefixed(iter.Value(), &key)
if ok := q.store.Get(KeyFromBz(key.Value), value); !ok {
return false
}
isQualified := filter(value)
if isQualified {
q.store.Delete(KeyFromBz(iter.Key()))
return true
}
if !continueIfNotQualified {
return false
}
}
return false
}
// IsEmpty returns true if the queue is empty; otherwise, false
func (q GeneralKVQueue) IsEmpty() bool {
iter := sdk.KVStorePrefixIterator(q.store.KVStore, q.name.AsKey())
defer CloseLogError(iter, q.logger)
return !iter.Valid()
}
// Keys returns a list with the keys for the values still enqueued
func (q GeneralKVQueue) Keys() []Key {
iter := sdk.KVStorePrefixIterator(q.store.KVStore, q.name.AsKey())
defer CloseLogError(iter, q.logger)
var keys []Key
for ; iter.Valid(); iter.Next() {
var key gogoprototypes.BytesValue
q.store.cdc.MustUnmarshalLengthPrefixed(iter.Value(), &key)
keys = append(keys, KeyFromBz(key.Value))
}
return keys
}
// ExportState exports the given queue's state from the kv store
func (q GeneralKVQueue) ExportState() (state QueueState) {
state.Items = make(map[string]QueueState_Item)
iter := sdk.KVStorePrefixIterator(q.store.KVStore, q.name.AsKey())
defer CloseLogError(iter, q.logger)
for ; iter.Valid(); iter.Next() {
var key gogoprototypes.BytesValue
q.store.cdc.MustUnmarshalLengthPrefixed(iter.Value(), &key)
item := QueueState_Item{
Key: key.Value,
Value: q.store.GetRaw(KeyFromBz(key.Value)),
}
state.Items[string(iter.Key())] = item
}
return state
}
// ImportState imports the given queue state into the kv store
func (q GeneralKVQueue) ImportState(state QueueState) {
name := string(q.name.AsKey())
for key, item := range state.Items {
if !strings.HasPrefix(key, fmt.Sprintf("%s%s", name, DefaultDelimiter)) {
panic(fmt.Errorf("queue key %s is invalid for queue %s", key, name))
}
q.store.Set(KeyFromStr(key), &gogoprototypes.BytesValue{Value: item.Key})
q.store.SetRaw(KeyFromBz(item.Key), item.Value)
}
}
// ValidateBasic returns an error if the given queue state is invalid
func (m QueueState) ValidateBasic(queueName ...string) error {
itemKeySeen := make(map[string]bool)
for key, item := range m.Items {
if itemKeySeen[string(item.Key)] {
return fmt.Errorf("duplicate item key")
}
if len(key) == 0 {
return fmt.Errorf("queue key cannot be empty")
}
if len(queueName) > 0 && !strings.HasPrefix(key, fmt.Sprintf("%s%s", queueName[0], DefaultDelimiter)) {
return fmt.Errorf("queue key %s is invalid for queue %s", key, queueName[0])
}
if len(item.Key) == 0 {
return fmt.Errorf("item key cannot be empty")
}
if len(item.Value) == 0 {
return fmt.Errorf("item value cannot be empty")
}
itemKeySeen[string(item.Key)] = true
}
return nil
}
// BlockHeightKVQueue is a queue that orders items with the block height at which the items are enqueued;
// the order of items that are enqueued at the same block height is deterministically based on their actual key
// in the KVStore
type BlockHeightKVQueue struct {
GeneralKVQueue
}
// NewBlockHeightKVQueue is the constructor of BlockHeightKVQueue
func NewBlockHeightKVQueue(name string, store KVStore, blockHeight int64, logger log.Logger) BlockHeightKVQueue {
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, uint64(blockHeight))
return BlockHeightKVQueue{
GeneralKVQueue: NewGeneralKVQueue(name, store, logger, func(_ codec.ProtoMarshaler) Key {
return KeyFromBz(bz)
}),
}
}
// SequenceKVQueue is a queue that orders items with the sequence number at which the items are enqueued;
type SequenceKVQueue struct {
store KVStore
maxSize uint64
seqNo uint64
size uint64
logger log.Logger
}
var (
sizeKey = KeyFromStr("size")
sequenceKey = KeyFromStr("sequence")
queueKey = KeyFromStr("queue")
)
// NewSequenceKVQueue is the constructor of SequenceKVQueue. The prefixStore should isolate the namespace of the queue
func NewSequenceKVQueue(prefixStore KVStore, maxSize uint64, logger log.Logger) SequenceKVQueue {
var seqNo uint64
bz := prefixStore.GetRaw(sequenceKey)
if bz != nil {
seqNo = binary.BigEndian.Uint64(bz)
}
var size uint64
bz = prefixStore.GetRaw(sizeKey)
if bz != nil {
size = binary.BigEndian.Uint64(bz)
}
return SequenceKVQueue{store: prefixStore, maxSize: maxSize, seqNo: seqNo, size: size, logger: logger}
}
// Enqueue pushes the given value onto the top of the queue and stores the value at given key. Returns queue position and status
func (q *SequenceKVQueue) Enqueue(value codec.ProtoMarshaler) error {
if q.size >= q.maxSize {
return fmt.Errorf("queue is full")
}
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, q.seqNo)
q.store.Set(queueKey.Append(KeyFromBz(bz)), value)
q.incrSize()
q.incrSeqNo()
return nil
}
// Dequeue pops the nth value off and unmarshals it into the given object, returns false if n is out of range
// n is 0-based
func (q *SequenceKVQueue) Dequeue(n uint64, value codec.ProtoMarshaler) bool {
key, ok := q.peek(n, value)
if ok {
q.store.Delete(key)
q.decrSize()
}
return ok
}
// Size returns the given current size of the queue
func (q SequenceKVQueue) Size() uint64 {
return q.size
}
// Peek unmarshals the value into the given object at the given index and returns its sequence number, returns false if n is out of range
// n is 0-based
func (q SequenceKVQueue) Peek(n uint64, value codec.ProtoMarshaler) bool {
_, ok := q.peek(n, value)
return ok
}
func (q SequenceKVQueue) peek(n uint64, value codec.ProtoMarshaler) (Key, bool) {
if n >= q.size {
return nil, false
}
var i uint64
iter := q.store.Iterator(queueKey)
defer CloseLogError(iter, q.logger)
for ; iter.Valid() && i < n; iter.Next() {
i++
}
iter.UnmarshalValue(value)
return iter.GetKey(), true
}
func (q *SequenceKVQueue) incrSize() {
q.size++
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, q.size)
q.store.SetRaw(sizeKey, bz)
}
func (q *SequenceKVQueue) decrSize() {
if q.size > 0 {
q.size--
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, q.size)
q.store.SetRaw(sizeKey, bz)
}
}
func (q *SequenceKVQueue) incrSeqNo() {
q.seqNo++
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, q.seqNo)
q.store.SetRaw(sequenceKey, bz)
}