-
Notifications
You must be signed in to change notification settings - Fork 6
/
state.go
98 lines (79 loc) · 2 KB
/
state.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
package statestore
import (
"bytes"
"context"
"reflect"
cborutil "github.com/filecoin-project/go-cbor-util"
"github.com/ipfs/go-datastore"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
)
type StoredState struct {
ds datastore.Datastore
name datastore.Key
}
func (st *StoredState) End() error {
has, err := st.ds.Has(context.TODO(), st.name)
if err != nil {
return err
}
if !has {
return xerrors.Errorf("No state for %s", st.name)
}
if err := st.ds.Delete(context.TODO(), st.name); err != nil {
return xerrors.Errorf("removing state from datastore: %w", err)
}
st.name = datastore.Key{}
st.ds = nil
return nil
}
func (st *StoredState) Get(out cbg.CBORUnmarshaler) error {
val, err := st.ds.Get(context.TODO(), st.name)
if err != nil {
if xerrors.Is(err, datastore.ErrNotFound) {
return xerrors.Errorf("No state for %s: %w", st.name, err)
}
return err
}
return out.UnmarshalCBOR(bytes.NewReader(val))
}
// mutator func(*T) error
func (st *StoredState) Mutate(mutator interface{}) error {
return st.mutate(cborMutator(mutator))
}
func (st *StoredState) mutate(mutator func([]byte) ([]byte, error)) error {
has, err := st.ds.Has(context.TODO(), st.name)
if err != nil {
return err
}
if !has {
return xerrors.Errorf("No state for %s", st.name)
}
cur, err := st.ds.Get(context.TODO(), st.name)
if err != nil {
return err
}
mutated, err := mutator(cur)
if err != nil {
return err
}
if bytes.Equal(mutated, cur) {
return nil
}
return st.ds.Put(context.TODO(), st.name, mutated)
}
func cborMutator(mutator interface{}) func([]byte) ([]byte, error) {
rmut := reflect.ValueOf(mutator)
return func(in []byte) ([]byte, error) {
state := reflect.New(rmut.Type().In(0).Elem())
err := cborutil.ReadCborRPC(bytes.NewReader(in), state.Interface())
if err != nil {
return nil, err
}
out := rmut.Call([]reflect.Value{state})
if err := out[0].Interface(); err != nil {
return nil, err.(error)
}
return cborutil.Dump(state.Interface())
}
}