Skip to content

Commit

Permalink
refactor: add mutex for thread safety in conversation and modem packages
Browse files Browse the repository at this point in the history
  • Loading branch information
damonto committed Jun 16, 2024
1 parent e4d559f commit 204b25d
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 12 deletions.
24 changes: 15 additions & 9 deletions internal/pkg/conversation/conversation.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package conversation

import (
"log/slog"
"sync"

"gopkg.in/telebot.v3"
)
Expand All @@ -17,23 +18,24 @@ type conversation struct {
steps map[string]telebot.HandlerFunc
next string
}
type converstations struct {
type conversations struct {
bot *telebot.Bot
mutex sync.Mutex
conversations map[int64]*conversation
}

var converstationsInstance *converstations
var conversationsInstance *conversations

func NewConversation(bot *telebot.Bot) *converstations {
converstationsInstance = &converstations{
func NewConversation(bot *telebot.Bot) *conversations {
conversationsInstance = &conversations{
bot: bot,
conversations: make(map[int64]*conversation),
}
converstationsInstance.handleText()
return converstationsInstance
conversationsInstance.handleText()
return conversationsInstance
}

func (c *converstations) handleText() {
func (c *conversations) handleText() {
c.bot.Handle(telebot.OnText, func(ctx telebot.Context) error {
if conv, ok := c.conversations[ctx.Chat().ID]; ok {
if step, ok := conv.steps[conv.next]; ok {
Expand All @@ -46,11 +48,13 @@ func (c *converstations) handleText() {
}

func New(ctx telebot.Context) Conversation {
conversationsInstance.mutex.Lock()
defer conversationsInstance.mutex.Unlock()
conversation := &conversation{
chatId: ctx.Chat().ID,
steps: make(map[string]telebot.HandlerFunc),
}
converstationsInstance.conversations[ctx.Chat().ID] = conversation
conversationsInstance.conversations[ctx.Chat().ID] = conversation
return conversation
}

Expand All @@ -63,5 +67,7 @@ func (c *conversation) Next(next string) {
}

func (c *conversation) Done() {
delete(converstationsInstance.conversations, c.chatId)
conversationsInstance.mutex.Lock()
defer conversationsInstance.mutex.Unlock()
delete(conversationsInstance.conversations, c.chatId)
}
2 changes: 1 addition & 1 deletion internal/pkg/modem/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ var (
)

type Modem struct {
lock sync.Mutex
mutex sync.Mutex
IsEuicc bool
modem modemmanager.Modem
}
Expand Down
4 changes: 2 additions & 2 deletions internal/pkg/modem/modem.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ var (
)

func (m *Modem) Lock() {
m.lock.Lock()
m.mutex.Lock()
}

func (m *Modem) Unlock() {
m.lock.Unlock()
m.mutex.Unlock()
}

func (m *Modem) isEuicc() bool {
Expand Down

0 comments on commit 204b25d

Please sign in to comment.