forked from PaulSonOfLars/gotgbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
in_memory.go
73 lines (56 loc) · 1.52 KB
/
in_memory.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
package conversation
import (
"errors"
"sync"
"github.com/asvedr/gotgbot/v2/ext"
)
var KeyNotFound = errors.New("conversation key not found")
// InMemoryStorage is a thread-safe in-memory implementation of the Storage 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 *ext.Context) (*State, error) {
key := StateKey(ctx, c.keyStrategy)
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 *ext.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) Delete(ctx *ext.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
}