Skip to content

Commit 549e7c5

Browse files
authored
Merge pull request #44 from m-messiah/revert-43-add-lock
Revert "Add RWMutex to Settings cache"
2 parents 92d501f + 5f9a1ae commit 549e7c5

File tree

4 files changed

+34
-65
lines changed

4 files changed

+34
-65
lines changed

commands.go

+13-29
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,13 @@ func (commandRequest *commandStart) Handle() error {
1414
"Я буду хуифицировать некоторые из ваших фраз\n" +
1515
"Сейчас режим вежливости *%s*\n" +
1616
"За подробностями в /help"
17-
current := settings.Get(commandRequest.request.cacheID)
18-
current.Enabled = false
19-
settings.Set(commandRequest.request.cacheID, current)
17+
settings.cache[commandRequest.request.cacheID].Enabled = true
2018
if err := settings.SaveCache(commandRequest.request.ctx, commandRequest.request.cacheID); err != nil {
2119
commandRequest.request.logWarn(err)
2220
// Do not send error to command
2321
return nil
2422
}
25-
if settings.Get(commandRequest.request.cacheID).Gentle {
23+
if settings.cache[commandRequest.request.cacheID].Gentle {
2624
message = fmt.Sprintf(message, "включен")
2725
} else {
2826
message = fmt.Sprintf(message, "отключен")
@@ -34,9 +32,7 @@ func (commandRequest *commandStart) Handle() error {
3432
type commandStop botCommand
3533

3634
func (commandRequest *commandStop) Handle() error {
37-
current := settings.Get(commandRequest.request.cacheID)
38-
current.Enabled = false
39-
settings.Set(commandRequest.request.cacheID, current)
35+
settings.cache[commandRequest.request.cacheID].Enabled = false
4036
if err := settings.SaveCache(commandRequest.request.ctx, commandRequest.request.cacheID); err != nil {
4137
commandRequest.request.logWarn(err)
4238
// Do not send error to command
@@ -70,9 +66,8 @@ type commandDelay botCommand
7066

7167
func (commandRequest *commandDelay) Handle() error {
7268
command := strings.Fields(commandRequest.request.updateMessage.Text)
73-
current := settings.Get(commandRequest.request.cacheID)
7469
if len(command) < 2 {
75-
commandRequest.request.answer("Сейчас я пропускаю случайное число сообщений от `0` до `"+strconv.Itoa(current.Delay)+"`", MarkdownV2)
70+
commandRequest.request.answer("Сейчас я пропускаю случайное число сообщений от `0` до `"+strconv.Itoa(settings.cache[commandRequest.request.cacheID].Delay)+"`", MarkdownV2)
7671
return nil
7772
}
7873
commandArg := command[len(command)-1]
@@ -81,23 +76,20 @@ func (commandRequest *commandDelay) Handle() error {
8176
commandRequest.request.answer("Неправильный аргумент, отправьте `/delay N`, где _N_ любое натуральное число меньше `500`", MarkdownV2)
8277
return nil
8378
}
84-
current.Delay = tryDelay
85-
settings.Set(commandRequest.request.cacheID, current)
79+
settings.cache[commandRequest.request.cacheID].Delay = tryDelay
8680
if err := settings.SaveCache(commandRequest.request.ctx, commandRequest.request.cacheID); err != nil {
8781
commandRequest.request.answerErrorWithLog("Не удалось сохранить, отправьте еще раз `/delay N`, где _N_ любое натуральное число меньше `500`", err, MarkdownV2)
8882
return nil
8983
}
90-
commandRequest.request.answer("Я буду пропускать случайное число сообщений от `0` до `"+strconv.Itoa(current.Delay)+"`", MarkdownV2)
84+
commandRequest.request.answer("Я буду пропускать случайное число сообщений от `0` до `"+strconv.Itoa(settings.cache[commandRequest.request.cacheID].Delay)+"`", MarkdownV2)
9185
delete(delayMap, commandRequest.request.updateMessage.Chat.ID)
9286
return nil
9387
}
9488

9589
type commandHardcore botCommand
9690

9791
func (commandRequest *commandHardcore) Handle() error {
98-
current := settings.Get(commandRequest.request.cacheID)
99-
current.Gentle = false
100-
settings.Set(commandRequest.request.cacheID, current)
92+
settings.cache[commandRequest.request.cacheID].Gentle = false
10193
if err := settings.SaveCache(commandRequest.request.ctx, commandRequest.request.cacheID); err != nil {
10294
commandRequest.request.logWarn(err)
10395
// Do not send error to command
@@ -110,9 +102,7 @@ func (commandRequest *commandHardcore) Handle() error {
110102
type commandGentle botCommand
111103

112104
func (commandRequest *commandGentle) Handle() error {
113-
current := settings.Get(commandRequest.request.cacheID)
114-
current.Gentle = true
115-
settings.Set(commandRequest.request.cacheID, current)
105+
settings.cache[commandRequest.request.cacheID].Gentle = true
116106
if err := settings.SaveCache(commandRequest.request.ctx, commandRequest.request.cacheID); err != nil {
117107
commandRequest.request.logWarn(err)
118108
// Do not send error to command
@@ -125,9 +115,7 @@ func (commandRequest *commandGentle) Handle() error {
125115
type commandReply botCommand
126116

127117
func (commandRequest *commandReply) Handle() error {
128-
current := settings.Get(commandRequest.request.cacheID)
129-
current.Reply = true
130-
settings.Set(commandRequest.request.cacheID, current)
118+
settings.cache[commandRequest.request.cacheID].Reply = true
131119
if err := settings.SaveCache(commandRequest.request.ctx, commandRequest.request.cacheID); err != nil {
132120
commandRequest.request.logWarn(err)
133121
// Do not send error to command
@@ -140,9 +128,7 @@ func (commandRequest *commandReply) Handle() error {
140128
type commandNoReply botCommand
141129

142130
func (commandRequest *commandNoReply) Handle() error {
143-
current := settings.Get(commandRequest.request.cacheID)
144-
current.Reply = false
145-
settings.Set(commandRequest.request.cacheID, current)
131+
settings.cache[commandRequest.request.cacheID].Reply = false
146132
if err := settings.SaveCache(commandRequest.request.ctx, commandRequest.request.cacheID); err != nil {
147133
commandRequest.request.logWarn(err)
148134
// Do not send error to command
@@ -156,9 +142,8 @@ type commandAmount botCommand
156142

157143
func (commandRequest *commandAmount) Handle() error {
158144
command := strings.Fields(commandRequest.request.updateMessage.Text)
159-
current := settings.Get(commandRequest.request.cacheID)
160145
if len(command) < 2 {
161-
commandRequest.request.answer("Сейчас я хуифицирую случайное число слов от `1` до `"+strconv.Itoa(current.WordsAmount)+"`", MarkdownV2)
146+
commandRequest.request.answer("Сейчас я хуифицирую случайное число слов от `1` до `"+strconv.Itoa(settings.cache[commandRequest.request.cacheID].WordsAmount)+"`", MarkdownV2)
162147
return nil
163148
}
164149
commandArg := command[len(command)-1]
@@ -167,13 +152,12 @@ func (commandRequest *commandAmount) Handle() error {
167152
commandRequest.request.answer("Неправильный аргумент, отправьте `/amount N`, где _N_ любое натуральное число не больше `10`", MarkdownV2)
168153
return nil
169154
}
170-
current.WordsAmount = tryWordsAmount
171-
settings.Set(commandRequest.request.cacheID, current)
155+
settings.cache[commandRequest.request.cacheID].WordsAmount = tryWordsAmount
172156
if err := settings.SaveCache(commandRequest.request.ctx, commandRequest.request.cacheID); err != nil {
173157
commandRequest.request.answerErrorWithLog("Не удалось сохранить, отправьте еще раз `/amount N`, где _N_ любое натуральное число не больше `10`", err, MarkdownV2)
174158
return nil
175159
}
176-
commandRequest.request.answer("Я буду хуифицировать случайное число слов от `1` до `"+strconv.Itoa(settings.Get(commandRequest.request.cacheID).WordsAmount)+"`", MarkdownV2)
160+
commandRequest.request.answer("Я буду хуифицировать случайное число слов от `1` до `"+strconv.Itoa(settings.cache[commandRequest.request.cacheID].WordsAmount)+"`", MarkdownV2)
177161
return nil
178162
}
179163

request.go

+4-5
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ func (request *requestInfo) answerErrorWithLog(message string, err error, parseM
4949
}
5050

5151
func (request *requestInfo) isReplyNeeded() bool {
52-
return settings.Get(request.cacheID).Reply ||
52+
return settings.cache[request.cacheID].Reply ||
5353
(request.updateMessage.ReplyTo != nil &&
5454
request.updateMessage.ReplyTo.From.Username != nil &&
5555
strings.Compare(*request.updateMessage.ReplyTo.From.Username, "xye_bot") == 0)
@@ -63,7 +63,7 @@ func (request *requestInfo) getReplyIDIfNeeded() *int64 {
6363
}
6464

6565
func (request *requestInfo) isStopped() bool {
66-
return !settings.Get(request.cacheID).Enabled
66+
return !settings.cache[request.cacheID].Enabled
6767
}
6868

6969
func (request *requestInfo) getStatusString() string {
@@ -121,7 +121,7 @@ func (request *requestInfo) handleDelay() {
121121
if _, ok := delayMap[request.updateMessage.Chat.ID]; ok {
122122
delayMap[request.updateMessage.Chat.ID]--
123123
} else {
124-
delayMap[request.updateMessage.Chat.ID] = rand.Intn(settings.Get(request.cacheID).Delay + 1)
124+
delayMap[request.updateMessage.Chat.ID] = rand.Intn(settings.cache[request.cacheID].Delay + 1)
125125
}
126126
}
127127

@@ -134,6 +134,5 @@ func (request *requestInfo) cleanDelay() {
134134
}
135135

136136
func (request *requestInfo) huify() string {
137-
cs := settings.Get(request.cacheID)
138-
return Huify(request.updateMessage.Text, cs.Gentle, rand.Intn(cs.WordsAmount)+1)
137+
return Huify(request.updateMessage.Text, settings.cache[request.cacheID].Gentle, rand.Intn(settings.cache[request.cacheID].WordsAmount)+1)
139138
}

settings.go

+16-30
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package main
33
import (
44
"context"
55
"log"
6-
"sync"
76

87
"cloud.google.com/go/datastore"
98
)
@@ -19,7 +18,6 @@ type ChatSettings struct {
1918
type Settings struct {
2019
client *datastore.Client
2120
cache map[string]*ChatSettings
22-
lock sync.RWMutex
2321
}
2422

2523
func initClient() *datastore.Client {
@@ -30,47 +28,35 @@ func initClient() *datastore.Client {
3028
return datastoreClient
3129
}
3230

33-
func NewSettings() *Settings {
34-
return &Settings{
31+
func NewSettings() Settings {
32+
return Settings{
3533
client: initClient(),
3634
cache: make(map[string]*ChatSettings),
3735
}
3836
}
3937

40-
func (s *Settings) Set(key string, cs *ChatSettings) {
41-
s.lock.Lock()
42-
defer s.lock.Unlock()
43-
s.cache[key] = cs
44-
}
45-
46-
func (s *Settings) Get(key string) *ChatSettings {
47-
s.lock.RLock()
48-
defer s.lock.RUnlock()
49-
return s.cache[key]
50-
}
51-
52-
func (s *Settings) Put(ctx context.Context, key *datastore.Key, src interface{}) (err error) {
38+
func (s Settings) Put(ctx context.Context, key *datastore.Key, src interface{}) (err error) {
5339
if _, err = s.client.Put(ctx, key, src); err != nil {
5440
s.client = initClient()
5541
_, err = s.client.Put(ctx, key, src)
5642
}
5743
return err
5844
}
5945

60-
func (s *Settings) Lookup(ctx context.Context, key *datastore.Key, dst interface{}) (err error) {
46+
func (s Settings) Get(ctx context.Context, key *datastore.Key, dst interface{}) (err error) {
6147
if err = s.client.Get(ctx, key, dst); err != nil {
6248
s.client = initClient()
6349
err = s.client.Get(ctx, key, dst)
6450
}
6551
return err
6652
}
6753

68-
func (s *Settings) datastoreKey(key string) *datastore.Key {
54+
func (s Settings) datastoreKey(key string) *datastore.Key {
6955
return datastore.NameKey("ChatSettings", key, nil)
7056
}
7157

72-
func (s *Settings) DefaultChatSettings() *ChatSettings {
73-
return &ChatSettings{
58+
func (s Settings) DefaultChatSettings() ChatSettings {
59+
return ChatSettings{
7460
Delay: 4,
7561
Enabled: true,
7662
Gentle: true,
@@ -79,29 +65,29 @@ func (s *Settings) DefaultChatSettings() *ChatSettings {
7965
}
8066
}
8167

82-
func (s *Settings) EnsureCache(ctx context.Context, key string) {
83-
if v := s.Get(key); v == nil {
68+
func (s Settings) EnsureCache(ctx context.Context, key string) {
69+
if _, ok := s.cache[key]; !ok {
8470
datastoreKey := s.datastoreKey(key)
85-
var resultStruct *ChatSettings
86-
if err := settings.Lookup(ctx, datastoreKey, resultStruct); err != nil {
71+
var resultStruct ChatSettings
72+
if err := settings.Get(ctx, datastoreKey, &resultStruct); err != nil {
8773
resultStruct = s.DefaultChatSettings()
8874
}
8975
// Check too big delay
9076
if resultStruct.Delay > 500 {
9177
resultStruct.Delay = s.DefaultChatSettings().Delay
9278
resultStruct.Enabled = false
9379
}
94-
s.Set(key, resultStruct)
80+
s.cache[key] = &resultStruct
9581
s.ForceSaveCache(ctx, key)
9682
}
9783
}
9884

99-
func (s *Settings) ForceSaveCache(ctx context.Context, key string) {
85+
func (s Settings) ForceSaveCache(ctx context.Context, key string) {
10086
if err := s.SaveCache(ctx, key); err != nil {
101-
log.Printf("[%v] %s %+v - %s", key, s.datastoreKey(key), s.Get(key), err.Error())
87+
log.Printf("[%v] %s %+v - %s", key, s.datastoreKey(key), s.cache[key], err.Error())
10288
}
10389
}
10490

105-
func (s *Settings) SaveCache(ctx context.Context, key string) error {
106-
return s.Put(ctx, s.datastoreKey(key), s.Get(key))
91+
func (s Settings) SaveCache(ctx context.Context, key string) error {
92+
return s.Put(ctx, s.datastoreKey(key), s.cache[key])
10793
}

xyebot.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const MarkdownV2 = "MarkdownV2"
1313

1414
var (
1515
delayMap map[int64]int
16-
settings *Settings
16+
settings Settings
1717
)
1818

1919
func sendMessage(w http.ResponseWriter, chatID int64, text string, replyToID *int64, parseMode string) {

0 commit comments

Comments
 (0)