Skip to content

MOBILE-652: Confirm push delivery by calling callbacks.deliveredUrl - #856

Closed
Vailence wants to merge 10 commits into
mission/transactional-pushfrom
feature/MOBILE-652-push-delivery-confirmation
Closed

Vailence wants to merge 10 commits into
mission/transactional-pushfrom
feature/MOBILE-652-push-delivery-confirmation

Conversation

@Vailence

Copy link
Copy Markdown
Collaborator

When a push carries callbacks.deliveredUrl, the SDK now tells Mindbox that the push reached the phone.

Notification service extension

  • The confirmation is saved to the App Group first. Then the extension sends one POST to the URL with the body {} and the query parameter dateTimeOffset (milliseconds since the push arrived), waiting no longer than 5 s.
  • 2xx or a final 4xx removes the file. 429, 5xx, a redirect, no connection or the timeout leave it for the app. Only https URLs are called, and redirects are not followed.
  • didReceive shows the push once both the image and the answer are in, or at the timeout.
  • pushDelivered(_:) keeps its signature. It writes the file before it returns and does not wait for the answer.
  • New public confirmDelivery(_:) async on MindboxNotificationService, for clients with their own extension who want to wait for the answer.

App

  • On every start and every return to the foreground, the app moves the files the extension left into guaranteed delivery as MobilePush.PushDeliveryConfirmation.
  • Guaranteed delivery calls the same URL with a fresh dateTimeOffset. It needs neither the configuration nor the device UUID.
  • With MOBILE-541, 429 pauses only these confirmations, while 5xx and a lost connection are retried. Other 4xx drop the confirmation.

The code both modules use lives in Mindbox/Shared/PushDeliveryConfirmation/: Foundation only, SPM target MindboxShared, and a path in MindboxNotifications.podspec. The SwiftLint rule shared_code_imports keeps other imports out.

The PR targets feature/MOBILE-541, because it relies on the 429 pause from that branch.

Checked

  • Unit tests on iPhone 17 (iOS 26.2): 2728 of 2731 pass. The 3 failures are in DateFormatMigrationTests, which fail on develop too.
  • SwiftLint --strict over the whole repo: 0 violations.
  • In ios-app on the simulator, against a local mock, checked before the rebase onto MOBILE-541:
    • a file from the extension goes out on cold start with 200;
    • 500 is retried by guaranteed delivery after about 60 s, then 200 with a recomputed dateTimeOffset;
    • 404 is not retried;
    • a return to the foreground picks up a new file.

Not checked on the simulator: the extension path. Simulated pushes (simctl push) do not launch a notification service extension, so this path needs a real APNs push on a device. Unit tests cover it.

https://tracker.yandex.ru/MOBILE-652

Vailence added 3 commits November 19, 2026 17:42
The notification service extension saves the confirmation to the App Group
and sends one POST with the body {} and dateTimeOffset, waiting up to 5 s.
What did not get through, the app hands to guaranteed delivery on start
and on return to the foreground. The code shared by both modules lives
in Mindbox/Shared.
MOBILE-541 pauses on 429 instead of dropping the event, so the queued
confirmation now stays after 429. The test builds DeliveryOperation with
the pause and retry delay managers MOBILE-541 added.
The system may stop the extension right after pushDelivered returns, so
the file for the app is saved synchronously and only the request runs
in a Task.
@Vailence
Vailence requested review from justSmK and sergeysozinov and removed request for justSmK November 19, 2026 12:44
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor
TestsPassed ✅SkippedFailedTime ⏱
Unit tests report3236 ran3236 ✅4m 20s 80ms

Vailence added 6 commits November 19, 2026 19:12
Before the first unlock after a restart the file is closed, and the app
removed it as broken. Only a file that is read but cannot be decoded is
removed now.
A file younger than the wait of the extension plus a second may still be
on its way, so the app takes it a bit later instead of sending the
confirmation a second time.
iOS 17 and later percent-encoded characters a URL may not contain, which
can break its signature. Such a URL now asks for no confirmation on every
iOS, as on iOS 15 and 16 and on Android.
pushDelivered writes the log line again, as before. The rich push guide
tells apps with their own extension to call pushDelivered and allows
didReceive after it, which sent two confirmations for one push.
didReceive prints the same log line itself.
An app that keeps no reference to MindboxNotificationService released it
while didReceive waited for the confirmation, so a push without an image
showed only when the extension ran out of time.

@justSmK justSmK left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Проверил сборками на голове PR (Xcode 27.2): SPM, как у Flutter-плагина; CocoaPods static и use_frameworks! (app + NSE); архивы XCFramework. CocoaPods и обёртки не ломаются.

Главное

  1. Таймаут ГД — MBEventRepository.swift:28.
  2. 5xx от приёмника растит общую задержку ГД — MBEventRepository.swift:192.
  3. Privacy-манифест MindboxNotifications пустой, хотя расширение теперь отправляет данные. Нужная запись — в комментарии ниже. После правки проверить в TestFlight.

Комментарии. Убрать все, кроме doc публичного API для клиента. Общий код и внутренние типы клиенту не видны, причины изменений описываются в коммитах. Шапки с копирайтом остаются.

До мержа

  • Живой прогон через sandbox APNs на симулятор iOS 16+ (simctl push NSE не запускает): пуш без картинки, пуш с картинкой, ответ 500 → досылка из приложения.
  • Зелёный SPM-job. В feature/MOBILE-541 его нет, поэтому на этом PR он не запускался.
  • Обновить описание PR: pushDelivered(_:) больше не пишет файл, а «Foundation only» неверно (есть CryptoKit).

