-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
417 lines (343 loc) · 8.78 KB
/
loader.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
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
package fs
import (
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/byxorna/jot/pkg/db"
"github.com/byxorna/jot/pkg/types/v1"
"github.com/fsnotify/fsnotify"
"github.com/go-playground/validator"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v3"
)
var (
StorageFilenameFormat = "2006-01-02.md"
StorageGlob = "*.md"
ErrUnableToFindMetadataSection = fmt.Errorf("unable to find metadata yaml at header of entry")
)
type Store struct {
*sync.Mutex
Directory string `yaml"directory" validate:"required,dir"`
status v1.SyncStatus `validate:"required"`
entries map[v1.ID]*v1.Entry
mtimeMap map[v1.ID]time.Time
watcher *fsnotify.Watcher
}
func New(dir string, createDirIfMissing bool) (*Store, error) {
expandedPath, err := homedir.Expand(dir)
if err != nil {
return nil, err
}
s := Store{
Mutex: &sync.Mutex{},
Directory: expandedPath,
status: v1.StatusUninitialized,
entries: map[v1.ID]*v1.Entry{},
mtimeMap: map[v1.ID]time.Time{},
}
{ // ensure the notes directory is created. TODO should this be part of the fs storage provider
expandedPath, err := homedir.Expand(s.Directory)
if err != nil {
return nil, err
}
finfo, err := os.Stat(expandedPath)
if err != nil || !finfo.IsDir() {
err := os.Mkdir(expandedPath, 0700)
if err != nil {
return nil, fmt.Errorf("error creating %s: %w", s.Directory, err)
}
}
err = s.Validate()
if err != nil {
return nil, fmt.Errorf("error validating storage provider: %w", err)
}
// Load up all the files we can find at startup
entryFiles, err := filepath.Glob(path.Join(expandedPath, StorageGlob))
if err != nil {
return nil, err
}
for _, fn := range entryFiles {
//fmt.Fprintf(os.Stderr, "loading %s\n", fn)
e, err := s.LoadFromFile(fn)
if err != nil {
return nil, err
}
s.entries[e.ID] = e
}
}
if err := s.startWatcher(); err != nil {
return nil, fmt.Errorf("unable to watch %s: %w", s.Directory, err)
}
s.status = v1.StatusOK
return &s, nil
}
func (x *Store) startWatcher() error {
if x.watcher != nil {
_ = x.watcher.Close()
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
err = watcher.Add(x.Directory)
if err != nil {
return fmt.Errorf("unable to watch %s: %w", x.Directory, err)
}
x.watcher = watcher
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
//fmt.Fprintf(os.Stderr, "event: %v\n", event)
if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create {
//fmt.Fprintln(os.Stderr, "modified file:", event.Name)
entries, _ := x.ListAll()
for _, e := range entries {
expectedFileName := path.Base(x.StoragePath(e.ID))
if expectedFileName == path.Base(event.Name) {
//fmt.Fprintf(os.Stderr, "reconciling %s\n", event.Name)
_, err := x.Reconcile(e.ID)
if err != nil {
// TODO: do something better
fmt.Fprintf(os.Stderr, "error reconciling %d: %v\n", int64(e.ID), err)
}
}
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Println("error:", err)
}
}
}()
return nil
}
func (x *Store) Validate() error {
validate := validator.New()
err := validate.Struct(*x)
//validationErrors := err.(validator.ValidationErrors)
return err
}
// Get loads an entry from disk and caches it in the entry map
func (x *Store) Get(id v1.ID, forceRead bool) (*v1.Entry, error) {
if forceRead {
n, err := x.Reconcile(id)
if err != nil {
return nil, fmt.Errorf("unable to reconcile %d: %w", id, err)
}
return n, nil
}
e, ok := x.entries[id]
if !ok {
return nil, db.ErrNoEntryFound
}
return e, nil
}
func (x *Store) CreateOrUpdateEntry(e *v1.Entry) (*v1.Entry, error) {
x.Lock()
defer x.Unlock()
if e.CreationTimestamp.IsZero() {
e.CreationTimestamp = time.Now()
}
if e.ID == 0 {
e.ID = v1.ID(e.CreationTimestamp.Unix())
}
//if x.HasEntry(e.ID) {
// t := time.Now()
// e.EntryMetadata.ModifiedTimestamp = &t
//}
// TODO: union tags and labels with defaults
if err := x.Write(e); err != nil {
return nil, fmt.Errorf("unable to store entry %d: %w", e.ID, err)
}
x.entries[e.ID] = e
return e, nil
}
func (x *Store) LoadFromFile(fileName string) (*v1.Entry, error) {
f, err := os.Open(fileName)
if err != nil {
return nil, fmt.Errorf("unable to open %s: %w", fileName, err)
}
return x.LoadFromReader(f)
}
func (x *Store) LoadFromID(id v1.ID) (*v1.Entry, error) {
return x.LoadFromFile(x.StoragePath(id))
}
func (x *Store) LoadFromReader(r io.Reader) (*v1.Entry, error) {
var e v1.Entry
bytes, err := ioutil.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("unable to read: %w", err)
}
nChunks := 3
chunks := strings.SplitN(string(bytes), "---", nChunks)
if len(chunks) != nChunks {
return nil, fmt.Errorf("unable to parse metadata section: %w", ErrUnableToFindMetadataSection)
}
err = yaml.Unmarshal([]byte(chunks[1]), &e.EntryMetadata)
if err != nil {
return nil, fmt.Errorf("unable to deserialize metadata: %w", err)
}
e.Content = chunks[2]
err = e.Validate()
if err != nil {
return nil, err
}
x.Lock()
defer x.Unlock()
x.entries[e.ID] = &e
return &e, nil
}
func (x *Store) expandedStoragePath(id v1.ID) string {
expandedPath, _ := homedir.Expand(x.shortStoragePath(id))
return expandedPath
}
func (x *Store) StoragePath(id v1.ID) string {
return x.expandedStoragePath(id)
}
func (x *Store) shortStoragePath(id v1.ID) string {
t := time.Unix(int64(id), int64(0))
fullPath := path.Join(x.Directory, t.Format(StorageFilenameFormat))
return fullPath
}
func (x *Store) Write(e *v1.Entry) error {
x.status = v1.StatusSynchronizing
targetpath := x.StoragePath(e.ID)
finfo, err := os.Stat(targetpath)
if err == nil && finfo.IsDir() {
err := os.RemoveAll(targetpath)
if err != nil {
x.status = v1.StatusError
return err
}
}
f, err := os.OpenFile(targetpath, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
if err != nil {
x.status = v1.StatusError
return err
}
defer f.Close()
metadata, err := yaml.Marshal(e.EntryMetadata)
if err != nil {
x.status = v1.StatusError
return fmt.Errorf("unable to marshal entry metadata for %d: %w", e.ID, err)
}
_, err = f.WriteString(fmt.Sprintf("---\n%s\n---\n", metadata))
if err != nil {
x.status = v1.StatusError
return fmt.Errorf("unable to write entry metadata for %d: %w", e.ID, err)
}
_, err = f.WriteString(e.Content + "\n")
if err != nil {
x.status = v1.StatusError
return fmt.Errorf("unable to write entry %d: %w", e.ID, err)
}
err = f.Sync()
if err != nil {
return fmt.Errorf("unable to sync entry %d: %w", e.ID, err)
}
x.status = v1.StatusOK
return nil
}
// ListAll returns entries in newest to oldest order
func (x *Store) ListAll() ([]*v1.Entry, error) {
x.Lock()
defer x.Unlock()
sorted := []*v1.Entry{}
for _, e := range x.entries {
sorted = append(sorted, e)
}
sort.Sort(sort.Reverse(v1.ByCreationTimestampEntryList(sorted)))
return sorted, nil
}
func (x *Store) idx(list []*v1.Entry, id v1.ID) (int, error) {
for i, o := range list {
if id == o.ID {
return i, nil
}
}
return 0, db.ErrNoEntryFound
}
func (x *Store) Next(id v1.ID) (*v1.Entry, error) {
// TODO: this is super slow, i know. ill make it faster after PoC
elements, err := x.ListAll()
if err != nil {
return nil, err
}
i, err := x.idx(elements, id)
if err != nil {
return nil, err
}
nextIdx := i - 1
if nextIdx < 0 || nextIdx >= len(elements) || elements[nextIdx] == nil {
return nil, db.ErrNoNextEntry
}
return elements[nextIdx], nil
}
func (x *Store) Previous(id v1.ID) (*v1.Entry, error) {
elements, err := x.ListAll()
if err != nil {
return nil, err
}
i, err := x.idx(elements, id)
if err != nil {
return nil, err
}
prevIdx := i + 1
if prevIdx < 0 || prevIdx >= len(elements) || elements[prevIdx] == nil {
return nil, db.ErrNoPrevEntry
}
return elements[prevIdx], nil
}
func (x *Store) Count() int {
x.Lock()
defer x.Unlock()
return len(x.entries)
}
func (x *Store) HasEntry(id v1.ID) bool {
_, ok := x.entries[id]
return ok
}
func (x *Store) Status() v1.SyncStatus {
return x.status
}
func (x *Store) Reconcile(id v1.ID) (*v1.Entry, error) {
// stat the file on disk, compare to last known mtime. if more recent
// reload
if !x.HasEntry(id) || x.ShouldReloadFromDisk(id) {
//fmt.Fprintf(os.Stderr, "forcing reconcile of %d\n", int64(id))
e, err := x.LoadFromID(id)
if err != nil {
return nil, err
}
return e, nil
}
if e, ok := x.entries[id]; ok {
return e, nil
} else {
return nil, db.ErrNoEntryFound
}
}
func (x *Store) ShouldReloadFromDisk(id v1.ID) bool {
finfo, err := os.Stat(x.StoragePath(id))
if err != nil {
return false
}
if x.mtimeMap[id].Before(finfo.ModTime()) {
return true
}
x.mtimeMap[id] = finfo.ModTime()
return false
}