From 4509fe2dc010106b9045c3cb731d3164f3328b47 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Mon, 11 May 2026 10:58:42 -0700 Subject: [PATCH] Initialize FCM client lazily during push send. Add ensureFCMClient() so push APIs retry FCM initialization at request time and return actionable initialization errors when the service account key is empty or invalid. Co-authored-by: Cursor --- internal/services/notification/service.go | 24 ++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go index 7c51cef..0dbeb46 100644 --- a/internal/services/notification/service.go +++ b/internal/services/notification/service.go @@ -15,6 +15,7 @@ import ( "net/http" "net/url" "strconv" + "strings" // "errors" "log/slog" @@ -22,11 +23,11 @@ import ( "time" // "github.com/segmentio/kafka-go" - "go.uber.org/zap" firebase "firebase.google.com/go/v4" "firebase.google.com/go/v4/messaging" "github.com/gorilla/websocket" "github.com/resend/resend-go/v2" + "go.uber.org/zap" "google.golang.org/api/option" // "github.com/redis/go-redis/v9" ) @@ -114,6 +115,19 @@ func (s *Service) initFCMClient() error { return nil } +func (s *Service) ensureFCMClient() error { + if s.fcmClient != nil { + return nil + } + if strings.TrimSpace(s.config.FCMServiceAccountKey) == "" { + return fmt.Errorf("FCM_SERVICE_ACCOUNT_KEY is empty") + } + if err := s.initFCMClient(); err != nil { + return fmt.Errorf("failed to initialize FCM client: %w", err) + } + return nil +} + func (s *Service) SendAfroMessageSMSTemp( ctx context.Context, receiverPhone string, @@ -539,8 +553,8 @@ func (s *Service) SendNotificationEmail(ctx context.Context, recipientID int64, } func (s *Service) SendPushNotification(ctx context.Context, notification *domain.Notification) error { - if s.fcmClient == nil { - return fmt.Errorf("FCM client not initialized") + if err := s.ensureFCMClient(); err != nil { + return err } // Get user device tokens @@ -622,8 +636,8 @@ func (s *Service) MessengerSvc() *messenger.Service { } func (s *Service) SendBulkPushNotification(ctx context.Context, userIDs []int64, notification *domain.Notification) (sent int, failed int, err error) { - if s.fcmClient == nil { - return 0, 0, fmt.Errorf("FCM client not initialized") + if err := s.ensureFCMClient(); err != nil { + return 0, 0, err } // Collect all device tokens for the given users