Repository navigation
fix(push): fetch notification metadata before FCM tears down the service - #100
Conversation
…ice (#100) Data-only pushes register in `private_push` mode, so the relay sends only `silo_delivery_id` — every word of user-visible text comes from the `GET /api/v1/notifications/{id}` lookup the client makes on receipt. When that lookup didn't finish, the notification fell back to "Silo notification" / "Open Silo to view it.", which is what users saw intermittently. `onMessageReceived` only *launched* that lookup on a service-scoped coroutine and returned. FCM's `EnhancedIntentService` completes the wakeful intent and calls `stopSelf()` the instant the callback returns (verified against firebase-messaging 25.1.0 bytecode), so `onDestroy` cancelled the scope mid-request. The cancellation was invisible: `safeApiCall` catches `Exception`, and JVM `CancellationException` is one, so the aborted call came back as a plain `NetworkError`. Everything after the fetch is non-suspending, so the notification still posted — just with the generic strings. Whether the request beat `stopSelf` came down to connection warmth, which is why it looked random. Run both callbacks inline instead. They execute on FCM's own intent-handling executor, never the main thread, so blocking there is the documented contract. `onNewToken` had the same bug and silently dropped token re-registration. - `PUSH_WORK_BUDGET_MS` (8s) bounds each network call. That executor is single-threaded (`FcmExecutors.newIntentHandleExecutor`), so deliveries in a burst queue head-to-tail and a callback must give the thread back promptly. Deliberately under the shared client's 10s connect timeout: a server we haven't connected to by then can't help us inside the window either. - `withinPushBudget` rethrows `CancellationException` ahead of its broad catch, matching the convention in the shared repositories and addressing review feedback on #71 that was never applied. Follow-up, deliberately not folded in: `safeApiCall` swallowing `CancellationException` breaks structured concurrency for ~179 call sites app-wide and deserves its own change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
📝 WalkthroughWalkthroughPush notification handling now stays within the synchronous FCM callback boundary with an 8-second work budget. Notification-row lookup occurs before the notification permission check, and cache misses refresh the repository before retrying the lookup. ChangesPush processing flow
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant FCM
participant SiloFirebaseMessagingService
participant Handler
participant PushNotificationPresenter
participant NotificationsRepository
FCM->>SiloFirebaseMessagingService: onMessageReceived
SiloFirebaseMessagingService->>Handler: runBlocking handle
Handler->>PushNotificationPresenter: present or sync
PushNotificationPresenter->>NotificationsRepository: fetch cached row
PushNotificationPresenter->>NotificationsRepository: refresh on miss
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/push/SiloFirebaseMessagingService.kt (1)
100-113: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider logging on the failure/timeout paths.
DI resolution failure,
handler.handleexceptions, and budget timeouts all fail silently today. Given the motivating bug for this PR was exactly this kind of hard-to-diagnose silent failure, a log line on each of these paths (missing handler/registrar, caught exception, timed-out budget) would materially help future triage without changing behavior.Also applies to: 116-122
🤖 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 `@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/push/SiloFirebaseMessagingService.kt` around lines 100 - 113, Update the Firebase message handling flow around PushMessageHandler resolution and handler.handle so DI resolution failures, caught handling exceptions, and budget timeouts each emit diagnostic log lines before preserving the existing return or swallow behavior. Include relevant exception details where available, and add equivalent logging for missing handler/registrar paths without changing notification handling behavior.
🤖 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.
Nitpick comments:
In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/push/SiloFirebaseMessagingService.kt`:
- Around line 100-113: Update the Firebase message handling flow around
PushMessageHandler resolution and handler.handle so DI resolution failures,
caught handling exceptions, and budget timeouts each emit diagnostic log lines
before preserving the existing return or swallow behavior. Include relevant
exception details where available, and add equivalent logging for missing
handler/registrar paths without changing notification handling behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: cba4592a-1fd3-4e4f-8d20-a2f6d3e65c7c
📒 Files selected for processing (2)
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/push/PushNotificationPresenter.ktandroidApp/src/androidMain/kotlin/org/siloserver/silo/android/push/SiloFirebaseMessagingService.kt
Problem
Push notifications intermittently showed generic text ("Silo notification" / "Open Silo to view it.") instead of the real title, e.g. "Severance — S2E4 The Hidden Hallway".
Android registers in
private_pushmode, so the relay sends a content-free data payload carrying onlysilo_delivery_id. Every word of user-visible text comes from theGET /api/v1/notifications/{id}lookup the client makes on receipt — if that lookup doesn't complete, the notification degrades to the hardcoded fallback inPushNotificationPresenter.Root cause
onMessageReceivedonly launched the lookup on a service-scoped coroutine and returned immediately:serviceScope.launch { handler.handle(...) } // returns instantly ... override fun onDestroy() { serviceScope.cancel() }FCM's
EnhancedIntentServicecompletes the wakeful intent (releasing the wake lock) and callsstopSelf()the instant the callback returns — verified againstfirebase-messaging-25.1.0bytecode.onDestroythen cancelled the scope with the HTTP request still in flight.The cancellation was invisible:
safeApiCallcatchesException, and JVMCancellationExceptionis one, so an aborted call came back as an ordinaryNetworkError. Everything after the fetch is non-suspending, so the notification still posted — just with the generic strings. Whether the request beatstopSelfdepended on connection warmth, cold-start, and whether the device was dozing, which is why it looked random.onNewTokenhad the identical bug, silently dropping FCM token re-registration.Fix
Run both callbacks inline. They execute on FCM's own intent-handling executor, never the main thread, so blocking there is the documented contract rather than a hazard.
PUSH_WORK_BUDGET_MS(8s) bounds each network call. That executor is single-threaded (FcmExecutors.newIntentHandleExecutor), so deliveries in a burst queue head-to-tail and each callback must give the thread back promptly. Set deliberately under the shared client's 10s connect timeout: a server we haven't connected to by then won't produce anything useful inside FCM's window either, and giving up early costs only generic text — while overrunning the window costs the whole notification.withinPushBudgetrethrowsCancellationExceptionahead of its broad catch, matching the convention already used across the shared repositories and addressing review feedback on feat(push): handle relay silo_delivery_id and silo_mode data keys #71 that was never applied.Verification
:androidApp:compileDebugKotlinand the full:androidApp:testDebugUnitTestsuite pass.firebase-messaging-25.1.0:EnhancedIntentServicecallsWakeLockHolder.completeWakefulIntentthenstopSelfResulton task completion;handleIntentOnMainThreadis hardcodedfalse; the intent executor isnewSingleThreadExecutor.withTimeoutOrNullstill returnsnullwhen its block swallows the cancellation, and that post-deadline suspend calls fail fast — so the budget is genuinely enforced throughsafeApiCall's broad catch.Not folded in:
safeApiCallswallowingCancellationExceptionbreaks structured concurrency for ~179 call sites app-wide and deserves its own change.🤖 Generated with Claude Code
Summary by CodeRabbit