forked from contribsys/faktory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transactions.go
88 lines (77 loc) · 1.64 KB
/
transactions.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
package storage
import (
"encoding/json"
"sync/atomic"
"github.com/contribsys/faktory"
"github.com/contribsys/gorocksdb"
)
type Transaction struct {
batch *gorocksdb.WriteBatch
onSuccess func()
}
func (store *rocksStore) newTransaction() *Transaction {
return &Transaction{
batch: gorocksdb.NewWriteBatch(),
}
}
/*
* Transactional operations
*/
/*
* Enqueue all moves all jobs within the given set into the
* queues associated with those jobs.
*/
func (store *rocksStore) EnqueueAll(set SortedSet) error {
return set.Each(func(idx int, key []byte, data []byte) error {
return store.EnqueueFrom(set, key)
})
}
func (store *rocksStore) EnqueueFrom(set SortedSet, key []byte) error {
return store.RunTransaction(func(xa *Transaction) error {
ss := set.(*rocksSortedSet)
data, err := ss.Get(key)
if err != nil {
return err
}
if data == nil {
return nil
}
var job faktory.Job
err = json.Unmarshal(data, &job)
if err != nil {
return err
}
queue, err := store.GetQueue(job.Queue)
if err != nil {
return err
}
q := queue.(*rocksQueue)
k := q.nextkey()
v := data
xa.batch.PutCF(q.cf, k, v)
xa.batch.DeleteCF(ss.cf, key)
xa.onSuccess = func() {
atomic.AddInt64(&q.size, 1)
atomic.AddInt64(&ss.size, -1)
}
return nil
})
}
func (store *rocksStore) RunTransaction(fn func(xa *Transaction) error) error {
xa := store.newTransaction()
defer xa.batch.Destroy()
err := fn(xa)
if err != nil {
return err
}
wo := gorocksdb.NewDefaultWriteOptions()
defer wo.Destroy()
err = store.db.Write(wo, xa.batch)
if err != nil {
return err
}
if xa.onSuccess != nil {
xa.onSuccess()
}
return nil
}