DoD: п.5 разделить на «из расширения ≤3 с» и «из ГД ≤5 с»; п.7 про http переформулировать — iOS и Android http-URL не вызывают.

trackingIdsResolver: TrackingIdsResolver,
trackingHostResolver: TrackingHostResolver) {
trackingHostResolver: TrackingHostResolver,
pushDeliveryConfirmationSender: PushDeliveryConfirmationSender = PushDeliveryConfirmationSender()) {

@justSmK justSmK Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Здесь нет таймаута, работают системные 60 с. Очередь ГД последовательная: если приёмник молчит, install, клики и операции ждут до 60 с на каждое подтверждение. По DoD и как на Android (MOBILE-650) — 5 с:

PushDeliveryConfirmationSender(timeout: PushDeliveryConfirmation.guaranteedDeliveryRequestTimeout)

Comment on lines +185 to +192
case let .failed(statusCode?):
completion(.failure(.serverError(.init(
status: .internalServerError,
errorMessage: "Push delivery confirmation failed",
httpStatusCode: statusCode
))))
case .failed(nil):
completion(.failure(.connectionError))

@justSmK justSmK Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

5xx и редирект сейчас становятся .serverFailure и растят общую задержку ГД до 3600 с. Повторы install, кликов и операций будут ждать до часа из-за сбоя приёмника. С .connectionError подтверждение остаётся в очереди, но паузу и общую задержку не трогает. Тест serverErrorIsServerError поправить вместе с этим.

Suggested change
case let .failed(statusCode?):
completion(.failure(.serverError(.init(
status: .internalServerError,
errorMessage: "Push delivery confirmation failed",
httpStatusCode: statusCode
))))
case .failed(nil):
completion(.failure(.connectionError))
case .failed:
completion(.failure(.connectionError))


/// How long the notification service extension waits for the answer before the push is shown.
/// Until then the app leaves the file of the confirmation alone: the extension may still be sending it.
public static let extensionWaitLimit: TimeInterval = 5

@justSmK justSmK Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

5 с в DoD пришли из Android-задачи. Там это про воркер ГД, и показ пуша запроса не ждёт. Здесь это задержка показа пуша без картинки. Если запрос не прошёл, досылка всё равно будет только при следующем запуске приложения, так что лишние 2 с почти ничего не дают. Предлагаю:

package static let extensionRequestTimeout: TimeInterval = 3
package static let guaranteedDeliveryRequestTimeout: TimeInterval = 5

inFlightWindow считать от первой константы. Нынешние extensionWaitLimit и waitLimit убрать: сейчас у одного значения три имени.

Comment thread Package.swift
// Compiled straight into each module by CocoaPods and the Xcode project; SwiftPM needs it as a target.
.target(
name: "MindboxShared",
path: "Mindbox/Shared"

@justSmK justSmK Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Mindbox/Shared лучше вынести в корень, в MindboxShared/ рядом с SDKVersionProvider/. Тогда уйдёт exclude, а путь будет одинаковым в Package.swift, podspec и правиле линтера.

}

/// `group.cloud.Mindbox.<bundle id of the host app>`, the App Group the SDK documents for the app and its extensions.
static func hostAppGroupIdentifier(bundle: Bundle) -> String? {

@justSmK justSmK Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Поиск host-бандла из .appex дублирует MBUtilitiesFetcher. Если выносить его в общий код, то вместе со строкой формата, иначе MindboxAppGroup ничего не даёт.

@justSmK

justSmK commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

К пункту 3 — запись для MindboxNotifications/PrivacyInfo.xcprivacy:

<key>NSPrivacyCollectedDataTypes</key>
<array>
	<dict>
		<key>NSPrivacyCollectedDataType</key>
		<string>NSPrivacyCollectedDataTypeProductInteraction</string>
		<key>NSPrivacyCollectedDataTypeLinked</key>
		<true/>
		<key>NSPrivacyCollectedDataTypeTracking</key>
		<false/>
		<key>NSPrivacyCollectedDataTypePurposes</key>
		<array>
			<string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>
			<string>NSPrivacyCollectedDataTypePurposeAnalytics</string>
		</array>
	</dict>
</array>
  • ProductInteraction — тот же тип, что у Mindbox для кликов по пушам. Так же заявляют OneSignalExtension и Customer.io.
  • Linked = true: идентификатора устройства в запросе нет, но бэк привязывает доставку к клиенту по ключу сообщения.
  • Цели: AppFunctionality (по подтверждению каскад решает, отправлять ли SMS) и Analytics.
  • NSPrivacyAccessedAPITypes не нужен. Манифест Mindbox не меняем: досылка отправляет те же данные, а privacy report объединяет оба модуля.

После правки загрузить PushOk в TestFlight и проверить privacy report для .appex.

- The shared imports rule also catches `import class/struct Module.Symbol`,
  and its message no longer claims Foundation only.
- EventRoute asserts when asked for the path of a push delivery confirmation.
- PayloadKey.deliveredUrl matches the payload key, PushDeliveryConfirmation.id
  becomes fileName.
- The headers of Mindbox/Shared keep only the copyright.
@justSmK
justSmK dismissed their stale review November 20, 2026 10:28

Замечания остаются комментариями, без блокировки мержа.

Base automatically changed from feature/MOBILE-541 to mission/transactional-push November 20, 2026 11:37
@Vailence Vailence closed this Nov 20, 2026
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