-
Notifications
You must be signed in to change notification settings - Fork 3
/
file.go
228 lines (197 loc) · 5.24 KB
/
file.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
// Copyright 2021 Flamego. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package session
import (
"context"
"fmt"
"io/fs"
"os"
"path/filepath"
"time"
"github.com/pkg/errors"
)
var _ Store = (*fileStore)(nil)
// fileStore is a file implementation of the session store.
type fileStore struct {
nowFunc func() time.Time // The function to return the current time
lifetime time.Duration // The duration to have no access to a session before being recycled
rootDir string // The root directory of file session items stored on the local file system
encoder Encoder
decoder Decoder
idWriter IDWriter
}
// newFileStore returns a new file session store based on given configuration.
func newFileStore(cfg FileConfig, idWriter IDWriter) *fileStore {
return &fileStore{
nowFunc: cfg.nowFunc,
lifetime: cfg.Lifetime,
rootDir: cfg.RootDir,
encoder: cfg.Encoder,
decoder: cfg.Decoder,
idWriter: idWriter,
}
}
// filename returns the computed file name with given sid.
func (s *fileStore) filename(sid string) string {
return filepath.Join(s.rootDir, string(sid[0]), string(sid[1]), sid)
}
// isFile returns true if given path exists as a file (i.e. not a directory).
func isFile(path string) bool {
f, e := os.Stat(path)
if e != nil {
return false
}
return !f.IsDir()
}
func (s *fileStore) Exist(_ context.Context, sid string) bool {
if len(sid) < minimumSIDLength {
return false
}
return isFile(s.filename(sid))
}
func (s *fileStore) Read(_ context.Context, sid string) (Session, error) {
if len(sid) < minimumSIDLength {
return nil, ErrMinimumSIDLength
}
filename := s.filename(sid)
if !isFile(filename) {
err := os.MkdirAll(filepath.Dir(filename), 0700)
if err != nil {
return nil, errors.Wrap(err, "create parent directory")
}
return NewBaseSession(sid, s.encoder, s.idWriter), nil
}
// Discard existing data if it's expired
fi, err := os.Stat(filename)
if err != nil {
return nil, errors.Wrap(err, "stat file")
}
if !fi.ModTime().Add(s.lifetime).After(s.nowFunc()) {
return NewBaseSession(sid, s.encoder, s.idWriter), nil
}
binary, err := os.ReadFile(filename)
if err != nil {
return nil, errors.Wrap(err, "read file")
}
data, err := s.decoder(binary)
if err != nil {
return nil, errors.Wrap(err, "decode")
}
return NewBaseSessionWithData(sid, s.encoder, s.idWriter, data), nil
}
func (s *fileStore) Destroy(_ context.Context, sid string) error {
if len(sid) < minimumSIDLength {
return nil
}
return os.Remove(s.filename(sid))
}
func (s *fileStore) Touch(_ context.Context, sid string) error {
filename := s.filename(sid)
if !isFile(filename) {
return nil
}
err := os.Chtimes(filename, s.nowFunc(), s.nowFunc())
if err != nil {
return errors.Wrap(err, "change times")
}
return nil
}
func (s *fileStore) Save(_ context.Context, sess Session) error {
if len(sess.ID()) < minimumSIDLength {
return ErrMinimumSIDLength
}
binary, err := sess.Encode()
if err != nil {
return errors.Wrap(err, "encode")
}
filename := s.filename(sess.ID())
err = os.WriteFile(filename, binary, 0600)
if err != nil {
return errors.Wrap(err, "write file")
}
err = os.Chtimes(filename, s.nowFunc(), s.nowFunc())
if err != nil {
return errors.Wrap(err, "change times")
}
return nil
}
func (s *fileStore) GC(ctx context.Context) error {
err := filepath.WalkDir(s.rootDir, func(path string, d fs.DirEntry, err error) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if err != nil {
return err
}
if d.IsDir() {
return nil
}
fi, err := d.Info()
if err != nil {
return err
}
if fi.ModTime().Add(s.lifetime).After(s.nowFunc()) {
return nil
}
return os.Remove(path)
})
if err != nil && !errors.Is(err, ctx.Err()) {
return err
}
return nil
}
// FileConfig contains options for the file session store.
type FileConfig struct {
// For tests only.
nowFunc func() time.Time
// Lifetime is the duration to have no access to a session before being
// recycled. Default is 3600 seconds.
Lifetime time.Duration
// RootDir is the root directory of file session items stored on the local file
// system. Default is "sessions".
RootDir string
// Encoder is the encoder to encode session data. Default is GobEncoder.
Encoder Encoder
// Decoder is the decoder to decode session data. Default is GobDecoder.
Decoder Decoder
}
// FileIniter returns the Initer for the file session store.
func FileIniter() Initer {
return func(ctx context.Context, args ...interface{}) (Store, error) {
var cfg *FileConfig
var idWriter IDWriter
for i := range args {
switch v := args[i].(type) {
case FileConfig:
cfg = &v
case IDWriter:
idWriter = v
}
}
if idWriter == nil {
return nil, errors.New("IDWriter not given")
}
if cfg == nil {
return nil, fmt.Errorf("config object with the type '%T' not found", FileConfig{})
}
if cfg.nowFunc == nil {
cfg.nowFunc = time.Now
}
if cfg.Lifetime.Seconds() < 1 {
cfg.Lifetime = 3600 * time.Second
}
if cfg.RootDir == "" {
cfg.RootDir = "sessions"
}
if cfg.Encoder == nil {
cfg.Encoder = GobEncoder
}
if cfg.Decoder == nil {
cfg.Decoder = GobDecoder
}
return newFileStore(*cfg, idWriter), nil
}
}