Skip to content

feat(messaging): wake APNS/FCM devices for Appwrite (MQTT) push - #14302

Merged
ArnabChatterjee20k merged 31 commits into
mainfrom
apns-fcm-fallback-wake-up-signal
Oct 14, 2026
Merged

ArnabChatterjee20k merged 31 commits into
mainfrom
apns-fcm-fallback-wake-up-signal

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

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).

  • Silent envelope — buildPushMessage($message, $wake) builds a Push with no title/body, contentAvailable: true, priority: HIGH, and data = {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.
  • Wake-channel whitelist — 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.
  • MQTT-reached users — resolved up front from the bounded explicit recipients (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.
  • User/target-addressed — a wake-channel target of an MQTT-reached user is skipped in the send loop and all their registered wake-channel devices are woken once after the loop, which also covers a device not named in a targetId send. Non-MQTT recipients (and non-wake providers) get the full notification.
  • Topic campaigns — the MQTT-reached users' wake-channel devices are woken per page via 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.
  • Billing — wakes flow through the existing 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: background and apns-priority: 5 — Apple drops a content-available push sent as alert at 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 notification block, 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 — here content-available: 1 with no alert, so the app is woken silently and nothing is shown), and data, our own keys. data must sit at the payload root, beside aps — not inside it — because the app reads custom fields as userInfo["data"]; nested under aps they land at userInfo["aps"]["data"], where the client never looks, so the wake marker is unreadable. This PR moves data from aps.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, Android onMessageReceived) must detect data.type === 'wake' and trigger an MQTT reconnect. This only replays correctly if the client reconnects with a stable push client id (the broker cursor is push:cursor:<project>:<userId>:<clientId>) — tracked separately on the SDK side. Apps should register native targets with the explicit fcm/apns providerId.

Tests

  • packages/messaging/tests/Adapter/Push/FCMTest.php::testSilentWakeIsDataOnly — asserts a wake renders as a data-only FCM message (no notification, content-available, Android high priority, APNs background/priority 5).
  • packages/messaging/tests/Adapter/Push/APNSTest.php::testSilentWakeHasNoAlert — asserts a wake renders with no alert, content-available: 1, and apns-push-type: background / apns-priority: 5 headers.
  • packages/messaging/tests/Adapter/Push/APNSTest.php::testAlertUsesAlertPushType — regression: a regular notification keeps apns-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

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]>
@luxor-code-review

luxor-code-review Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

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.

Files Change
src/Appwrite/Platform/Workers/Messaging.php Adds silent wake task fan-out before provider sends, MQTT-user resolution, and usage accounting alongside the existing batched send path.
packages/messaging/tests/Adapter/Push/APNSTest.php Covers APNs wake payload construction, including headers and content-available handling.
packages/messaging/tests/Adapter/Push/FCMTest.php Covers FCM data-only wake message shape and priority fields.

One high-severity issue in the APNs wake headers and one medium-severity pagination issue remain to address.

Reviewed commit: e7cf993

@ghost

ghost commented Oct 9, 2026 •

Copy link
Copy Markdown

🟡 Tier B · Needs changes before merging

Two previously reported wake-routing issues remain open.

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.

Verdict New comments Fixed Still open
💬 Commented 0 0 2
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
File Change
src/Appwrite/Platform/Workers/Messaging.php Resolves MQTT-reached users and routes wake-channel pushes separately from full notifications, with distinct delivery accounting.
packages/messaging/src/Adapter/Push/APNS.php Renders silent background pushes with APNS background headers and custom data at the payload root.
packages/messaging/src/Adapter/Push/FCM.php Renders data-only wakes with Android priority and APNS background headers.
packages/messaging/src/Messages/Push.php Adds mutable-content support to push messages.
packages/messaging/tests/Adapter/Push/APNSTest.php Covers APNS background, alert, and mutable-content payload behavior.
packages/messaging/tests/Adapter/Push/FCMTest.php Covers FCM data-only wake payloads and platform-specific fields.
⏳ Still open from earlier reviews · 2

