-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
mem.go
99 lines (78 loc) · 1.65 KB
/
mem.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 mk
import (
"fmt"
"cuelang.org/go/cue"
"github.com/hofstadter-io/cuetils/flow/context"
)
func init() {
context.Register("kv.Mem", NewMem)
}
type Mem struct {}
func NewMem(val cue.Value) (context.Runner, error) {
return &Mem{}, nil
}
func (T *Mem) Run(ctx *context.Context) (interface{}, error) {
val := ctx.Value
var k string
var v interface{}
var del bool
var loaded bool
var err error
ferr := func () error {
ctx.CUELock.Lock()
defer func() {
ctx.CUELock.Unlock()
}()
// lookup key
key := val.LookupPath(cue.ParsePath("key"))
if key.Err() != nil {
return key.Err()
} else if key.Exists() {
k, err = key.String()
if err != nil {
return err
}
} else {
err := fmt.Errorf("unknown key:", key)
return err
}
// lookup val
vv := val.LookupPath(cue.ParsePath("val"))
if vv.Exists() {
v = vv
}
// lookup delete
dv := val.LookupPath(cue.ParsePath("delete"))
if dv.Exists() {
del, err = dv.Bool()
if err != nil {
return err
}
}
return nil
}()
if ferr != nil {
return nil, ferr
}
if v != nil {
if del {
ctx.ValStore.Delete(k)
v = nil
} else {
ctx.ValStore.Store(k,v)
}
} else {
if del {
v, loaded = ctx.ValStore.LoadAndDelete(k)
} else {
v, loaded = ctx.ValStore.Load(k)
}
// lock when we need to fill in a loaded value
ctx.CUELock.Lock()
defer ctx.CUELock.Unlock()
val = val.FillPath(cue.ParsePath("val"), v)
val = val.FillPath(cue.ParsePath("loaded"), loaded)
return val, nil
}
return nil, nil
}