-
Notifications
You must be signed in to change notification settings - Fork 0
/
keybase.go
239 lines (216 loc) · 7 KB
/
keybase.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
// Copyright (c) 2024 Maxtek Consulting
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package keybase
import (
"context"
"database/sql"
"fmt"
"sync"
"time"
_ "modernc.org/sqlite"
)
const (
defaultTTL time.Duration = time.Second * 10
defaultStorage string = ":memory:"
invalidCount int = -1
)
type options struct {
storage string
ttl time.Duration
}
func parseOptions(opts ...Option) *options {
config := &options{
storage: defaultStorage,
ttl: defaultTTL,
}
for _, opt := range opts {
switch opt.key {
case "ttl":
config.ttl = opt.value.(time.Duration)
case "storage":
config.storage = opt.value.(string)
}
}
return config
}
// Set filepath for persistent keybase storage
func WithStorage(path string) Option {
return Option{
key: "storage",
value: path,
}
}
// Set TTL for keys
func WithTTL(ttl time.Duration) Option {
return Option{
key: "ttl",
value: ttl,
}
}
// Option opaque configuration parameter
type Option struct {
key string
value interface{}
}
// Keybase concurrent key storage with timeouts and optional persistence
type Keybase struct {
mu *sync.RWMutex
db *sql.DB
ttl time.Duration
}
// Open opens new or existing keybase
func Open(ctx context.Context, opts ...Option) (*Keybase, error) {
config := parseOptions(opts...)
db, err := sqlOpen("sqlite", config.storage)
if err != nil {
return nil, fmt.Errorf("keybase.Open: failed to open database: %v", err)
}
err = newCreateTableQuery().queryExec(ctx, db)
if err != nil {
return nil, fmt.Errorf("keybase.Open: failed to create table: %v", err)
}
return &Keybase{
mu: new(sync.RWMutex),
db: db,
ttl: config.ttl,
}, nil
}
// Close closes keybase
func (k *Keybase) Close() {
_ = k.db.Close() // error is unreachable
}
// Put inserts new value
func (k *Keybase) Put(ctx context.Context, namespace, key string) error {
expiration := time.Now().Add(k.ttl).UnixMilli()
k.mu.Lock()
defer k.mu.Unlock()
tx := newPutQuery(namespace, key, expiration)
err := tx.queryExec(ctx, k.db)
if err != nil {
return fmt.Errorf("keybase.Put: failed to insert key: %v", err)
}
return nil
}
// MatchKey collect list of keys from a given namespace that match a specific pattern
func (k *Keybase) MatchKey(ctx context.Context, namespace, pattern string, active, unique bool) ([]string, error) {
timestamp := time.Now().UnixMilli()
k.mu.RLock()
defer k.mu.RUnlock()
keys, err := newMatchKeyQuery(namespace, pattern, active, unique, timestamp).queryValues(ctx, k.db)
if err != nil {
return nil, fmt.Errorf("keybase.MatchKey: failed to query database: %v", err)
}
return keys, nil
}
// CountKey count active frequency of a specific key from a given namespace
func (k *Keybase) CountKey(ctx context.Context, namespace, key string, active bool) (int, error) {
timestamp := time.Now().UnixMilli()
k.mu.RLock()
defer k.mu.RUnlock()
count, err := newCountKeyQuery(namespace, key, active, timestamp).queryCount(ctx, k.db)
if err != nil {
return invalidCount, fmt.Errorf("keybase.CountKey: failed to query database: %v", err)
}
return count, nil
}
// GetKeys collects a list of active keys from a given namespace
func (k *Keybase) GetKeys(ctx context.Context, namespace string, active, unique bool) ([]string, error) {
timestamp := time.Now().UnixMilli()
k.mu.RLock()
defer k.mu.RUnlock()
keys, err := newGetKeysQuery(namespace, active, unique, timestamp).queryValues(ctx, k.db)
if err != nil {
return nil, fmt.Errorf("keybase.GetKeys: failed to query database: %v", err)
}
return keys, nil
}
// CountKeys counts the active keys from a given namespace
func (k *Keybase) CountKeys(ctx context.Context, namespace string, active, unique bool) (int, error) {
timestamp := time.Now().UnixMilli()
k.mu.RLock()
defer k.mu.RUnlock()
count, err := newCountKeysQuery(namespace, active, unique, timestamp).queryCount(ctx, k.db)
if err != nil {
return invalidCount, fmt.Errorf("keybase.CountKeys: failed to query database: %v", err)
}
return count, nil
}
// GetNamespace collects a list of active namespaces
func (k *Keybase) GetNamespaces(ctx context.Context, active bool) ([]string, error) {
timestamp := time.Now().UnixMilli()
k.mu.RLock()
defer k.mu.RUnlock()
keys, err := newGetNamespacesQuery(active, timestamp).queryValues(ctx, k.db)
if err != nil {
return nil, fmt.Errorf("keybase.GetNamespaces: failed to query database: %v", err)
}
return keys, nil
}
// CountNamespaces counts active namespaces
func (k *Keybase) CountNamespaces(ctx context.Context, active bool) (int, error) {
timestamp := time.Now().UnixMilli()
k.mu.RLock()
defer k.mu.RUnlock()
count, err := newCountNamespacesQuery(active, timestamp).queryCount(ctx, k.db)
if err != nil {
return invalidCount, fmt.Errorf("keybase.CountNamespaces: failed to query database: %v", err)
}
return count, nil
}
// CountEntries counts all keys in all namespaces
func (k *Keybase) CountEntries(ctx context.Context, active, unique bool) (int, error) {
timestamp := time.Now().UnixMilli()
k.mu.RLock()
defer k.mu.RUnlock()
count, err := newCountEntriesQuery(active, unique, timestamp).queryCount(ctx, k.db)
if err != nil {
return invalidCount, fmt.Errorf("keybase.CountEntries: failed to query database: %v", err)
}
return count, nil
}
// PruneEntries removes stale entries.
func (k *Keybase) PruneEntries(ctx context.Context) error {
timestamp := time.Now().UnixMilli()
k.mu.Lock()
defer k.mu.Unlock()
err := newPruneEntriesQuery(timestamp).queryExec(ctx, k.db)
if err != nil {
return fmt.Errorf("keybase.PruneEntries: failed to insert key: %v", err)
}
return nil
}
// ClearEntries removes all entries.
func (k *Keybase) ClearEntries(ctx context.Context) error {
k.mu.Lock()
defer k.mu.Unlock()
err := newClearEntriesQuery().queryExec(ctx, k.db)
if err != nil {
return fmt.Errorf("keybase.PruneEntries: failed to insert key: %v", err)
}
return nil
}
func sqlOpen(driverName string, dataSourceName string) (*sql.DB, error) {
db, _ := sql.Open(driverName, dataSourceName)
err := db.Ping()
if err != nil {
return nil, err
}
return db, nil
}