forked from kataras/go-sessions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
248 lines (201 loc) · 6.13 KB
/
database.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
package badger
import (
"fmt"
"os"
"runtime"
"time"
"github.com/kataras/go-sessions"
"github.com/kataras/golog"
"github.com/dgraph-io/badger"
)
// DefaultFileMode used as the default database's "fileMode"
// for creating the sessions directory path, opening and write the session file.
var (
DefaultFileMode = 0755
)
// Database the badger(key-value file-based) session storage.
type Database struct {
// Service is the underline badger database connection,
// it's initialized at `New` or `NewFromDB`.
// Can be used to get stats.
Service *badger.DB
}
var _ sessions.Database = (*Database)(nil)
// New creates and returns a new badger(key-value file-based) storage
// instance based on the "directoryPath".
// DirectoryPath should is the directory which the badger database will store the sessions,
// i.e ./sessions
//
// It will remove any old session files.
func New(directoryPath string) (*Database, error) {
if directoryPath == "" {
return nil, fmt.Errorf("directoryPath is missing")
}
lindex := directoryPath[len(directoryPath)-1]
if lindex != os.PathSeparator && lindex != '/' {
directoryPath += string(os.PathSeparator)
}
// create directories if necessary
if err := os.MkdirAll(directoryPath, os.FileMode(DefaultFileMode)); err != nil {
return nil, err
}
opts := badger.DefaultOptions
opts.Dir = directoryPath
opts.ValueDir = directoryPath
service, err := badger.Open(opts)
if err != nil {
golog.Errorf("unable to initialize the badger-based session database: %v", err)
return nil, err
}
return NewFromDB(service), nil
}
// NewFromDB same as `New` but accepts an already-created custom badger connection instead.
func NewFromDB(service *badger.DB) *Database {
db := &Database{Service: service}
runtime.SetFinalizer(db, closeDB)
return db
}
// Acquire receives a session's lifetime from the database,
// if the return value is LifeTime{} then the session manager sets the life time based on the expiration duration lives in configuration.
func (db *Database) Acquire(sid string, expires time.Duration) sessions.LifeTime {
txn := db.Service.NewTransaction(true)
defer txn.Commit(nil)
bsid := []byte(sid)
item, err := txn.Get(bsid)
if err == nil {
// found, return the expiration.
return sessions.LifeTime{Time: time.Unix(int64(item.ExpiresAt()), 0)}
}
// not found, create an entry with ttl and return an empty lifetime, session manager will do its job.
if err != nil {
if err == badger.ErrKeyNotFound {
// create it and set the expiration, we don't care about the value there.
err = txn.SetWithTTL(bsid, bsid, expires)
}
}
if err != nil {
golog.Error(err)
}
return sessions.LifeTime{} // session manager will handle the rest.
}
var delim = byte('*')
func makeKey(sid, key string) []byte {
return append([]byte(sid), append([]byte(key), delim)...)
}
// Set sets a key value of a specific session.
// Ignore the "immutable".
func (db *Database) Set(sid string, lifetime sessions.LifeTime, key string, value interface{}, immutable bool) {
valueBytes, err := sessions.DefaultTranscoder.Marshal(value)
if err != nil {
golog.Error(err)
return
}
err = db.Service.Update(func(txn *badger.Txn) error {
return txn.SetWithTTL(makeKey(sid, key), valueBytes, lifetime.DurationUntilExpiration())
})
if err != nil {
golog.Error(err)
}
}
// Get retrieves a session value based on the key.
func (db *Database) Get(sid string, key string) (value interface{}) {
err := db.Service.View(func(txn *badger.Txn) error {
item, err := txn.Get(makeKey(sid, key))
if err != nil {
return err
}
// item.ValueCopy
valueBytes, err := item.Value()
if err != nil {
return err
}
return sessions.DefaultTranscoder.Unmarshal(valueBytes, &value)
})
if err != nil && err != badger.ErrKeyNotFound {
golog.Error(err)
return nil
}
return
}
// Visit loops through all session keys and values.
func (db *Database) Visit(sid string, cb func(key string, value interface{})) {
prefix := append([]byte(sid), delim)
txn := db.Service.NewTransaction(false)
defer txn.Discard()
iter := txn.NewIterator(badger.DefaultIteratorOptions)
defer iter.Close()
for iter.Rewind(); iter.ValidForPrefix(prefix); iter.Next() {
item := iter.Item()
valueBytes, err := item.Value()
if err != nil {
golog.Error(err)
continue
}
var value interface{}
if err = sessions.DefaultTranscoder.Unmarshal(valueBytes, &value); err != nil {
golog.Error(err)
continue
}
cb(string(item.Key()), value)
}
}
var iterOptionsNoValues = badger.IteratorOptions{
PrefetchValues: false,
PrefetchSize: 100,
Reverse: false,
AllVersions: false,
}
// Len returns the length of the session's entries (keys).
func (db *Database) Len(sid string) (n int) {
prefix := append([]byte(sid), delim)
txn := db.Service.NewTransaction(false)
iter := txn.NewIterator(iterOptionsNoValues)
for iter.Rewind(); iter.ValidForPrefix(prefix); iter.Next() {
n++
}
iter.Close()
txn.Discard()
return
}
// Delete removes a session key value based on its key.
func (db *Database) Delete(sid string, key string) (deleted bool) {
txn := db.Service.NewTransaction(true)
err := txn.Delete(makeKey(sid, key))
if err != nil {
golog.Error(err)
}
txn.Commit(nil)
return err == nil
}
// Clear removes all session key values but it keeps the session entry.
func (db *Database) Clear(sid string) {
prefix := append([]byte(sid), delim)
txn := db.Service.NewTransaction(true)
defer txn.Commit(nil)
iter := txn.NewIterator(iterOptionsNoValues)
defer iter.Close()
for iter.Rewind(); iter.ValidForPrefix(prefix); iter.Next() {
txn.Delete(iter.Item().Key())
}
}
// Release destroys the session, it clears and removes the session entry,
// session manager will create a new session ID on the next request after this call.
func (db *Database) Release(sid string) {
// clear all $sid-$key.
db.Clear(sid)
// and remove the $sid.
txn := db.Service.NewTransaction(true)
txn.Delete([]byte(sid))
txn.Commit(nil)
}
// Close shutdowns the badger connection.
func (db *Database) Close() error {
return closeDB(db)
}
func closeDB(db *Database) error {
err := db.Service.Close()
if err != nil {
golog.Warnf("closing the badger connection: %v", err)
}
return err
}