Skip to content

Modern Docker Management, Designed for Everyone

fix: image polling notifications context being canceled early or not registered at all (#3089)

Kyle Mendell202c0c6a8755
diff --git a/backend/api/handlers/notifications.go b/backend/api/handlers/notifications.go
index b98986e13..6c530190b 100644
--- a/backend/api/handlers/notifications.go
+++ b/backend/api/handlers/notifications.go
@@ -73,7 +73,7 @@ type DispatchNotificationInput struct {
}
type DispatchNotificationOutput struct {
- Body base.ApiResponse[base.MessageResponse]
+ Body base.ApiResponse[notification.DispatchResponse]
}
var supportedNotificationTestTypes = map[string]struct{}{
@@ -287,7 +287,8 @@ func (h *NotificationHandler) DispatchNotification(ctx context.Context, input *D
if strings.TrimSpace(input.APIKey) == "" {
return nil, huma.Error401Unauthorized("missing remote environment access token")
}
- if err := h.notificationService.DispatchNotification(ctx, input.APIKey, input.Body); err != nil {
+ dispatchResponse, err := h.notificationService.DispatchNotification(ctx, input.APIKey, input.Body)
+ if err != nil {
if errors.Is(err, services.ErrUnsupportedDispatchKind) {
return nil, huma.Error400BadRequest("unsupported dispatch kind")
}
@@ -298,9 +299,9 @@ func (h *NotificationHandler) DispatchNotification(ctx context.Context, input *D
}
return &DispatchNotificationOutput{
- Body: base.ApiResponse[base.MessageResponse]{
+ Body: base.ApiResponse[notification.DispatchResponse]{
Success: true,
- Data: base.MessageResponse{Message: "Notification dispatched successfully"},
+ Data: dispatchResponse,
},
}, nil
}
diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.go
index 351196ba6..3f87c3c37 100644
--- a/backend/internal/services/image_update_service.go
+++ b/backend/internal/services/image_update_service.go
@@ -251,12 +251,7 @@ func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef stri
slog.WarnContext(ctx, "Failed to save update result", "imageRef", imageRef, "error", saveErr.Error())
}
- // Send notification if update is available
- if digestResult.HasUpdate && s.notificationService != nil {
- if notifErr := s.notificationService.SendImageUpdateNotification(ctx, imageRef, digestResult, models.NotificationEventImageUpdate); notifErr != nil {
- slog.WarnContext(ctx, "Failed to send update notification", "imageRef", imageRef, "error", notifErr.Error())
- }
- }
+ s.notifyImageUpdateInternal(ctx, imageRef, digestResult, snapshot)
finalMessage := "Image update check completed"
if digestResult.HasUpdate {
@@ -266,6 +261,49 @@ func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef stri
return digestResult, nil
}
+// notifyImageUpdateInternal sends the single-image update notification and marks the
+// record notified only when it was actually delivered to at least one provider with
+// no send errors. Mirroring the batch path, any send error leaves the record
+// unnotified so a later check retries it — a failed send must never silently poison
+// the notification_sent flag. Prefer the snapshot's image ID: it is the same key
+// saveUpdateResultWithSnapshotInternal stored the record under.
+func (s *ImageUpdateService) notifyImageUpdateInternal(ctx context.Context, imageRef string, digestResult *imageupdate.Response, snapshot *localImageSnapshot) {
+ if !digestResult.HasUpdate || s.notificationService == nil {
+ return
+ }
+
+ delivered, notifErr := s.notificationService.SendImageUpdateNotification(ctx, imageRef, digestResult, models.NotificationEventImageUpdate)
+ if notifErr != nil {
+ slog.WarnContext(ctx, "Failed to send update notification", "imageRef", imageRef, "error", notifErr.Error())
+ }
+ if notifErr != nil || delivered == 0 {
+ return
+ }
+
+ imageID := s.resolveNotifiedImageIDInternal(ctx, imageRef, snapshot)
+ if imageID == "" {
+ return
+ }
+ if markErr := s.MarkUpdatesAsNotified(ctx, []string{imageID}); markErr != nil {
+ slog.WarnContext(ctx, "Failed to mark update as notified", "imageRef", imageRef, "error", markErr.Error())
+ }
+}
+
+// resolveNotifiedImageIDInternal returns the image ID used to mark an update
+// notified, preferring the snapshot's image ID and falling back to a lookup by
+// reference.
+func (s *ImageUpdateService) resolveNotifiedImageIDInternal(ctx context.Context, imageRef string, snapshot *localImageSnapshot) string {
+ if snapshot != nil && snapshot.ImageID != "" {
+ return snapshot.ImageID
+ }
+ resolved, err := s.getImageIDByRef(ctx, imageRef)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to resolve image ID to mark notified", "imageRef", imageRef, "error", err.Error())
+ return ""
+ }
+ return resolved
+}
+
func digestPinnedImageUpdateResultInternal(imageRef string) (*imageupdate.Response, bool) {
imageRef = strings.TrimSpace(imageRef)
pinnedDigest, ok := updaterdigest.FromReferenceSuffix(imageRef)
@@ -1326,10 +1364,15 @@ func (s *ImageUpdateService) sendBatchImageUpdateNotificationsInternal(ctx conte
slog.InfoContext(ctx, "Sending notifications for unnotified updates", "count", len(updatesToNotify))
- if notifErr := s.notificationService.SendBatchImageUpdateNotification(notifCtx, updatesToNotify); notifErr != nil {
+ delivered, notifErr := s.notificationService.SendBatchImageUpdateNotification(notifCtx, updatesToNotify)
+ if notifErr != nil {
slog.WarnContext(ctx, "Failed to send batch update notification", "error", notifErr.Error())
return
}
+ if delivered == 0 {
+ slog.DebugContext(ctx, "No eligible notification providers for image updates; leaving records unnotified", "count", len(imageIDsToMark))
+ return
+ }
if markErr := s.MarkUpdatesAsNotified(notifCtx, imageIDsToMark); markErr != nil {
slog.WarnContext(ctx, "Failed to mark updates as notified", "error", markErr.Error())
}
diff --git a/backend/internal/services/image_update_service_test.go b/backend/internal/services/image_update_service_test.go
index b31e02de0..13082a67a 100644
--- a/backend/internal/services/image_update_service_test.go
+++ b/backend/internal/services/image_update_service_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"net/url"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -1303,7 +1304,25 @@ func TestImageUpdateService_MarkUpdatesAsNotified_EmptyList(t *testing.T) {
// with "context canceled" so notifications were never dispatched (issue #2920).
func TestImageUpdateService_SendBatchNotifications_DetachesCanceledContext(t *testing.T) {
db := setupImageUpdateTestDB(t)
- require.NoError(t, db.AutoMigrate(&models.NotificationSettings{}))
+ require.NoError(t, db.AutoMigrate(&models.NotificationSettings{}, &models.NotificationLog{}))
+
+ // A provider that actually delivers (returns 200), so the record is only marked
+ // notified when the send genuinely reaches it.
+ var calls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls.Add(1)
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer server.Close()
+ require.NoError(t, db.Create(&models.NotificationSettings{
+ Provider: models.NotificationProviderGeneric,
+ Enabled: true,
+ Config: models.JSON{
+ "webhookUrl": server.URL,
+ "method": "POST",
+ "contentType": "application/json",
+ },
+ }).Error)
notif := NewNotificationService(db, nil, nil)
svc := NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)
@@ -1323,14 +1342,47 @@ func TestImageUpdateService_SendBatchNotifications_DetachesCanceledContext(t *te
svc.sendBatchImageUpdateNotificationsInternal(ctx)
- // With no providers configured the send is a no-op success, so the record being
- // marked notified proves GetUnnotifiedUpdates + MarkUpdatesAsNotified ran despite
- // the canceled parent ctx.
+ // The provider being reached, and the record being marked notified, both prove
+ // GetUnnotifiedUpdates + the send + MarkUpdatesAsNotified ran despite the canceled
+ // parent ctx (issue #2920).
+ require.EqualValues(t, 1, calls.Load())
var reloaded models.ImageUpdateRecord
require.NoError(t, db.First(&reloaded, "id = ?", "sha256:img1").Error)
assert.True(t, reloaded.NotificationSent)
}
+// TestImageUpdateService_SendBatchNotifications_NoEligibleProviders_LeavesUnnotified
+// is the regression guard for issue #3079: a background check that finds an update
+// while no provider has the image-update event enabled must NOT mark the record
+// notified — otherwise, once the user later configures a provider, the still-pending
+// update is permanently suppressed (it only re-surfaces on a future digest change).
+func TestImageUpdateService_SendBatchNotifications_NoEligibleProviders_LeavesUnnotified(t *testing.T) {
+ db := setupImageUpdateTestDB(t)
+ require.NoError(t, db.AutoMigrate(&models.NotificationSettings{}))
+
+ notif := NewNotificationService(db, nil, nil)
+ svc := NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)
+
+ rec := models.ImageUpdateRecord{
+ ID: "sha256:img-no-provider",
+ Repository: "test/repo",
+ Tag: "latest",
+ HasUpdate: true,
+ NotificationSent: false,
+ }
+ require.NoError(t, db.Create(&rec).Error)
+
+ svc.sendBatchImageUpdateNotificationsInternal(context.Background())
+
+ var reloaded models.ImageUpdateRecord
+ require.NoError(t, db.First(&reloaded, "id = ?", "sha256:img-no-provider").Error)
+ assert.False(t, reloaded.NotificationSent)
+
+ unnotified, err := svc.GetUnnotifiedUpdates(context.Background())
+ require.NoError(t, err)
+ require.Contains(t, unnotified, "sha256:img-no-provider")
+}
+
func TestImageUpdateService_GetUpdateSummaryForImageIDs_FiltersToLiveImages(t *testing.T) {
ctx := context.Background()
db := setupImageUpdateTestDB(t)
diff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.go
index b167e2998..b3e25c1ba 100644
--- a/backend/internal/services/notification_service.go
+++ b/backend/internal/services/notification_service.go
@@ -163,76 +163,85 @@ func (s *NotificationService) resolveNotificationTargetForAccessTokenInternal(ct
}, nil
}
-func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.Context, payload notificationdto.DispatchRequest) error {
+func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.Context, payload notificationdto.DispatchRequest) (notificationdto.DispatchResponse, error) {
if s.config == nil || strings.TrimSpace(s.config.GetManagerBaseURL()) == "" {
- return errors.New("manager API URL is required for notification dispatch")
+ return notificationdto.DispatchResponse{}, errors.New("manager API URL is required for notification dispatch")
}
if strings.TrimSpace(s.config.AgentToken) == "" {
- return errors.New("agent token is required for notification dispatch")
+ return notificationdto.DispatchResponse{}, errors.New("agent token is required for notification dispatch")
}
body, err := json.Marshal(payload)
if err != nil {
- return fmt.Errorf("failed to marshal notification dispatch payload: %w", err)
+ return notificationdto.DispatchResponse{}, fmt.Errorf("failed to marshal notification dispatch payload: %w", err)
}
dispatchURL := strings.TrimRight(s.config.GetManagerBaseURL(), "/") + "/api/notifications/dispatch"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, dispatchURL, bytes.NewReader(body))
if err != nil {
- return fmt.Errorf("failed to create notification dispatch request: %w", err)
+ return notificationdto.DispatchResponse{}, fmt.Errorf("failed to create notification dispatch request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Api-Key", s.config.AgentToken)
resp, err := s.httpClient.Do(req)
if err != nil {
- return fmt.Errorf("failed to dispatch notification to manager: %w", err)
+ return notificationdto.DispatchResponse{}, fmt.Errorf("failed to dispatch notification to manager: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices {
- return nil
+ var apiResponse struct {
+ Data notificationdto.DispatchResponse `json:"data"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil {
+ return notificationdto.DispatchResponse{}, fmt.Errorf("failed to decode manager notification dispatch response: %w", err)
+ }
+ return apiResponse.Data, nil
}
responseBody, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("manager notification dispatch failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(responseBody)))
+ return notificationdto.DispatchResponse{}, fmt.Errorf("manager notification dispatch failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(responseBody)))
}
-func (s *NotificationService) DispatchNotification(ctx context.Context, accessToken string, payload notificationdto.DispatchRequest) error {
+func (s *NotificationService) DispatchNotification(ctx context.Context, accessToken string, payload notificationdto.DispatchRequest) (notificationdto.DispatchResponse, error) {
if s.config != nil && s.config.AgentMode {
- return errors.New("notification dispatch is manager-only")
+ return notificationdto.DispatchResponse{}, errors.New("notification dispatch is manager-only")
}
target, err := s.resolveNotificationTargetForAccessTokenInternal(ctx, accessToken)
if err != nil {
- return err
+ return notificationdto.DispatchResponse{}, err
}
+ dispatchResponse := notificationdto.DispatchResponse{Message: "Notification dispatched successfully"}
switch payload.Kind {
case notificationdto.DispatchKindImageUpdate:
if payload.ImageUpdate == nil {
- return errors.New("image update payload is required")
+ return notificationdto.DispatchResponse{}, errors.New("image update payload is required")
}
logManagerDispatchNotificationInternal(ctx, target, payload.Kind)
- return s.sendImageUpdateNotificationForTargetInternal(ctx, target, payload.ImageUpdate.ImageRef, &payload.ImageUpdate.UpdateInfo, models.NotificationEventImageUpdate)
+ dispatchResponse.Delivered, err = s.sendImageUpdateNotificationForTargetInternal(ctx, target, payload.ImageUpdate.ImageRef, &payload.ImageUpdate.UpdateInfo, models.NotificationEventImageUpdate)
+ return dispatchResponse, err
case notificationdto.DispatchKindBatchImageUpdate:
if payload.BatchImageUpdate == nil {
- return errors.New("batch image update payload is required")
+ return notificationdto.DispatchResponse{}, errors.New("batch image update payload is required")
}
logManagerDispatchNotificationInternal(ctx, target, payload.Kind)
- return s.sendBatchImageUpdateNotificationForTargetInternal(ctx, target, payload.BatchImageUpdate.Updates)
+ dispatchResponse.Delivered, err = s.sendBatchImageUpdateNotificationForTargetInternal(ctx, target, payload.BatchImageUpdate.Updates)
+ return dispatchResponse, err
case notificationdto.DispatchKindContainerUpdate:
if payload.ContainerUpdate == nil {
- return errors.New("container update payload is required")
+ return notificationdto.DispatchResponse{}, errors.New("container update payload is required")
}
logManagerDispatchNotificationInternal(ctx, target, payload.Kind)
- return s.sendContainerUpdateNotificationForTargetInternal(ctx, target, payload.ContainerUpdate.ContainerName, payload.ContainerUpdate.ImageRef, payload.ContainerUpdate.OldDigest, payload.ContainerUpdate.NewDigest)
+ return dispatchResponse, s.sendContainerUpdateNotificationForTargetInternal(ctx, target, payload.ContainerUpdate.ContainerName, payload.ContainerUpdate.ImageRef, payload.ContainerUpdate.OldDigest, payload.ContainerUpdate.NewDigest)
case notificationdto.DispatchKindVulnerabilityFound:
if payload.VulnerabilityFound == nil {
- return errors.New("vulnerability payload is required")
+ return notificationdto.DispatchResponse{}, errors.New("vulnerability payload is required")
}
logManagerDispatchNotificationInternal(ctx, target, payload.Kind)
- return s.sendVulnerabilityNotificationForTargetInternal(ctx, target, VulnerabilityNotificationPayload{
+ return dispatchResponse, s.sendVulnerabilityNotificationForTargetInternal(ctx, target, VulnerabilityNotificationPayload{
CVEID: payload.VulnerabilityFound.CVEID,
CVELink: payload.VulnerabilityFound.CVELink,
Severity: payload.VulnerabilityFound.Severity,
@@ -243,18 +252,18 @@ func (s *NotificationService) DispatchNotification(ctx context.Context, accessTo
})
case notificationdto.DispatchKindPruneReport:
if payload.PruneReport == nil {
- return errors.New("prune report payload is required")
+ return notificationdto.DispatchResponse{}, errors.New("prune report payload is required")
}
logManagerDispatchNotificationInternal(ctx, target, payload.Kind)
- return s.sendPruneReportNotificationForTargetInternal(ctx, target, &payload.PruneReport.Result)
+ return dispatchResponse, s.sendPruneReportNotificationForTargetInternal(ctx, target, &payload.PruneReport.Result)
case notificationdto.DispatchKindAutoHeal:
if payload.AutoHeal == nil {
- return errors.New("auto-heal payload is required")
+ return notificationdto.DispatchResponse{}, errors.New("auto-heal payload is required")
}
logManagerDispatchNotificationInternal(ctx, target, payload.Kind)
- return s.sendAutoHealNotificationForTargetInternal(ctx, target, payload.AutoHeal.ContainerName, payload.AutoHeal.ContainerID)
+ return dispatchResponse, s.sendAutoHealNotificationForTargetInternal(ctx, target, payload.AutoHeal.ContainerName, payload.AutoHeal.ContainerID)
default:
- return fmt.Errorf("%w: %s", ErrUnsupportedDispatchKind, payload.Kind)
+ return notificationdto.DispatchResponse{}, fmt.Errorf("%w: %s", ErrUnsupportedDispatchKind, payload.Kind)
}
}
@@ -397,35 +406,43 @@ func (s *NotificationService) DeleteSettings(ctx context.Context, provider model
return nil
}
-func (s *NotificationService) SendImageUpdateNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, eventType models.NotificationEventType) error {
+// SendImageUpdateNotification dispatches a single-image update notification and
+// returns the number of eligible providers it was delivered to (0 means no
+// provider has this event enabled, so callers must not mark the update notified).
+func (s *NotificationService) SendImageUpdateNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, eventType models.NotificationEventType) (int, error) {
if updateInfo == nil {
- return errors.New("updateInfo is required")
+ return 0, errors.New("updateInfo is required")
}
if s.config != nil && s.config.AgentMode {
- return s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
+ dispatchResponse, err := s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
Kind: notificationdto.DispatchKindImageUpdate,
ImageUpdate: &notificationdto.DispatchImageUpdate{
ImageRef: imageRef,
UpdateInfo: *updateInfo,
},
})
+ if err != nil {
+ return 0, err
+ }
+ return dispatchResponse.Delivered, nil
}
target, err := s.resolveNotificationTargetInternal(ctx, "")
if err != nil {
- return err
+ return 0, err
}
return s.sendImageUpdateNotificationForTargetInternal(ctx, target, imageRef, updateInfo, eventType)
}
-func (s *NotificationService) sendImageUpdateNotificationForTargetInternal(ctx context.Context, target NotificationTarget, imageRef string, updateInfo *imageupdate.Response, eventType models.NotificationEventType) error {
+func (s *NotificationService) sendImageUpdateNotificationForTargetInternal(ctx context.Context, target NotificationTarget, imageRef string, updateInfo *imageupdate.Response, eventType models.NotificationEventType) (int, error) {
settings, err := s.GetAllSettings(ctx)
if err != nil {
- return fmt.Errorf("failed to get notification settings: %w", err)
+ return 0, fmt.Errorf("failed to get notification settings: %w", err)
}
+ delivered := 0
var errors []string
for _, setting := range settings {
if !setting.Enabled {
@@ -471,6 +488,8 @@ func (s *NotificationService) sendImageUpdateNotificationForTargetInternal(ctx c
msg := sendErr.Error()
errMsg = new(msg)
errors = append(errors, fmt.Sprintf("%s: %s", setting.Provider, msg))
+ } else {
+ delivered++
}
s.logNotification(ctx, setting.Provider, imageRef, status, errMsg, models.JSON{
@@ -483,10 +502,10 @@ func (s *NotificationService) sendImageUpdateNotificationForTargetInternal(ctx c
}
if len(errors) > 0 {
- return fmt.Errorf("notification errors: %s", strings.Join(errors, "; "))
+ return delivered, fmt.Errorf("notification errors: %s", strings.Join(errors, "; "))
}
- return nil
+ return delivered, nil
}
// isEventEnabled checks if a specific event type is enabled in the config
@@ -506,7 +525,7 @@ func (s *NotificationService) isEventEnabled(config models.JSON, eventType model
func (s *NotificationService) SendContainerUpdateNotification(ctx context.Context, containerName, imageRef, oldDigest, newDigest string) error {
if s.config != nil && s.config.AgentMode {
- return s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
+ _, err := s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
Kind: notificationdto.DispatchKindContainerUpdate,
ContainerUpdate: &notificationdto.DispatchContainerUpdate{
ContainerName: containerName,
@@ -515,6 +534,7 @@ func (s *NotificationService) SendContainerUpdateNotification(ctx context.Contex
NewDigest: newDigest,
},
})
+ return err
}
target, err := s.resolveNotificationTargetInternal(ctx, "")
@@ -606,7 +626,7 @@ func (s *NotificationService) SendVulnerabilityNotification(ctx context.Context,
}
if s.config != nil && s.config.AgentMode {
- return s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
+ _, err := s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
Kind: notificationdto.DispatchKindVulnerabilityFound,
VulnerabilityFound: &notificationdto.DispatchVulnerabilityFound{
CVEID: payload.CVEID,
@@ -618,6 +638,7 @@ func (s *NotificationService) SendVulnerabilityNotification(ctx context.Context,
InstalledVersion: payload.InstalledVersion,
},
})
+ return err
}
target, err := s.resolveNotificationTargetInternal(ctx, "")
@@ -1360,24 +1381,31 @@ func (s *NotificationService) logNotification(ctx context.Context, provider mode
}
}
-func (s *NotificationService) SendBatchImageUpdateNotification(ctx context.Context, updates map[string]*imageupdate.Response) error {
+// SendBatchImageUpdateNotification dispatches a batched image-update notification
+// and returns the number of eligible providers it was delivered to (0 means no
+// provider has this event enabled, so callers must not mark the updates notified).
+func (s *NotificationService) SendBatchImageUpdateNotification(ctx context.Context, updates map[string]*imageupdate.Response) (int, error) {
updatesWithChanges := filterUpdatesWithChangesInternal(updates)
if len(updatesWithChanges) == 0 {
- return nil
+ return 0, nil
}
if s.config != nil && s.config.AgentMode {
- return s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
+ dispatchResponse, err := s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
Kind: notificationdto.DispatchKindBatchImageUpdate,
BatchImageUpdate: &notificationdto.DispatchBatchImageUpdate{
Updates: updatesWithChanges,
},
})
+ if err != nil {
+ return 0, err
+ }
+ return dispatchResponse.Delivered, nil
}
target, err := s.resolveNotificationTargetInternal(ctx, "")
if err != nil {
- return err
+ return 0, err
}
return s.sendBatchImageUpdateNotificationForTargetInternal(ctx, target, updatesWithChanges)
@@ -1393,18 +1421,19 @@ func filterUpdatesWithChangesInternal(updates map[string]*imageupdate.Response)
return updatesWithChanges
}
-func (s *NotificationService) sendBatchImageUpdateNotificationForTargetInternal(ctx context.Context, target NotificationTarget, updates map[string]*imageupdate.Response) error {
+func (s *NotificationService) sendBatchImageUpdateNotificationForTargetInternal(ctx context.Context, target NotificationTarget, updates map[string]*imageupdate.Response) (int, error) {
updatesWithChanges := filterUpdatesWithChangesInternal(updates)
if len(updatesWithChanges) == 0 {
- return nil
+ return 0, nil
}
settings, err := s.GetAllSettings(ctx)
if err != nil {
- return fmt.Errorf("failed to get notification settings: %w", err)
+ return 0, fmt.Errorf("failed to get notification settings: %w", err)
}
+ delivered := 0
var errors []string
for _, setting := range settings {
if !setting.Enabled {
@@ -1421,6 +1450,10 @@ func (s *NotificationService) sendBatchImageUpdateNotificationForTargetInternal(
continue
}
+ if sendErr == nil {
+ delivered++
+ }
+
status, errMsg := collectNotificationSendResultInternal(&errors, setting.Provider, sendErr)
imageRefs := make([]string, 0, len(updatesWithChanges))
@@ -1436,10 +1469,10 @@ func (s *NotificationService) sendBatchImageUpdateNotificationForTargetInternal(
}
if len(errors) > 0 {
- return fmt.Errorf("notification errors: %s", strings.Join(errors, "; "))
+ return delivered, fmt.Errorf("notification errors: %s", strings.Join(errors, "; "))
}
- return nil
+ return delivered, nil
}
func (s *NotificationService) sendBatchDiscordNotification(ctx context.Context, environmentName string, updates map[string]*imageupdate.Response, config models.JSON) error {
@@ -2437,12 +2470,13 @@ func (s *NotificationService) SendPruneReportNotification(ctx context.Context, r
}
if s.config != nil && s.config.AgentMode {
- return s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
+ _, err := s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
Kind: notificationdto.DispatchKindPruneReport,
PruneReport: &notificationdto.DispatchPruneReport{
Result: *result,
},
})
+ return err
}
target, err := s.resolveNotificationTargetInternal(ctx, "")
@@ -2715,13 +2749,14 @@ func (s *NotificationService) sendGenericPruneNotification(ctx context.Context,
// SendAutoHealNotification sends a notification when a container is auto-healed.
func (s *NotificationService) SendAutoHealNotification(ctx context.Context, containerName, containerID string) error {
if s.config != nil && s.config.AgentMode {
- return s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
+ _, err := s.dispatchNotificationToManagerInternal(ctx, notificationdto.DispatchRequest{
Kind: notificationdto.DispatchKindAutoHeal,
AutoHeal: &notificationdto.DispatchAutoHeal{
ContainerName: containerName,
ContainerID: containerID,
},
})
+ return err
}
target, err := s.resolveNotificationTargetInternal(ctx, "")
diff --git a/backend/internal/services/notification_service_test.go b/backend/internal/services/notification_service_test.go
index 429e58799..948222fa0 100644
--- a/backend/internal/services/notification_service_test.go
+++ b/backend/internal/services/notification_service_test.go
@@ -134,7 +134,7 @@ func TestNotificationService_DispatchNotification_InvalidAccessTokenReturnsUnaut
ctx := context.Background()
_, _, svc := setupNotificationTestServiceInternal(t)
- err := svc.DispatchNotification(ctx, "missing-token", notificationdto.DispatchRequest{
+ _, err := svc.DispatchNotification(ctx, "missing-token", notificationdto.DispatchRequest{
Kind: notificationdto.DispatchKindImageUpdate,
ImageUpdate: &notificationdto.DispatchImageUpdate{
ImageRef: "nginx:latest",
@@ -161,7 +161,7 @@ func TestNotificationService_DispatchNotification_UnsupportedKindReturnsSentinel
AccessToken: &token,
}).Error)
- err := svc.DispatchNotification(ctx, token, notificationdto.DispatchRequest{
+ _, err := svc.DispatchNotification(ctx, token, notificationdto.DispatchRequest{
Kind: notificationdto.DispatchKind("bogus_kind"),
})
@@ -188,7 +188,7 @@ func TestNotificationService_DispatchNotification_LogsManagerDispatchForAgent(t
AccessToken: &token,
}).Error)
- err := svc.DispatchNotification(ctx, token, notificationdto.DispatchRequest{
+ dispatchResponse, err := svc.DispatchNotification(ctx, token, notificationdto.DispatchRequest{
Kind: notificationdto.DispatchKindImageUpdate,
ImageUpdate: &notificationdto.DispatchImageUpdate{
ImageRef: "nginx:latest",
@@ -197,6 +197,8 @@ func TestNotificationService_DispatchNotification_LogsManagerDispatchForAgent(t
})
require.NoError(t, err)
+ require.Equal(t, "Notification dispatched successfully", dispatchResponse.Message)
+ require.Equal(t, 0, dispatchResponse.Delivered)
logs := logBuffer.String()
require.Contains(t, logs, "Manager dispatching notification on behalf of agent")
require.Contains(t, logs, "environment_id=env-remote")
@@ -217,7 +219,13 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeDispatchesToMa
require.Equal(t, "agent-token", r.Header.Get("X-API-Key"))
require.NoError(t, json.NewDecoder(r.Body).Decode(&dispatched))
calls.Add(1)
- w.WriteHeader(http.StatusOK)
+ require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
+ "success": true,
+ "data": notificationdto.DispatchResponse{
+ Message: "Notification dispatched successfully",
+ Delivered: 2,
+ },
+ }))
}))
defer server.Close()
@@ -228,14 +236,53 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeDispatchesToMa
ManagerApiUrl: server.URL,
}, envSvc)
- err := svc.SendImageUpdateNotification(ctx, "nginx:latest", newNotificationTestUpdateInfoInternal(), models.NotificationEventImageUpdate)
+ delivered, err := svc.SendImageUpdateNotification(ctx, "nginx:latest", newNotificationTestUpdateInfoInternal(), models.NotificationEventImageUpdate)
require.NoError(t, err)
+ require.EqualValues(t, 2, delivered)
require.EqualValues(t, 1, calls.Load())
require.Equal(t, notificationdto.DispatchKindImageUpdate, dispatched.Kind)
require.NotNil(t, dispatched.ImageUpdate)
require.Equal(t, "nginx:latest", dispatched.ImageUpdate.ImageRef)
}
+func TestNotificationService_SendBatchImageUpdateNotification_AgentModeUsesManagerDeliveredCountInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ envSvc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
+
+ var dispatched notificationdto.DispatchRequest
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodPost, r.Method)
+ require.Equal(t, "/api/notifications/dispatch", r.URL.Path)
+ require.Equal(t, "agent-token", r.Header.Get("X-API-Key"))
+ require.NoError(t, json.NewDecoder(r.Body).Decode(&dispatched))
+ require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
+ "success": true,
+ "data": notificationdto.DispatchResponse{
+ Message: "Notification dispatched successfully",
+ Delivered: 0,
+ },
+ }))
+ }))
+ defer server.Close()
+
+ svc := NewNotificationService(db, &config.Config{
+ AppUrl: "http://localhost:3552",
+ AgentMode: true,
+ AgentToken: "agent-token",
+ ManagerApiUrl: server.URL,
+ }, envSvc)
+
+ delivered, err := svc.SendBatchImageUpdateNotification(ctx, map[string]*imageupdate.Response{
+ "nginx:latest": newNotificationTestUpdateInfoInternal(),
+ })
+ require.NoError(t, err)
+ require.EqualValues(t, 0, delivered)
+ require.Equal(t, notificationdto.DispatchKindBatchImageUpdate, dispatched.Kind)
+ require.NotNil(t, dispatched.BatchImageUpdate)
+ require.Contains(t, dispatched.BatchImageUpdate.Updates, "nginx:latest")
+}
+
func TestNotificationService_SendImageUpdateNotification_AgentModeRequiresUpdateInfo(t *testing.T) {
ctx := context.Background()
db := setupNotificationTestDB(t)
@@ -246,7 +293,7 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeRequiresUpdate
AgentMode: true,
}, envSvc)
- err := svc.SendImageUpdateNotification(ctx, "nginx:latest", nil, models.NotificationEventImageUpdate)
+ _, err := svc.SendImageUpdateNotification(ctx, "nginx:latest", nil, models.NotificationEventImageUpdate)
require.Error(t, err)
require.Contains(t, err.Error(), "updateInfo is required")
}
@@ -271,13 +318,14 @@ func TestNotificationService_SendBatchImageUpdateNotification_AgentModeSkipsNoOp
}, envSvc)
t.Run("empty updates", func(t *testing.T) {
- err := svc.SendBatchImageUpdateNotification(ctx, map[string]*imageupdate.Response{})
+ delivered, err := svc.SendBatchImageUpdateNotification(ctx, map[string]*imageupdate.Response{})
require.NoError(t, err)
+ require.EqualValues(t, 0, delivered)
require.EqualValues(t, 0, calls.Load())
})
t.Run("no changed updates", func(t *testing.T) {
- err := svc.SendBatchImageUpdateNotification(ctx, map[string]*imageupdate.Response{
+ delivered, err := svc.SendBatchImageUpdateNotification(ctx, map[string]*imageupdate.Response{
"nginx:latest": {
HasUpdate: false,
CurrentDigest: "sha256:current",
@@ -286,6 +334,7 @@ func TestNotificationService_SendBatchImageUpdateNotification_AgentModeSkipsNoOp
"redis:latest": nil,
})
require.NoError(t, err)
+ require.EqualValues(t, 0, delivered)
require.EqualValues(t, 0, calls.Load())
})
}
diff --git a/types/notification/notification.go b/types/notification/notification.go
index 02d00ea05..949dd17ce 100644
--- a/types/notification/notification.go
+++ b/types/notification/notification.go
@@ -132,3 +132,8 @@ type DispatchRequest struct {
PruneReport *DispatchPruneReport `json:"pruneReport,omitempty"`
AutoHeal *DispatchAutoHeal `json:"autoHeal,omitempty"`
}
+
+type DispatchResponse struct {
+ Message string `json:"message"`
+ Delivered int `json:"delivered"`
+}