/
pegasus.go
303 lines (256 loc) · 7.19 KB
/
pegasus.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
package store
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/XiaoMi/pegasus-go-client/admin"
"github.com/XiaoMi/pegasus-go-client/pegasus"
"github.com/spf13/cast"
)
const (
// PegasusType represents the storage type as a string value
PegasusType = "pegasus"
// PegasusTagPattern represents the tag pattern to be used as a key in specified storage
PegasusTagPattern = "gocache_tag_%s"
// PegasusNOTTL ttl(time-to-live) in seconds: -1 if ttl is not set; -2 if entry doesn't exist
PegasusNOTTL = -1
PegasusNOENTRY = -2
DefaultTable = "gocache_pegasus"
DefaultTablePartitionNum = 4
DefaultScanNum = 100
)
// empty represent empty sort key, more info reference: https://github.com/XiaoMi/pegasus-go-client/blob/f3b6b08bc4c227982bb5b73106329435fda97a38/pegasus/table_connector.go#L83
var empty = []byte("-")
// OptionsPegasus is options of Pegasus
type OptionsPegasus struct {
*Options
MetaServers []string
TableName string
TablePartitionNum int
TableScanNum int
}
// PegasusStore is a store for Pegasus
type PegasusStore struct {
client pegasus.Client
options *OptionsPegasus
}
// NewPegasus creates a new store to pegasus instance(s)
func NewPegasus(ctx context.Context, options *OptionsPegasus) (*PegasusStore, error) {
if options == nil {
options = &OptionsPegasus{}
}
if err := CreatePegasusTable(ctx, options); err != nil {
return nil, err
}
client := pegasus.NewClient(pegasus.Config{
MetaServers: options.MetaServers,
})
table, err := client.OpenTable(ctx, options.TableName)
if err != nil {
return nil, err
}
defer table.Close()
return &PegasusStore{
client: client,
options: options,
}, nil
}
// ValidatePegasusOptions validate pegasus options
func ValidatePegasusOptions(options *OptionsPegasus) error {
if len(options.MetaServers) == 0 {
return errors.New("pegasus meta servers must fill")
}
if len(options.TableName) == 0 {
options.TableName = DefaultTable
}
if options.TablePartitionNum < 1 {
options.TablePartitionNum = DefaultTablePartitionNum
}
if options.TableScanNum < 1 {
options.TableScanNum = DefaultScanNum
}
return nil
}
// CreatePegasusTable for create table by options
func CreatePegasusTable(ctx context.Context, options *OptionsPegasus) error {
if err := ValidatePegasusOptions(options); err != nil {
return err
}
tableClient := admin.NewClient(admin.Config{MetaServers: options.MetaServers})
tableList, err := tableClient.ListTables(ctx)
if err != nil {
return err
}
for i := range tableList {
if tableList[i].Name == options.TableName {
return nil
}
}
// if not found then create table of options
return tableClient.CreateTable(ctx, options.TableName, options.TablePartitionNum)
}
// DropPegasusTable for drop table
func DropPegasusTable(ctx context.Context, options *OptionsPegasus) error {
if err := ValidatePegasusOptions(options); err != nil {
return err
}
tableClient := admin.NewClient(admin.Config{MetaServers: options.MetaServers})
return tableClient.DropTable(ctx, options.TableName)
}
// Close when exit store
func (p *PegasusStore) Close() error {
return p.client.Close()
}
// Get returns data stored from a given key
func (p *PegasusStore) Get(ctx context.Context, key any) (any, error) {
table, err := p.client.OpenTable(ctx, p.options.TableName)
if err != nil {
return nil, err
}
defer table.Close()
value, err := table.Get(ctx, []byte(cast.ToString(key)), empty)
if err != nil {
return nil, err
}
if value == nil {
return nil, &NotFound{}
}
return value, nil
}
// GetWithTTL returns data stored from a given key and its corresponding TTL
func (p *PegasusStore) GetWithTTL(ctx context.Context, key any) (any, time.Duration, error) {
table, err := p.client.OpenTable(ctx, p.options.TableName)
if err != nil {
return nil, 0, err
}
defer table.Close()
value, err := table.Get(ctx, []byte(cast.ToString(key)), empty)
if err != nil {
return nil, 0, err
}
if value == nil {
return nil, 0, &NotFound{}
}
ttl, err := table.TTL(ctx, []byte(cast.ToString(key)), empty)
if err != nil {
return nil, 0, err
}
return value, time.Duration(ttl) * time.Second, nil
}
// Set defines data in Pegasus for given key identifier
func (p *PegasusStore) Set(ctx context.Context, key, value any, options ...Option) error {
opts := applyOptions(options...)
table, err := p.client.OpenTable(ctx, p.options.TableName)
if err != nil {
return err
}
defer table.Close()
err = table.SetTTL(ctx, []byte(cast.ToString(key)), empty, []byte(cast.ToString(value)), opts.Expiration)
if err != nil {
return err
}
if tags := opts.Tags; len(tags) > 0 {
if err = p.SetTags(ctx, key, tags); err != nil {
return err
}
}
return nil
}
func (p *PegasusStore) SetTags(ctx context.Context, key any, tags []string) error {
for _, tag := range tags {
tagKey := fmt.Sprintf(PegasusTagPattern, tag)
cacheKeys := []string{}
if result, err := p.Get(ctx, tagKey); err == nil {
if bytes, ok := result.([]byte); ok {
cacheKeys = strings.Split(string(bytes), ",")
}
}
alreadyInserted := false
for _, cacheKey := range cacheKeys {
if cacheKey == key.(string) {
alreadyInserted = true
break
}
}
if !alreadyInserted {
cacheKeys = append(cacheKeys, key.(string))
}
if err := p.Set(ctx, tagKey, []byte(strings.Join(cacheKeys, ",")), WithExpiration(720*time.Hour)); err != nil {
return err
}
}
return nil
}
// Delete removes data from Pegasus for given key identifier
func (p *PegasusStore) Delete(ctx context.Context, key any) error {
table, err := p.client.OpenTable(ctx, p.options.TableName)
if err != nil {
return err
}
defer table.Close()
return table.Del(ctx, []byte(cast.ToString(key)), empty)
}
// Invalidate invalidates some cache data in Pegasus for given options
func (p *PegasusStore) Invalidate(ctx context.Context, options ...InvalidateOption) error {
opts := applyInvalidateOptions(options...)
if tags := opts.Tags; len(tags) > 0 {
for _, tag := range tags {
tagKey := fmt.Sprintf(PegasusTagPattern, tag)
result, err := p.Get(ctx, tagKey)
if err != nil {
return nil
}
cacheKeys := []string{}
if bytes, ok := result.([]byte); ok {
cacheKeys = strings.Split(string(bytes), ",")
}
for _, cacheKey := range cacheKeys {
if err := p.Delete(ctx, cacheKey); err != nil {
return err
}
}
}
}
return nil
}
// Clear resets all data in the store
func (p *PegasusStore) Clear(ctx context.Context) error {
table, err := p.client.OpenTable(ctx, p.options.TableName)
if err != nil {
return err
}
defer table.Close()
// init full scan
scanners, err := table.GetUnorderedScanners(ctx, p.options.TablePartitionNum, &pegasus.ScannerOptions{
BatchSize: p.options.TableScanNum,
// Values can be optimized out during scanning to reduce the workload.
NoValue: true,
})
if err != nil {
return err
}
// full scan and delete
for _, scanner := range scanners {
// Iterates sequentially.
for {
completed, hashKey, _, _, err := scanner.Next(ctx)
if err != nil {
return err
}
if completed {
break
}
err = p.Delete(ctx, hashKey)
if err != nil {
return err
}
}
}
return nil
}
// GetType returns the store type
func (p *PegasusStore) GetType() string {
return PegasusType
}