-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory_store.go
188 lines (170 loc) · 4.48 KB
/
memory_store.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
// MIT License
// Copyright (c) 2020 Tree Xie
// 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 session
import (
"context"
"encoding/json"
"io/ioutil"
"net/http"
"sync/atomic"
"time"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/vicanso/hes"
)
var (
// ErrNotInit error not init
ErrNotInit = &hes.Error{
Message: "client not init",
Category: ErrCategory,
StatusCode: http.StatusInternalServerError,
Exception: true,
}
defaultInterval = 60 * time.Second
)
const (
flushStatusStop = iota
flushStatusRunning
)
type (
// MemoryStore memory store for session
MemoryStore struct {
client *lru.Cache[string, *MemoryStoreInfo]
flushStatus int32
}
// MemoryStoreInfo memory store info
MemoryStoreInfo struct {
ExpiredAt int64
Data []byte
}
// MemoryStoreConfig memory store config
MemoryStoreConfig struct {
Size int
// SaveAs save as file
SaveAs string
// Interval save interval
Interval time.Duration
}
)
// Get get the seesion from memory
func (ms *MemoryStore) Get(_ context.Context, key string) (data []byte, err error) {
client := ms.client
if client == nil {
err = ErrNotInit
return
}
info, found := client.Get(key)
if !found {
return
}
if info.ExpiredAt < time.Now().Unix() {
return
}
data = info.Data
return
}
// Set set the session to memory
func (ms *MemoryStore) Set(_ context.Context, key string, data []byte, ttl time.Duration) (err error) {
client := ms.client
if client == nil {
err = ErrNotInit
return
}
expiredAt := time.Now().Unix() + int64(ttl.Seconds())
info := &MemoryStoreInfo{
ExpiredAt: expiredAt,
Data: data,
}
client.Add(key, info)
return
}
// Destroy remove the session from memory
func (ms *MemoryStore) Destroy(_ context.Context, key string) (err error) {
client := ms.client
if client == nil {
err = ErrNotInit
return
}
client.Remove(key)
return
}
func (ms *MemoryStore) intervalFlush(saveAs string, interval time.Duration) {
client := ms.client
if client == nil {
return
}
atomic.StoreInt32(&ms.flushStatus, flushStatusRunning)
if interval < time.Second {
interval = defaultInterval
}
ticker := time.NewTicker(interval)
for range ticker.C {
if atomic.LoadInt32(&ms.flushStatus) == flushStatusStop {
return
}
keys := client.Keys()
m := make(map[string]*MemoryStoreInfo)
for _, key := range keys {
info, found := client.Get(key)
if !found {
continue
}
if info.ExpiredAt < time.Now().Unix() {
continue
}
m[key] = info
}
buf, _ := json.Marshal(&m)
_ = ioutil.WriteFile(saveAs, buf, 0600)
}
}
// StopFlush stop flush
func (ms *MemoryStore) StopFlush() {
atomic.StoreInt32(&ms.flushStatus, flushStatusStop)
}
// NewMemoryStore create new memory store instance
func NewMemoryStore(size int) (store *MemoryStore, err error) {
client, err := lru.New[string, *MemoryStoreInfo](size)
if err != nil {
return
}
store = &MemoryStore{
client: client,
}
return
}
// NewMemoryStoreByConfig create new memory store instance by config
func NewMemoryStoreByConfig(config MemoryStoreConfig) (store *MemoryStore, err error) {
store, err = NewMemoryStore(config.Size)
if err != nil {
return
}
file := config.SaveAs
if file != "" {
// 从文件中恢复
buf, _ := ioutil.ReadFile(file)
m := make(map[string]*MemoryStoreInfo)
// 如果读取失败,则忽略
_ = json.Unmarshal(buf, &m)
for key, value := range m {
store.client.Add(key, value)
}
// 定时写入文件
go store.intervalFlush(file, config.Interval)
}
return
}