-
Notifications
You must be signed in to change notification settings - Fork 81
/
queue.go
331 lines (272 loc) · 7.21 KB
/
queue.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
330
331
package goque
import (
"bytes"
"encoding/gob"
"encoding/json"
"os"
"sync"
"github.com/syndtr/goleveldb/leveldb"
)
// Queue is a standard FIFO (first in, first out) queue.
type Queue struct {
sync.RWMutex
DataDir string
db *leveldb.DB
head uint64
tail uint64
isOpen bool
}
// OpenQueue opens a queue if one exists at the given directory. If one
// does not already exist, a new queue is created.
func OpenQueue(dataDir string) (*Queue, error) {
var err error
// Create a new Queue.
q := &Queue{
DataDir: dataDir,
db: &leveldb.DB{},
head: 0,
tail: 0,
isOpen: false,
}
// Open database for the queue.
q.db, err = leveldb.OpenFile(dataDir, nil)
if err != nil {
return q, err
}
// Check if this Goque type can open the requested data directory.
ok, err := checkGoqueType(dataDir, goqueQueue)
if err != nil {
return q, err
}
if !ok {
return q, ErrIncompatibleType
}
// Set isOpen and return.
q.isOpen = true
return q, q.init()
}
// Enqueue adds an item to the queue.
func (q *Queue) Enqueue(value []byte) (*Item, error) {
q.Lock()
defer q.Unlock()
// Check if queue is closed.
if !q.isOpen {
return nil, ErrDBClosed
}
// Create new Item.
item := &Item{
ID: q.tail + 1,
Key: idToKey(q.tail + 1),
Value: value,
}
// Add it to the queue.
if err := q.db.Put(item.Key, item.Value, nil); err != nil {
return nil, err
}
// Increment tail position.
q.tail++
return item, nil
}
// EnqueueString is a helper function for Enqueue that accepts a
// value as a string rather than a byte slice.
func (q *Queue) EnqueueString(value string) (*Item, error) {
return q.Enqueue([]byte(value))
}
// EnqueueObject is a helper function for Enqueue that accepts any
// value type, which is then encoded into a byte slice using
// encoding/gob.
//
// Objects containing pointers with zero values will decode to nil
// when using this function. This is due to how the encoding/gob
// package works. Because of this, you should only use this function
// to encode simple types.
func (q *Queue) EnqueueObject(value interface{}) (*Item, error) {
var buffer bytes.Buffer
enc := gob.NewEncoder(&buffer)
if err := enc.Encode(value); err != nil {
return nil, err
}
return q.Enqueue(buffer.Bytes())
}
// EnqueueObjectAsJSON is a helper function for Enqueue that accepts
// any value type, which is then encoded into a JSON byte slice using
// encoding/json.
//
// Use this function to handle encoding of complex types.
func (q *Queue) EnqueueObjectAsJSON(value interface{}) (*Item, error) {
jsonBytes, err := json.Marshal(value)
if err != nil {
return nil, err
}
return q.Enqueue(jsonBytes)
}
// Dequeue removes the next item in the queue and returns it.
func (q *Queue) Dequeue() (*Item, error) {
q.Lock()
defer q.Unlock()
// Check if queue is closed.
if !q.isOpen {
return nil, ErrDBClosed
}
// Try to get the next item in the queue.
item, err := q.getItemByID(q.head + 1)
if err != nil {
return nil, err
}
// Remove this item from the queue.
if err := q.db.Delete(item.Key, nil); err != nil {
return nil, err
}
// Increment head position.
q.head++
return item, nil
}
// Peek returns the next item in the queue without removing it.
func (q *Queue) Peek() (*Item, error) {
q.RLock()
defer q.RUnlock()
// Check if queue is closed.
if !q.isOpen {
return nil, ErrDBClosed
}
return q.getItemByID(q.head + 1)
}
// PeekByOffset returns the item located at the given offset,
// starting from the head of the queue, without removing it.
func (q *Queue) PeekByOffset(offset uint64) (*Item, error) {
q.RLock()
defer q.RUnlock()
// Check if queue is closed.
if !q.isOpen {
return nil, ErrDBClosed
}
return q.getItemByID(q.head + offset + 1)
}
// PeekByID returns the item with the given ID without removing it.
func (q *Queue) PeekByID(id uint64) (*Item, error) {
q.RLock()
defer q.RUnlock()
// Check if queue is closed.
if !q.isOpen {
return nil, ErrDBClosed
}
return q.getItemByID(id)
}
// Update updates an item in the queue without changing its position.
func (q *Queue) Update(id uint64, newValue []byte) (*Item, error) {
q.Lock()
defer q.Unlock()
// Check if queue is closed.
if !q.isOpen {
return nil, ErrDBClosed
}
// Check if item exists in queue.
if id <= q.head || id > q.tail {
return nil, ErrOutOfBounds
}
// Create new Item.
item := &Item{
ID: id,
Key: idToKey(id),
Value: newValue,
}
// Update this item in the queue.
if err := q.db.Put(item.Key, item.Value, nil); err != nil {
return nil, err
}
return item, nil
}
// UpdateString is a helper function for Update that accepts a value
// as a string rather than a byte slice.
func (q *Queue) UpdateString(id uint64, newValue string) (*Item, error) {
return q.Update(id, []byte(newValue))
}
// UpdateObject is a helper function for Update that accepts any
// value type, which is then encoded into a byte slice using
// encoding/gob.
//
// Objects containing pointers with zero values will decode to nil
// when using this function. This is due to how the encoding/gob
// package works. Because of this, you should only use this function
// to encode simple types.
func (q *Queue) UpdateObject(id uint64, newValue interface{}) (*Item, error) {
var buffer bytes.Buffer
enc := gob.NewEncoder(&buffer)
if err := enc.Encode(newValue); err != nil {
return nil, err
}
return q.Update(id, buffer.Bytes())
}
// UpdateObjectAsJSON is a helper function for Update that accepts
// any value type, which is then encoded into a JSON byte slice using
// encoding/json.
//
// Use this function to handle encoding of complex types.
func (q *Queue) UpdateObjectAsJSON(id uint64, newValue interface{}) (*Item, error) {
jsonBytes, err := json.Marshal(newValue)
if err != nil {
return nil, err
}
return q.Update(id, jsonBytes)
}
// Length returns the total number of items in the queue.
func (q *Queue) Length() uint64 {
return q.tail - q.head
}
// Close closes the LevelDB database of the queue.
func (q *Queue) Close() error {
q.Lock()
defer q.Unlock()
// Check if queue is already closed.
if !q.isOpen {
return nil
}
// Close the LevelDB database.
if err := q.db.Close(); err != nil {
return err
}
// Reset queue head and tail and set
// isOpen to false.
q.head = 0
q.tail = 0
q.isOpen = false
return nil
}
// Drop closes and deletes the LevelDB database of the queue.
func (q *Queue) Drop() error {
if err := q.Close(); err != nil {
return err
}
return os.RemoveAll(q.DataDir)
}
// getItemByID returns an item, if found, for the given ID.
func (q *Queue) getItemByID(id uint64) (*Item, error) {
// Check if empty or out of bounds.
if q.Length() == 0 {
return nil, ErrEmpty
} else if id <= q.head || id > q.tail {
return nil, ErrOutOfBounds
}
// Get item from database.
var err error
item := &Item{ID: id, Key: idToKey(id)}
if item.Value, err = q.db.Get(item.Key, nil); err != nil {
return nil, err
}
return item, nil
}
// init initializes the queue data.
func (q *Queue) init() error {
// Create a new LevelDB Iterator.
iter := q.db.NewIterator(nil, nil)
defer iter.Release()
// Set queue head to the first item.
if iter.First() {
q.head = keyToID(iter.Key()) - 1
}
// Set queue tail to the last item.
if iter.Last() {
q.tail = keyToID(iter.Key())
}
return iter.Error()
}