Skip to content

Commit

Permalink
Implement sync wait for telegram config update (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
pablomendezroyo authored Dec 11, 2024
1 parent fb0e6da commit f09720c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
3 changes: 3 additions & 0 deletions internal/adapters/notifier/notifier_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ func (tb *TelegramBot) SendNotification(message string) error {
return nil
}

// print user id
logger.DebugWithPrefix(tb.servicePrefix, "Sending notification to user ID: %d", tb.UserID)

msg := tgbotapi.NewMessage(tb.UserID, message)
_, err := tb.Bot.Send(msg)
if err != nil {
Expand Down
25 changes: 17 additions & 8 deletions internal/adapters/storage/telegram.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package storage

import (
"lido-events/internal/application/domain"
"sync"
)

// TODO: determine if token should be stored hashed
Expand All @@ -20,7 +21,7 @@ func (fs *Storage) SaveTelegramConfig(config domain.TelegramConfig) error {
return err
}

fs.notifyTelegramConfigListeners() // Notify listeners of the change
fs.notifyTelegramConfigListenersSync() // Notify listeners of the change
return nil
}

Expand All @@ -40,18 +41,26 @@ func (fs *Storage) RegisterTelegramConfigListener() chan domain.TelegramConfig {
return updateChan
}

// notifyTelegramConfigListeners sends updates to all registered listeners of Telegram config changes.
func (fs *Storage) notifyTelegramConfigListeners() {
// notifyTelegramConfigListenersSync sends updates to all registered listeners of Telegram config changes.
func (fs *Storage) notifyTelegramConfigListenersSync() {
config, err := fs.GetTelegramConfig()
if err != nil {
return
}

var wg sync.WaitGroup
for _, listener := range fs.telegramConfigListeners {
select {
case listener <- config:
default:
// Ignore if channel is full to prevent blocking
}
wg.Add(1)
go func(listener chan domain.TelegramConfig) {
defer wg.Done()
select {
case listener <- config:
// Config sent successfully
default:
// Ignore if channel is full to prevent blocking
}
}(listener)
}

wg.Wait() // Wait for all listeners to process the update
}

0 comments on commit f09720c

Please sign in to comment.