aboutsummaryrefslogtreecommitdiff
path: root/state/memory_state.go
blob: 97ecad135d07f3d44e36d97e3340558b1309664f (plain)
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
package state

import (
	"context"
)

type memoryStateValue struct {
	backend   *MemoryStateBackend
	stateName string
}

func (m *memoryStateValue) Value(ctx context.Context) (any, error) {
	kg := m.backend.currentGroupKey
	key := m.backend.currentKey
	ns := m.backend.currentNamespace
	if kgMap, ok := m.backend.states[m.stateName][kg][key]; ok {
		if v, hasKey := kgMap[ns]; hasKey {
			return v, nil
		}
	}

	return nil, nil
}

func (m *memoryStateValue) Update(ctx context.Context, newVal any) (any, error) {
	kg := m.backend.currentGroupKey
	key := m.backend.currentKey
	ns := m.backend.currentNamespace

	if _, ok := m.backend.states[m.stateName][kg]; !ok {
		m.backend.states[m.stateName][kg] = make(map[string]map[any]any)
	}

	if _, ok := m.backend.states[m.stateName][kg][key]; !ok {
		m.backend.states[m.stateName][kg][key] = make(map[any]any)
	}

	m.backend.states[m.stateName][kg][key][ns] = newVal
	return newVal, nil
}

func (m *memoryStateValue) Clear(ctx context.Context) error {
	kg := m.backend.currentGroupKey
	key := m.backend.currentKey
	ns := m.backend.currentNamespace
	if kgMap, ok := m.backend.states[m.stateName][kg]; ok {
		if nsMap, ok := kgMap[key]; ok {
			delete(nsMap, ns)
		}
	}
	return nil
}