Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
89 lines (83 loc) · 2.51 KB
/
Copy pathmain.go
File metadata and controls
89 lines (83 loc) · 2.51 KB
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
// Command persistent demonstrates cloned state, schema migration and write-behind persistence. Run with -file pointing to a new file or a legacy JSON word map.
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io/fs"
"log"
"maps"
"time"
"github.com/yldm-tech/nodra"
)
type wordState struct {
Words map[string]int `json:"words"`
}
func run(path string) error { return runWithRecovery(path, false) }
func runWithRecovery(path string, recoverBackup bool) (result error) {
store := nodra.NewWithClone(wordState{Words: map[string]int{}}, func(v wordState) wordState {
v.Words = maps.Clone(v.Words)
return v
})
defer func() { _ = store.Close() }()
codec := nodra.VersionedJSONCodec[wordState]{
Version: 1, AllowUnversioned: true,
Migrations: map[int]nodra.JSONMigration{
0: func(raw json.RawMessage) (json.RawMessage, error) {
var words map[string]int
if err := json.Unmarshal(raw, &words); err != nil {
return nil, err
}
return json.Marshal(wordState{Words: words})
},
},
}
persistence := nodra.NewPersistence(store, nodra.FileStorage{Path: path, Backup: true}, codec)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if recoverBackup {
if err := persistence.LoadBackup(ctx); err != nil {
return err
}
fmt.Printf("Recovered %d words into memory; primary and backup files were left untouched.\n", len(store.Get().Words))
return nil
}
if err := persistence.Load(ctx); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
writer, err := persistence.AutoSaveAsync(ctx, nodra.AsyncOptions{Debounce: 25 * time.Millisecond})
if err != nil {
return err
}
// Drain before canceling the parent or closing the store. Preserve any shutdown write error so the caller can surface it to the user.
defer func() { result = errors.Join(result, writer.Close(ctx)) }()
if err := store.Update(func(v *wordState) {
if v.Words == nil {
v.Words = map[string]int{}
}
v.Words["hello"]++
}); err != nil {
return err
}
if err := writer.Flush(ctx); err != nil {
return err
}
fmt.Printf("saved version %d: hello=%d\n", store.Version(), store.Get().Words["hello"])
return nil
}
func main() {
path := flag.String("file", "state.json", "path to the state file")
recoverBackup := flag.Bool("recover-backup", false, "validate and load the backup without rewriting either file")
flag.Parse()
var err error
if *recoverBackup {
err = runWithRecovery(*path, true)
} else {
err = run(*path)
}
if err != nil {
log.Fatal(err)
}
}