From f09720c0b52850a1049a003cf5b7fcbef8e7ac6e Mon Sep 17 00:00:00 2001 From: pablomendezroyo <41727368+pablomendezroyo@users.noreply.github.com> Date: Wed, 11 Dec 2024 16:28:54 +0100 Subject: [PATCH] Implement sync wait for telegram config update (#82) --- .../adapters/notifier/notifier_adapter.go | 3 +++ internal/adapters/storage/telegram.go | 25 +++++++++++++------ 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/internal/adapters/notifier/notifier_adapter.go b/internal/adapters/notifier/notifier_adapter.go index 2c3978f..a083c71 100644 --- a/internal/adapters/notifier/notifier_adapter.go +++ b/internal/adapters/notifier/notifier_adapter.go @@ -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 { diff --git a/internal/adapters/storage/telegram.go b/internal/adapters/storage/telegram.go index e26fbb5..df7e59f 100644 --- a/internal/adapters/storage/telegram.go +++ b/internal/adapters/storage/telegram.go @@ -2,6 +2,7 @@ package storage import ( "lido-events/internal/application/domain" + "sync" ) // TODO: determine if token should be stored hashed @@ -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 } @@ -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 }