-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlivefile.go
190 lines (163 loc) · 4.02 KB
/
livefile.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
package livefile
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"sync"
"time"
)
type LiveFile[StateT any] struct {
path string
lastModTime time.Time
cached StateT
mutex sync.Mutex
defaultFunc func() StateT
errHandler func(context.Context, error)
onLoaded func(context.Context, *StateT)
}
// DefaultErrorHandler is the default error handler used for all [LiveFile]
// instances created without an explicit [WithDefault].
var DefaultErrorHandler = func(_ context.Context, err error) {
panic(err)
}
// BaseDir is the base directory for the relative paths passed to the [New]
// function.
var BaseDir string
// New creates a new [LiveFile] instance with the given path and options.
// The path can be either absolute or relative. If it is relative,
// it will be joined with the [BaseDir].
func New[T any](path string, opts ...Opt[T]) *LiveFile[T] {
if !filepath.IsAbs(path) && BaseDir != "" {
path = filepath.Join(BaseDir, path)
}
lf := &LiveFile[T]{
path: path,
errHandler: DefaultErrorHandler,
}
for _, opt := range opts {
opt(lf)
}
if lf.defaultFunc == nil {
lf.defaultFunc = func() T {
var zero T
return zero
}
}
lf.cached = lf.defaultFunc()
return lf
}
// View retrieves the current state of the file and passes it to the given
// function. The state pointer is only valid within the function call and
// must not be stored.
// The function must not modify the state or call other [LiveFile] methods.
func (lf *LiveFile[T]) View(ctx context.Context, f func(state *T)) {
lf.mutex.Lock()
defer lf.mutex.Unlock()
lf.ensure(ctx)
f(&lf.cached)
}
// Update calls the given function with a mutable reference to the current file
// state. If the function returns an error, the state is rolled back to the
// previous value.
// The function MUST NOT call other [LiveFile] methods.
func (lf *LiveFile[T]) Update(ctx context.Context, f func(state *T) error) error {
lf.mutex.Lock()
defer lf.mutex.Unlock()
lf.ensure(ctx)
file, err := os.OpenFile(lf.path, os.O_RDWR|os.O_CREATE, 0o660)
if errors.Is(err, os.ErrNotExist) {
err = os.MkdirAll(path.Dir(lf.path), 0o770)
if err != nil {
return err
}
file, err = os.OpenFile(lf.path, os.O_RDWR|os.O_CREATE, 0o660)
}
if err != nil {
return err
}
defer file.Close()
lf.loadIfUpdated(ctx, file)
err = f(&lf.cached)
if err != nil {
// Update failed, rollback changes.
lf.forceLoad(ctx, file)
return err
}
err = file.Truncate(0)
if err != nil {
return err
}
enc := json.NewEncoder(file)
enc.SetIndent("", " ")
err = enc.Encode(lf.cached)
if err != nil {
return err
}
err = file.Sync()
if err != nil {
return err
}
stat, err := file.Stat()
if err == nil {
lf.lastModTime = stat.ModTime()
}
return err
}
// Peek retrieves the current state of the file and returns its copy.
func (lf *LiveFile[T]) Peek(ctx context.Context) T {
lf.mutex.Lock()
lf.ensure(ctx)
c := lf.cached
lf.mutex.Unlock()
return c
}
func (lf *LiveFile[T]) ensure(ctx context.Context) {
file, err := os.Open(lf.path)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
lf.errHandler(ctx, err)
}
} else {
lf.loadIfUpdated(ctx, file)
file.Close()
}
}
func (lf *LiveFile[T]) loadIfUpdated(ctx context.Context, file *os.File) {
stat, err := file.Stat()
if err != nil {
lf.errHandler(ctx, fmt.Errorf("stat failed: %w", err))
}
if stat.Size() == 0 {
return
}
modTime := stat.ModTime()
if modTime.After(lf.lastModTime) {
lf.forceLoad(ctx, file)
lf.lastModTime = modTime
}
}
func (lf *LiveFile[T]) forceLoad(ctx context.Context, file *os.File) {
_, err := file.Seek(0, io.SeekStart)
if err != nil {
lf.errHandler(ctx, fmt.Errorf("failed to rewind file: %w", err))
}
decoder := json.NewDecoder(file)
err = decoder.Decode(&lf.cached)
// File empty
if err == io.EOF && decoder.InputOffset() == 0 {
lf.cached = lf.defaultFunc()
err = nil
}
if err != nil {
lf.errHandler(ctx, fmt.Errorf("invalid JSON: %w", err))
} else {
if lf.onLoaded != nil {
lf.onLoaded(ctx, &lf.cached)
}
}
}