Debian Codegraph @

queue.go

raw symbols SCIP
1 // Copyright 2019 Lunny Xiao. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 package levelqueue
6
7 import (
8 "bytes"
9 "encoding/binary"
10 "sync"
11
12 "github.com/syndtr/goleveldb/leveldb"
13 "github.com/syndtr/goleveldb/leveldb/errors"
14 )
15
16 const (
17 lowKeyStr = "low"
18 highKeyStr = "high"
19 )
20
21 // Queue defines a queue struct
22 type Queue struct {
23 db *leveldb.DB
24 lowLock sync.Mutex // If you are locking both high and low locks, lock the low lock before the high lock
25 highLock sync.Mutex // If you are locking both high and low locks, lock the low lock before the high lock
26 low int64
27 high int64
28 lowKey []byte
29 highKey []byte
30 prefix []byte
31 closeUnderlyingDB bool
32 }
33
34 // Open opens a queue from the db path or creates a
35 // queue if it doesn't exist.
36 // The keys will not be prefixed by default
37 func Open(dataDir string) (*Queue, error) {
38 db, err := leveldb.OpenFile(dataDir, nil)
39 if err != nil {
40 if !errors.IsCorrupted(err) {
41 return nil, err
42 }
43 db, err = leveldb.RecoverFile(dataDir, nil)
44 if err != nil {
45 return nil, err
46 }
47 }
48 return NewQueue(db, []byte{}, true)
49 }
50
51 // NewQueue creates a queue from a db. The keys will be prefixed with prefix
52 // and at close the db will be closed as per closeUnderlyingDB
53 func NewQueue(db *leveldb.DB, prefix []byte, closeUnderlyingDB bool) (*Queue, error) {
54 var err error
55
56 queue := &Queue{
57 db: db,
58 closeUnderlyingDB: closeUnderlyingDB,
59 }
60
61 queue.prefix = make([]byte, len(prefix))
62 copy(queue.prefix, prefix)
63 queue.lowKey = withPrefix(prefix, []byte(lowKeyStr))
64 queue.highKey = withPrefix(prefix, []byte(highKeyStr))
65
66 lowKeyExist := true
67 queue.low, err = queue.readID(queue.lowKey)
68 if err == leveldb.ErrNotFound {
69 queue.low = 1
70 err = db.Put(queue.lowKey, id2bytes(1), nil)
71 lowKeyExist = false
72 }
73 if err != nil {
74 return nil, err
75 }
76
77 queue.high, err = queue.readID(queue.highKey)
78 if err == leveldb.ErrNotFound {
79 err = db.Put(queue.highKey, id2bytes(0), nil)
80 }
81 if err != nil {
82 return nil, err
83 }
84
85 // We're not opening a new database (low key exists). There are supposed to
86 // be items in this queue (low < high).
87 if lowKeyExist && queue.low < queue.high {
88 // Corruption check, this `low` value might be inconsistent with the
89 // current state of the queue on-disk. Specifically, it might need to be
90 // increased a few times. One documented case of position being 1 too
91 // low, another case of it being 2 positions too low. Safe to try the
92 // next five items.
93 var found bool
94 var write bool
95 for range 5 {
96 has, err := queue.db.Has(withPrefix(queue.prefix, id2bytes(queue.low)), nil)
97 // err is not ErrNotFound, so return it.
98 if err != nil {
99 return nil, err
100 }
101 if has {
102 found = true
103 break
104 }
105 queue.low++
106 write = true
107 // Bound `low` to never be larger than `high+1`. In this case the
108 // state of the queue is reset and the next item that is pushed
109 // will be picked up correctly.
110 if queue.low > queue.high {
111 found = true
112 break
113 }
114 }
115 if !found {
116 return nil, ErrLowIDNotExists
117 } else if write {
118 if err := db.Put(queue.lowKey, id2bytes(queue.low), nil); err != nil {
119 return nil, err
120 }
121 }
122 }
123
124 return queue, nil
125 }
126
127 func (queue *Queue) readID(key []byte) (int64, error) {
128 bs, err := queue.db.Get(key, nil)
129 if err != nil {
130 return 0, err
131 }
132 return bytes2id(bs)
133 }
134
135 func (queue *Queue) highincrement() (int64, error) {
136 queue.high++
137 err := queue.db.Put(queue.highKey, id2bytes(queue.high), nil)
138 if err != nil {
139 queue.high--
140 return 0, err
141 }
142 return queue.high, nil
143 }
144
145 func (queue *Queue) highdecrement() error {
146 queue.high--
147 err := queue.db.Put(queue.highKey, id2bytes(queue.high), nil)
148 if err != nil {
149 queue.high++
150 return err
151 }
152 return nil
153 }
154
155 func (queue *Queue) lowincrement() error {
156 queue.low++
157 err := queue.db.Put(queue.lowKey, id2bytes(queue.low), nil)
158 if err != nil {
159 queue.low--
160 return err
161 }
162 return nil
163 }
164
165 func (queue *Queue) lowdecrement() (int64, error) {
166 queue.low--
167 err := queue.db.Put(queue.lowKey, id2bytes(queue.low), nil)
168 if err != nil {
169 queue.low++
170 return 0, err
171 }
172 return queue.low, nil
173 }
174
175 // Len returns the length of the queue
176 func (queue *Queue) Len() int64 {
177 queue.lowLock.Lock()
178 queue.highLock.Lock()
179 l := queue.high - queue.low + 1
180 queue.highLock.Unlock()
181 queue.lowLock.Unlock()
182 return l
183 }
184
185 func id2bytes(id int64) []byte {
186 buf := make([]byte, 8)
187 binary.PutVarint(buf, id)
188 return buf
189 }
190
191 func bytes2id(b []byte) (int64, error) {
192 return binary.ReadVarint(bytes.NewReader(b))
193 }
194
195 func withPrefix(prefix []byte, value []byte) []byte {
196 if len(prefix) == 0 {
197 return value
198 }
199 prefixed := make([]byte, len(prefix)+1+len(value))
200 copy(prefixed[0:len(prefix)], prefix)
201 prefixed[len(prefix)] = '-'
202 copy(prefixed[len(prefix)+1:], value)
203 return prefixed
204 }
205
206 // RPush pushes a data from right of queue
207 func (queue *Queue) RPush(data []byte) error {
208 queue.highLock.Lock()
209 if queue.db == nil {
210 queue.highLock.Unlock()
211 return leveldb.ErrClosed
212 }
213 id, err := queue.highincrement()
214 if err != nil {
215 queue.highLock.Unlock()
216 return err
217 }
218 err = queue.db.Put(withPrefix(queue.prefix, id2bytes(id)), data, nil)
219 queue.highLock.Unlock()
220 return err
221 }
222
223 // LPush pushes a data from left of queue
224 func (queue *Queue) LPush(data []byte) error {
225 queue.lowLock.Lock()
226 if queue.db == nil {
227 queue.lowLock.Unlock()
228 return leveldb.ErrClosed
229 }
230 id, err := queue.lowdecrement()
231 if err != nil {
232 queue.lowLock.Unlock()
233 return err
234 }
235 err = queue.db.Put(withPrefix(queue.prefix, id2bytes(id)), data, nil)
236 queue.lowLock.Unlock()
237 return err
238 }
239
240 // RPop pop a data from right of queue
241 func (queue *Queue) RPop() ([]byte, error) {
242 queue.highLock.Lock()
243 defer queue.highLock.Unlock()
244 if queue.db == nil {
245 return nil, leveldb.ErrClosed
246 }
247 currentID := queue.high
248
249 res, err := queue.db.Get(withPrefix(queue.prefix, id2bytes(currentID)), nil)
250 if err != nil {
251 if err == leveldb.ErrNotFound {
252 return nil, ErrNotFound
253 }
254 return nil, err
255 }
256
257 if err := queue.highdecrement(); err != nil {
258 return nil, err
259 }
260
261 err = queue.db.Delete(withPrefix(queue.prefix, id2bytes(currentID)), nil)
262 if err != nil {
263 return nil, err
264 }
265 return res, nil
266 }
267
268 // RHandle receives a user callback function to handle the right element of the queue, if function return nil, then delete the element, otherwise keep the element.
269 func (queue *Queue) RHandle(h func([]byte) error) error {
270 queue.highLock.Lock()
271 defer queue.highLock.Unlock()
272 if queue.db == nil {
273 return leveldb.ErrClosed
274 }
275 currentID := queue.high
276
277 res, err := queue.db.Get(withPrefix(queue.prefix, id2bytes(currentID)), nil)
278 if err != nil {
279 if err == leveldb.ErrNotFound {
280 return ErrNotFound
281 }
282 return err
283 }
284
285 if err = h(res); err != nil {
286 return err
287 }
288
289 if err := queue.highdecrement(); err != nil {
290 return err
291 }
292
293 return queue.db.Delete(withPrefix(queue.prefix, id2bytes(currentID)), nil)
294 }
295
296 // LPop pop a data from left of queue
297 func (queue *Queue) LPop() ([]byte, error) {
298 queue.lowLock.Lock()
299 defer queue.lowLock.Unlock()
300 if queue.db == nil {
301 return nil, leveldb.ErrClosed
302 }
303 currentID := queue.low
304
305 res, err := queue.db.Get(withPrefix(queue.prefix, id2bytes(currentID)), nil)
306 if err != nil {
307 if err == leveldb.ErrNotFound {
308 return nil, ErrNotFound
309 }
310 return nil, err
311 }
312
313 if err := queue.lowincrement(); err != nil {
314 return nil, err
315 }
316
317 err = queue.db.Delete(withPrefix(queue.prefix, id2bytes(currentID)), nil)
318 if err != nil {
319 return nil, err
320 }
321 return res, nil
322 }
323
324 // LHandle receives a user callback function to handle the left element of the queue, if function return nil, then delete the element, otherwise keep the element.
325 func (queue *Queue) LHandle(h func([]byte) error) error {
326 queue.lowLock.Lock()
327 defer queue.lowLock.Unlock()
328 if queue.db == nil {
329 return leveldb.ErrClosed
330 }
331 currentID := queue.low
332
333 res, err := queue.db.Get(withPrefix(queue.prefix, id2bytes(currentID)), nil)
334 if err != nil {
335 if err == leveldb.ErrNotFound {
336 return ErrNotFound
337 }
338 return err
339 }
340
341 if err = h(res); err != nil {
342 return err
343 }
344
345 if err := queue.lowincrement(); err != nil {
346 return err
347 }
348
349 return queue.db.Delete(withPrefix(queue.prefix, id2bytes(currentID)), nil)
350 }
351
352 // Close closes the queue (and the underlying db is set to closeUnderlyingDB)
353 func (queue *Queue) Close() error {
354 queue.lowLock.Lock()
355 queue.highLock.Lock()
356 defer queue.lowLock.Unlock()
357 defer queue.highLock.Unlock()
358
359 if !queue.closeUnderlyingDB || queue.db == nil {
360 queue.db = nil
361 return nil
362 }
363 err := queue.db.Close()
364 queue.db = nil
365 return err
366 }