This repository was archived by the owner on Feb 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.go
253 lines (210 loc) · 5.37 KB
/
db.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
package backend
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"time"
"golang.org/x/net/context"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/log"
"google.golang.org/appengine/memcache"
)
// Errors
var (
ErrNoBlocks = errors.New("no blocks available")
ErrNoStats = errors.New("no stats available")
)
// Datastore implements DB via Google Cloud Datastore
type Datastore struct {
ctx context.Context
}
// DB is an interface for the known blocks
type DB interface {
// SaveBlock saves the given block into the database
SaveBlock(Block) error
// GetConfig gets the current config from the database
GetConfig() (Config, error)
// LatestBlock returns the latest block (by height) in the database
LatestBlock() (Block, error)
// LatestStats returns the latest stats in the database
LatestStats() (Stats, error)
// GetStats returns the (up to) n latest stats
GetStats(int) ([]Stats, error)
// SaveStats saves the given stats into the db
SaveStats(Stats) error
// ForEachFrom calls the given method for each saves Block starting from the
// given Timestamp
ForEachFrom(ts time.Time, f func(Block)) error
}
// SaveBlock saves the given block into the database
func (ds *Datastore) SaveBlock(b Block) error {
k := datastore.NewKey(ds.ctx, "Block", "block-"+strconv.Itoa(b.Height), 0, nil)
_, err := datastore.Put(ds.ctx, k, &b)
return err
}
func (ds *Datastore) dayStatsKey(t time.Time) *datastore.Key {
return datastore.NewKey(ds.ctx, "Stats", "stats-"+t.UTC().Format("2006-01-02"), 0, nil)
}
// SaveStats saves the given stats into the db
func (ds *Datastore) SaveStats(s Stats) error {
log.Infof(ds.ctx, "saving stats %v", s)
err := datastore.RunInTransaction(ds.ctx, func(tctx context.Context) error {
k := ds.dayStatsKey(s.Timestamp)
_, terr := datastore.Put(tctx, k, &s)
if terr != nil {
return terr
}
for sv, v := range s.Votes {
vk := datastore.NewKey(tctx, "Vote", sv, 0, k)
_, terr := datastore.Put(tctx, vk, &v)
if terr != nil {
return terr
}
}
return nil
}, nil)
return err
}
// GetConfig gets the current config from the database
func (ds *Datastore) GetConfig() (c Config, err error) {
k := datastore.NewKey(ds.ctx, "Config", "config", 0, nil)
err = datastore.Get(ds.ctx, k, &c)
if err == datastore.ErrNoSuchEntity {
_, err = datastore.Put(ds.ctx, k, &c)
}
return c, err
}
// LatestBlock returns the latest block (by height) in the database
func (ds *Datastore) LatestBlock() (b Block, err error) {
// run query
bs := []Block{}
_, err = datastore.NewQuery("Block").
Limit(1).
Order("-Height").
GetAll(ds.ctx, &bs)
if err != nil {
return
}
if len(bs) == 0 {
return b, ErrNoBlocks
}
b = bs[0]
return
}
// LatestStats returns the latest stats in the database
func (ds *Datastore) LatestStats() (Stats, error) {
ss, err := ds.GetStats(1)
if err != nil {
return Stats{}, err
}
return ss[0], nil
}
// GetStats returns the n latest stats
func (ds *Datastore) GetStats(n int) ([]Stats, error) {
ss := []Stats{}
// get stats/ancestor keys
ks, err := datastore.NewQuery("Stats").
Limit(n).
Order("-Timestamp").
GetAll(ds.ctx, &ss)
if err != nil {
return nil, err
}
if len(ss) == 0 {
return nil, ErrNoStats
}
// create list of vote/child keys (sw0, bu0, sw1, bu1,...)
vks := []*datastore.Key{}
for _, k := range ks {
swk := datastore.NewKey(ds.ctx, "Vote", "segwit", 0, k)
s2xk := datastore.NewKey(ds.ctx, "Vote", "s2x", 0, k)
eck := datastore.NewKey(ds.ctx, "Vote", "ec", 0, k)
vks = append(vks, swk, eck, s2xk)
}
// get child values (sw0, bu0, sw1, bu1,...)
vs := make([]Vote, len(vks))
err = datastore.GetMulti(ds.ctx, vks, vs)
switch err.(type) {
case appengine.MultiError:
break
default:
return nil, err
}
// fill stats with child data
for i := range ss {
ss[i].Votes = make(map[string]Vote)
ss[i].Votes["segwit"] = vs[3*i]
ss[i].Votes["ec"] = vs[3*i+1]
ss[i].Votes["s2x"] = vs[3*i+2]
ss[i].Votes["unlimited"] = ss[i].Votes["ec"]
}
return ss, nil
}
// ForEachFrom calls the given method for each saves Block starting from the
// given Timestamp
func (ds *Datastore) ForEachFrom(ts time.Time, f func(Block)) error {
// get all block keys for period
t := datastore.NewQuery("Block").
Filter("Timestamp >=", ts).
KeysOnly().
Run(ds.ctx)
var bks []*datastore.Key
c := 0
for {
c++
bk, err := t.Next(nil)
if err == datastore.Done {
break
}
if err != nil {
return fmt.Errorf("error after iterating over %d block keys: %v", c, err)
}
bks = append(bks, bk)
}
log.Infof(ds.ctx, "iterated over %d keys", c)
// iterate over blocks
for _, bk := range bks {
b, err := ds.getBlock(bk)
if err != nil {
return err
}
f(b)
}
return nil
}
func (ds *Datastore) getBlock(bk *datastore.Key) (Block, error) {
var b Block
item, err := memcache.Get(ds.ctx, bk.StringID())
// cache miss
if err == memcache.ErrCacheMiss {
// get from DB
err = datastore.Get(ds.ctx, bk, &b)
if err != nil {
return b, err
}
// encode for memcache
var v []byte
v, err = json.Marshal(&b)
if err != nil {
return b, err
}
item = &memcache.Item{
Key: bk.StringID(),
Value: v,
}
// set to memcache
err = memcache.Set(ds.ctx, item)
if err != nil {
return b, err
}
return b, nil
}
// something else went wrong
if err != nil {
return b, err
}
err = json.Unmarshal(item.Value, &b)
return b, err
}