Merged main (4c524bb); no changes to this PR's code since 136fa68 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · 1 blocking finding to address. Summary

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]>
@github-actions

github-actions Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +255 to +268
$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;
}
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

Addressed the APNs background-delivery finding in 1b9df21.

A content-available push with no alert is now sent as a proper iOS background push: apns-push-type: background + apns-priority: 5 (Apple rejects priority 10 for background). Fixed in both native routes:

  • Direct APNS adapter — no longer hardcodes apns-push-type: alert; detects a no-alert content-available message and sets background type + priority 5. Also moved apns-priority out of the JSON body (where APNs ignores it) into the HTTP header.
  • FCM adapter — the APNs side of a data-only content-available message gets apns-push-type: background + apns-priority: 5, while Android keeps high priority so the data wake still arrives promptly.

New unit tests lock the background headers on both adapters and a regression test keeps the regular alert path on apns-push-type: alert.

@hansi-codes review

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

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]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

Addressed the per-page $mqttUsers finding in 545d6e3.

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 $sequence pages is still recognised and the split doesn't send a duplicate full push.

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 streamRecipients() is designed to avoid. Campaigns compute their MQTT-reached set per page (and wakeTasks() dedups within a page); the only residual is that a user whose campaign targets span a 5000-row page boundary may get a second silent, harmless wake — a deliberate trade for bounded memory.

Both of the APNs/background findings are fixed in 1b9df21 (background push type + priority 5, with unit tests). @hansi-codes review @tenki-reviewer review

@luxor-code-review

luxor-code-review Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (2)

  • 🟡 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

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.

Files Change
src/Appwrite/Platform/Workers/Messaging.php Adds MQTT-reached-user detection, per-page wake task scheduling, and wake-aware delivery/billing accounting
packages/messaging/src/Adapter/Push/APNS.php, packages/messaging/src/Adapter/Push/FCM.php Support data-only silent wake payloads (background push headers / Android priority handling)
packages/messaging/tests/Adapter/Push/APNSTest.php, packages/messaging/tests/Adapter/Push/FCMTest.php Test coverage for the new wake payload behavior

Reviewed commit: 545d6e3

@github-actions

github-actions Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → apns-fcm-fallback-wake-up-signal (after).

Metric Before After Change
🚀 Requests/sec 206.4 208.79 ⚪ +1.2%
⏱️ Latency P50 81.66 ms 81.95 ms ⚪ +0.3%
⏱️ Latency P95 201.43 ms 194.92 ms ⚪ -3.2%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 81.95 194.92 13,224 208.79 -6.51
Account 147.37 276.52 696 11.51 -30.02
TablesDB 77.12 139.84 7,192 116.36 -13.05
Storage 81.24 181.47 3,480 57.84 +20.54
Functions 123.02 240.18 1,856 31.36 +2.7

Top API waits (after)

API request Max wait (ms)
tablesdb.rows.delete 407.59
functions.create 404.3
account.name.update 376.18
functions.variables.create 364.34
functions.variables.update 355.92

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · See the inline comments. Summary

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]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

Both findings fixed in 84e1ff8:

  1. Null-providerId native targets — wakeTasks no longer filters on isNotNull('providerId'). It fetches every push target for the MQTT-reached users and classifies each by its resolved provider: a target inheriting the default is woken when that default is APNS/FCM, and skipped only when it resolves to the Appwrite (MQTT) provider (no device token).

  2. Background classifier — a silent/background push is now required to have no sound, critical, or badge in addition to no title/body, since APNs rejects a background push carrying those. A contentAvailable push with a badge/sound stays an alert push. Added testContentAvailableWithBadgeStaysAlert to lock it.

@hansi-codes review @tenki-reviewer review

@luxor-code-review

luxor-code-review Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

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 apns-push-type: background with priority 5; FCM data-only with a minimal APNs config), and reworks the Messaging worker to fan out auxiliary wake tasks to native push devices of users already reached over MQTT, keeping those sends out of delivery status and billing.

