-
Notifications
You must be signed in to change notification settings - Fork 3
/
nuts_db_data_manager.go
395 lines (362 loc) · 11.2 KB
/
nuts_db_data_manager.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package core
import (
"encoding/binary"
"errors"
"fmt"
"github.com/nutsdb/nutsdb"
"github.com/ryogrid/nostrp2p/glo_val"
"github.com/ryogrid/nostrp2p/np2p_const"
"github.com/ryogrid/nostrp2p/np2p_util"
"github.com/ryogrid/nostrp2p/schema"
"log"
"math"
"os"
"strconv"
)
type NutsDBItr struct {
curIdx int
elems []interface{}
}
func NewNutsDBItr(elems []interface{}) *NutsDBItr {
return &NutsDBItr{
curIdx: -1,
elems: elems,
}
}
func (n *NutsDBItr) Next() bool {
if n.curIdx+1 < len(n.elems) && len(n.elems) > 0 {
n.curIdx++
return true
}
return false
}
var _ Np2pItr = &NutsDBItr{}
func (n *NutsDBItr) Value() interface{} {
return n.elems[n.curIdx]
}
type NutsDBDataManager struct {
dbFilePath string
db *nutsdb.DB
}
var _ DataManager = &NutsDBDataManager{}
const EventListTimeKey = "EvtListTimeKey"
const EventIdxMapIdKey = "EvtIdxMapIdKey"
const ProfEvtIdxMap = "ProfEvtIdxMap"
const FollowListEvtIdxMap = "FollowListEvtIdxMap"
const ReSendNeededEvtList = "ReSendNeededEvtList"
func NewNutsDBDataManager() DataManager {
dbFilePath := "./" + strconv.FormatUint(glo_val.SelfPubkey64bit, 16)
if _, err := os.Stat(dbFilePath); os.IsNotExist(err) {
err2 := os.Mkdir(dbFilePath, os.ModePerm)
if err2 != nil {
panic(err2)
}
}
opt := nutsdb.DefaultOptions
opt.EntryIdxMode = nutsdb.HintKeyValAndRAMIdxMode
// memory usage limit for caching buffer
opt.HintKeyAndRAMIdxCacheSize = np2p_const.MemoryUsageLimitForDBBuffer
db, err := nutsdb.Open(
opt,
nutsdb.WithDir(dbFilePath),
)
if err != nil {
log.Fatal(err)
}
// key: "timestamp"
// score: timestamp(float64) -> value: serialized schema.Np2pEvent
if err2 := db.Update(func(tx *nutsdb.Tx) error {
return tx.NewBucket(nutsdb.DataStructureSortedSet, EventListTimeKey)
}); err2 != nil {
fmt.Println(err2)
}
// serialized event ID [32]byte -> serialized timestamp(unt64)
if err2 := db.Update(func(tx *nutsdb.Tx) error {
return tx.NewBucket(nutsdb.DataStructureBTree, EventIdxMapIdKey)
}); err2 != nil {
fmt.Println(err2)
}
// serialized pubkey lower 64bit (uint64) -> serialized timestamp(unt64)
if err3 := db.Update(func(tx *nutsdb.Tx) error {
return tx.NewBucket(nutsdb.DataStructureBTree, ProfEvtIdxMap)
}); err3 != nil {
fmt.Println(err3)
}
// serialized pubkey lower 64bit (uint64) -> serialized timestamp(unt64)
if err4 := db.Update(func(tx *nutsdb.Tx) error {
return tx.NewBucket(nutsdb.DataStructureBTree, FollowListEvtIdxMap)
}); err4 != nil {
fmt.Println(err4)
}
// serialized event ID(32byte) -> timestamp(int64)
if err6 := db.Update(func(tx *nutsdb.Tx) error {
return tx.NewBucket(nutsdb.DataStructureSortedSet, ReSendNeededEvtList)
}); err6 != nil {
fmt.Println(err6)
}
return &NutsDBDataManager{
dbFilePath: dbFilePath,
db: db,
}
}
func (n *NutsDBDataManager) StoreEvent(evt *schema.Np2pEvent) {
if err := n.db.Update(func(tx *nutsdb.Tx) error {
return tx.ZAdd(EventListTimeKey, []byte("time"), float64(evt.Created_at), evt.Encode())
}); err != nil {
fmt.Println(err)
}
if err := n.db.Update(func(tx *nutsdb.Tx) error {
return tx.Put(EventIdxMapIdKey, evt.Id[:], np2p_util.ConvInt64ToBytes(evt.Created_at), nutsdb.Persistent)
}); err != nil {
fmt.Println(err)
}
}
func (n *NutsDBDataManager) getEventByTimestampBytes(tx *nutsdb.Tx, tsBytes []byte) (*schema.Np2pEvent, error) {
var ret *schema.Np2pEvent
ts := float64(binary.BigEndian.Uint64(tsBytes))
if entries, err := tx.ZRangeByScore(EventListTimeKey, []byte("time"), ts, ts, nil); err != nil {
return nil, err
} else {
if len(entries) == 0 {
return nil, errors.New("getEventByTimestampBytes: no target event")
}
ret, _ = schema.NewNp2pEventFromBytes(entries[0].Value)
return ret, nil
}
}
func (n *NutsDBDataManager) removeEventByTimestampBytes(tx *nutsdb.Tx, tsBytes []byte) error {
ts := float64(binary.BigEndian.Uint64(tsBytes))
if entries, err := tx.ZRangeByScore(EventListTimeKey, []byte("time"), ts, ts, nil); err != nil {
return err
} else {
if len(entries) == 0 {
fmt.Println("removeEventByTimestampBytes: no target event")
return errors.New("removeEventByTimestampBytes: no target event")
}
// remove target event
err2 := tx.ZRem(EventListTimeKey, []byte("time"), entries[0].Value)
if err2 != nil {
return err2
}
return nil
}
}
func (n *NutsDBDataManager) GetEventById(evtId [32]byte) (*schema.Np2pEvent, bool) {
var ret *schema.Np2pEvent
if err := n.db.View(func(tx *nutsdb.Tx) error {
if val, err2 := tx.Get(EventIdxMapIdKey, evtId[:]); err2 != nil {
return err2
} else {
var err3 error
ret, err3 = n.getEventByTimestampBytes(tx, val)
return err3
}
}); err != nil {
fmt.Println(err)
return nil, false
}
return ret, true
}
func (n *NutsDBDataManager) StoreProfile(evt *schema.Np2pEvent) {
if err := n.db.Update(func(tx *nutsdb.Tx) error {
tmpPubKey := evt.Pubkey
key := tmpPubKey[len(tmpPubKey)-8:]
if val, err2 := tx.Get(ProfEvtIdxMap, key); err2 != nil {
return err2
} else {
if val != nil {
// remove old profile event data
return n.removeEventByTimestampBytes(tx, val)
}
}
return tx.Put(ProfEvtIdxMap, key, np2p_util.ConvInt64ToBytes(evt.Created_at), nutsdb.Persistent)
}); err != nil {
fmt.Println("StoreProfile failed: ", err)
}
}
func (n *NutsDBDataManager) GetProfileLocal(pubkey64bit uint64) *schema.Np2pEvent {
var ret *schema.Np2pEvent
if err := n.db.View(func(tx *nutsdb.Tx) error {
if val, err2 := tx.Get(ProfEvtIdxMap, np2p_util.ConvUint64ToBytes(pubkey64bit)); err2 != nil {
return err2
} else {
var err3 error
ret, err3 = n.getEventByTimestampBytes(tx, val)
return err3
}
}); err != nil {
fmt.Println(err)
return nil
}
return ret
}
// NOTE:
// not support apply limit to event filtered by since and until
// limit is used only for getting latest events with limitation
func (n *NutsDBDataManager) GetLatestEvents(since int64, until int64, limit int64) *[]*schema.Np2pEvent {
var ret []*schema.Np2pEvent
// when limit is set, get latest events with limitation
if limit != -1 {
if err := n.db.View(func(tx *nutsdb.Tx) error {
if entries, err2 := tx.ZRangeByRank(EventListTimeKey, []byte("time"), -1*int(limit), -1); err2 != nil {
return err2
} else {
if entries != nil {
ret = make([]*schema.Np2pEvent, len(entries))
for idx, entry := range entries {
ret[idx], _ = schema.NewNp2pEventFromBytes(entry.Value)
}
return nil
} else {
ret = make([]*schema.Np2pEvent, 0)
return nil
}
}
}); err != nil {
fmt.Println(err)
ret = make([]*schema.Np2pEvent, 0)
return &ret
}
} else {
if err := n.db.View(func(tx *nutsdb.Tx) error {
if entries, err2 := tx.ZRangeByScore(EventListTimeKey, []byte("time"), float64(since), float64(until), nil); err2 != nil {
return err2
} else {
if entries != nil {
ret = make([]*schema.Np2pEvent, len(entries))
for idx, entry := range entries {
ret[idx], _ = schema.NewNp2pEventFromBytes(entry.Value)
}
return nil
} else {
ret = make([]*schema.Np2pEvent, 0)
return nil
}
}
}); err != nil {
fmt.Println("GetLatestEvents failed: ", err)
ret = make([]*schema.Np2pEvent, 0)
return &ret
}
}
return &ret
}
func (n *NutsDBDataManager) StoreFollowList(evt *schema.Np2pEvent) {
if err := n.db.Update(func(tx *nutsdb.Tx) error {
tmpPubKey := evt.Pubkey
key := tmpPubKey[len(tmpPubKey)-8:]
if val, err2 := tx.Get(FollowListEvtIdxMap, key); err2 != nil {
return err2
} else {
if val != nil {
// remove old follow event data
n.removeEventByTimestampBytes(tx, val)
}
}
return tx.Put(FollowListEvtIdxMap, key, np2p_util.ConvInt64ToBytes(evt.Created_at), nutsdb.Persistent)
}); err != nil {
fmt.Println("StoreFollowList failed: ", err)
}
}
func (n *NutsDBDataManager) GetFollowListLocal(pubkey64bit uint64) *schema.Np2pEvent {
var ret *schema.Np2pEvent
if err := n.db.View(func(tx *nutsdb.Tx) error {
if val, err2 := tx.Get(FollowListEvtIdxMap, np2p_util.ConvUint64ToBytes(pubkey64bit)); err2 != nil {
return err2
} else {
var err3 error
ret, err3 = n.getEventByTimestampBytes(tx, val)
return err3
}
}); err != nil {
fmt.Println(err)
return nil
}
return ret
}
func (n *NutsDBDataManager) AddReSendNeededEvent(destIds []uint64, evt *schema.Np2pEvent, _isLogging bool) {
resendEvent := schema.NewResendEvent(destIds, evt.Id, evt.Created_at)
if err := n.db.Update(func(tx *nutsdb.Tx) error {
return tx.ZAdd(ReSendNeededEvtList, []byte("time"), float64(evt.Created_at), resendEvent.Encode())
}); err != nil {
fmt.Println(err)
}
}
func (n *NutsDBDataManager) RemoveReSendNeededEvent(resendEvt *schema.ResendEvent, _evt *schema.Np2pEvent) {
if err := n.db.Update(func(tx *nutsdb.Tx) error {
return tx.ZRem(ReSendNeededEvtList, []byte("time"), resendEvt.Encode())
}); err != nil {
fmt.Println(err)
}
}
func (n *NutsDBDataManager) GetReSendNeededEventItr() Np2pItr {
var ret []interface{} // *schema.ResendEvent
var entries_ []*nutsdb.SortedSetMember
if err := n.db.View(func(tx *nutsdb.Tx) error {
if entries, err2 := tx.ZRangeByScore(ReSendNeededEvtList, []byte("time"), 0, math.MaxFloat64, nil); err2 != nil {
return err2
} else {
entries_ = entries
return nil
}
}); err != nil {
fmt.Println(err)
return nil
}
for _, entry := range entries_ {
decoded, _ := schema.NewResendEventFromBytes(entry.Value)
ret = append(ret, decoded)
}
return NewNutsDBItr(ret)
}
func (n *NutsDBDataManager) RemoveStoreAmountLimitOveredEvents() {
var eventsShouldBeAlive []*schema.Np2pEvent
var eventsShouldBeAliveBytes [][]byte
if err := n.db.Update(func(tx *nutsdb.Tx) error {
if num, err2 := tx.ZCard(EventListTimeKey, []byte("time")); err2 != nil {
return err2
} else {
// +100 correnspond to increase amount of reverting events...
if num > np2p_const.DBStoreEventDataNumMax+100 {
// remove limit overd events
removeNum := num - np2p_const.DBStoreEventDataNumMax
if entries, err3 := tx.ZRangeByRank(EventListTimeKey, []byte("time"), 1, removeNum); err3 != nil {
return err3
} else {
if entries != nil && len(entries) > 0 {
eventsShouldBeAlive = make([]*schema.Np2pEvent, 0)
eventsShouldBeAliveBytes = make([][]byte, 0)
for _, entry := range entries {
evt, _ := schema.NewNp2pEventFromBytes(entry.Value)
if evt.Kind == KIND_EVT_PROFILE || evt.Kind == KIND_EVT_FOLLOW_LIST {
eventsShouldBeAlive = append(eventsShouldBeAlive, evt)
eventsShouldBeAliveBytes = append(eventsShouldBeAliveBytes, entry.Value)
}
}
// remove target events
if err4 := tx.ZRemRangeByRank(EventListTimeKey, []byte("time"), 1, removeNum); err4 != nil {
return err4
}
}
}
}
// remove is not needed
return nil
}
}); err != nil {
fmt.Println("RemoveStoreAmountLimitOveredEvents failed: ", err)
}
// when events which should be reverted exist, store them again
if eventsShouldBeAlive != nil && len(eventsShouldBeAlive) > 0 {
if err := n.db.Update(func(tx *nutsdb.Tx) error {
for idx, evt := range eventsShouldBeAlive {
if err2 := tx.ZAdd(EventListTimeKey, []byte("time"), float64(evt.Created_at), eventsShouldBeAliveBytes[idx]); err2 != nil {
return err2
}
}
return nil
}); err != nil {
fmt.Println("RemoveStoreAmountLimitOveredEvents failed: ", err)
}
}
}