forked from textileio/go-threads
/
common.go
134 lines (108 loc) · 2.49 KB
/
common.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
package db
import (
"errors"
"sync"
"time"
datastore "github.com/textileio/go-datastore"
"github.com/textileio/go-datastore/query"
core "github.com/singyiu/go-threads/core/db"
)
type TxMapDatastore struct {
*datastore.MapDatastore
lock sync.RWMutex
}
func NewTxMapDatastore() *TxMapDatastore {
return &TxMapDatastore{
MapDatastore: datastore.NewMapDatastore(),
}
}
func (d *TxMapDatastore) NewTransaction(_ bool) (datastore.Txn, error) {
d.lock.RLock()
defer d.lock.RUnlock()
return NewSimpleTx(d), nil
}
type op struct {
delete bool
value []byte
}
// SimpleTx implements the transaction interface for datastores who do
// not have any sort of underlying transactional support.
type SimpleTx struct {
ops map[datastore.Key]op
lock sync.RWMutex
target datastore.Datastore
}
func NewSimpleTx(ds datastore.Datastore) datastore.Txn {
return &SimpleTx{
ops: make(map[datastore.Key]op),
target: ds,
}
}
func (bt *SimpleTx) Query(q query.Query) (query.Results, error) {
bt.lock.RLock()
defer bt.lock.RUnlock()
return bt.target.Query(q)
}
func (bt *SimpleTx) Get(k datastore.Key) ([]byte, error) {
bt.lock.RLock()
defer bt.lock.RUnlock()
return bt.target.Get(k)
}
func (bt *SimpleTx) Has(k datastore.Key) (bool, error) {
bt.lock.RLock()
defer bt.lock.RUnlock()
return bt.target.Has(k)
}
func (bt *SimpleTx) GetSize(k datastore.Key) (int, error) {
bt.lock.RLock()
defer bt.lock.RUnlock()
return bt.target.GetSize(k)
}
func (bt *SimpleTx) Put(key datastore.Key, val []byte) error {
bt.lock.RLock()
defer bt.lock.RUnlock()
bt.ops[key] = op{value: val}
return nil
}
func (bt *SimpleTx) Delete(key datastore.Key) error {
bt.lock.RLock()
defer bt.lock.RUnlock()
bt.ops[key] = op{delete: true}
return nil
}
func (bt *SimpleTx) Discard() {
bt.lock.RLock()
defer bt.lock.RUnlock()
}
func (bt *SimpleTx) Commit() error {
bt.lock.RLock()
defer bt.lock.RUnlock()
var err error
for k, op := range bt.ops {
if op.delete {
err = bt.target.Delete(k)
} else {
err = bt.target.Put(k, op.value)
}
if err != nil {
break
}
}
return err
}
type nullReducer struct{}
var _ Reducer = (*nullReducer)(nil)
func (n *nullReducer) Reduce(_ []core.Event) error {
return nil
}
type errorReducer struct{}
var _ Reducer = (*errorReducer)(nil)
func (n *errorReducer) Reduce(_ []core.Event) error {
return errors.New("error")
}
type slowReducer struct{}
var _ Reducer = (*slowReducer)(nil)
func (n *slowReducer) Reduce(_ []core.Event) error {
time.Sleep(2 * time.Second)
return nil
}