fix: surface FCM bulk push delivery failures

Return per-token Firebase errors and project ID in bulk push responses, log actionable hints, and only deactivate truly expired tokens.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-06-16 01:53:52 -07:00
parent 7d436e3e5d
commit c66a7be28f
3 changed files with 167 additions and 49 deletions

View File

@ -0,0 +1,62 @@
package notificationservice
import (
"strings"
"firebase.google.com/go/v4/messaging"
)
// BulkPushFailure describes a single FCM delivery failure for one device token.
type BulkPushFailure struct {
UserID int64 `json:"user_id"`
TokenPreview string `json:"token_preview"`
Error string `json:"error"`
Hint string `json:"hint,omitempty"`
}
// BulkPushDeliveryResult is the outcome of a bulk FCM send attempt.
type BulkPushDeliveryResult struct {
Sent int
Failed int
DevicesTargeted int
FCMProjectID string
Failures []BulkPushFailure
}
func tokenPreview(token string) string {
token = strings.TrimSpace(token)
if len(token) <= 12 {
return token
}
return "..." + token[len(token)-12:]
}
func fcmFailureHint(err error) string {
switch {
case messaging.IsSenderIDMismatch(err), messaging.IsMismatchedCredential(err):
return "The device token was issued by a different Firebase project than the server FCM_SERVICE_ACCOUNT_KEY. Ensure the client app uses the same Firebase project."
case messaging.IsUnregistered(err), messaging.IsRegistrationTokenNotRegistered(err):
return "The device token is expired or invalid. Re-register via POST /api/v1/devices/register from the client app."
case messaging.IsInvalidAPNSCredentials(err), messaging.IsThirdPartyAuthError(err):
return "Firebase cannot deliver to Apple devices. Configure APNS credentials in the Firebase console."
case messaging.IsInvalidArgument(err):
return "FCM rejected the message or token format. Verify the client sends a native FCM registration token (not Expo or another push provider)."
default:
return ""
}
}
func shouldDeactivateFCMToken(err error) bool {
return messaging.IsUnregistered(err) || messaging.IsRegistrationTokenNotRegistered(err)
}
func buildFCMNotification(title, body, imageURL string) *messaging.Notification {
n := &messaging.Notification{
Title: title,
Body: body,
}
if strings.TrimSpace(imageURL) != "" {
n.ImageURL = imageURL
}
return n
}

View File

