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 <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-05-11 10:58:42 -07:00
parent 23322c69cc
commit 4509fe2dc0

View File

@ -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