-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
98 lines (80 loc) · 1.58 KB
/
pool.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
package db
import (
"bytes"
"context"
"encoding/binary"
"sync"
"github.com/dgraph-io/badger/v3"
)
var pool = &sync.Pool{
New: func() interface{} { return new(Key) },
}
var (
UsersID = []byte("/u/i/")
UsersEmail = []byte("/u/e/")
SiteSession = []byte("/s/s/")
SessionLease = []byte("/s/l/")
SiteHash = []byte("/s/h/")
Domains = []byte("/d/")
)
type Key struct {
bytes.Buffer
}
func (k *Key) UserID(id []byte) *Key {
k.Write(UsersID)
k.Write(id[:])
return k
}
func (k *Key) UserEmail(email string) *Key {
k.Write(UsersEmail)
k.WriteString(email)
return k
}
func (k *Key) SessionID(userID uint64, domain string) *Key {
k.Write(SiteSession[:])
k.WriteString(domain)
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, userID)
k.Write(b)
return k
}
func (k *Key) Domain(domain string) *Key {
k.Write(Domains)
k.WriteString(domain)
return k
}
func (k *Key) Hash() *Key {
k.Write(SiteHash)
return k
}
func gk() *Key {
return pool.Get().(*Key)
}
func pk(k *Key) {
k.Reset()
pool.Put(k)
}
type dbKey struct{}
func GetStore(ctx context.Context) *badger.DB {
return ctx.Value(dbKey{}).(*badger.DB)
}
func SetStore(ctx context.Context, s *badger.DB) context.Context {
return context.WithValue(ctx, dbKey{}, s)
}
func Set(ctx context.Context, value []byte, keys ...*Key) error {
defer func() {
for _, k := range keys {
pk(k)
}
}()
return GetStore(ctx).Update(func(txn *badger.Txn) error {
for _, key := range keys {
if err := txn.Set(key.Bytes(), value); err != nil {
return nil
}
}
return nil
})
}
func Session(ctx context.Context) {
}