Repository navigation
feat(messaging): wake APNS/FCM devices for Appwrite (MQTT) push - #14302
Conversation
A backgrounded mobile app cannot hold the Appwrite push MQTT socket open, so
a push published while it is suspended is missed until it next reconnects. When
a recipient is reached over MQTT, also send a silent wake to that user's
registered APNS/FCM devices so the app reconnects and replays from its cursor.
- buildPushMessage(wake) emits a silent envelope: no title/body, content-available
on iOS / data-only on Android, carrying {type:'wake', messageId} for correlation.
- User/target-addressed: a native push is split per user — woken when the user is
reached over MQTT in the page, full notification otherwise (their only channel).
- Topic campaigns: additively wake the MQTT-reached users' native devices, leaving
native subscribers' own notifications intact.
- Engages off whether an Appwrite provider is among the recipients' providers, not
off which push provider is default.
- Wakes flow through the existing send/usage path, so they are billed normally.
Adds FCM/APNS unit tests locking the silent-wake payload contract.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Review complete. 🟠 1 high · 🟡 1 medium 💬 Inline comments (2)
This PR introduces a silent wake mechanism in the messaging worker so MQTT-connected subscribers are pinged before the platform pushes through APNs and FCM, adding adapter-level wake payload handling plus tests for both adapters. The wake fan-out reuses the worker's coroutine batching and a shared resolved-provider cache, and the send loop pages through targets by sequence cursor.
One high-severity issue in the APNs wake headers and one medium-severity pagination issue remain to address. Reviewed commit: e7cf993 |
🟡 Tier B · Needs changes before merging
Adds silent native push wake signals for users reached through Appwrite MQTT, while keeping the message payload on MQTT and tracking wake delivery separately from message status. APNS and FCM adapters render background/data-only payloads, and the push message supports mutable content for alert notifications. Adapter tests cover silent payloads and APNS alert behavior. Latest changes: The newest commits preserve explicitly addressed MQTT users when combining them with topic-page reachability and avoid scheduling an extra page-level wake for addressed users who will be woken after the send loop.
Fix with agent prompt### Issue 1
src/Appwrite/Platform/Workers/Messaging.php:1431
**Wake pushes display a generic alert when no extension is installed**
This makes every APNS wake an alert, so devices without a notification service extension (which this repository does not provide or configure) show “New message” to users instead of receiving a silent wake. Since the worker cannot tell whether an extension will replace it, this affects ordinary background delivery too and can produce a visible notification for every MQTT message.
### Issue 2
src/Appwrite/Platform/Workers/Messaging.php:317
**Topic-page wakes omit other registered devices**
An Appwrite target can subscribe to a topic independently of the user's APNS target, since subscriptions are per target. This only wakes APNS identifiers present in the topic page, so another registered APNS device receives neither the topic notification nor a wake to reconnect and replay; preserve the user-based wake delivery for all of their wake-channel targets.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.📂 Walkthrough · 6
⏳ Still open from earlier reviews · 2
Merged |
A silent wake is auxiliary to the MQTT delivery, so its outcome must not drive the message's status: a stale APNS/FCM token could otherwise flip an otherwise successful message to FAILED, leak a device token into deliveryErrors, or double-count a recipient already delivered to over MQTT. sendBatch now reports `wake: true`, and the aggregator bills the wake (usage is still enqueued) but excludes it from deliveredTotal/failedTotal/deliveryErrors, tracking it under a message.wake_signals span instead. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Security rulesNo new WARNING or ERROR findings from security rules. 19 existing findings tracked in
|
There was a problem hiding this comment.
Expand to see previous review
Adds silent MQTT wake pushes before APNs/FCM full sends in the messaging worker, but the APNs wake is sent with alert-type headers and cursor pagination can split a wake user across pages.
Key findings
- 🟠 Silent wake sent with
apns-push-type: alertand priority 10 — Messaging.php:1324 - 🟡 Per-page
$mqttUserssplits one user across pages — Messaging.php:255
| $mqttUsers = []; | ||
| if ($providerType === MESSAGE_TYPE_PUSH) { | ||
| foreach ($page as $providerId => $identifiers) { | ||
| if ($this->resolveProvider($dbForProject, $providerId, $providers, $default)->getAttribute('provider') !== 'appwrite') { | ||
| continue; | ||
| } | ||
|
|
||
| foreach ($identifiers as $userId) { | ||
| if (!empty($userId)) { | ||
| $mqttUsers[$userId] = true; | ||
| } | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 bug · medium
Per-page $mqttUsers splits one user across pages
$mqttUsers is computed per streamRecipients() page and reset on each iteration (src/Appwrite/Platform/Workers/Messaging.php:255-268), but user-addressed push targets are streamed in $sequence-ordered pages that cut between a user's targets (src/Appwrite/Platform/Workers/Messaging.php:519-551). A user whose Appwrite-provider target and native-provider target land in different pages gets the MQTT delivery from one page and a full native push from the other, because the native page never sees the user in $mqttUsers — the exact duplicate the wake split is designed to prevent. The per-page wakeTasks() call (src/Appwrite/Platform/Workers/Messaging.php:341-345) likewise re-scans targets and re-sends duplicate silent wakes for users whose targets span pages.
📋 Prompt for AI Agents
In src/Appwrite/Platform/Workers/Messaging.php, $mqttUsers is initialized at line 255 inside the foreach ($this->streamRecipients(...) as [$page, $perUser]) loop and reset on every page, while streamRecipients (lines 519-551) pages user targets by $sequence, so a user's Appwrite-provider target and native-provider target can land in different pages and the native page sends a duplicate full push; the per-page wakeTasks() call (lines 341-345) also re-scans and duplicates wakes for such users. Hoist the $mqttUsers = [] declaration above the loop so it accumulates across pages, ensuring the per-user wake/full split (lines 295-317) and wakeTasks() benefit from the complete MQTT-reached user set.
A content-available push with no alert is an iOS background notification, which Apple only delivers when sent with the `background` push type and priority 5 — it drops one sent as `alert` at priority 10, so the wake never reached suspended devices via either native route. - APNS adapter: a no-alert content-available message now sends apns-push-type `background` and apns-priority `5`. (Also moves apns-priority from the JSON body, where APNs ignores it, into the HTTP header where it belongs.) - FCM adapter: the APNs side of a data-only content-available message gets apns-push-type `background` and apns-priority `5`, while Android keeps its requested (high) priority so the data wake still arrives promptly. - Tests assert the background headers and the regular alert path is unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed the APNs background-delivery finding in 1b9df21. A content-available push with no alert is now sent as a proper iOS background push:
New unit tests lock the background headers on both adapters and a regression test keeps the regular alert path on @hansi-codes review |
User-/target-addressed targets stream in $sequence-ordered pages that can cut between a user's Appwrite and native targets, so a per-page MQTT-reached set could send a full native push on one page and the MQTT delivery on another — the duplicate the wake split exists to prevent. The reached-user set now accumulates across pages for these sends, whose recipients are a bounded explicit set. Topic campaigns are unbounded, so their reached users stay computed per page to keep streaming memory O(page); a user whose campaign targets span pages may get a second (silent, harmless) wake rather than growing an unbounded in-memory set. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed the per-page The MQTT-reached user set now accumulates across pages for user-/target-addressed sends (a bounded, explicit recipient set), so a user whose Appwrite and native targets stream in different I intentionally did not accumulate for topic campaigns: subscribers are unbounded, and holding every reached userId in memory would reintroduce the O(topic-size) footprint that Both of the APNs/background findings are fixed in 1b9df21 (background push type + priority 5, with unit tests). @hansi-codes review @tenki-reviewer review |
|
Review complete. 🟡 2 medium 💬 Inline comments (2)
Push notifications can now be split: users whose MQTT subscription already covers the message get a silent wake push, while everyone else gets the full notification. The worker streams recipients page by page, tracks MQTT-reached users, and issues deferred wake batches for both explicit-recipient and topic campaigns.
Reviewed commit: 545d6e3 |
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
Two review findings: - wakeTasks excluded targets with no providerId, but such a target inherits the default provider — a wakeable device when that default is APNS/FCM. Drop the providerId filter and classify every candidate by its resolved provider, so a native default device is woken while an Appwrite (MQTT) one is still skipped. - A content-available push may legally carry a sound, critical flag, or badge, which APNs forbids on a background push. The silent-push classifier in both adapters now also requires those to be absent, so such a push stays an alert and is not rejected as a malformed background push. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Both findings fixed in 84e1ff8:
@hansi-codes review @tenki-reviewer review |
|
Review complete. 🟡 2 medium 💬 Inline comments (2)
The change teaches the APNs and FCM adapters to render content-available-only messages as true background pushes (APNs
Two medium findings remain around the worker pipeline: the concurrency semaphore permit is held across retry backoff sleeps (starving sibling batches under provider throttling), and native targets can be classified as full sends before the cross-page MQTT-reached user set is complete, causing a duplicated visible push and double billing for straddling users. Reviewed commit: 84e1ff8 |
There was a problem hiding this comment.
Expand to see previous review
This PR adds silent-wake demotion to push delivery so users already reachable over MQTT receive a data-only wake instead of a full native notification, with corresponding payload handling in the APNs and FCM adapters and test coverage.
Key findings
- 🟡 Wake split misses users whose native target precedes Appwrite target — Messaging.php:276
- 🟡 Topic wake re-sends and re-bills tokens across pages and topics — Messaging.php:350
| @@ -273,25 +301,55 @@ private function sendExternalMessage( | |||
| $recipients = \array_keys($userTopics); | |||
| } | |||
|
|
|||
| $batches = \array_chunk( | |||
| $recipients, | |||
| $adapter->getMaxMessagesPerRequest() | |||
| ); | |||
| // A user-/target-addressed native push is split into a woken group (user reached over | |||
| // MQTT) and a full group; everything else is a single full group of [recipients, wake]. | |||
| $groups = [[$recipients, false]]; | |||
| $isNativePush = $resolvedProviderType === MESSAGE_TYPE_PUSH && $provider->getAttribute('provider') !== 'appwrite'; | |||
| if ($perUser && $isNativePush && $mqttUsers !== []) { | |||
| $wakeRecipients = []; | |||
| $fullRecipients = []; | |||
| foreach ($identifiers as $identifier => $userId) { | |||
| if (!empty($userId) && isset($mqttUsers[$userId])) { | |||
| $wakeRecipients[] = $identifier; | |||
| } else { | |||
| $fullRecipients[] = $identifier; | |||
| } | |||
| } | |||
There was a problem hiding this comment.
🟡 bug · medium
Wake split misses users whose native target precedes Appwrite target
The perUser wake/full split consults only $mqttUsers accumulated from pages yielded so far ($mqttUsers += $pageMqttUsers at src/Appwrite/Platform/Workers/Messaging.php:276, read at line 312), but streamRecipients yields pages in ascending $sequence order with no second pass. When a user's native-provider target lands on an earlier page than their Appwrite-provider target — or the user is targetless and reached by the fallback yield after all target pages (line 585) — the native push is sent as a full notification while $mqttUsers does not yet contain them. The comment at lines 246-251 claims cross-page recognition, but the implementation only recognizes users seen on earlier or same pages. Impact: the user receives both the full native push and the MQTT delivery, with usage billed twice — the exact duplicate notification the wake demotion exists to prevent.
📋 Prompt for AI Agents
In src/Appwrite/Platform/Workers/Messaging.php around lines 246-326, the $mqttUsers set is accumulated incrementally (line 276) while pages stream, but the native-push wake/full split (lines 308-317) consults it per page, so a user whose native target appears on an earlier $sequence page than their Appwrite target (or the targetless fallback yielded later in streamRecipients) gets a full push plus the MQTT delivery — a duplicate notification with double billing. Fix by pre-computing the complete $mqttUsers set for user-/target-addressed sends before entering the page loop (a single targets query over the message's user ids with providerType = MESSAGE_TYPE_PUSH, collecting userIds whose resolved provider is the Appwrite provider), and seed $mqttUsers from it before iterating streamRecipients; keep the per-page $pageMqttUsers computation only for the topic-campaign wakeTasks path.
| if (!$perUser && $pageMqttUsers !== []) { | ||
| foreach ($this->wakeTasks($pageMqttUsers, $providers, $default, $dbForProject, $project, $message, $publisherForUsage, $semaphore) as $task) { | ||
| $tasks[] = $task; | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 bug · medium
Topic wake re-sends and re-bills tokens across pages and topics
For topic campaigns, wakeTasks() is called once per streamed page with only that page's $pageMqttUsers and no memory of users woken on earlier pages or topics (src/Appwrite/Platform/Workers/Messaging.php:350-354). A user appearing on more than one page — targets spanning $sequence pagination, or subscriptions to two topics in the same message — has their native tokens re-queried and re-sent as silent wakes once per occurrence, and each sendBatch(..., wake: true) still enqueues full usage metrics for the duplicate batch (lines 824-842). The per-page design bounds memory but not duplicate sends or billing: the same device is woken and billed repeatedly for one campaign.
📋 Prompt for AI Agents
In src/Appwrite/Platform/Workers/Messaging.php, add a job-scoped dedup set (e.g. $wokenUsers) next to $mqttUsers (~line 252); in wakeTasks() (lines 697-785), skip users already present in that set, adding them as they are scheduled, so a user is woken at most once per message even when their subscribers span multiple pages or multiple topics in the same campaign. This prevents repeated identical device wakes and duplicate METRIC_MESSAGES usage enqueues while preserving the existing wake/full result accounting.
There was a problem hiding this comment.
this is fixed as well
There was a problem hiding this comment.
Expand to see previous review
This PR adds silent wake-signal push support so MQTT-reached users' native push devices receive a background notification instead of a duplicate full push.
Key findings
- 🟡 Semaphore permit held across retry backoff sleep — Messaging.php:330
- 🟡 Native targets classified before MQTT set is complete — Messaging.php:275
| $tasks[] = fn (): array => $semaphore->withLock( | ||
| fn (): array => $this->sendBatch( | ||
| $batch, | ||
| $message, | ||
| $provider, | ||
| $resolvedProviderType, | ||
| $adapter, | ||
| $dbForProject, | ||
| $project, | ||
| $publisherForUsage, | ||
| $attachments, | ||
| $wake | ||
| ) | ||
| ); |
There was a problem hiding this comment.
🟡 performance · medium
Semaphore permit held across retry backoff sleep
withLock wraps sendBatch, whose retrySend sleeps for exponential backoff across up to MESSAGE_SEND_MAX_RETRIES attempts while the semaphore permit is still held (src/Appwrite/Platform/Workers/Messaging.php:330-343, backoff sleep at :987-989). A throttled batch therefore pins one of the 10 MESSAGE_SEND_CONCURRENCY permits for the entire backoff duration, so a few provider throttling responses can occupy all permits and starve sibling batches of any concurrency — defeating the comment at line 982 claiming sibling sends keep progressing. The sleep is coroutine-safe, but the permit is never released during it.
📋 Prompt for AI Agents
In src/Appwrite/Platform/Workers/Messaging.php, the task closures at lines 330-343 wrap the entire sendBatch call (including retrySend's exponential-backoff sleeps at lines 985-989) in $semaphore->withLock, so a throttled batch pins one of the MESSAGE_SEND_CONCURRENCY permits for the whole backoff duration and can starve sibling batches. Restructure so the semaphore covers only the adapter send attempt: acquire the permit around the provider call inside retrySend (around line 925 $adapter->send($data)) and release it before the backoff sleep, leaving retries/backoff outside the locked region.
| if ($perUser) { | ||
| $mqttUsers += $pageMqttUsers; | ||
| } |
There was a problem hiding this comment.
🟡 bug · medium
Native targets classified before MQTT set is complete
The comment at src/Appwrite/Platform/Workers/Messaging.php:246-251 says the MQTT-reached user set is accumulated across pages so a user whose Appwrite and native targets land in different $sequence pages is still recognised, but $mqttUsers += $pageMqttUsers (lines 275-277) only merges each page just before that page's native targets are classified (lines 308-326). A native target on an earlier page whose user's Appwrite target appears on a later page is classified as a full send before the user is known to be MQTT-reached, so the device receives a full visible push instead of a silent wake — duplicating the notification the user also gets over MQTT and billing both sends. The same gap covers the targetless fallback and targetIds pages, which streamRecipients yields after the userIds target pages.
📋 Prompt for AI Agents
In src/Appwrite/Platform/Workers/Messaging.php, the per-user wake classification (lines 246-326) merges each page's MQTT-reached users into $mqttUsers (lines 275-277) immediately before classifying that page's native targets (lines 308-326), so a native target on an earlier page whose user's Appwrite target lands on a later page (or in the targetless fallback / targetIds sections yielded later) is sent as a full push instead of a silent wake, duplicating the MQTT delivery and double-billing. Restructure the loop so the complete $mqttUsers set is built in a first pass over streamRecipients before any native target is classified for wake, or otherwise defer classification until all pages have been scanned.
- The per-page MQTT-reached set only recognised a user once their Appwrite
target's page had streamed, so a native target on an earlier $sequence page
was sent as a full notification and then duplicated by the MQTT delivery (and
double-billed). The set is now resolved up front for the bounded user-/target-
addressed recipients via mqttReachedUsers(), so the per-user wake/full split is
order-independent. Topic campaigns stay per page to keep memory O(page).
- APNS adapter placed custom data under the reserved `aps` dictionary, where an
iOS handler's userInfo["data"] never finds it; moved it to the payload root
beside `aps` so the wake's {type, messageId} is readable.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Fixes + positions on the latest round (61d1f6f): Fixed — MQTT recipients discovered before any native page (hansi #1, tenki "native classified before set complete"). The MQTT-reached user set is now resolved up front via Fixed — APNs custom data placement (hansi #2). Positions on the remaining two (deliberate trade-offs, not oversights):
@hansi-codes review @tenki-reviewer review |
|
Review complete. 🟠 1 high 💬 Inline comments (1)
🧹 Nitpicks (1) — 🟢 1 low
This PR introduces a wake-only delivery path in the messaging worker: users whose targets resolve to the Appwrite provider are demoted from full payload delivery to a wake (data-only) push, while native-provider subscribers continue receiving full payloads. It also updates the APNs and FCM adapters to shape silent/background push payloads and adds unit tests for that shaping.
Reviewers should focus on the wake/full recipient split and its interaction with usage accounting, since most of the new worker behavior has no test coverage. Reviewed commit: 61d1f6f |
… Simulator builds as sandbox appwrite/appwrite#14302 puts the wake marker under a top-level data key beside aps, which Push did not read, so it treated the wake as another service's push. It now reads messageId and type under data as well as under appwrite, aps.data or at the top level; a data key without a messageId is still not Appwrite's. A Simulator build has no provisioning profile, so its environment fell back to production, but Simulator device tokens are always sandbox ones and the target pointed the server at the wrong APNs provider. Simulator builds now register as sandbox.
Send a visible placeholder push (generic title + mutable-content) to the Apple wake-channel devices of MQTT-reached users, instead of a silent one. iOS never launches a swiped-away app for a silent push and the Simulator refuses them, but a mutable-content push always runs the app's notification service extension, which pulls the real message over MQTT and swaps it in. No content or message id travels through Apple. Adds a mutableContent flag to the Push message, emitted on the APNs payload by both the APNS and FCM adapters.
| if ($wake) { | ||
| return new Push( | ||
| to: $to, | ||
| title: self::APPWRITE_PUSH_WAKEUP_SIGNAL_TITLE, |
There was a problem hiding this comment.
Wake pushes display a generic alert when no extension is installed
This makes every APNS wake an alert, so devices without a notification service extension (which this repository does not provide or configure) show “New message” to users instead of receiving a silent wake. Since the worker cannot tell whether an extension will replace it, this affects ordinary background delivery too and can produce a visible notification for every MQTT message.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Platform/Workers/Messaging.php
Line: 1431
Comment:
**Wake pushes display a generic alert when no extension is installed**
This makes every APNS wake an alert, so devices without a notification service extension (which this repository does not provide or configure) show “New message” to users instead of receiving a silent wake. Since the worker cannot tell whether an extension will replace it, this affects ordinary background delivery too and can produce a visible notification for every MQTT message.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟠 Major · bug · Reply if this doesn't apply.
|
@hansi-codes re-review |
Findings
|
The native-target suppression only ran for user/target sends. On a topic page, an MQTT-reached user with a wake-channel (apns) target got both the full notification and the wake-up signal, billed twice. Apply the same suppression to topic sends using this page's MQTT-reached users.
|
@hansi-codes This is intended, not a regression. The wake deliberately moved from a silent push to a visible placeholder: iOS will not launch a swiped-away (force-quit) app for a silent push, and the Simulator refuses silent pushes entirely, so a silent wake never reaches those states. A visible On "this affects ordinary background delivery too" — it does not. |
|
The force-quit limitation doesn’t close this finding: it explains why you chose a visible alert, but doesn’t make that alert silent. The worker unconditionally sets the wake title and So APNS targets without that extension can receive a visible placeholder for every MQTT message. Please gate this behavior on explicit client opt-in/capability, or otherwise make the visible fallback an explicit documented contract rather than treating it as a silent wake. |
…ts don't double-send A topic's recipients stream in pages, so a user's Appwrite target and their APNS/FCM target can land on different pages. The per-page MQTT-user list only saw one page, so the page with the Appwrite target woke the user's devices while a later page, seeing no MQTT recipient, also sent the full push -- delivered and billed twice. Resolve the topic's full MQTT-reached user set up front (getMqttUsersFromTopics), alongside the addressed-recipient set (getMqttUsersFromTargets), and use it for both suppression and a single wake after the loop. Rename the two helpers for what each scans.
… the whole set The up-front getMqttUsersFromTopics pass built and held every MQTT-reached user for the topic, and buildWakeTasks then gathered every wake token before sending -- two topic-sized piles in memory, plus a third full scan of the subscribers. Resolve the wake/full split per page instead: each page's own Appwrite targets are known directly, and a single bounded userId IN lookup (capped at the page size) recovers the users whose Appwrite target straddled a page boundary. Topic pages wake their suppressed devices straight from the page, so no whole-topic token set is held. Peak memory is now one page regardless of topic size. Topic wake now reaches a user's wake-channel devices subscribed to the topic rather than every device they own; addressed sends keep waking all of a user's devices.
| if (empty($userId) || !isset($mqttReached[$userId])) { | ||
| $recipients[] = $identifier; | ||
| } else { | ||
| $wakeRecipients[] = $identifier; |
There was a problem hiding this comment.
Topic-page wakes omit other registered devices
An Appwrite target can subscribe to a topic independently of the user's APNS target, since subscriptions are per target. This only wakes APNS identifiers present in the topic page, so another registered APNS device receives neither the topic notification nor a wake to reconnect and replay; preserve the user-based wake delivery for all of their wake-channel targets.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Platform/Workers/Messaging.php
Line: 317
Comment:
**Topic-page wakes omit other registered devices**
An Appwrite target can subscribe to a topic independently of the user's APNS target, since subscriptions are per target. This only wakes APNS identifiers present in the topic page, so another registered APNS device receives neither the topic notification nor a wake to reconnect and replay; preserve the user-based wake delivery for all of their wake-channel targets.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟠 Major · bug · Reply if this doesn't apply.
…e-up-signal # Conflicts: # packages/messaging/src/Adapter/Push/APNS.php
A send that mixes topics with explicit users or targets overwrote the addressed MQTT set with the topic page's own, so an explicitly reached user who was also a topic subscriber got a full push on the topic page plus a wake after the loop. Union the two sets for suppression, and wake only topic-reached users per page -- addressed users are already woken across all their devices after the loop, so one in both sets is not woken twice.
|
Re: @hansi-codes — "Topic-page wakes omit other registered devices" (Messaging.php:317) By design — and this only affects the Appwrite-push (MQTT) + wake-up path, not ordinary delivery. Topic campaigns deliver to the targets subscribed to the topic. A device that never subscribed to the topic is not a recipient of this campaign — it would not receive the message over MQTT even if it were woken — so it is intentionally neither sent the full notification nor woken. The per-page wake wakes exactly the topic-subscribed wake-channel devices of the users reached over MQTT. The previous user-based wake fanned out to every device a user owned, including ones not subscribed to the topic; that fan-out is what we deliberately dropped, together with the whole-topic in-memory set it required (see the bounded-memory finding). |
|
The topic-campaign rationale is sound: waking only wake-channel targets subscribed to that topic avoids waking devices that cannot receive the campaign over MQTT. One issue remains: the default APNS wake is still a visible alert for devices without a Notification Service Extension. The default wake-channel list includes APNS ( |
|
@hansi-codes This is a deliberate choice, and the extension side is handled in the SDK. The visible placeholder is intentional, not a silent wake. iOS does not relaunch a force-quit / swiped-away app for a silent (background) push, and the Simulator refuses them outright — so a silent wake cannot reliably bring the app back to pull the message over MQTT. A visible That extension ships with the Appwrite SDK (sdk-generator#2012), so for apps built on the SDK the user sees the real message, not the |
|
This remains a medium finding. The default I don’t see this requirement or fallback documented in the checked-in push-target registration docs. Please gate demotion on explicit opt-in/capability, or document the extension requirement and visible fallback in the user-facing docs; this should not be described as a silent wake. |
|
@hansi-codes Deliberate choice. In this path the APNS push is only a wake signal — no content or messageId travels through Apple. The real message is always consumed over Appwrite MQTT, and the Appwrite iOS SDK ships the Notification Service Extension that pulls it over MQTT and replaces the placeholder. So extension presence is not something the worker gates on — it is part of the SDK contract, so any supported client has it. The worker cannot (and need not) detect it per target. The |
|
I still consider this open. The SDK-extension contract isn’t documented in this repository, and the push-target docs describe registering a device with an optional provider without mentioning an extension requirement or the visible “New message” fallback (docs). Meanwhile, APNS is a default wake channel (worker), and the wake is rendered as an alert titled “New message” (wake construction, APNS payload). Please add the extension requirement and fallback behavior to the user-facing push-target documentation, or gate demotion on explicit opt-in/capability. A claim that unsupported clients are outside the contract isn’t enough while the checked-in contract doesn’t say that. |
What
Appwrite push delivers over a persistent MQTT connection. A backgrounded mobile app — iOS especially — cannot hold that socket open, so a push published while the app is suspended sits in the ledger until the app next reconnects. This adds a silent wake signal: when a recipient is reached over MQTT, we also send a silent push to that user's wake-channel devices so the OS wakes the app, it reconnects, and replays from its own cursor. The real payload stays in the MQTT channel; the native push only nudges the device.
How it works
All of this lives in the Messaging worker's send loop (
src/Appwrite/Platform/Workers/Messaging.php).buildPushMessage($message, $wake)builds aPushwith no title/body,contentAvailable: true,priority: HIGH, anddata = {type:'wake', messageId}. No title/body → silent on iOS (content-available) and data-only on Android. The payload carries only a wake marker + source message id for client correlation; the client replays from its own stored cursor on reconnect, so no replay offset is sent.APPWRITE_PUSH_WAKEUP_SIGNAL_PROVIDERS(a list in the worker) names the push provider types that act as silent-wake channels, default['apns']. When a user is reached over MQTT, a target of a listed type is not sent a separate full notification — it gets a silent wake instead. A type left out (e.g.fcm) is delivered normally and never woken; an empty list disables the wake entirely. iOS is the channel that can't hold the MQTT socket open, hence the default.mqttReachedUsers()), so the per-user decision is order-independent across streamed pages. A user counts only if they hold a non-expired Appwrite-provider target among the send's recipients (expired targets aren't delivered, so they don't count). Topic campaigns are unbounded, so their MQTT-reached users are resolved per page.targetIdsend. Non-MQTT recipients (and non-wake providers) get the full notification.wakeTasks(); full notifications from non-wake providers are untouched, so a user reached only through a native target is never left with a silent wake and nothing to pull.sendBatch()→ usage path, counted under the provider like any other push; wake outcomes are kept out of the message's own delivery status so a stale token can't fail the message.FCM and APNS message payloads
A wake is
Push(to: [...], title: null, body: null, data: ['type'=>'wake','messageId'=>'<id>'], contentAvailable: true, priority: HIGH). The adapters render it as:A silent/background push on iOS must be sent with
apns-push-type: backgroundandapns-priority: 5— Apple drops a content-available push sent asalertat priority 10 — so both adapters were corrected to render a no-alert content-available message as a background push. Android keeps high priority so a data wake still arrives promptly there.FCM (
packages/messaging/src/Adapter/Push/FCM.php)Data-only message — no
notificationblock, so FCM delivers it in the background:{ "message": { "data": { "type": "wake", "messageId": "<messageId>" }, "android": { "priority": "high" }, "apns": { "payload": { "aps": { "content-available": 1 } }, "headers": { "apns-push-type": "background", "apns-priority": "5" } }, "token": "<device-token>" } }APNS (
packages/messaging/src/Adapter/Push/APNS.php)An APNs payload has two parts:
aps, Apple's reserved dictionary (iOS reads it to decide what to do — herecontent-available: 1with noalert, so the app is woken silently and nothing is shown), anddata, our own keys.datamust sit at the payload root, besideaps— not inside it — because the app reads custom fields asuserInfo["data"]; nested underapsthey land atuserInfo["aps"]["data"], where the client never looks, so the wake marker is unreadable. This PR movesdatafromaps.data(old, wrong) to the payload root:{ "aps": { "content-available": 1 }, "data": { "type": "wake", "messageId": "<messageId>" } }HTTP headers:
apns-topic: <bundleId>,apns-push-type: background,apns-priority: 5,Authorization: Bearer <ES256 JWT>.Client side (SDK)
The wake arrives over the OS push channel, not the SDK transport, so the app's native push handler (iOS
didReceiveRemoteNotification, AndroidonMessageReceived) must detectdata.type === 'wake'and trigger an MQTT reconnect. This only replays correctly if the client reconnects with a stable push client id (the broker cursor ispush:cursor:<project>:<userId>:<clientId>) — tracked separately on the SDK side. Apps should register native targets with the explicitfcm/apnsproviderId.Tests
packages/messaging/tests/Adapter/Push/FCMTest.php::testSilentWakeIsDataOnly— asserts a wake renders as a data-only FCM message (nonotification,content-available, Android high priority, APNsbackground/priority 5).packages/messaging/tests/Adapter/Push/APNSTest.php::testSilentWakeHasNoAlert— asserts a wake renders with noalert,content-available: 1, andapns-push-type: background/apns-priority: 5headers.packages/messaging/tests/Adapter/Push/APNSTest.php::testAlertUsesAlertPushType— regression: a regular notification keepsapns-push-type: alert.These lock the on-the-wire silent-wake contract. The worker's routing is covered by the existing Appwrite-provider push e2e (
testSendPushViaAppwriteProvider); the native wake payload itself is not observable through e2e (native push tests are gated on a real FCM DSN and capture no payload), which is why the contract is locked at the adapter level.🤖 Generated with Claude Code