@ -48,6 +48,7 @@ type Service struct {
mongoLogger *zap.Logger mongoLogger *zap.Logger
logger *slog.Logger logger *slog.Logger
fcmClient *messaging.Client fcmClient *messaging.Client
fcmProjectID string
} }
func New( func New(
@ -103,6 +104,7 @@ func (s *Service) initFCMClient() error {
// Prepare client options; if a service account JSON string is provided, use it. // Prepare client options; if a service account JSON string is provided, use it.
var opts []option.ClientOption var opts []option.ClientOption
var fbConfig *firebase.Config var fbConfig *firebase.Config
var projectID string
if s.config.FCMServiceAccountKey != "" { if s.config.FCMServiceAccountKey != "" {
credJSON, errNorm := normalizeFCMCredentialsJSON(s.config.FCMServiceAccountKey) credJSON, errNorm := normalizeFCMCredentialsJSON(s.config.FCMServiceAccountKey)
if errNorm != nil { if errNorm != nil {
@ -114,11 +116,12 @@ func (s *Service) initFCMClient() error {
if err := json.Unmarshal(credJSON, &sa); err != nil { if err := json.Unmarshal(credJSON, &sa); err != nil {
return fmt.Errorf("invalid FCM service account JSON: %w", err) return fmt.Errorf("invalid FCM service account JSON: %w", err)
} }
if strings.TrimSpace(sa.ProjectID) == "" { projectID = strings.TrimSpace(sa.ProjectID)
if projectID == "" {
return fmt.Errorf("FCM_SERVICE_ACCOUNT_KEY is missing project_id") return fmt.Errorf("FCM_SERVICE_ACCOUNT_KEY is missing project_id")
} }
fbConfig = &firebase.Config{ fbConfig = &firebase.Config{
ProjectID: strings.TrimSpace(sa.ProjectID), ProjectID: projectID,
} }
opts = append(opts, option.WithCredentialsJSON(credJSON)) opts = append(opts, option.WithCredentialsJSON(credJSON))
} }
@ -136,6 +139,10 @@ func (s *Service) initFCMClient() error {
} }
s.fcmClient = client s.fcmClient = client
s.fcmProjectID = projectID
s.mongoLogger.Info("FCM client initialized",
zap.String("project_id", s.fcmProjectID),
)
return nil return nil
} }
@ -618,11 +625,11 @@ func (s *Service) SendPushNotification(ctx context.Context, notification *domain
// Create FCM message // Create FCM message
message := &messaging.Message{ message := &messaging.Message{
Notification: &messaging.Notification{ Notification: buildFCMNotification(
Title: notification.Payload.Headline, notification.Payload.Headline,
Body: notification.Payload.Message, notification.Payload.Message,
ImageURL: notification.Image, notification.Image,
}, ),
Data: map[string]string{ Data: map[string]string{
"type": string(notification.Type), "type": string(notification.Type),
"recipient_id": strconv.FormatInt(notification.RecipientID, 10), "recipient_id": strconv.FormatInt(notification.RecipientID, 10),
@ -637,14 +644,15 @@ func (s *Service) SendPushNotification(ctx context.Context, notification *domain
response, err := s.fcmClient.Send(ctx, message) response, err := s.fcmClient.Send(ctx, message)
if err != nil { if err != nil {
s.mongoLogger.Error("[NotificationSvc.SendPushNotification] Failed to send FCM message", s.mongoLogger.Error("[NotificationSvc.SendPushNotification] Failed to send FCM message",
zap.String("token", token), zap.String("token", tokenPreview(token)),
zap.Int64("userID", notification.RecipientID), zap.Int64("userID", notification.RecipientID),
zap.String("fcm_project_id", s.fcmProjectID),
zap.String("hint", fcmFailureHint(err)),
zap.Error(err), zap.Error(err),
zap.Time("timestamp", time.Now()), zap.Time("timestamp", time.Now()),
) )
// Check if token is invalid/unregistered and deactivate it if shouldDeactivateFCMToken(err) {
if messaging.IsUnregistered(err) || messaging.IsInvalidArgument(err) {
if deactivateErr := s.userSvc.DeactivateDevice(ctx, notification.RecipientID, token); deactivateErr != nil { if deactivateErr := s.userSvc.DeactivateDevice(ctx, notification.RecipientID, token); deactivateErr != nil {
s.mongoLogger.Warn("[NotificationSvc.SendPushNotification] Failed to deactivate invalid token", s.mongoLogger.Warn("[NotificationSvc.SendPushNotification] Failed to deactivate invalid token",
zap.String("token", token), zap.String("token", token),
@ -680,10 +688,13 @@ func (s *Service) MessengerSvc() *messenger.Service {
return s.messengerSvc return s.messengerSvc
} }
func (s *Service) SendBulkPushNotification(ctx context.Context, userIDs []int64, notification *domain.Notification) (sent int, failed int, devicesTargeted int, err error) { func (s *Service) SendBulkPushNotification(ctx context.Context, userIDs []int64, notification *domain.Notification) (BulkPushDeliveryResult, error) {
result := BulkPushDeliveryResult{FCMProjectID: s.fcmProjectID}
if err := s.ensureFCMClient(); err != nil { if err := s.ensureFCMClient(); err != nil {
return 0, 0, 0, err return result, err
} }
result.FCMProjectID = s.fcmProjectID
// Collect all device tokens for the given users // Collect all device tokens for the given users
var allTokens []string var allTokens []string
@ -703,19 +714,19 @@ func (s *Service) SendBulkPushNotification(ctx context.Context, userIDs []int64,
allTokens = append(allTokens, tokens...) allTokens = append(allTokens, tokens...)
} }
devicesTargeted = len(allTokens) result.DevicesTargeted = len(allTokens)
if devicesTargeted == 0 { if result.DevicesTargeted == 0 {
s.mongoLogger.Info("[NotificationSvc.SendBulkPushNotification] No device tokens found for any user", s.mongoLogger.Info("[NotificationSvc.SendBulkPushNotification] No device tokens found for any user",
zap.Int("userCount", len(userIDs)), zap.Int("userCount", len(userIDs)),
) )
return 0, 0, 0, nil return result, nil
} }
fcmNotification := &messaging.Notification{ fcmNotification := buildFCMNotification(
Title: notification.Payload.Headline, notification.Payload.Headline,
Body: notification.Payload.Message, notification.Payload.Message,
ImageURL: notification.Image, notification.Image,
} )
data := map[string]string{ data := map[string]string{
"type": string(notification.Type), "type": string(notification.Type),
"notification_id": notification.ID, "notification_id": notification.ID,
@ -741,32 +752,58 @@ func (s *Service) SendBulkPushNotification(ctx context.Context, userIDs []int64,
s.mongoLogger.Error("[NotificationSvc.SendBulkPushNotification] Multicast send failed", s.mongoLogger.Error("[NotificationSvc.SendBulkPushNotification] Multicast send failed",
zap.Error(err), zap.Error(err),
zap.Int("batchSize", len(batch)), zap.Int("batchSize", len(batch)),
zap.String("fcm_project_id", s.fcmProjectID),
) )
failed += len(batch) for _, token := range batch {
result.Failed++
result.Failures = append(result.Failures, BulkPushFailure{
UserID: tokenUserMap[token],
TokenPreview: tokenPreview(token),
Error: err.Error(),
Hint: fcmFailureHint(err),
})
}
continue continue
} }
sent += resp.SuccessCount result.Sent += resp.SuccessCount
failed += resp.FailureCount result.Failed += resp.FailureCount
// Deactivate invalid tokens
for j, sendResp := range resp.Responses { for j, sendResp := range resp.Responses {
if sendResp.Error != nil && (messaging.IsUnregistered(sendResp.Error) || messaging.IsInvalidArgument(sendResp.Error)) { if sendResp.Error == nil {
token := batch[j] continue
if uid, ok := tokenUserMap[token]; ok { }
_ = s.userSvc.DeactivateDevice(ctx, uid, token)
} token := batch[j]
userID := tokenUserMap[token]
s.mongoLogger.Error("[NotificationSvc.SendBulkPushNotification] FCM delivery failed",
zap.Int64("userID", userID),
zap.String("token", tokenPreview(token)),
zap.String("fcm_project_id", s.fcmProjectID),
zap.String("hint", fcmFailureHint(sendResp.Error)),
zap.Error(sendResp.Error),
)
result.Failures = append(result.Failures, BulkPushFailure{
UserID: userID,
TokenPreview: tokenPreview(token),
Error: sendResp.Error.Error(),
Hint: fcmFailureHint(sendResp.Error),
})
if shouldDeactivateFCMToken(sendResp.Error) {
_ = s.userSvc.DeactivateDevice(ctx, userID, token)
} }
} }
} }
s.mongoLogger.Info("[NotificationSvc.SendBulkPushNotification] Bulk push completed", s.mongoLogger.Info("[NotificationSvc.SendBulkPushNotification] Bulk push completed",
zap.Int("totalTokens", len(allTokens)), zap.Int("totalTokens", len(allTokens)),
zap.Int("sent", sent), zap.Int("sent", result.Sent),
zap.Int("failed", failed), zap.Int("failed", result.Failed),
zap.String("fcm_project_id", s.fcmProjectID),
) )
return sent, failed, devicesTargeted, nil return result, nil
} }
// SendBulkSMS sends an SMS to multiple phone numbers using AfroMessage. // SendBulkSMS sends an SMS to multiple phone numbers using AfroMessage.
@ -1327,15 +1364,18 @@ func (s *Service) dispatchScheduledPush(ctx context.Context, sn *domain.Schedule
}, },
} }
sent, failed, devicesTargeted, err := s.SendBulkPushNotification(ctx, userIDs, notification) delivery, err := s.SendBulkPushNotification(ctx, userIDs, notification)
if err != nil { if err != nil {
return err return err
} }
if devicesTargeted == 0 { if delivery.DevicesTargeted == 0 {
return fmt.Errorf("no registered device tokens for %d target user(s)", len(userIDs)) return fmt.Errorf("no registered device tokens for %d target user(s)", len(userIDs))
} }
if sent == 0 && failed > 0 { if delivery.Sent == 0 && delivery.Failed > 0 {
return fmt.Errorf("all %d push deliveries failed", failed) if len(delivery.Failures) > 0 {
return fmt.Errorf("all %d push deliveries failed: %s", delivery.Failed, delivery.Failures[0].Error)
}
return fmt.Errorf("all %d push deliveries failed", delivery.Failed)
} }
return nil return nil
} }

View File

@ -2,6 +2,7 @@ package handlers
import ( import (
"Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/domain"
"Yimaru-Backend/internal/pkgs/helpers"
notificationservice "Yimaru-Backend/internal/services/notification" notificationservice "Yimaru-Backend/internal/services/notification"
"Yimaru-Backend/internal/web_server/ws" "Yimaru-Backend/internal/web_server/ws"
"bufio" "bufio"
@ -1128,7 +1129,8 @@ func (h *Handler) SendBulkPushNotification(c *fiber.Ctx) error {
} }
notification := &domain.Notification{ notification := &domain.Notification{
Type: "system_alert", ID: helpers.GenerateID(),
Type: domain.NOTIFICATION_TYPE_SYSTEM_ALERT,
DeliveryChannel: domain.DeliveryChannelPush, DeliveryChannel: domain.DeliveryChannelPush,
Image: imageURL, Image: imageURL,
Payload: domain.NotificationPayload{ Payload: domain.NotificationPayload{
@ -1137,7 +1139,7 @@ func (h *Handler) SendBulkPushNotification(c *fiber.Ctx) error {
}, },
} }
sent, failed, devicesTargeted, err := h.notificationSvc.SendBulkPushNotification(c.Context(), userIDs, notification) delivery, err := h.notificationSvc.SendBulkPushNotification(c.Context(), userIDs, notification)
if err != nil { if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to send bulk push notification", Message: "Failed to send bulk push notification",
@ -1152,28 +1154,42 @@ func (h *Handler) SendBulkPushNotification(c *fiber.Ctx) error {
h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkPushNotification] Bulk push sent", h.mongoLoggerSvc.Info("[NotificationHandler.SendBulkPushNotification] Bulk push sent",
zap.Int("targetUsers", len(userIDs)), zap.Int("targetUsers", len(userIDs)),
zap.Int("devicesTargeted", devicesTargeted), zap.Int("devicesTargeted", delivery.DevicesTargeted),
zap.Int("sent", sent), zap.Int("sent", delivery.Sent),
zap.Int("failed", failed), zap.Int("failed", delivery.Failed),
zap.String("fcmProjectID", delivery.FCMProjectID),
zap.Time("timestamp", time.Now()), zap.Time("timestamp", time.Now()),
) )
responseMessage := "Bulk push notification sent" responseMessage := "Bulk push notification sent"
if devicesTargeted == 0 { switch {
case delivery.DevicesTargeted == 0:
responseMessage = "No registered device tokens for target users" responseMessage = "No registered device tokens for target users"
case delivery.Sent == 0 && delivery.Failed > 0:
responseMessage = "Bulk push completed with delivery failures"
case delivery.Failed > 0:
responseMessage = "Bulk push partially delivered"
}
responseData := map[string]interface{}{
"target_users": len(userIDs),
"devices_targeted": delivery.DevicesTargeted,
"sent": delivery.Sent,
"failed": delivery.Failed,
"image": imageURL,
}
if delivery.FCMProjectID != "" {
responseData["fcm_project_id"] = delivery.FCMProjectID
}
if len(delivery.Failures) > 0 {
responseData["failures"] = delivery.Failures
} }
return c.Status(fiber.StatusOK).JSON(domain.Response{ return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: responseMessage, Message: responseMessage,
Success: true, Success: true,
StatusCode: fiber.StatusOK, StatusCode: fiber.StatusOK,
Data: map[string]interface{}{ Data: responseData,
"target_users": len(userIDs),
"devices_targeted": devicesTargeted,
"sent": sent,
"failed": failed,
"image": imageURL,
},
}) })
} }