Repository navigation
Expand file tree
/
Copy pathstore.go
More file actions
474 lines (395 loc) · 9.89 KB
/
Copy pathstore.go
File metadata and controls
474 lines (395 loc) · 9.89 KB
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package sqlitestore
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net"
"sync"
"time"
sq "github.com/Masterminds/squirrel"
"github.com/jellydator/sessionup"
)
var (
// ErrInvalidTable is returned when invalid table name is provided.
ErrInvalidTable = errors.New("invalid table name")
// ErrInvalidInterval is returned when invalid cleanup interval is provided.
ErrInvalidInterval = errors.New("invalid cleanup interval")
)
// SQLiteStore is a SQLite implementation of sessionup.Store.
type SQLiteStore struct {
db *sql.DB
table string
deletion struct {
mu sync.Mutex
nextID uint64
fns map[uint64]func(sessionup.Session)
}
}
// New creates and returns a fresh intance of SQLiteStore.
func New(db *sql.DB, table string) (*SQLiteStore, error) {
if _, err := db.Exec(fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
id TEXT PRIMARY KEY,
user_key TEXT NOT NULL,
expires_at DATETIME NOT NULL,
created_at DATETIME NOT NULL,
ip TEXT,
agent_os TEXT,
agent_browser TEXT,
meta BLOB
)`, table)); err != nil {
return nil, err
}
st := &SQLiteStore{
db: db,
table: table,
}
st.deletion.fns = make(map[uint64]func(sessionup.Session))
return st, nil
}
// NewWithCleanup creates and returns a fresh instance of SQLiteStore and
// additionally spins up cleanup go routine. To manage new go routine
// a cleanup errors channel and cleanup close delegate function is returned.
func NewWithCleanup(
db *sql.DB,
table string,
dur time.Duration,
) (*SQLiteStore, <-chan error, func(), error) {
if dur <= 0 {
return nil, nil, nil, ErrInvalidInterval
}
st, err := New(db, table)
if err != nil {
return nil, nil, nil, err
}
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
errCh := make(chan error)
wg.Add(1)
go func() {
defer wg.Done()
for {
err := st.Cleanup(ctx, dur)
if errors.Is(err, ctx.Err()) {
return
}
select {
case errCh <- err:
default:
// slow receiver.
}
}
}()
return st, errCh, func() {
cancel()
wg.Wait()
// drain errors channel.
close(errCh)
for range errCh {
}
}, nil
}
// Cleanup periodically removes all expired records from the store by their
// expiration time.
// Duration specifies how often cleanup should be ran.
// If duration is less than zero, an ErrInvalidInterval error will be returned.
func (st *SQLiteStore) Cleanup(ctx context.Context, dur time.Duration) error {
if dur <= 0 {
return ErrInvalidInterval
}
tc := time.NewTimer(dur)
defer tc.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-tc.C:
if err := st.removeExpiredSessions(ctx); err != nil {
return err
}
tc.Reset(dur)
}
}
}
// OnDeletion sets provided handler to be executed whenever a session is deleted.
// Unsubscribe method is returned, that allows to unset the handler.
// If the returned unsubscribe method is invoked with true, then it will
// block until the provided handler returns. Otherwise, it will
// not block.
func (st *SQLiteStore) OnDeletion(fn func(context.Context, sessionup.Session)) func(bool) {
st.deletion.mu.Lock()
defer st.deletion.mu.Unlock()
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
id := st.deletion.nextID
st.deletion.nextID++
st.deletion.fns[id] = func(s sessionup.Session) {
wg.Add(1)
go func() {
fn(ctx, s)
wg.Done()
}()
}
return func(wait bool) {
cancel()
if wait {
wg.Wait()
}
st.deletion.mu.Lock()
delete(st.deletion.fns, id)
st.deletion.mu.Unlock()
}
}
// Create inserts provided session into the store.
func (st *SQLiteStore) Create(ctx context.Context, session sessionup.Session) error {
var (
data []byte
err error
)
if session.Meta != nil {
data, err = json.Marshal(session.Meta)
if err != nil {
// unlikely to happen.
return err
}
}
_, err = sq.Insert(st.table).
SetMap(map[string]interface{}{
"id": session.ID,
"user_key": session.UserKey,
"expires_at": session.ExpiresAt,
"created_at": session.CreatedAt,
"ip": session.IP.String(),
"agent_os": session.Agent.OS,
"agent_browser": session.Agent.Browser,
"meta": data,
}).
RunWith(st.db).
ExecContext(ctx)
return err
}
// FetchByID retrieves a session from the store by the provided ID.
// The second returned value indicates whether the session was found
// or not (true == found), error will be nil if session is not found.
// If session is expired, it will be treated as not found.
func (st *SQLiteStore) FetchByID(ctx context.Context, id string) (sessionup.Session, bool, error) {
sessions, err := st.selectSessions(ctx, st.db, func(b sq.SelectBuilder) sq.SelectBuilder {
return b.Where(sq.Eq{"id": id})
})
if err != nil {
return sessionup.Session{}, false, err
}
if len(sessions) == 0 || sessions[0].ExpiresAt.Before(time.Now()) {
return sessionup.Session{}, false, nil
}
return sessions[0], true, nil
}
// FetchByUserKey retrieves all sessions associated with the
// provided user key. If none are found, both return values will be nil.
// If list contains expired sessions, they will not be returned.
func (st *SQLiteStore) FetchByUserKey(ctx context.Context, key string) ([]sessionup.Session, error) {
ss, err := st.selectSessions(ctx, st.db, func(b sq.SelectBuilder) sq.SelectBuilder {
return b.Where(sq.Eq{"user_key": key})
})
if err != nil {
return nil, err
}
var (
valid []sessionup.Session
tstamp = time.Now()
)
for _, session := range ss {
if !session.ExpiresAt.Before(tstamp) {
valid = append(valid, session)
}
}
return valid, nil
}
// DeleteByID deletes the session from the store by the provided ID.
// If session is found OnDeletion handlers will be executed.
// If session is not found, this function will be no-op.
func (st *SQLiteStore) DeleteByID(ctx context.Context, id string) error {
tx, err := st.beginImmediateTransaction(ctx)
if err != nil {
return err
}
defer tx.Rollback() // nolint: errcheck // this error is meaningless.
sessions, err := st.selectSessions(ctx, tx, func(b sq.SelectBuilder) sq.SelectBuilder {
return b.Where(sq.Eq{"id": id})
})
if err != nil {
// unlikely to happen.
return err
}
if len(sessions) == 0 {
return nil
}
_, err = sq.Delete(st.table).
Where("id = ?", id).
RunWith(tx).
ExecContext(ctx)
if err != nil {
// unlikely to happen
return err
}
if err := tx.Commit(); err != nil {
// unlikely to happen.
return err
}
for _, fn := range st.deletion.fns {
fn(sessions[0])
}
return nil
}
// DeleteByUserKey deletes all sessions associated with the provided user key,
// except those whose IDs are provided as last argument.
// For each deleted session all OnDeletion handlers will be executed.
// If none are found, this function will no-op.
func (st *SQLiteStore) DeleteByUserKey(ctx context.Context, key string, expIDs ...string) error {
tx, err := st.beginImmediateTransaction(ctx)
if err != nil {
return err
}
defer tx.Rollback() // nolint: errcheck // this error is meaningless.
sessions, err := st.selectSessions(ctx, tx, func(b sq.SelectBuilder) sq.SelectBuilder {
return b.Where(sq.And{
sq.Eq{"user_key": key},
sq.NotEq{"id": expIDs},
})
})
if err != nil {
// unlikely to happen
return err
}
ids := make([]string, len(sessions))
for i, session := range sessions {
ids[i] = session.ID
}
_, err = sq.Delete(st.table).
Where(sq.Eq{"id": ids}).
RunWith(tx).
ExecContext(ctx)
if err != nil {
// unlikely to happen
return err
}
if err := tx.Commit(); err != nil {
// unlikely to happen.
return err
}
for _, session := range sessions {
for _, fn := range st.deletion.fns {
fn(session)
}
}
return nil
}
func (st *SQLiteStore) selectSessions(
ctx context.Context,
br sq.BaseRunner,
dec func(sq.SelectBuilder) sq.SelectBuilder,
) ([]sessionup.Session, error) {
rows, err := dec(sq.
Select(
"id",
"user_key",
"expires_at",
"created_at",
"ip",
"agent_os",
"agent_browser",
"meta",
).
From(st.table).
RunWith(br),
).QueryContext(ctx)
if err != nil {
return nil, err
}
defer rows.Close() // nolint: errcheck // this error is meaningless.
var sessions []sessionup.Session
for rows.Next() {
var (
session sessionup.Session
ip string
data []byte
)
if err := rows.Scan(
&session.ID,
&session.UserKey,
&session.ExpiresAt,
&session.CreatedAt,
&ip,
&session.Agent.OS,
&session.Agent.Browser,
&data,
); err != nil {
// unlikely to happen.
return nil, err
}
if len(data) > 0 {
if err := json.Unmarshal(data, &session.Meta); err != nil {
// unlikely to happen.
return nil, err
}
}
session.IP = net.ParseIP(ip)
sessions = append(sessions, session)
}
return sessions, nil
}
func (st *SQLiteStore) removeExpiredSessions(ctx context.Context) error {
tx, err := st.beginImmediateTransaction(ctx)
if err != nil {
return err
}
defer tx.Rollback() // nolint: errcheck // this error is meaningless.
sessions, err := st.selectSessions(ctx, tx, func(b sq.SelectBuilder) sq.SelectBuilder {
return b.Where(sq.LtOrEq{
"expires_at": time.Now().UTC(),
})
})
if err != nil {
// unlikely to happen.
return err
}
if len(sessions) == 0 {
return nil
}
ids := make([]string, len(sessions))
for i, session := range sessions {
ids[i] = session.ID
}
_, err = sq.Delete(st.table).
Where(sq.Eq{"id": ids}).
RunWith(tx).
ExecContext(ctx)
if err != nil {
// unlikely to happen.
return err
}
if err := tx.Commit(); err != nil {
// unlikely to happen.
return err
}
for _, session := range sessions {
for _, fn := range st.deletion.fns {
fn(session)
}
}
return nil
}
func (st *SQLiteStore) beginImmediateTransaction(ctx context.Context) (*sql.Tx, error) {
tx, err := st.db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
_, err = tx.Exec("ROLLBACK; BEGIN IMMEDIATE")
if err != nil {
// unlikely to happen.
return nil, err
}
return tx, nil
}