Files Change
packages/messaging/src/Adapter/Push/APNS.php, FCM.php Detect content-available-only pushes and emit background-type payloads/headers per provider requirements.
packages/messaging/tests/Adapter/Push/APNSTest.php, FCMTest.php Add unit tests covering the background payload/header construction for both adapters.
src/Appwrite/Platform/Workers/Messaging.php Page recipients, classify MQTT-reached users, and dispatch silent wake tasks to native devices alongside the normal send pipeline.

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

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · See the inline comments. Summary

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · See the inline comments. Summary

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +276 to +317
@@ -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;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Comment on lines 350 to 354
if (!$perUser && $pageMqttUsers !== []) {
foreach ($this->wakeTasks($pageMqttUsers, $providers, $default, $dbForProject, $project, $message, $publisherForUsage, $semaphore) as $task) {
$tasks[] = $task;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is fixed as well

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +330 to +343
$tasks[] = fn (): array => $semaphore->withLock(
fn (): array => $this->sendBatch(
$batch,
$message,
$provider,
$resolvedProviderType,
$adapter,
$dbForProject,
$project,
$publisherForUsage,
$attachments,
$wake
)
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Comment on lines +275 to +277
if ($perUser) {
$mqttUsers += $pageMqttUsers;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

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 mqttReachedUsers() for the bounded user-/target-addressed recipients, so the per-user wake/full split is order-independent — a native target on an earlier $sequence page than the user's Appwrite target is no longer sent full-then-duplicated. Topic campaigns stay per-page (unbounded subscribers).

Fixed — APNs custom data placement (hansi #2). data moved from aps.data to the payload root beside aps, so an iOS handler reads it as userInfo["data"]["type"]. Test updated to assert root placement and absence under aps.

Positions on the remaining two (deliberate trade-offs, not oversights):

  • Topic wake re-send/re-bill across pages (tenki). A complete cross-page dedup for campaigns requires remembering every woken user, i.e. O(topic-size) memory — the exact footprint streamRecipients() streams to avoid. I chose bounded memory: the duplicate is a silent wake (functionally harmless — the device reconnects and replays once regardless), and the billing over-count is bounded by rare page-straddle / multi-topic-in-one-message cases. User-/target-addressed sends have no duplicate (resolved up front). Happy to revisit if you'd prefer the memory cost.

  • Semaphore held across retry backoff (tenki). This is pre-existing behavior of sendBatch/retrySend (backoff sleeps inside withLock) that predates this PR and applies to all sends, not just wakes; releasing the permit during backoff is a change to the shared concurrency/retry hot path best done in its own PR rather than bundled into the wake feature.

@hansi-codes review @tenki-reviewer review

@luxor-code-review

luxor-code-review Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Review complete. 🟠 1 high

💬 Inline comments (1)

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 No tests cover the wake demotion and fanout logic (Messaging.php:308) — The PR adds substantial worker behavior — the up-front $mqttUsers discovery, the per-user wake/full split (src/Appwrite/Platform/Workers/Messaging.php:308-326), and the topic-campaign wakeTasks() path — but no test covers any of it; the new adapter unit tests only assert payload shaping.

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.

Files Change
src/Appwrite/Platform/Workers/Messaging.php Adds MQTT-user discovery, per-user wake/full recipient split, and topic-campaign wake tasks alongside the existing delivery fan-out and usage accounting
packages/messaging/src/Adapter/Push/APNS.php Shapes background (content-available) push payloads and adjusts priority/header handling for silent pushes
packages/messaging/src/Adapter/Push/FCM.php Shapes data-only message payloads consistent with the FCM v1 contract
packages/messaging/tests/Adapter/Push/APNSTest.php, packages/messaging/tests/Adapter/Push/FCMTest.php Unit tests covering the new payload shaping in both adapters

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

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

ArnabChatterjee20k added a commit to appwrite/sdk-generator that referenced this pull request Oct 12, 2026
… 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.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · 1 blocking finding to address. Summary

if ($wake) {
return new Push(
to: $to,
title: self::APPWRITE_PUSH_WAKEUP_SIGNAL_TITLE,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@hansi-codes re-review

@ghost

ghost commented Oct 13, 2026

Copy link
Copy Markdown

Findings

  • 🟠 Wake pushes are still user-visible alerts. buildPushMessage() sets a non-null title and mutableContent: true. That makes the APNs adapter classify the push as an alert, not a background push; without an installed notification service extension to replace it, users see “New message” instead of receiving a silent wake. Mutable content only lets an extension modify the alert—it doesn’t make the push silent.

  • 🟡 Topic campaigns send both a full push and a wake to MQTT-reached users. The native-target suppression branch only runs when $perUser is true; for topic pages, the code passes all identifiers to the normal send at Messaging.php. It then schedules wake tasks for those users at Messaging.php. When a user’s MQTT and native targets are on the same page, their wake-channel device receives both sends, and both are billed.

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.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · See the inline comments. Summary

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@hansi-codes
Re: hansi finding "Wake pushes display a generic alert when no extension is installed" (src/Appwrite/Platform/Workers/Messaging.php:1431):

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 mutable-content push always runs the app's Notification Service Extension, which connects over MQTT, pulls the real message, and replaces the placeholder — so the user sees the real content, not "New message". The extension ships in the Apple SDK (sdk-generator#2012); "New message" is only the fallback if no extension is installed.

On "this affects ordinary background delivery too" — it does not. buildPushMessage(wake: true) is only reached from buildWakeTasks (the wake path); ordinary delivery uses wake: false with the message's own title/body (or data-only), so regular MQTT messages are never turned into a generic alert.

@ghost

ghost commented Oct 13, 2026

Copy link
Copy Markdown

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 mutableContent: true (Messaging.php). mutable-content lets an installed Notification Service Extension modify an alert; without one, iOS displays “New message.” There’s no extension-capability check before APNS targets are demoted to wakes, and APNS is enabled as a wake channel by default (Messaging.php).

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.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · See the inline comments. Summary

… 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.
ghost
ghost previously requested changes Oct 13, 2026

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · 1 blocking finding to address. Summary

if (empty($userId) || !isset($mqttReached[$userId])) {
$recipients[] = $identifier;
} else {
$wakeRecipients[] = $identifier;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

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).

@ghost

ghost commented Oct 13, 2026

Copy link
Copy Markdown

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 (Messaging.php L63-L69), and the wake message always sets a title and mutableContent (Messaging.php L1552-L1566). APNS renders that title as an alert (APNS.php L48-L50); mutable-content lets an installed extension modify it, but does not suppress it when no extension is installed. Since there’s no capability check or opt-in before demoting the full notification, those devices can show “New message” for each MQTT delivery. Please gate this on an explicit capability/opt-in, or make the visible fallback an explicit documented contract rather than describing this as a silent wake.

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@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 mutable-content alert always runs the app's Notification Service Extension, which fetches the real message over MQTT and swaps it into the placeholder before it is shown.

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 New message placeholder. The visible placeholder is therefore the explicit, documented contract (placeholder + extension) rather than a silent wake — the wording has been updated accordingly. No content or messageId travels through Apple; the placeholder carries neither.

@ghost

ghost commented Oct 13, 2026

Copy link
Copy Markdown

This remains a medium finding. The default ['apns'] wake list applies to APNS targets generally, but the worker has no way to know whether a target’s app embeds the notification service extension. It replaces the full notification with an alert titled “New message” (Messaging.php lines 66–69, Messaging.php lines 1556–1566); APNS renders that title as an alert (APNS.php lines 48–50). If the extension is absent or doesn’t replace the alert, the user sees the placeholder and never gets the full push.

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.

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@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 New message placeholder only persists for a client not using the Appwrite SDK, which is outside the supported path.

@ghost

ghost commented Oct 13, 2026

Copy link
Copy Markdown

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.

@ArnabChatterjee20k
ArnabChatterjee20k merged commit 61833ff into main Oct 14, 2026
49 of 51 checks passed
@ArnabChatterjee20k ArnabChatterjee20k mentioned this pull request Oct 16, 2026
4 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants