-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory_storage.go
91 lines (74 loc) · 1.9 KB
/
memory_storage.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
package telebot
import (
"errors"
"fmt"
"sync"
)
var KeyNotFound = errors.New("conversation key not found")
// InMemoryStorage is a thread-safe in-memory implementation of the IStorage interface.
type InMemoryStorage struct {
// keyStrategy defines how to calculate keys for each conversation.
keyStrategy KeyStrategy
// conversations is a map of key -> state, which tracks at which point of each conversation a user/chat is.
conversations map[string]State
// lock allows us to ensure synchronous data access.
lock sync.RWMutex
}
func NewInMemoryStorage(strategy KeyStrategy) *InMemoryStorage {
return &InMemoryStorage{
keyStrategy: strategy,
lock: sync.RWMutex{},
conversations: map[string]State{},
}
}
func (c *InMemoryStorage) Get(ctx Context) (*State, error) {
key := StateKey(ctx, c.keyStrategy)
fmt.Println("InMemoryStorage get Key:", key)
c.lock.RLock()
defer c.lock.RUnlock()
if c.conversations == nil {
return nil, KeyNotFound
}
s, ok := c.conversations[key]
if !ok {
return nil, KeyNotFound
}
return &s, nil
}
func (c *InMemoryStorage) Set(ctx Context, state State) error {
key := StateKey(ctx, c.keyStrategy)
c.lock.Lock()
defer c.lock.Unlock()
if c.conversations == nil {
c.conversations = map[string]State{}
}
c.conversations[key] = state
return nil
}
func (c *InMemoryStorage) Next(ctx Context, keyStr string) error {
s, err := c.Get(ctx)
if err != nil {
s = &State{}
}
s.SetKey(keyStr)
return c.Set(ctx, *s)
}
func (c *InMemoryStorage) UpdateData(ctx Context, act string, data any) error {
s, err := c.Get(ctx)
if err != nil {
// create
_ = c.Set(ctx, State{Data: map[string]any{act: data}})
}
s.UpdateData(act, data)
return nil
}
func (c *InMemoryStorage) Delete(ctx Context) error {
key := StateKey(ctx, c.keyStrategy)
c.lock.Lock()
defer c.lock.Unlock()
if c.conversations == nil {
return nil
}
delete(c.conversations, key)
return nil
}