Repository navigation
Add Apple push notifications support - #255
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThis PR adds Apple push device registration, relay-backed delivery attempts, Apple push sending and testing, dynamic notification display metadata, new admin and user API endpoints, database schema, system wiring, and admin settings UI for a Silo Push Relay channel. ChangesApple Push Relay Feature
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant AdminSettingsUI
participant AdminApplePushHandler
participant PushRelay
participant ServerSettings
AdminSettingsUI->>AdminApplePushHandler: POST /admin/notifications/push/relay/register
AdminApplePushHandler->>PushRelay: POST /v1/deployments/register
PushRelay-->>AdminApplePushHandler: deployment_id, api_key, apns_topics
AdminApplePushHandler->>ServerSettings: persist relay URL, deployment ID, API key
AdminApplePushHandler-->>AdminSettingsUI: registration response
sequenceDiagram
participant FanoutWorker
participant PushDeviceRepository
participant PushDispatcher
participant pushSender
participant PushRelay
FanoutWorker->>PushDeviceRepository: ListEnabledAppleByProfiles + EnqueuePushAttempts
PushDispatcher->>PushDeviceRepository: ClaimPendingPushForDelivery / ClaimDuePushAttempts
PushDispatcher->>pushSender: processAttempt(attempt)
pushSender->>PushRelay: POST push payload
PushRelay-->>pushSender: relay outcome
pushSender->>PushDeviceRepository: FinalizePushAttempt / RecordPushSuccess / RecordPushFailure
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 02fe3ee685
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| last_failure_code text, | ||
| created_at timestamptz NOT NULL DEFAULT now(), | ||
| updated_at timestamptz NOT NULL DEFAULT now(), | ||
| CONSTRAINT push_devices_profile_device_platform_key UNIQUE (profile_id, device_id, platform), |
There was a problem hiding this comment.
Enforce one row per APNs token
Because this only dedupes by (profile_id, device_id, platform), the same APNs token can be registered repeatedly under a new local device ID or another profile; ListEnabledAppleByProfiles then fans out to every enabled row, so one physical APNs endpoint can receive duplicate pushes and keep receiving pushes for old profiles after a profile switch/reinstall. Consider making apns_token_hash unique/reassigning the existing row, similar to the web push endpoint model.
Useful? React with 👍 / 👎.
| response.Title != "New episode of Severance" || | ||
| response.Body != "S2E1 - Hello, Ms. Cobel" || |
There was a problem hiding this comment.
Update DB-backed display test expectations
When SILO_TEST_DATABASE_URL is set, this test fails because HandleApplePushDisplay uses BuildNotificationDisplay, whose episode formatter now returns The latest episode of Severance S02E01 just dropped! with body Hello, Ms. Cobel; these older title/body expectations will never match the handler response.
Useful? React with 👍 / 👎.
|
Caution Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted. Error details |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (5)
internal/notifications/webpush_logic_test.go (1)
21-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider covering the remaining
BuildNotificationDisplaybranches.
TestBuildNotificationDisplayonly exercises "episode available", "request declined", and "unknown type".request_fulfilled,request_approved, andwebhook_auto_disabledare indirectly covered viaTestBuildWebPushPayloadbut theirThreadID/Categoryfields (unique toNotificationDisplay) aren't asserted anywhere.Also applies to: 86-119
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/notifications/webpush_logic_test.go` around lines 21 - 24, Expand TestBuildNotificationDisplay to explicitly cover the remaining BuildNotificationDisplay branches for request_fulfilled, request_approved, and webhook_auto_disabled. Use the existing BuildNotificationDisplay function and assert the NotificationDisplay-specific ThreadID and Category fields for each case, since these branches are only indirectly exercised in TestBuildWebPushPayload today. Keep the current coverage for episode available, request declined, and unknown type, but add direct assertions for the missing notification types.internal/notifications/fanout_worker.go (1)
357-389: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate profile-dedup / attempt-construction logic across outboxes.
enqueuePushOutboxrepeats the same profile-ID dedup pattern already used inenqueueWebPushOutbox(lines 394-420), and its device→PushDeliveryAttemptconstruction loop is nearly identical to the one inoperational_dispatch.go's push block (lines 82-100). Consider extracting a shared helper (e.g.,uniqueProfileIDs(inserted []InsertedDelivery) []stringand abuildPushAttempts(deliveryID string, devices []PushDevice) []PushDeliveryAttempt) to avoid the growing copy-paste across these three call sites.♻️ Example helper extraction
func uniqueProfileIDs(inserted []InsertedDelivery) []string { seen := make(map[string]struct{}, len(inserted)) ids := make([]string, 0, len(inserted)) for _, row := range inserted { if _, ok := seen[row.ProfileID]; !ok { seen[row.ProfileID] = struct{}{} ids = append(ids, row.ProfileID) } } return ids } func buildPushAttempts(deliveryID string, devices []PushDevice) []PushDeliveryAttempt { attempts := make([]PushDeliveryAttempt, 0, len(devices)) for _, device := range devices { attempts = append(attempts, PushDeliveryAttempt{ ID: ulid.Make().String(), NotificationDeliveryID: &deliveryID, PushDeviceID: device.ID, TriggerType: PushTriggerDelivery, }) } return attempts }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/notifications/fanout_worker.go` around lines 357 - 389, `enqueuePushOutbox` is duplicating the profile de-duplication and push-attempt building logic used elsewhere, so extract shared helpers to keep the outbox code consistent and easier to maintain. Move the unique profile collection from `enqueuePushOutbox` and `enqueueWebPushOutbox` into a helper like `uniqueProfileIDs`, and factor the device-to-`PushDeliveryAttempt` loop into a reusable builder like `buildPushAttempts` that can be used here and in `operational_dispatch.go`’s push path. Keep the existing behavior and symbols such as `InsertedDelivery`, `PushDeliveryAttempt`, and `PushTriggerDelivery` unchanged while switching the call sites to the new helpers.web/src/pages/admin-settings/AdminSettingsLayout.test.tsx (1)
16-38: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDuplicate QueryClient construction between the two render helpers.
renderLayoutandrenderInteractiveLayoutboth build an identicalnew QueryClient({ defaultOptions: { queries: { retry: false } } }). Consider factoring this into a shared helper to avoid drift if the options ever need to change.♻️ Proposed refactor
+function createTestQueryClient() { + return new QueryClient({ defaultOptions: { queries: { retry: false } } }); +} + function renderLayout(search = "") { - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const client = createTestQueryClient(); return renderToStaticMarkup( <QueryClientProvider client={client}> <MemoryRouter initialEntries={[`/admin/settings${search}`]}> <AdminSettingsLayout /> </MemoryRouter> </QueryClientProvider>, ); } function renderInteractiveLayout(search = "") { - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const client = createTestQueryClient(); return render( <QueryClientProvider client={client}> <MemoryRouter initialEntries={[`/admin/settings${search}`]}> <AdminSettingsLayout /> </MemoryRouter> </QueryClientProvider>, ); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/admin-settings/AdminSettingsLayout.test.tsx` around lines 16 - 38, Both render helpers are duplicating the same QueryClient setup, so factor the shared `new QueryClient({ defaultOptions: { queries: { retry: false } } })` construction into a single helper and reuse it from `renderLayout` and `renderInteractiveLayout`. Keep the `AdminSettingsLayout` test wrappers unchanged otherwise, and update both helpers to call the shared QueryClient factory so future option changes stay consistent.internal/api/handlers/admin_apple_push.go (1)
199-224: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winRelay registration failures aren't logged server-side.
Errors from
h.client.Do, non-2xx relay responses, and JSON unmarshal failures are only ever returned to the caller — nothing is logged viaslog. For a self-hosted relay dependency, this makes production troubleshooting (e.g. "why did relay registration fail last night") harder than necessary.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/admin_apple_push.go` around lines 199 - 224, Relay registration failures are only returned, not recorded, so add server-side slog logging in the relay registration flow around h.client.Do and the response parsing path. Log when the HTTP request fails, when a non-2xx relay response is received, and when json.Unmarshal of the relay response fails, using the existing relayRegistrationError context (status/code/message) so operators can diagnose failures later. Keep the returned errors unchanged, but ensure each failure path emits a clear slog entry before returning.internal/notifications/settings.go (1)
356-382: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDuplicate URL trim logic between write-path and read-path.
PushRelayURL's trailing-slash trim (Line 364) duplicates the samestrings.TrimRight(..., "/")normalization done inadmin.go'sHandleUpdateSetting(Line 2152). Since the write path already normalizes and validates the value, this is currently harmless, but if one side changes (e.g., admin.go loosens/tightens validation) the two could silently diverge.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/notifications/settings.go` around lines 356 - 382, PushRelayURL currently repeats the same trailing-slash normalization already performed in HandleUpdateSetting, so the read path and write path can drift. Update PushRelayURL in Settings to rely on the stored value as-is (or extract a shared normalization helper used by both PushRelayURL and HandleUpdateSetting) so there is a single source of truth for PushRelayURL trimming and validation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/api/handlers/admin_apple_push.go`:
- Around line 156-174: Handle the relay settings update in HandleRegisterRelay
as an atomic operation instead of three independent h.settings.Set calls.
Capture the existing values for notifications.SettingPushRelayURL,
notifications.SettingPushRelayDeploymentID, and
notifications.SettingPushRelayAPIKey up front, then if any later write fails,
roll back the already-written keys to their previous values before returning an
error. Keep the cache invalidation in sync only after all three settings are
successfully persisted.
In `@internal/notifications/push_delivery.go`:
- Around line 286-311: FinalizePushAttempt currently updates
push_delivery_attempts by id only, so a stale worker can overwrite a newer
result after lease expiry. Update the FinalizePushAttempt query to include an
optimistic guard on the previously claimed state and attempt number, using the
existing attemptNumber parameter plus the row’s claim/finalization fields from
PushDeviceRepository. Ensure the UPDATE only applies when the row still matches
the expected in-flight attempt, and handle the no-row-updated case as a stale
finalize rather than success.
In `@internal/notifications/push_devices.go`:
- Around line 141-162: Normalize push_mode the same way as APNsEnvironment in
push_devices.go: in the registration validation path, trim and lowercase the
value before the switch so case-insensitive inputs are accepted consistently.
Update the PushDevices registration logic around the pushMode handling to
compare against the normalized value, while still defaulting empty input to
PushModePrivatePush. Also adjust or add tests for the
ApplePushDeviceRegistration flow to cover mixed-case push_mode values like “OFF”
and “Private_Push”.
In `@internal/notifications/push_sender.go`:
- Around line 105-106: The `processAttempt` path in `push_sender.go` is
permanently failing claimed deliveries when `ApplePushDeliveryEnabled(ctx)` is
false, which should instead be retried later. Update the logic around the
`processAttempt`/`finalize` flow to separate the global delivery-toggle check
from device invalidation: keep device-level failures going through `finalize`,
but when Apple push delivery is globally disabled, do not mark the attempt as
failed and do not finalize the row so the queued work remains eligible for
retry.
- Around line 133-137: The push success path in push_sender.go ignores the error
from FinalizePushAttempt, which can mark the device as successful even when the
attempt was not finalized. In the result.OK branch of the push sender logic,
check and handle the error returned by s.devices.FinalizePushAttempt before
calling s.devices.RecordPushSuccess, and abort or log/return on failure so
success metadata is only updated after finalization succeeds.
In `@migrations/sql/20260701143000_push_devices.sql`:
- Around line 3-36: The push_devices_apple_fields_check constraint is written as
an unconditional AND, so it currently requires every row to be apple instead of
only requiring APNS fields when platform is apple. Update the CHECK in the
push_devices table definition to use a conditional implication pattern, similar
to push_delivery_attempts_delivery_required_check, so non-apple platforms can be
added later without failing this constraint while still enforcing apns_* fields
for apple rows.
---
Nitpick comments:
In `@internal/api/handlers/admin_apple_push.go`:
- Around line 199-224: Relay registration failures are only returned, not
recorded, so add server-side slog logging in the relay registration flow around
h.client.Do and the response parsing path. Log when the HTTP request fails, when
a non-2xx relay response is received, and when json.Unmarshal of the relay
response fails, using the existing relayRegistrationError context
(status/code/message) so operators can diagnose failures later. Keep the
returned errors unchanged, but ensure each failure path emits a clear slog entry
before returning.
In `@internal/notifications/fanout_worker.go`:
- Around line 357-389: `enqueuePushOutbox` is duplicating the profile
de-duplication and push-attempt building logic used elsewhere, so extract shared
helpers to keep the outbox code consistent and easier to maintain. Move the
unique profile collection from `enqueuePushOutbox` and `enqueueWebPushOutbox`
into a helper like `uniqueProfileIDs`, and factor the
device-to-`PushDeliveryAttempt` loop into a reusable builder like
`buildPushAttempts` that can be used here and in `operational_dispatch.go`’s
push path. Keep the existing behavior and symbols such as `InsertedDelivery`,
`PushDeliveryAttempt`, and `PushTriggerDelivery` unchanged while switching the
call sites to the new helpers.
In `@internal/notifications/settings.go`:
- Around line 356-382: PushRelayURL currently repeats the same trailing-slash
normalization already performed in HandleUpdateSetting, so the read path and
write path can drift. Update PushRelayURL in Settings to rely on the stored
value as-is (or extract a shared normalization helper used by both PushRelayURL
and HandleUpdateSetting) so there is a single source of truth for PushRelayURL
trimming and validation.
In `@internal/notifications/webpush_logic_test.go`:
- Around line 21-24: Expand TestBuildNotificationDisplay to explicitly cover the
remaining BuildNotificationDisplay branches for request_fulfilled,
request_approved, and webhook_auto_disabled. Use the existing
BuildNotificationDisplay function and assert the NotificationDisplay-specific
ThreadID and Category fields for each case, since these branches are only
indirectly exercised in TestBuildWebPushPayload today. Keep the current coverage
for episode available, request declined, and unknown type, but add direct
assertions for the missing notification types.
In `@web/src/pages/admin-settings/AdminSettingsLayout.test.tsx`:
- Around line 16-38: Both render helpers are duplicating the same QueryClient
setup, so factor the shared `new QueryClient({ defaultOptions: { queries: {
retry: false } } })` construction into a single helper and reuse it from
`renderLayout` and `renderInteractiveLayout`. Keep the `AdminSettingsLayout`
test wrappers unchanged otherwise, and update both helpers to call the shared
QueryClient factory so future option changes stay consistent.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 409c915c-fe06-46be-a5d8-631b12d44e95
📒 Files selected for processing (30)
internal/api/handlers/admin.gointernal/api/handlers/admin_apple_push.gointernal/api/handlers/admin_apple_push_test.gointernal/api/handlers/notifications.gointernal/api/handlers/notifications_apple_display_test.gointernal/api/handlers/notifications_push_devices.gointernal/api/handlers/notifications_push_devices_test.gointernal/api/router.gointernal/catalog/encrypted_settings_repo.gointernal/catalog/encrypted_settings_repo_test.gointernal/notifications/display.gointernal/notifications/fanout_worker.gointernal/notifications/operational_dispatch.gointernal/notifications/operational_dispatch_test.gointernal/notifications/push_delivery.gointernal/notifications/push_devices.gointernal/notifications/push_devices_test.gointernal/notifications/push_sender.gointernal/notifications/push_sender_test.gointernal/notifications/settings.gointernal/notifications/system.gointernal/notifications/webpush_logic_test.gointernal/notifications/webpush_sender.gomigrations/push_devices_test.gomigrations/sql/20260701143000_push_devices.sqlmigrations/sql/20260701170000_push_delivery_attempts.sqlweb/src/lib/adminSettingsSearch.tsweb/src/pages/admin-settings/AdminSettingsLayout.test.tsxweb/src/pages/admin-settings/NotificationsAdminSettings.test.tsxweb/src/pages/admin-settings/NotificationsAdminSettings.tsx
| if err := h.settings.Set(r.Context(), notifications.SettingPushRelayURL, relayURL); err != nil { | ||
| writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay URL") | ||
| return | ||
| } | ||
| if err := h.settings.Set(r.Context(), notifications.SettingPushRelayDeploymentID, relayResp.DeploymentID); err != nil { | ||
| writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay deployment id") | ||
| return | ||
| } | ||
| if err := h.settings.Set(r.Context(), notifications.SettingPushRelayAPIKey, relayResp.APIKey); err != nil { | ||
| writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay API key") | ||
| return | ||
| } | ||
| if h.system != nil && h.system.Settings != nil { | ||
| h.system.Settings.Invalidate( | ||
| notifications.SettingPushRelayURL, | ||
| notifications.SettingPushRelayDeploymentID, | ||
| notifications.SettingPushRelayAPIKey, | ||
| ) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Non-atomic multi-key settings write can leave relay config inconsistent.
HandleRegisterRelay writes SettingPushRelayURL, SettingPushRelayDeploymentID, and SettingPushRelayAPIKey via three sequential Set calls. If the process crashes or a later call fails (e.g. encryption error, transient DB failure) after an earlier one succeeds, the server ends up with a relay URL that doesn't match the persisted deployment ID/API key — silently breaking previously-working push delivery until an admin retries. Per the upstream contract, EncryptedSettingsRepo.Set encrypts sensitive setting keys (when value is non-empty) before delegating to the inner settings store per-call, with no visible multi-key transaction support.
Consider capturing the previous values up front and rolling back on partial failure, or persisting all three under a single settings entry so the write is atomic.
🔧 Suggested best-effort rollback
+ oldURL, _ := h.settings.Get(r.Context(), notifications.SettingPushRelayURL)
+ oldAPIKey, _ := h.settings.Get(r.Context(), notifications.SettingPushRelayAPIKey)
+
if err := h.settings.Set(r.Context(), notifications.SettingPushRelayURL, relayURL); err != nil {
writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay URL")
return
}
if err := h.settings.Set(r.Context(), notifications.SettingPushRelayDeploymentID, relayResp.DeploymentID); err != nil {
+ _ = h.settings.Set(r.Context(), notifications.SettingPushRelayURL, oldURL)
writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay deployment id")
return
}
if err := h.settings.Set(r.Context(), notifications.SettingPushRelayAPIKey, relayResp.APIKey); err != nil {
+ _ = h.settings.Set(r.Context(), notifications.SettingPushRelayURL, oldURL)
+ _ = h.settings.Set(r.Context(), notifications.SettingPushRelayAPIKey, oldAPIKey)
writeError(w, http.StatusInternalServerError, "settings_error", "Failed to save push relay API key")
return
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/api/handlers/admin_apple_push.go` around lines 156 - 174, Handle the
relay settings update in HandleRegisterRelay as an atomic operation instead of
three independent h.settings.Set calls. Capture the existing values for
notifications.SettingPushRelayURL, notifications.SettingPushRelayDeploymentID,
and notifications.SettingPushRelayAPIKey up front, then if any later write
fails, roll back the already-written keys to their previous values before
returning an error. Keep the cache invalidation in sync only after all three
settings are successfully persisted.
| func (r *PushDeviceRepository) FinalizePushAttempt(ctx context.Context, attemptID, outcome string, attemptNumber int, relayRequestID string, upstreamStatus *int, upstreamReason, failureMessage string, nextRetryAt *time.Time) (*PushDeliveryAttempt, error) { | ||
| var relayRequestIDPtr *string | ||
| if relayRequestID != "" { | ||
| relayRequestIDPtr = &relayRequestID | ||
| } | ||
| var upstreamReasonPtr *string | ||
| if upstreamReason != "" { | ||
| upstreamReasonPtr = &upstreamReason | ||
| } | ||
| var failureMessagePtr *string | ||
| if failureMessage != "" { | ||
| failureMessagePtr = &failureMessage | ||
| } | ||
| rows, err := r.pool.Query(ctx, ` | ||
| UPDATE push_delivery_attempts | ||
| SET outcome = $2, | ||
| attempt_number = $3, | ||
| attempted_at = now(), | ||
| next_retry_at = $4, | ||
| relay_request_id = $5, | ||
| upstream_status = $6, | ||
| upstream_reason = left($7, 256), | ||
| failure_message = left($8, 256), | ||
| updated_at = now() | ||
| WHERE id = $1`+pushAttemptReturning, | ||
| attemptID, outcome, attemptNumber, nextRetryAt, relayRequestIDPtr, upstreamStatus, upstreamReasonPtr, failureMessagePtr) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Guard finalization against stale workers.
FinalizePushAttempt updates by id only. If one worker exceeds the claim lease, another worker can reclaim/finalize the same row, and the stale worker can later overwrite the newer outcome. Add an optimistic guard on the claimed state and previous attempt number.
Proposed fix
- WHERE id = $1`+pushAttemptReturning,
- attemptID, outcome, attemptNumber, nextRetryAt, relayRequestIDPtr, upstreamStatus, upstreamReasonPtr, failureMessagePtr)
+ WHERE id = $1
+ AND outcome = $9
+ AND attempt_number = $3 - 1`+pushAttemptReturning,
+ attemptID, outcome, attemptNumber, nextRetryAt, relayRequestIDPtr, upstreamStatus, upstreamReasonPtr, failureMessagePtr, PushOutcomeRetrying)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (r *PushDeviceRepository) FinalizePushAttempt(ctx context.Context, attemptID, outcome string, attemptNumber int, relayRequestID string, upstreamStatus *int, upstreamReason, failureMessage string, nextRetryAt *time.Time) (*PushDeliveryAttempt, error) { | |
| var relayRequestIDPtr *string | |
| if relayRequestID != "" { | |
| relayRequestIDPtr = &relayRequestID | |
| } | |
| var upstreamReasonPtr *string | |
| if upstreamReason != "" { | |
| upstreamReasonPtr = &upstreamReason | |
| } | |
| var failureMessagePtr *string | |
| if failureMessage != "" { | |
| failureMessagePtr = &failureMessage | |
| } | |
| rows, err := r.pool.Query(ctx, ` | |
| UPDATE push_delivery_attempts | |
| SET outcome = $2, | |
| attempt_number = $3, | |
| attempted_at = now(), | |
| next_retry_at = $4, | |
| relay_request_id = $5, | |
| upstream_status = $6, | |
| upstream_reason = left($7, 256), | |
| failure_message = left($8, 256), | |
| updated_at = now() | |
| WHERE id = $1`+pushAttemptReturning, | |
| attemptID, outcome, attemptNumber, nextRetryAt, relayRequestIDPtr, upstreamStatus, upstreamReasonPtr, failureMessagePtr) | |
| func (r *PushDeviceRepository) FinalizePushAttempt(ctx context.Context, attemptID, outcome string, attemptNumber int, relayRequestID string, upstreamStatus *int, upstreamReason, failureMessage string, nextRetryAt *time.Time) (*PushDeliveryAttempt, error) { | |
| var relayRequestIDPtr *string | |
| if relayRequestID != "" { | |
| relayRequestIDPtr = &relayRequestID | |
| } | |
| var upstreamReasonPtr *string | |
| if upstreamReason != "" { | |
| upstreamReasonPtr = &upstreamReason | |
| } | |
| var failureMessagePtr *string | |
| if failureMessage != "" { | |
| failureMessagePtr = &failureMessage | |
| } | |
| rows, err := r.pool.Query(ctx, ` | |
| UPDATE push_delivery_attempts | |
| SET outcome = $2, | |
| attempt_number = $3, | |
| attempted_at = now(), | |
| next_retry_at = $4, | |
| relay_request_id = $5, | |
| upstream_status = $6, | |
| upstream_reason = left($7, 256), | |
| failure_message = left($8, 256), | |
| updated_at = now() | |
| WHERE id = $1 | |
| AND outcome = $9 | |
| AND attempt_number = $3 - 1`+pushAttemptReturning, | |
| attemptID, outcome, attemptNumber, nextRetryAt, relayRequestIDPtr, upstreamStatus, upstreamReasonPtr, failureMessagePtr, PushOutcomeRetrying) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/notifications/push_delivery.go` around lines 286 - 311,
FinalizePushAttempt currently updates push_delivery_attempts by id only, so a
stale worker can overwrite a newer result after lease expiry. Update the
FinalizePushAttempt query to include an optimistic guard on the previously
claimed state and attempt number, using the existing attemptNumber parameter
plus the row’s claim/finalization fields from PushDeviceRepository. Ensure the
UPDATE only applies when the row still matches the expected in-flight attempt,
and handle the no-row-updated case as a stale finalize rather than success.
| environment := strings.ToLower(strings.TrimSpace(input.APNsEnvironment)) | ||
| if environment != APNsEnvironmentProd && environment != APNsEnvironmentSandbox { | ||
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_environment must be production or sandbox", ErrPushDeviceInvalid) | ||
| } | ||
|
|
||
| topic := strings.TrimSpace(input.APNsTopic) | ||
| if topic == "" { | ||
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is required", ErrPushDeviceInvalid) | ||
| } | ||
| if topic != ApplePushTopicSilo { | ||
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is not supported", ErrPushDeviceUnsupported) | ||
| } | ||
|
|
||
| pushMode := strings.TrimSpace(input.PushMode) | ||
| if pushMode == "" { | ||
| pushMode = PushModePrivatePush | ||
| } | ||
| switch pushMode { | ||
| case PushModeOff, PushModeInAppOnly, PushModePrivatePush: | ||
| default: | ||
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: push_mode is not supported", ErrPushDeviceUnsupported) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Inconsistent case normalization for push_mode.
APNsEnvironment is lowercased before comparison (line 141), but PushMode is only trimmed (line 154) and compared with case-sensitive switch. A client sending "Private_Push" or "OFF" will be rejected with ErrPushDeviceUnsupported even though the equivalent lowercase value is valid — an inconsistency with the environment field's normalization and untested by the current test suite (which only exercises exact-case constants).
🐛 Proposed fix
- pushMode := strings.TrimSpace(input.PushMode)
+ pushMode := strings.ToLower(strings.TrimSpace(input.PushMode))
if pushMode == "" {
pushMode = PushModePrivatePush
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| environment := strings.ToLower(strings.TrimSpace(input.APNsEnvironment)) | |
| if environment != APNsEnvironmentProd && environment != APNsEnvironmentSandbox { | |
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_environment must be production or sandbox", ErrPushDeviceInvalid) | |
| } | |
| topic := strings.TrimSpace(input.APNsTopic) | |
| if topic == "" { | |
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is required", ErrPushDeviceInvalid) | |
| } | |
| if topic != ApplePushTopicSilo { | |
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is not supported", ErrPushDeviceUnsupported) | |
| } | |
| pushMode := strings.TrimSpace(input.PushMode) | |
| if pushMode == "" { | |
| pushMode = PushModePrivatePush | |
| } | |
| switch pushMode { | |
| case PushModeOff, PushModeInAppOnly, PushModePrivatePush: | |
| default: | |
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: push_mode is not supported", ErrPushDeviceUnsupported) | |
| } | |
| environment := strings.ToLower(strings.TrimSpace(input.APNsEnvironment)) | |
| if environment != APNsEnvironmentProd && environment != APNsEnvironmentSandbox { | |
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_environment must be production or sandbox", ErrPushDeviceInvalid) | |
| } | |
| topic := strings.TrimSpace(input.APNsTopic) | |
| if topic == "" { | |
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is required", ErrPushDeviceInvalid) | |
| } | |
| if topic != ApplePushTopicSilo { | |
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: apns_topic is not supported", ErrPushDeviceUnsupported) | |
| } | |
| pushMode := strings.ToLower(strings.TrimSpace(input.PushMode)) | |
| if pushMode == "" { | |
| pushMode = PushModePrivatePush | |
| } | |
| switch pushMode { | |
| case PushModeOff, PushModeInAppOnly, PushModePrivatePush: | |
| default: | |
| return ApplePushDeviceRegistration{}, fmt.Errorf("%w: push_mode is not supported", ErrPushDeviceUnsupported) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/notifications/push_devices.go` around lines 141 - 162, Normalize
push_mode the same way as APNsEnvironment in push_devices.go: in the
registration validation path, trim and lowercase the value before the switch so
case-insensitive inputs are accepted consistently. Update the PushDevices
registration logic around the pushMode handling to compare against the
normalized value, while still defaulting empty input to PushModePrivatePush.
Also adjust or add tests for the ApplePushDeviceRegistration flow to cover
mixed-case push_mode values like “OFF” and “Private_Push”.
| if result.OK { | ||
| updated, _ := s.devices.FinalizePushAttempt(ctx, attempt.ID, PushOutcomeDelivered, attemptNumber, | ||
| result.RelayRequestID, &result.HTTPStatus, result.UpstreamReason, "", nil) | ||
| _ = s.devices.RecordPushSuccess(ctx, device.ID) | ||
| return updated |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Handle finalization failure before recording success.
If the relay accepts the push but FinalizePushAttempt fails, the attempt remains retryable and may be sent again later. Don’t ignore this error; log/return before updating device success metadata.
Proposed fix
if result.OK {
- updated, _ := s.devices.FinalizePushAttempt(ctx, attempt.ID, PushOutcomeDelivered, attemptNumber,
+ updated, err := s.devices.FinalizePushAttempt(ctx, attempt.ID, PushOutcomeDelivered, attemptNumber,
result.RelayRequestID, &result.HTTPStatus, result.UpstreamReason, "", nil)
+ if err != nil && ctx.Err() == nil {
+ s.logger.Warn("finalize delivered push attempt failed", "attempt_id", attempt.ID, "error", err)
+ return nil
+ }
_ = s.devices.RecordPushSuccess(ctx, device.ID)
return updated
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/notifications/push_sender.go` around lines 133 - 137, The push
success path in push_sender.go ignores the error from FinalizePushAttempt, which
can mark the device as successful even when the attempt was not finalized. In
the result.OK branch of the push sender logic, check and handle the error
returned by s.devices.FinalizePushAttempt before calling
s.devices.RecordPushSuccess, and abort or log/return on failure so success
metadata is only updated after finalization succeeds.
| CREATE TABLE public.push_devices ( | ||
| id text PRIMARY KEY, | ||
| user_id integer NOT NULL, | ||
| profile_id text NOT NULL, | ||
| device_id varchar(128) NOT NULL, | ||
| platform text NOT NULL, | ||
| provider text NOT NULL, | ||
| apns_environment text, | ||
| apns_topic text, | ||
| apns_token_ciphertext text, | ||
| apns_token_hash text, | ||
| server_device_id text NOT NULL, | ||
| push_mode text NOT NULL DEFAULT 'private_push', | ||
| enabled boolean NOT NULL DEFAULT true, | ||
| last_seen_at timestamptz, | ||
| last_success_at timestamptz, | ||
| last_failure_at timestamptz, | ||
| last_failure_code text, | ||
| created_at timestamptz NOT NULL DEFAULT now(), | ||
| updated_at timestamptz NOT NULL DEFAULT now(), | ||
| CONSTRAINT push_devices_profile_device_platform_key UNIQUE (profile_id, device_id, platform), | ||
| CONSTRAINT push_devices_server_device_id_key UNIQUE (server_device_id), | ||
| CONSTRAINT push_devices_platform_check CHECK (platform IN ('apple')), | ||
| CONSTRAINT push_devices_provider_check CHECK (provider IN ('silo_relay')), | ||
| CONSTRAINT push_devices_apns_environment_check CHECK (apns_environment IN ('production', 'sandbox')), | ||
| CONSTRAINT push_devices_push_mode_check CHECK (push_mode IN ('off', 'in_app_only', 'private_push')), | ||
| CONSTRAINT push_devices_apple_fields_check CHECK ( | ||
| platform = 'apple' | ||
| AND apns_environment IS NOT NULL | ||
| AND apns_topic IS NOT NULL | ||
| AND apns_token_ciphertext IS NOT NULL | ||
| AND apns_token_hash IS NOT NULL | ||
| ) | ||
| ); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
push_devices_apple_fields_check is an unconditional AND, not a per-platform implication.
Lines 29-35 read:
CONSTRAINT push_devices_apple_fields_check CHECK (
platform = 'apple'
AND apns_environment IS NOT NULL
...
)This forces every row to have platform = 'apple' — it's not "if apple then these fields are required" (which the nullable apns_* columns imply is the intent), it's "every row must be apple AND have these fields." Today this is harmless only because push_devices_platform_check already restricts platform IN ('apple'). But the moment a future migration adds another platform (e.g. android), any such row will violate this constraint and fail to insert, since it isn't 'apple'. The sibling migration in this same PR (push_delivery_attempts_delivery_required_check) correctly implements this same "required-if" pattern as an implication ((trigger_type = 'delivery' AND ... IS NOT NULL) OR trigger_type = 'test'), so this constraint should follow the same shape.
🐛 Proposed fix
CONSTRAINT push_devices_apple_fields_check CHECK (
- platform = 'apple'
- AND apns_environment IS NOT NULL
- AND apns_topic IS NOT NULL
- AND apns_token_ciphertext IS NOT NULL
- AND apns_token_hash IS NOT NULL
+ platform != 'apple'
+ OR (
+ apns_environment IS NOT NULL
+ AND apns_topic IS NOT NULL
+ AND apns_token_ciphertext IS NOT NULL
+ AND apns_token_hash IS NOT NULL
+ )
)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@migrations/sql/20260701143000_push_devices.sql` around lines 3 - 36, The
push_devices_apple_fields_check constraint is written as an unconditional AND,
so it currently requires every row to be apple instead of only requiring APNS
fields when platform is apple. Update the CHECK in the push_devices table
definition to use a conditional implication pattern, similar to
push_delivery_attempts_delivery_required_check, so non-apple platforms can be
added later without failing this constraint while still enforcing apns_* fields
for apple rows.
- Gate the capability endpoint's apple_push availability on the admin delivery toggle, matching web push: Available now means setup will actually deliver. - Reject direct admin writes to push_relay_deployment_id/api_key; the relay issues them as a pair during registration and a lone write desyncs them (and poisons the next rotation request). - Purge a device's registrations under other profiles when it re-registers, so a profile switch on a shared device stops the old profile's pushes (attempts cascade); adds a DB-backed test. - Extract the shared channelDispatcher core + retry sweep and rebuild the webhook/web push/Apple push dispatchers on it instead of keeping three copies of the worker-pool/retry loop. - Deduplicate relay URL validation (admin setting + register flow) and the push outbox attempt-building loops behind shared helpers. - Cap free-text decline reasons in notification display bodies. - Fix TestHandleApplePushDisplayDB expectations to match the shared display copy (test previously failed under SILO_TEST_DATABASE_URL). Co-Authored-By: Claude Fable 5 <[email protected]>
|
Pushed 9810c79 addressing the code-review findings:
Verified with 🤖 Generated with Claude Code |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/notifications/webpush_sender.go (1)
9-10: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick winKeep
fmtimported whilefmt.Sprintfis still used.The import cleanup removed
fmt, but Line 191 still callsfmt.Sprintf, so this file will not compile.Proposed fix
import ( "context" + "fmt" "log/slog" "net/http" "time" )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/notifications/webpush_sender.go` around lines 9 - 10, The import cleanup in webpush_sender.go removed fmt even though WebpushSender still uses fmt.Sprintf, so the file no longer compiles. Restore the fmt import alongside the existing imports and verify the formatting call in the WebpushSender path still resolves correctly without changing the current string construction logic.
🧹 Nitpick comments (1)
internal/notifications/display.go (1)
122-133: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueGuard against
max <= 0to avoid a slice panic.
runes[:max-1]underflows to a negative index ifmaxis ever0or negative. The only current call site passes the fixeddisplayBodyMaxLen(240), so this isn't reachable today, but the helper is general-purpose and a future caller with a smaller/zero bound would panic instead of degrading gracefully.🛡️ Optional defensive guard
func truncateDisplayText(s string, max int) string { + if max <= 0 { + return "" + } runes := []rune(s) if len(runes) <= max { return s } return strings.TrimSpace(string(runes[:max-1])) + "…" }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/notifications/display.go` around lines 122 - 133, truncateDisplayText should defensively handle max <= 0 before slicing runes, since runes[:max-1] can panic on zero or negative bounds. Update the helper to return a safe fallback (for example, the original string or an empty/truncated result without slicing) when max is non-positive, while keeping the existing behavior for valid limits; this change belongs in truncateDisplayText near displayBodyMaxLen.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/api/handlers/admin.go`:
- Around line 2152-2164: Direct writes to notifications.push_relay_url in
admin.go still bypass the push relay registration flow and can leave the stored
URL out of sync with the deployment ID/API key pair. Update the settings
handling in the same switch that already rejects
notifications.SettingPushRelayDeploymentID and
notifications.SettingPushRelayAPIKey so that notifications.SettingPushRelayURL
is also rejected with a bad_request and a message pointing to
HandleRegisterRelay / POST /admin/notifications/push/relay/register. Keep
HandleRegisterRelay as the only path that persists the URL, deployment ID, and
API key together.
---
Outside diff comments:
In `@internal/notifications/webpush_sender.go`:
- Around line 9-10: The import cleanup in webpush_sender.go removed fmt even
though WebpushSender still uses fmt.Sprintf, so the file no longer compiles.
Restore the fmt import alongside the existing imports and verify the formatting
call in the WebpushSender path still resolves correctly without changing the
current string construction logic.
---
Nitpick comments:
In `@internal/notifications/display.go`:
- Around line 122-133: truncateDisplayText should defensively handle max <= 0
before slicing runes, since runes[:max-1] can panic on zero or negative bounds.
Update the helper to return a safe fallback (for example, the original string or
an empty/truncated result without slicing) when max is non-positive, while
keeping the existing behavior for valid limits; this change belongs in
truncateDisplayText near displayBodyMaxLen.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7a41a38a-f05e-4497-9f61-62f64f60374b
📒 Files selected for processing (16)
internal/api/handlers/admin.gointernal/api/handlers/admin_apple_push.gointernal/api/handlers/notifications.gointernal/api/handlers/notifications_apple_display_test.gointernal/notifications/channel_dispatcher.gointernal/notifications/display.gointernal/notifications/fanout_worker.gointernal/notifications/operational_dispatch.gointernal/notifications/push_delivery.gointernal/notifications/push_devices.gointernal/notifications/push_devices_test.gointernal/notifications/push_sender.gointernal/notifications/push_sender_test.gointernal/notifications/settings.gointernal/notifications/webhook_dispatcher.gointernal/notifications/webpush_sender.go
🚧 Files skipped from review as they are similar to previous changes (10)
- internal/notifications/operational_dispatch.go
- internal/api/handlers/notifications_apple_display_test.go
- internal/notifications/push_sender_test.go
- internal/notifications/settings.go
- internal/notifications/push_devices_test.go
- internal/notifications/fanout_worker.go
- internal/api/handlers/notifications.go
- internal/notifications/push_delivery.go
- internal/api/handlers/admin_apple_push.go
- internal/notifications/push_devices.go
…only Direct writes to notifications.push_relay_url via the admin settings endpoint bypassed the relay registration flow, letting the stored URL drift out of sync with the deployment id / API key pair the relay minted for it. Reject the URL alongside the deployment id and API key in the settings handler; POST /admin/notifications/push/relay/register remains the only path that persists all three together. The admin UI's Relay URL field now edits local draft state and is applied by the Register/Rotate action instead of the settings save. Co-Authored-By: Claude Fable 5 <[email protected]>
* Add push notifications support * fix(notifications): address push notification review findings - Gate the capability endpoint's apple_push availability on the admin delivery toggle, matching web push: Available now means setup will actually deliver. - Reject direct admin writes to push_relay_deployment_id/api_key; the relay issues them as a pair during registration and a lone write desyncs them (and poisons the next rotation request). - Purge a device's registrations under other profiles when it re-registers, so a profile switch on a shared device stops the old profile's pushes (attempts cascade); adds a DB-backed test. - Extract the shared channelDispatcher core + retry sweep and rebuild the webhook/web push/Apple push dispatchers on it instead of keeping three copies of the worker-pool/retry loop. - Deduplicate relay URL validation (admin setting + register flow) and the push outbox attempt-building loops behind shared helpers. - Cap free-text decline reasons in notification display bodies. - Fix TestHandleApplePushDisplayDB expectations to match the shared display copy (test previously failed under SILO_TEST_DATABASE_URL). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(notifications): route push relay URL writes through registration only Direct writes to notifications.push_relay_url via the admin settings endpoint bypassed the relay registration flow, letting the stored URL drift out of sync with the deployment id / API key pair the relay minted for it. Reject the URL alongside the deployment id and API key in the settings handler; POST /admin/notifications/push/relay/register remains the only path that persists all three together. The admin UI's Relay URL field now edits local draft state and is applied by the Register/Rotate action instead of the settings save. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
Summary
Testing
Summary by CodeRabbit
New Features
Bug Fixes