-
Notifications
You must be signed in to change notification settings - Fork 5
/
db_kv.go
93 lines (75 loc) · 1.79 KB
/
db_kv.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
// Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
package agents
import (
"errors"
"github.com/TeaOSLab/EdgeNode/internal/events"
"github.com/TeaOSLab/EdgeNode/internal/utils/kvstore"
)
type KVDB struct {
table *kvstore.Table[*AgentIP]
encoder *AgentIPEncoder[*AgentIP]
lastKey string
}
func NewKVDB() *KVDB {
var db = &KVDB{}
events.OnClose(func() {
_ = db.Close()
})
return db
}
func (this *KVDB) Init() error {
store, err := kvstore.DefaultStore()
if err != nil {
return err
}
db, err := store.NewDB("agents")
if err != nil {
return err
}
{
this.encoder = &AgentIPEncoder[*AgentIP]{}
table, tableErr := kvstore.NewTable[*AgentIP]("agent_ips", this.encoder)
if tableErr != nil {
return tableErr
}
db.AddTable(table)
this.table = table
}
return nil
}
func (this *KVDB) InsertAgentIP(ipId int64, ip string, agentCode string) error {
if this.table == nil {
return errors.New("table should not be nil")
}
var item = &AgentIP{
Id: ipId,
IP: ip,
AgentCode: agentCode,
}
var key = this.encoder.EncodeKey(item)
return this.table.Set(key, item)
}
func (this *KVDB) ListAgentIPs(offset int64, size int64) (agentIPs []*AgentIP, err error) {
if this.table == nil {
return nil, errors.New("table should not be nil")
}
err = this.table.
Query().
Limit(int(size)).
Offset(this.lastKey).
FindAll(func(tx *kvstore.Tx[*AgentIP], item kvstore.Item[*AgentIP]) (goNext bool, err error) {
this.lastKey = item.Key
agentIPs = append(agentIPs, item.Value)
return true, nil
})
return
}
func (this *KVDB) Close() error {
return nil
}
func (this *KVDB) Flush() error {
if this.table == nil {
return errors.New("table should not be nil")
}
return this.table.DB().Store().Flush()
}