diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a917133..c80c6a04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,7 @@ Minor version. Read the install change below before upgrading. ### Fixed - Expo: an app without `expo-router` can now bundle `@datalyr/react-native/expo`. The entry's lazy `require('expo-router')` had no try/catch, so Metro could not treat it as optional and stopped with `Unable to resolve module expo-router` (also in 1.8.0). Now only `useDatalyrScreenTracking()` needs expo-router, and without it the hook throws a clear error. - iOS: events that carry the IDFA no longer get stuck when the user turns tracking off. The SDK chose `tracking.datalyr.com` (the privacy manifest's tracking domain) from the IDFA saved when the event was built; iOS blocks that host whenever tracking is not authorized at send time, so an event queued while tracking was allowed and sent after it was turned off failed as a network error and held every later event from the device. The host is now chosen when the event is sent, from the live ATT status: the tracking host only with an IDFA and status `authorized`; otherwise the normal host, with `idfa` and `alart` removed and `att_status` / `advertiser_tracking_enabled` set to the status at send time. If the tracking host fails with a network error twice in a row for one event, that event is also tried on the normal host without its IDFA, so it cannot hold the queue. Android is unchanged. +- iOS: in the launch where the user allows tracking, events are no longer sent to a host iOS still blocks. iOS opens `tracking.datalyr.com` only to app launches that start after tracking was allowed. The SDK now uses that host only when tracking was already allowed when the app started; until the next launch, events go to the normal host at once, without the IDFA (`att_status` still reads 3). On the next launch the SDK sends `$att_status` once (`resent: true`) with the IDFA, under one fixed event id per grant, so a kill during that launch cannot count it twice. `alart` without an IDFA follows the same rule: tracking host or removed, never on the normal host. The tracking host now counts as failing on an HTTP error too, not only on a network error. After two failures in a row the event goes to the normal host without the IDFA, and other IDFA events then skip the tracking host for 10 minutes instead of failing twice each. - Events are no longer dead-lettered by a server outage. A 5xx (503 included), 429, 408, a timeout or a network error keeps the event in the queue with the same `eventId`, uses none of its retry budget, and backs the whole queue off (5 s doubling to 5 minutes with 0.5x to 1.0x jitter; never sooner than the server's `Retry-After`, honoured up to 10 minutes, plus 0 to 25% jitter). Before, three failed flushes (about 1 to 2 minutes of 5xx or 429) moved events to the dead-letter store, and a timeout (`Aborted`) was not recognised as a connectivity failure. - `Retry-After` is now honoured on 5xx answers (ingest answers 503 with `Retry-After` when the fault is its own), not only on 429 and 408. A `Retry-After` longer than 30 s is no longer cut short in-request. - Any 2xx is a delivered event, whatever its body. Ingest answers 204 with no body for a filtered event; that used to count as a failed send and re-send the event. diff --git a/README.md b/README.md index 4cbd1bd9..2bdc7123 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,8 @@ Add the config plugin to `app.json`: Use a development build (`npx expo run:ios` or EAS). Expo Go ignores the plugin and sends events only. +iOS: after the user allows tracking, the advertising ID is sent from the next app launch. Events in the launch where the user taps Allow are sent at once without it. + Find your API key in DATALYR under **Settings → API**. The key starts with `dk_`. ## Quick start diff --git a/ios/DatalyrNativeModule.swift b/ios/DatalyrNativeModule.swift index 96109e16..9b2f8077 100644 --- a/ios/DatalyrNativeModule.swift +++ b/ios/DatalyrNativeModule.swift @@ -3,11 +3,42 @@ import AdServices import AppTrackingTransparency import AdSupport +// The ATT status when this app process started. iOS lifts its block on the privacy +// manifest's tracking domains only for processes started after tracking was allowed, so the +// JS side may use the tracking host only when this reads authorized. Process-wide (a JS +// reload keeps it), in memory only. +final class DatalyrProcessStartATT: @unchecked Sendable { + static let shared = DatalyrProcessStartATT() + private let lock = NSLock() + private var status: Int? + + /// Records the status the first time it is called in this process; later calls keep it. + func record() { + lock.lock(); defer { lock.unlock() } + if status != nil { return } + if #available(iOS 14, *) { + status = Int(ATTrackingManager.trackingAuthorizationStatus.rawValue) + } else { + status = 3 + } + } + + var value: Int? { + lock.lock(); defer { lock.unlock() } + return status + } +} + public class DatalyrNativeModule: Module { public func definition() -> ModuleDefinition { Name("DatalyrNative") + // Created with the app's module registry at start-up, before the app can ask for ATT. + OnCreate { + DatalyrProcessStartATT.shared.record() + } + // MARK: - SDK Availability Check AsyncFunction("getSDKAvailability") { (promise: Promise) in @@ -59,6 +90,10 @@ public class DatalyrNativeModule: Module { } } + if let startStatus = DatalyrProcessStartATT.shared.value { + result["att_status_at_process_start"] = startStatus + } + promise.resolve(result) } diff --git a/src/event-queue.ts b/src/event-queue.ts index 40dd449d..8c6d3964 100644 --- a/src/event-queue.ts +++ b/src/event-queue.ts @@ -22,6 +22,12 @@ export const MAX_RETRY_AFTER_MS = 10 * 60 * 1000; */ export const TRACKING_HOST_FALLBACK_AFTER = 2; +/** + * After the tracking host failed and the normal host answered, IDFA events go straight to + * the normal host (without the IDFA) for this long; then the tracking host is tried again. + */ +export const TRACKING_HOST_COOL_DOWN_MS = 10 * 60 * 1000; + interface QueueConfig { maxQueueSize: number; batchSize: number; @@ -265,15 +271,25 @@ export class EventQueue { for (const queuedEvent of eventsToProcess) { try { let response = await this.httpClient.sendEvent(queuedEvent.payload); - if (response.viaTrackingHost && !response.success && response.transient && response.status === 0) { - // Nothing answered on the tracking host. iOS blocks it whenever tracking is - // not authorized; the status is read just before the send, but if the block - // or the host keeps failing, send to the normal host without the IDFA rather + if (!response.viaTrackingHost) { + // This attempt did not use the tracking host: the count is of failures in a row. + queuedEvent.trackingHostFailures = 0; + } + if (response.viaTrackingHost && !response.success && !response.authPending) { + // The tracking host failed: nothing answered (iOS blocks it unless tracking is + // authorized), or an HTTP error (a filter or proxy can answer for that host + // only). If it keeps failing, send to the normal host without the IDFA rather // than hold every later event behind this one. queuedEvent.trackingHostFailures = (queuedEvent.trackingHostFailures || 0) + 1; if (queuedEvent.trackingHostFailures >= TRACKING_HOST_FALLBACK_AFTER) { debugLog(`Tracking host keeps failing; sending without the IDFA to the normal host: ${queuedEvent.payload.eventName}`); response = await this.httpClient.sendEvent(queuedEvent.payload, { avoidTrackingHost: true }); + if (response.success) { + // The normal host answered while the tracking host did not: send later IDFA + // events straight to the normal host for a while instead of failing each one + // twice first. Offline never gets here (the normal host must answer). + this.httpClient.avoidTrackingHostFor(TRACKING_HOST_COOL_DOWN_MS); + } } } diff --git a/src/http-client.ts b/src/http-client.ts index ef1d798c..0c09635f 100644 --- a/src/http-client.ts +++ b/src/http-client.ts @@ -106,7 +106,8 @@ export class HttpClient { // Apple privacy manifest: NSPrivacyTracking=true REQUIRES a non-empty // NSPrivacyTrackingDomains, and iOS fails every request to a listed host until the // user grants ATT. So the manifest lists ONLY tracking.datalyr.com, and only events - // that carry the IDFA while ATT is authorized AT SEND TIME are sent there (routeFor); + // that carry the IDFA while ATT is authorized AT SEND TIME, and was already authorized + // when the app process started, are sent there (routeFor); // all other events go to ingest.datalyr.com and are never blocked. Same backend handler. static readonly TRACKING_ENDPOINT = 'https://tracking.datalyr.com/track'; @@ -118,6 +119,33 @@ export class HttpClient { this.trackingAuthorizationProvider = provider; } + // iOS: the status when this app process started. iOS lifts the tracking-domain block only + // for processes started after tracking was allowed. Not set (or unknown) = not authorized + // at start, so the tracking host is never used. + private statusAtProcessStartProvider: TrackingAuthorizationProvider | null = null; + + setTrackingStatusAtProcessStartProvider(provider: TrackingAuthorizationProvider | null): void { + this.statusAtProcessStartProvider = provider; + } + + // While set and in the future, IDFA events skip the tracking host (sent to the normal host + // without the IDFA): it failed while the normal host answered (see avoidTrackingHostFor). + private trackingHostAvoidedUntil = 0; + + /** The tracking host failed and the normal host answered: skip it for `ms`, then try again. */ + avoidTrackingHostFor(ms: number): void { + this.trackingHostAvoidedUntil = Date.now() + ms; + } + + private async authorizedAtProcessStart(): Promise { + if (!this.statusAtProcessStartProvider) return false; + try { + return (await this.statusAtProcessStartProvider()) === 3; + } catch { + return false; + } + } + /** * Where to send `payload`, and what to send. iOS checks the tracking domain when the * request is SENT, but the IDFA was copied into the event when it was BUILT: an event @@ -126,6 +154,12 @@ export class HttpClient { * live status is authorized (3); otherwise the event goes to the normal host with the * IDFA and the other tracking-only fields removed (from a copy; the queued event keeps * them for a later authorized send). + * + * iOS also keeps blocking the tracking host for the rest of the launch in which the user + * allowed tracking. So it is used only when tracking was ALREADY authorized when this + * process started; until the next launch an authorized event goes to the normal host + * without the IDFA (its status fields stay true). The same applies during the cool-down + * after the tracking host failed while the normal host answered. */ private async routeFor(payload: EventPayload, options?: SendOptions): Promise<{ url: string; payload: EventPayload; viaTrackingHost: boolean }> { if (this.config.useServerTracking === false) return { url: this.endpoint, payload, viaTrackingHost: false }; @@ -147,10 +181,17 @@ export class HttpClient { } catch { status = undefined; // unknown can never read as authorized } - if (status === 3 && !options?.avoidTrackingHost) { - return hasIdfa - ? { url: HttpClient.TRACKING_ENDPOINT, payload, viaTrackingHost: true } - : { url: this.endpoint, payload, viaTrackingHost: false }; + // Authorization-only fields (a real IDFA, `alart`) go only to the tracking host. + if (status === 3 && !hasIdfa && data.alart === undefined) { + return { url: this.endpoint, payload, viaTrackingHost: false }; + } + if ( + status === 3 && + !options?.avoidTrackingHost && + Date.now() >= this.trackingHostAvoidedUntil && + (await this.authorizedAtProcessStart()) + ) { + return { url: HttpClient.TRACKING_ENDPOINT, payload, viaTrackingHost: true }; } const stripped: Record = { ...data }; for (const key of TRACKING_ONLY_KEYS) delete stripped[key]; diff --git a/src/native/DatalyrNativeBridge.ts b/src/native/DatalyrNativeBridge.ts index 9a31b759..22e2e7ca 100644 --- a/src/native/DatalyrNativeBridge.ts +++ b/src/native/DatalyrNativeBridge.ts @@ -59,6 +59,8 @@ interface DatalyrNativeModule { gaid?: string; att_status: number; advertiser_tracking_enabled: boolean; + // iOS, 1.9.0+ native code: the status when this app process started. + att_status_at_process_start?: number; } | null>; // Apple Search Ads Methods (iOS only) @@ -185,6 +187,45 @@ export const AdvertiserInfoBridge = { }, }; +// MARK: - ATT status at process start (iOS only) + +// iOS lifts its block on the privacy manifest's tracking domains only for app processes +// started AFTER the user allowed tracking: in the launch where the user taps "Allow", +// requests to tracking.datalyr.com still fail although the status reads authorized. So the +// tracking host may be used only when tracking was already authorized at process start. +// Kept in memory only, never stored: the next process reads its own. +let processStartRead: Promise | null = null; +const asAttStatus = (v: unknown): number | undefined => (v === 0 || v === 1 || v === 2 || v === 3 ? v : undefined); + +export const TrackingStartBridge = { + /** + * The ATT status when this process started, or undefined when unknown (never authorized). + * Prefers the native module's own value (captured when the module was created at app + * start, and it survives JS reloads). An older native binary lacks it: then the first read + * this JS runtime made, started when this file was loaded. + */ + statusAtProcessStart(): Promise { + if (!processStartRead) { + processStartRead = (async () => { + if (Platform.OS !== 'ios' || !DatalyrNative) return undefined; + try { + const info: any = await DatalyrNative.getAdvertiserInfo(); + if (!info) return undefined; + return info.att_status_at_process_start !== undefined + ? asAttStatus(info.att_status_at_process_start) + : asAttStatus(info.att_status); + } catch { + return undefined; + } + })(); + } + return processStartRead; + }, +}; + +// As early as the JS side can: when the SDK's code is first loaded. +if (Platform.OS === 'ios') void TrackingStartBridge.statusAtProcessStart(); + // MARK: - Play Install Referrer Bridge (Android only) export const PlayInstallReferrerNativeBridge = { diff --git a/src/sdk-core.ts b/src/sdk-core.ts index 12f2ef69..c2200558 100644 --- a/src/sdk-core.ts +++ b/src/sdk-core.ts @@ -41,7 +41,7 @@ import { AutoEventsManager } from './auto-events'; import { ConversionValueEncoder, ConversionTemplates } from './ConversionValueEncoder'; import { SKAdNetworkBridge } from './native/SKAdNetworkBridge'; import { appleSearchAdsIntegration, playInstallReferrerIntegration } from './integrations'; -import { AppleSearchAdsAttribution, AdvertiserInfoBridge, isNativeModuleAvailable } from './native/DatalyrNativeBridge'; +import { AppleSearchAdsAttribution, AdvertiserInfoBridge, TrackingStartBridge, isNativeModuleAvailable } from './native/DatalyrNativeBridge'; import { networkStatusManager } from './network-status'; // Provider namespaces the server's webhooks join on `external_ids` (one list shared by // both entry points; MUST match the server's person-contract.js). @@ -84,6 +84,7 @@ export interface PlatformUtils { USER_ID_PROVISIONAL: string; LAST_IDENTITY_HASH: string; DEFERRED_LOOKUP_NEEDS_ATT_STATUS: string; + ATT_ID_WITHHELD: string; }; } @@ -281,6 +282,8 @@ export class DatalyrSDKCore { // below loads and drains the stored events). Not on Android: no such block there. if (Platform.OS === 'ios') { this.httpClient.setTrackingAuthorizationProvider(() => this.liveTrackingStatus()); + // ...and lifts it only for processes started after tracking was allowed. + this.httpClient.setTrackingStatusAtProcessStartProvider(() => TrackingStartBridge.statusAtProcessStart()); } // Initialize event queue @@ -456,6 +459,8 @@ export class DatalyrSDKCore { console.warn('[Datalyr] Native modules not linked — SKAdNetwork, IDFA and Apple Search Ads are disabled. Expo Go does not support them; use a development build and re-run pod install.'); } + await this.resendAttStatusIfIdWithheld(); + // Handlers registered before initialize() finished get their first push now (ids // and any deferred web attribution are in place). this.notifyProviderAttributeHandlers(); @@ -1170,7 +1175,46 @@ export class DatalyrSDKCore { private async liveTrackingStatus(): Promise { const info = await AdvertiserInfoBridge.getAdvertiserInfo(); if (info) this.cachedAdvertiserInfo = info; - return attStatusFrom(info); + const status = attStatusFrom(info); + if (status === 3 && !this.idWithheldNoted && (await TrackingStartBridge.statusAtProcessStart()) !== 3) { + // Allowed during this launch: the IDFA is withheld until the next one (see routeFor). + // The stored value is the re-send's fixed event id, made once per grant. + this.idWithheldNoted = true; + const key = this.u.STORAGE_KEYS.ATT_ID_WITHHELD; + if (!(await this.u.Storage.getItem(key))) { + await this.u.Storage.setItem(key, `att_resend_${this.u.generateUUID()}`); + } + } + return status; + } + + private idWithheldNoted = false; + + /** + * The previous launch allowed tracking mid-session, so its events reached the server + * without the IDFA. If tracking was authorized when this process started, send + * `$att_status` once: it carries the IDFA (to the tracking host) for the same device ids. + */ + private async resendAttStatusIfIdWithheld(): Promise { + if (Platform.OS !== 'ios') return; + const key = this.u.STORAGE_KEYS.ATT_ID_WITHHELD; + try { + const grantId = await this.u.Storage.getItem(key); + if (!grantId) return; + const now = attStatusFrom(this.cachedAdvertiserInfo); + if (now === 3 && (await TrackingStartBridge.statusAtProcessStart()) === 3) { + // The flag is removed only after the event is queued (so it cannot be lost), and the + // event id is fixed per grant: if the app is killed in between, the next launch sends + // it again with the SAME id, which the server de-duplicates. + const eventId = typeof grantId === 'string' ? grantId : undefined; + await this.track('$att_status', { authorized: true, status: 3, status_name: ATT_STATUS_NAMES[3], att_status: 3, resent: true, ...(eventId ? { event_id: eventId } : {}) }); + await this.u.Storage.removeItem(key); + } else if (now !== undefined && now !== 3) { + await this.u.Storage.removeItem(key); // no longer allowed: nothing to send + } + } catch (error) { + errorLog('Failed to re-send the ATT status:', error as Error); + } } /** Re-read IDFA/IDFV/ATT status from the native module into the cache. */ diff --git a/src/utils-expo.ts b/src/utils-expo.ts index 107f26fa..1c983806 100644 --- a/src/utils-expo.ts +++ b/src/utils-expo.ts @@ -51,6 +51,8 @@ export const STORAGE_KEYS = { // Set when the server declined the lookup for ATT while the native module was missing // (no ATT status to send); lookups are skipped until the module reports a status. DEFERRED_LOOKUP_NEEDS_ATT_STATUS: '@datalyr/deferred_lookup_needs_att_status', + // iOS: tracking was allowed mid-launch, so that launch's events went without the IDFA. + ATT_ID_WITHHELD: '@datalyr/att_id_withheld', } as const; // Debug logging: prints in a development build or with `debug: true`. diff --git a/src/utils.ts b/src/utils.ts index fd104e34..f5feb912 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -45,6 +45,8 @@ export const STORAGE_KEYS = { // Set when the server declined the lookup for ATT while the native module was missing // (no ATT status to send); lookups are skipped until the module reports a status. DEFERRED_LOOKUP_NEEDS_ATT_STATUS: '@datalyr/deferred_lookup_needs_att_status', + // iOS: tracking was allowed mid-launch, so that launch's events went without the IDFA. + ATT_ID_WITHHELD: '@datalyr/att_id_withheld', }; // Constants diff --git a/tests/tracking-host-process-start.test.ts b/tests/tracking-host-process-start.test.ts new file mode 100644 index 00000000..81e15af5 --- /dev/null +++ b/tests/tracking-host-process-start.test.ts @@ -0,0 +1,571 @@ +// iOS lifts its block on the privacy manifest's tracking domain (tracking.datalyr.com) only +// for app PROCESSES STARTED AFTER the user allowed tracking. Proved on a real iPhone +// (2026-11-25): in the launch where the user taps "Allow", requests to the tracking host still +// fail (NSURLErrorDomain -1009) although the status reads authorized; after a relaunch they +// succeed. Choosing the host from the live status alone sent every event of that first launch +// to a host it could not reach, and it reached ingest only after two failures and a backoff, +// without the IDFA. +// +// Rule now: the tracking host is used only when tracking was ALREADY authorized when this +// process started AND is authorized now AND the event carries a real IDFA. Otherwise the event +// goes to ingest at once, with the IDFA removed. The next process re-sends `$att_status` once, +// so the IDFA still reaches the server. +// +// Each "process" here is a fresh module registry (jest.isolateModules): the SDK, its bridges +// and its in-memory state are created again, as in a new app launch. AsyncStorage is shared, +// as on a real device. The native module is a fake whose status the test changes. + +import AsyncStorageShared from '@react-native-async-storage/async-storage'; +import { HttpClient } from '../src/http-client'; +import { EventQueue } from '../src/event-queue'; +import type { EventPayload } from '../src/types'; + +const INGEST = 'https://ingest.datalyr.com/track'; +const TRACKING = 'https://tracking.datalyr.com/track'; +const IDFA = '6D92078A-8246-4BA4-AE5B-76104861E7DC'; + +type Sent = { url: string; body: any }; +let sent: Sent[] = []; + +// The phone. `status` is the live ATT status. `startStatus` is what iOS saw when the current +// process started: the tracking host answers only when both are authorized. +const phone = { status: 0 as number, startStatus: 0 as number, readable: true, platform: 'ios' as 'ios' | 'android' }; +let trackingHostFails = false; +let nativeReads = 0; + +const ok = () => ({ ok: true, status: 200, statusText: 'OK', headers: { get: () => null }, json: async () => ({}) }); +const answer = (status: number) => ({ ok: status < 400, status, statusText: String(status), headers: { get: () => null }, json: async () => ({}) }); + +const installFetch = () => { + (globalThis as any).fetch = async (url: string, init: any) => { + const u = String(url); + if (u.startsWith(INGEST) || u.startsWith(TRACKING)) { + sent.push({ url: u, body: JSON.parse(init.body) }); + if (u.startsWith(TRACKING) && (trackingHostFails || !(phone.startStatus === 3 && phone.status === 3))) { + return Promise.reject(new TypeError('Network request failed')); + } + } + return ok(); + }; +}; + +/** + * Start a new app process. `nativeStartField` = the native module reports the status it saw + * when the process started (this release's native code); false = an older native binary + * (for example new JS through an over-the-air update), where the JS side reads it at load. + */ +const startProcess = (opts: { nativeStartField?: boolean; jsReloadOnly?: boolean } = {}) => { + const nativeStartField = opts.nativeStartField !== false; + // A JS reload (over-the-air update, dev reload) restarts the JS side in the SAME process: + // iOS keeps the process's block, and the native module keeps its start value. + if (!opts.jsReloadOnly) phone.startStatus = phone.status; + const startStatus = phone.startStatus; + const fakeNative: any = { + getAdvertiserInfo: async () => { + nativeReads++; + if (!phone.readable) throw new Error('native read failed (test)'); + if (phone.platform === 'android') { + return { gaid: 'GAID-TEST', att_status: 3, advertiser_tracking_enabled: true }; + } + return { + idfv: 'IDFV-TEST', + att_status: phone.status, + advertiser_tracking_enabled: phone.status === 3, + ...(phone.status === 3 ? { idfa: IDFA } : {}), + ...(nativeStartField ? { att_status_at_process_start: startStatus } : {}), + }; + }, + getAppleSearchAdsAttribution: async () => null, + getSDKAvailability: async () => ({ appleSearchAds: false }), + }; + let mod: any; + jest.isolateModules(() => { + jest.doMock('@react-native-async-storage/async-storage', () => AsyncStorageShared); + jest.doMock('react-native', () => { + const rn = jest.requireActual('../test-mocks/react-native.js'); + return { + ...rn, + Platform: { ...rn.Platform, OS: phone.platform }, + NativeModules: phone.platform === 'android' ? { DatalyrNative: fakeNative } : {}, + AppState: { ...rn.AppState, addEventListener: () => ({ remove: () => {} }) }, + }; + }); + jest.doMock('expo-modules-core', () => ({ + ...jest.requireActual('../test-mocks/expo-modules-core.js'), + requireNativeModule: (name: string) => { + if (name === 'DatalyrNative') return fakeNative; + throw new Error('native module unavailable (test)'); + }, + })); + mod = require('../src/datalyr-sdk'); + }); + return new mod.DatalyrSDK(); +}; + +const init = async (sdk: any) => { + await sdk.initialize({ apiKey: 'dk_test', flushInterval: 999999, enableAutoEvents: false, enableWebToAppAttribution: false }); +}; +// Drain until empty or stuck. A drain started by track() may still be running (flush() +// returns at once then), so wait for it between tries. +const flush = async (sdk: any) => { + const q = sdk.eventQueue; + for (let i = 0; i < 50 && q.getStats().queueSize > 0; i++) { + q.retryNotBefore = 0; + await q.flush(); + await new Promise((r) => setTimeout(r, 5)); + } +}; +const named = (name: string) => sent.filter((s) => s.body.event === name); +const expectNoIdOnIngest = () => { + for (const s of sent) if (s.url === INGEST) expect(s.body.properties.idfa).toBeUndefined(); +}; + +beforeEach(async () => { + await (AsyncStorageShared as any).clear(); + sent = []; + phone.status = 0; + phone.startStatus = 0; + phone.readable = true; + phone.platform = 'ios'; + trackingHostFails = false; + nativeReads = 0; + installFetch(); +}); + +describe.each([ + ['native reports the process-start status', true], + ['older native binary (JS reads it at load)', false], +])('iOS, %s', (_name, nativeStartField) => { + test('not authorized at start, user allows mid-session → ingest at once, IDFA removed, no failed request first', async () => { + const sdk = startProcess({ nativeStartField }); + try { + await init(sdk); + await sdk.track('paywall_viewed'); + phone.status = 3; // the user taps "Allow" + await sdk.updateTrackingAuthorization(true); + await sdk.track('purchase', { value: 9 }); + await flush(sdk); + + expect(sent.filter((s) => s.url === TRACKING)).toHaveLength(0); + for (const name of ['$att_status', 'purchase']) { + const copies = named(name); + expect(copies).toHaveLength(1); // delivered on the first attempt + expect(copies[0].url).toBe(INGEST); + expect(copies[0].body.properties.idfa).toBeUndefined(); + // The status itself is true: the user did allow tracking. + expect(copies[0].body.properties.att_status).toBe(3); + } + expect(named('purchase')[0].body.properties.value).toBe(9); + expect(sdk.eventQueue.getStats().queueSize).toBe(0); + expectNoIdOnIngest(); + } finally { + sdk.destroy(); + } + }); + + test('authorized at start and still authorized → tracking host with the IDFA', async () => { + phone.status = 3; + const sdk = startProcess({ nativeStartField }); + try { + await init(sdk); + await sdk.track('purchase', { value: 2 }); + await flush(sdk); + const purchase = named('purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(TRACKING); + expect(purchase[0].body.properties.idfa).toBe(IDFA); + expectNoIdOnIngest(); + } finally { + sdk.destroy(); + } + }); + + test('authorized at start, revoked mid-session → ingest, IDFA removed', async () => { + phone.status = 3; + const sdk = startProcess({ nativeStartField }); + try { + await init(sdk); + sdk.eventQueue.isOnline = false; + await sdk.track('purchase', { value: 4 }); + phone.status = 2; // Settings → tracking off + sdk.eventQueue.isOnline = true; + await flush(sdk); + const purchase = named('purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(INGEST); + expect(purchase[0].body.properties.idfa).toBeUndefined(); + expect(purchase[0].body.properties.att_status).toBe(2); + } finally { + sdk.destroy(); + } + }); + + test('a new process after allowing → tracking host, and $att_status re-sent once with the IDFA', async () => { + const first = startProcess({ nativeStartField }); + try { + await init(first); + phone.status = 3; + await first.updateTrackingAuthorization(true); + await flush(first); + } finally { + first.destroy(); + } + expect(sent.filter((s) => s.url === TRACKING)).toHaveLength(0); + + sent = []; + const second = startProcess({ nativeStartField }); // kill and relaunch + try { + await init(second); + await second.track('screen_viewed'); + await flush(second); + const att = named('$att_status'); + expect(att).toHaveLength(1); + expect(att[0].url).toBe(TRACKING); + expect(att[0].body.properties.idfa).toBe(IDFA); + expect(att[0].body.properties.att_status).toBe(3); + expect(named('screen_viewed')[0].url).toBe(TRACKING); + expect(sent.every((s) => s.url === TRACKING)).toBe(true); + } finally { + second.destroy(); + } + + // Only once: a third launch sends no extra $att_status. + sent = []; + const third = startProcess({ nativeStartField }); + try { + await init(third); + await flush(third); + expect(named('$att_status')).toHaveLength(0); + } finally { + third.destroy(); + } + }); +}); + +describe('iOS: more launches', () => { + const resent = () => named('$att_status').filter((s) => s.body.properties.resent === true); + + test('authorized at start (for example an upgrade): no re-send, no flag', async () => { + phone.status = 3; + for (let i = 0; i < 2; i++) { + const sdk = startProcess(); + try { + await init(sdk); + await sdk.track('screen_viewed'); + await flush(sdk); + } finally { + sdk.destroy(); + } + } + expect(resent()).toHaveLength(0); + expect(await (AsyncStorageShared as any).getItem('@datalyr/att_id_withheld')).toBeNull(); + }); + + test('flag cleared on a launch where tracking is no longer allowed; no re-send later', async () => { + const first = startProcess(); + try { + await init(first); + phone.status = 3; + await first.updateTrackingAuthorization(true); + await flush(first); + } finally { + first.destroy(); + } + expect(await (AsyncStorageShared as any).getItem('@datalyr/att_id_withheld')).not.toBeNull(); + + phone.status = 2; // turned off in Settings + const second = startProcess(); + try { + await init(second); + await flush(second); + } finally { + second.destroy(); + } + expect(await (AsyncStorageShared as any).getItem('@datalyr/att_id_withheld')).toBeNull(); + + phone.status = 3; // allowed again in Settings (iOS relaunches the app) + sent = []; + const third = startProcess(); + try { + await init(third); + await flush(third); + } finally { + third.destroy(); + } + expect(resent()).toHaveLength(0); + }); + + test('an IDFA event stored by an earlier launch, sent in a launch not authorized at start → ingest without it', async () => { + phone.status = 3; + const first = startProcess(); + try { + await init(first); + first.eventQueue.isOnline = false; + await first.track('purchase', { value: 7 }); + } finally { + first.destroy(); // killed with the event still queued + } + sent = []; + phone.status = 2; + const second = startProcess(); + try { + await init(second); + phone.status = 3; // allowed again during this launch + await flush(second); + } finally { + second.destroy(); + } + const purchase = named('purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(INGEST); + expect(purchase[0].body.properties.idfa).toBeUndefined(); + expect(purchase[0].body.properties.value).toBe(7); + expect(sent.filter((s) => s.url === TRACKING)).toHaveLength(0); + }); + + test('killed between the re-send and clearing its flag: sent again with the SAME event id', async () => { + const first = startProcess(); + try { + await init(first); + phone.status = 3; + await first.updateTrackingAuthorization(true); + await flush(first); + } finally { + first.destroy(); + } + // Second launch: the re-send is queued, then the app dies before the flag is removed. + const realRemove = (AsyncStorageShared as any).removeItem; + (AsyncStorageShared as any).removeItem = async (k: string) => { + if (k === '@datalyr/att_id_withheld') throw new Error('killed (test)'); + return realRemove(k); + }; + const second = startProcess(); + try { + await init(second); + await flush(second); + } finally { + second.destroy(); + (AsyncStorageShared as any).removeItem = realRemove; + } + const third = startProcess(); + try { + await init(third); + await flush(third); + } finally { + third.destroy(); + } + const copies = resent(); + expect(copies.length).toBe(2); + expect(new Set(copies.map((c) => c.body.eventId)).size).toBe(1); + expect(copies.every((c) => c.url === TRACKING && c.body.properties.idfa === IDFA)).toBe(true); + expect(await (AsyncStorageShared as any).getItem('@datalyr/att_id_withheld')).toBeNull(); + }); + + test.each([ + ['new native: still not authorized at start → ingest at once', true], + ['older native: reads authorized (wrong) → tracking host fails, falls back, then skips it', false], + ])('JS reload in the same process after Allow, %s', async (_name, nativeStartField) => { + const first = startProcess({ nativeStartField }); + try { + await init(first); + phone.status = 3; // allowed, then the JS side reloads in the same process + } finally { + first.destroy(); + } + sent = []; + const reloaded = startProcess({ nativeStartField, jsReloadOnly: true }); + try { + await init(reloaded); + await reloaded.track('purchase', { value: 5 }); + await flush(reloaded); + await reloaded.track('later'); + await flush(reloaded); + expect(named('purchase').filter((s) => s.url === INGEST)).toHaveLength(1); + expect(named('later')).toEqual([expect.objectContaining({ url: INGEST })]); + expect(reloaded.eventQueue.getStats().queueSize).toBe(0); + if (nativeStartField) expect(sent.filter((s) => s.url === TRACKING)).toHaveLength(0); + expectNoIdOnIngest(); + } finally { + reloaded.destroy(); + } + }); +}); + +test('iOS: status unreadable at start → treated as not authorized at start (ingest, IDFA removed)', async () => { + phone.status = 3; + phone.readable = false; + const sdk = startProcess({ nativeStartField: false }); + phone.readable = true; // later reads work and say authorized + try { + await init(sdk); + await sdk.track('purchase', { value: 1 }); + await flush(sdk); + const purchase = named('purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(INGEST); + expect(purchase[0].body.properties.idfa).toBeUndefined(); + expect(sent.filter((s) => s.url === TRACKING)).toHaveLength(0); + } finally { + sdk.destroy(); + } +}); + +test('Android: unchanged (ingest, GAID kept, no process-start or per-send status reads)', async () => { + phone.platform = 'android'; + const sdk = startProcess(); + try { + await init(sdk); + const reads = nativeReads; + await sdk.track('purchase', { value: 1 }); + await flush(sdk); + const purchase = named('purchase'); + expect(purchase).toHaveLength(1); + expect(purchase[0].url).toBe(INGEST); + expect(purchase[0].body.properties.gaid).toBe('GAID-TEST'); + expect(purchase[0].body.properties.att_status).toBe(3); + expect(nativeReads).toBe(reads); + expect(named('$att_status')).toHaveLength(0); + } finally { + sdk.destroy(); + } +}); + +// Second line of defence (from 1.9.0's send-time fix): the tracking host fails for an +// authorized user (a DNS or company filter, a zone problem) while ingest works. +describe('tracking host unreachable while authorized', () => { + const payload = (name: string): EventPayload => ({ + workspaceId: 'ws_test', visitorId: 'anon', anonymousId: 'anon', sessionId: 'sess', + eventId: `evt_${name}`, eventName: name, source: 'mobile_app', timestamp: new Date(0).toISOString(), + eventData: { idfa: IDFA, idfv: 'IDFV-TEST', att_status: 3, advertiser_tracking_enabled: true }, + }); + const newClient = () => { + const client = new HttpClient(INGEST, { apiKey: 'test_key_not_real', maxRetries: 0, retryDelay: 1, timeout: 50, debug: false, useServerTracking: true }); + client.setTrackingAuthorizationProvider(async () => phone.status); + (client as any).setTrackingStatusAtProcessStartProvider?.(async () => phone.startStatus); + return client; + }; + const newQueue = async (client: HttpClient) => { + const q = new EventQueue(client, { maxQueueSize: 100, batchSize: 10, flushInterval: 999999, maxRetryCount: 3 }); + await new Promise((r) => setTimeout(r, 10)); + return q; + }; + const enqueueQuiet = async (q: EventQueue, p: EventPayload) => { + (q as any).isOnline = false; + await q.enqueue(p); + (q as any).isOnline = true; + }; + const flushNow = async (q: EventQueue) => { + (q as any).retryNotBefore = 0; + await q.flush(); + }; + + beforeEach(() => { + phone.status = 3; + phone.startStatus = 3; + }); + + test('the counter is "two in a row": an attempt that did not use the tracking host resets it', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, payload('purchase')); + (globalThis as any).fetch = async (url: string, init: any) => { + sent.push({ url: String(url), body: JSON.parse(init.body) }); + if (String(url).startsWith(INGEST)) return answer(503); // ingest busy for this test + return Promise.reject(new TypeError('Network request failed')); + }; + await flushNow(q); // tracking host fails (1) + phone.status = 2; // briefly revoked: this attempt goes to ingest (503), the row is broken + await flushNow(q); + phone.status = 3; + await flushNow(q); // tracking host fails (1 again): no fallback yet + expect(sent.map((s) => s.url)).toEqual([TRACKING, INGEST, TRACKING]); + expect(q.getStats().queueSize).toBe(1); + expect((q as any).queue[0].payload.eventData.idfa).toBe(IDFA); + }); + + test.each([403, 503])('an HTTP %i from the tracking host counts too: fallback after two, then the cool-down', async (code) => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, payload('a')); + (globalThis as any).fetch = async (url: string, init: any) => { + sent.push({ url: String(url), body: JSON.parse(init.body) }); + return String(url).startsWith(TRACKING) ? answer(code) : ok(); + }; + await flushNow(q); + await flushNow(q); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['a', TRACKING], ['a', TRACKING], ['a', INGEST]]); + expect(sent[2].body.properties.idfa).toBeUndefined(); + expect(q.getStats().queueSize).toBe(0); + sent = []; + await enqueueQuiet(q, payload('b')); + await flushNow(q); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['b', INGEST]]); + }); + + test('a 2xx from the tracking host is sent once, with no fallback copy', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, payload('a')); + await flushNow(q); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['a', TRACKING]]); + expect(q.getStats().queueSize).toBe(0); + }); + + test('alart only: tracking host when authorized at start and now; otherwise ingest without it', async () => { + const client = newClient(); + const alartOnly = (name: string): EventPayload => ({ ...payload(name), eventData: { alart: 'applovin_user_1', att_status: 3, advertiser_tracking_enabled: true } }); + await client.sendEvent(alartOnly('x')); + phone.startStatus = 0; // a launch that was not authorized at start + await client.sendEvent(alartOnly('y')); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['x', TRACKING], ['y', INGEST]]); + expect(sent[0].body.properties.alart).toBe('applovin_user_1'); + expect(sent[1].body.properties.alart).toBeUndefined(); + expect(sent[1].body.properties.att_status).toBe(3); + }); + + test('after one fallback, IDFA events go straight to ingest for a cool-down, then the tracking host is tried again', async () => { + trackingHostFails = true; + const q = await newQueue(newClient()); + await enqueueQuiet(q, payload('a')); + await flushNow(q); + await flushNow(q); // second failure → fallback to ingest, delivered + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['a', TRACKING], ['a', TRACKING], ['a', INGEST]]); + + sent = []; + await enqueueQuiet(q, payload('b')); + await enqueueQuiet(q, payload('c')); + await flushNow(q); + // No tracking-host attempt during the cool-down: each delivered at once, without the IDFA. + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['b', INGEST], ['c', INGEST]]); + expect(sent.every((s) => s.body.properties.idfa === undefined)).toBe(true); + expect(sent.every((s) => s.body.properties.att_status === 3)).toBe(true); + expect(q.getStats().queueSize).toBe(0); + + // After the cool-down the tracking host is tried again (here it works again). + const realNow = Date.now; + const later = realNow() + 11 * 60 * 1000; + jest.spyOn(Date, 'now').mockImplementation(() => later); + try { + trackingHostFails = false; + sent = []; + await enqueueQuiet(q, payload('d')); + await flushNow(q); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['d', TRACKING]]); + expect(sent[0].body.properties.idfa).toBe(IDFA); + } finally { + (Date.now as jest.Mock).mockRestore?.(); + } + }); + + test('both hosts down (offline-like) does not start the cool-down', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, payload('a')); + (globalThis as any).fetch = async (url: string, init: any) => { + sent.push({ url: String(url), body: JSON.parse(init.body) }); + return Promise.reject(new TypeError('Network request failed')); + }; + for (let i = 0; i < 3; i++) await flushNow(q); + installFetch(); + sent = []; + await flushNow(q); + expect(sent.map((s) => s.url)).toEqual([TRACKING]); + expect(sent[0].body.properties.idfa).toBe(IDFA); + }); +}); diff --git a/tests/tracking-host-send-time.test.ts b/tests/tracking-host-send-time.test.ts index 1ee4741a..7ffe9419 100644 --- a/tests/tracking-host-send-time.test.ts +++ b/tests/tracking-host-send-time.test.ts @@ -96,6 +96,9 @@ const authorizedFields = (extra: Record = {}) => ({ const newClient = () => { const client = new HttpClient(INGEST, { apiKey: 'test_key_not_real', maxRetries: 0, retryDelay: 1, timeout: 50, debug: false, useServerTracking: true }); (client as any).setTrackingAuthorizationProvider?.(async () => { providerCalls++; return liveStatus; }); + // Tracking was already authorized when this process started (see + // tracking-host-process-start.test.ts for the other case). + (client as any).setTrackingStatusAtProcessStartProvider?.(async () => 3); return client; };