Skip to content

Commit

Permalink
fix: concurrent map writes
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielolivrp committed Nov 3, 2023
1 parent 63712e0 commit 0a3f78b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 17 deletions.
3 changes: 3 additions & 0 deletions configs/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type ZapMeow struct {
Instances map[string]*Instance
Config ZapMeowConfig
Wg *sync.WaitGroup
Mutex *sync.Mutex
StopCh *chan struct{}
}

Expand All @@ -31,6 +32,7 @@ func NewZapMeow(
instances map[string]*Instance,
config ZapMeowConfig,
wg *sync.WaitGroup,
mutex *sync.Mutex,
stopCh *chan struct{},
) *ZapMeow {
return &ZapMeow{
Expand All @@ -40,6 +42,7 @@ func NewZapMeow(
Instances: instances,
Config: config,
Wg: wg,
Mutex: mutex,
StopCh: stopCh,
}
}
7 changes: 6 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
waLog "go.mau.fi/whatsmeow/util/log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

// @title ZapMeow API
Expand Down Expand Up @@ -45,7 +46,9 @@ func main() {
panic(err)
}

databaseClient, err := gorm.Open(sqlite.Open(config.DatabaseURL))
databaseClient, err := gorm.Open(sqlite.Open(config.DatabaseURL), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
panic("Failed to connect to database")
}
Expand Down Expand Up @@ -75,6 +78,7 @@ func main() {
panic(err)
}

var mutex sync.Mutex
var wg sync.WaitGroup
wg.Add(1)
stopCh := make(chan struct{})
Expand All @@ -87,6 +91,7 @@ func main() {
instances,
config,
&wg,
&mutex,
&stopCh,
)

Expand Down
39 changes: 23 additions & 16 deletions services/wpp_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -521,24 +521,31 @@ func (w *wppService) qrcode(instanceID string) {
case "success":
return
case "timeout":
// fmt.Println("[qrcode]: timeout error")
err := w.accountService.UpdateAccount(instanceID, map[string]interface{}{
"QrCode": "",
"Status": "TIMEOUT",
})
if err != nil {
fmt.Println("[qrcode]: ", err)
for {
w.app.Mutex.Lock()
err := w.accountService.UpdateAccount(instanceID, map[string]interface{}{
"QrCode": "",
"Status": "TIMEOUT",
})
w.app.Mutex.Unlock()
if err != nil {
fmt.Println("[qrcode]: ", err)
}

delete(w.app.Instances, instanceID)
}

delete(w.app.Instances, instanceID)
case "code":
w.accountService.UpdateAccount(instanceID, map[string]interface{}{
"QrCode": evt.Code,
"Status": "UNPAIRED",
"WasSynced": false,
})
if err != nil {
fmt.Println("[qrcode]: ", err)
for {
w.app.Mutex.Lock()
w.accountService.UpdateAccount(instanceID, map[string]interface{}{
"QrCode": evt.Code,
"Status": "UNPAIRED",
"WasSynced": false,
})
w.app.Mutex.Unlock()
if err != nil {
fmt.Println("[qrcode]: ", err)
}
}
}
}
Expand Down

0 comments on commit 0a3f78b

Please sign in to comment.