diff --git a/CHANGELOG.md b/CHANGELOG.md index 88a2c2b7..0a917133 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,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. - 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/src/event-queue.ts b/src/event-queue.ts index 4df2b48e..40dd449d 100644 --- a/src/event-queue.ts +++ b/src/event-queue.ts @@ -15,6 +15,12 @@ export const TRANSIENT_BACKOFF_BASE_MS = 5000; export const TRANSIENT_BACKOFF_MAX_MS = 5 * 60 * 1000; /** Longest Retry-After the queue honours; a larger value is treated as this. */ export const MAX_RETRY_AFTER_MS = 10 * 60 * 1000; +/** + * Network failures in a row on the tracking host (tracking.datalyr.com) before the event + * is also tried on the normal host without its IDFA, so a host that keeps failing cannot + * hold the queue. During a real outage that try fails too and the event keeps its IDFA. + */ +export const TRACKING_HOST_FALLBACK_AFTER = 2; interface QueueConfig { maxQueueSize: number; @@ -258,7 +264,18 @@ export class EventQueue { for (const queuedEvent of eventsToProcess) { try { - const response = await this.httpClient.sendEvent(queuedEvent.payload); + 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 + // 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) { debugLog(`Event sent successfully: ${queuedEvent.payload.eventName}`); diff --git a/src/http-client.ts b/src/http-client.ts index ce1053ae..ef1d798c 100644 --- a/src/http-client.ts +++ b/src/http-client.ts @@ -33,8 +33,26 @@ interface HttpResponse { rejected?: boolean; // The server's Retry-After, in ms, when it sent one with a transient answer. retryAfterMs?: number; + // true when the request went to the tracking host (tracking.datalyr.com). + viaTrackingHost?: boolean; } +/** Options for one send. */ +export interface SendOptions { + // Send to the normal host with the tracking-only fields removed, even when tracking is + // authorized. The queue uses it when the tracking host keeps failing. + avoidTrackingHost?: boolean; +} + +/** + * Reads the app's App Tracking Transparency status NOW (0 notDetermined, 1 restricted, + * 2 denied, 3 authorized; undefined when unknown). Set on iOS only. + */ +export type TrackingAuthorizationProvider = () => Promise; + +/** Event fields that may be sent only while tracking is authorized. */ +const TRACKING_ONLY_KEYS = ['idfa', 'alart'] as const; + /** Longest a single in-request retry waits; a longer Retry-After goes to the queue. */ const MAX_INLINE_RETRY_WAIT_MS = 30000; @@ -88,21 +106,70 @@ 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 actually carry the IDFA (i.e. ATT already authorized) are sent there; all - // other events go to ingest.datalyr.com and are never blocked. Same backend handler. + // that carry the IDFA while ATT is authorized AT SEND TIME 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'; - private endpointFor(payload: EventPayload): string { - if (this.config.useServerTracking === false) return this.endpoint; - const idfa = (payload.eventData as Record | undefined)?.idfa; - return typeof idfa === 'string' && idfa.length > 0 ? HttpClient.TRACKING_ENDPOINT : this.endpoint; + // iOS: reads the live ATT status at send time. Null elsewhere (Android has no tracking + // domain block), which keeps the routing below exactly as it was. + private trackingAuthorizationProvider: TrackingAuthorizationProvider | null = null; + + setTrackingAuthorizationProvider(provider: TrackingAuthorizationProvider | null): void { + this.trackingAuthorizationProvider = provider; + } + + /** + * 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 + * queued while tracking was allowed and sent after the user turned it off would go to a + * blocked host. So the tracking host is used only when the event carries an IDFA AND the + * 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). + */ + 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 }; + const data = payload.eventData as Record | undefined; + const idfa = data?.idfa; + const hasIdfa = typeof idfa === 'string' && idfa.length > 0; + const provider = this.trackingAuthorizationProvider; + if (!provider) { + return hasIdfa + ? { url: HttpClient.TRACKING_ENDPOINT, payload, viaTrackingHost: true } + : { url: this.endpoint, payload, viaTrackingHost: false }; + } + if (!data || !TRACKING_ONLY_KEYS.some((k) => data[k] !== undefined)) { + return { url: this.endpoint, payload, viaTrackingHost: false }; + } + let status: number | undefined; + try { + status = await provider(); + } 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 }; + } + const stripped: Record = { ...data }; + for (const key of TRACKING_ONLY_KEYS) delete stripped[key]; + if (status !== 3) { + // The event must not claim tracking is allowed: report the status at send time. + stripped.advertiser_tracking_enabled = false; + if (status === undefined) delete stripped.att_status; + else stripped.att_status = status; + } + return { url: this.endpoint, payload: { ...payload, eventData: stripped as EventPayload['eventData'] }, viaTrackingHost: false }; } /** * Send a single event with retry logic */ - async sendEvent(payload: EventPayload): Promise { - return this.sendWithRetry(payload, 0); + async sendEvent(payload: EventPayload, options?: SendOptions): Promise { + const route = await this.routeFor(payload, options); + const response = await this.sendWithRetry(route.payload, 0, route.url); + return route.viaTrackingHost ? { ...response, viaTrackingHost: true } : response; } /** @@ -117,7 +184,7 @@ export class HttpClient { /** * Send request with exponential backoff retry */ - private async sendWithRetry(payload: EventPayload, retryCount: number): Promise { + private async sendWithRetry(payload: EventPayload, retryCount: number, url: string): Promise { try { // Defense-in-depth: never fire a server-tracking request without an API key — it // would 401 and (after retries) permanently dead-letter the event. Signal the queue @@ -165,7 +232,7 @@ export class HttpClient { const body = JSON.stringify(requestBody); let response: Response; try { - response = await fetch(this.endpointFor(payload), { + response = await fetch(url, { method: 'POST', headers, body, @@ -263,7 +330,7 @@ export class HttpClient { await this.delay(delay); // Same payload object, so the same eventId: ingest dedupes a retry of an event // whose first answer was lost. - return this.sendWithRetry(payload, retryCount + 1); + return this.sendWithRetry(payload, retryCount + 1, url); } if (httpStatus === undefined) { diff --git a/src/sdk-core.ts b/src/sdk-core.ts index 84820f2d..12f2ef69 100644 --- a/src/sdk-core.ts +++ b/src/sdk-core.ts @@ -276,6 +276,12 @@ export class DatalyrSDKCore { debug: this.state.config.debug || false, useServerTracking: this.state.config.useServerTracking ?? true, }); + // iOS blocks the privacy manifest's tracking domain unless tracking is authorized + // when the request is sent, so the client reads the status then (before the queue + // below loads and drains the stored events). Not on Android: no such block there. + if (Platform.OS === 'ios') { + this.httpClient.setTrackingAuthorizationProvider(() => this.liveTrackingStatus()); + } // Initialize event queue this.eventQueue = new EventQueue(this.httpClient, { @@ -1156,6 +1162,17 @@ export class DatalyrSDKCore { await this.runDeferredLookupIfEligible(); } + /** + * The ATT status right now, from the native module (a cheap read), for the send-time + * host choice. Also refreshes the cache, so events built next carry the current IDFA. + * Undefined when the module is unavailable or the read fails: never authorized. + */ + private async liveTrackingStatus(): Promise { + const info = await AdvertiserInfoBridge.getAdvertiserInfo(); + if (info) this.cachedAdvertiserInfo = info; + return attStatusFrom(info); + } + /** Re-read IDFA/IDFV/ATT status from the native module into the cache. */ private async refreshAdvertiserInfo(): Promise { try { diff --git a/src/types.ts b/src/types.ts index a2e6121c..42bdb9ac 100644 --- a/src/types.ts +++ b/src/types.ts @@ -234,6 +234,9 @@ export interface QueuedEvent { // Set on dead-letter entries that can never deliver (e.g. server 413 payload too // large). replayDeadLetter skips them; they are kept only for inspection. permanent?: boolean; + // Network failures in a row on the tracking host; past TRACKING_HOST_FALLBACK_AFTER the + // event is also tried on the normal host without its IDFA (see EventQueue). + trackingHostFailures?: number; } // App State - Updated for React Native 0.80 diff --git a/tests/tracking-host-send-time.test.ts b/tests/tracking-host-send-time.test.ts new file mode 100644 index 00000000..1ee4741a --- /dev/null +++ b/tests/tracking-host-send-time.test.ts @@ -0,0 +1,362 @@ +// iOS fails every request to a domain the privacy manifest lists under +// NSPrivacyTrackingDomains (tracking.datalyr.com) while the app's App Tracking Transparency +// status is not "authorized", checked when the request is SENT. The host used to be chosen +// from the IDFA copied into the event when it was BUILT, so an event queued while tracking +// was allowed and sent after the user turned it off went to a blocked host. The failure is a +// network error: no retry is spent, the drain backs off, and every later event from the +// device waits behind it for as long as tracking stays off. +// +// Now: the tracking host is used only when the event has an IDFA AND the live ATT status, +// read at send time, is authorized (3). Otherwise the event goes to ingest.datalyr.com with +// the IDFA and the other tracking-only fields removed. A tracking-host request that keeps +// failing with a network error falls back to ingest (without the IDFA) so it cannot hold the +// queue. Android has no tracking-domain block and is unchanged. + +jest.mock('expo-application', () => ({ + nativeApplicationVersion: '1.0.0', + nativeBuildVersion: '1', + applicationId: 'com.datalyr.test', + getInstallationTimeAsync: async () => new Date(0), +}), { virtual: true }); + +jest.mock('expo-device', () => ({ + modelName: 'Test Device', + deviceName: 'Test Device', + manufacturer: 'Test', + osVersion: '17.0', + isDevice: true, +}), { virtual: true }); + +jest.mock('expo-network', () => ({ + NetworkStateType: { WIFI: 'WIFI' }, + getNetworkStateAsync: async () => ({ type: 'WIFI', isConnected: true }), +}), { virtual: true }); + +import AsyncStorage from '@react-native-async-storage/async-storage'; +import { AppState, Platform } from 'react-native'; +import { EventQueue } from '../src/event-queue'; +import { HttpClient } from '../src/http-client'; +import { DatalyrSDK } from '../src/datalyr-sdk'; +import { DatalyrSDKExpo } from '../src/datalyr-sdk-expo'; +import { attributionManager } from '../src/attribution'; +import { journeyManager } from '../src/journey'; +import { AdvertiserInfoBridge } from '../src/native/DatalyrNativeBridge'; +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 live ATT status the provider reports (undefined = unknown / no native module). +let liveStatus: number | undefined = 3; +let providerCalls = 0; +// When true, every request to the tracking host fails the way iOS fails a blocked +// tracking domain: React Native's fetch rejects with TypeError('Network request failed'). +let trackingHostFails = false; + +const ok = () => ({ ok: true, status: 200, statusText: 'OK', 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) }); + // iOS blocks the declared tracking domain unless ATT is authorized at send time. + if (u.startsWith(TRACKING) && (trackingHostFails || liveStatus !== 3)) { + return Promise.reject(new TypeError('Network request failed')); + } + } + return ok(); + }; +}; + +const makePayload = (name: string, data: Record = {}): EventPayload => ({ + workspaceId: 'ws_test', + visitorId: 'anon_test', + anonymousId: 'anon_test', + sessionId: 'sess_test', + eventId: `evt_${name}`, + eventName: name, + eventData: data, + source: 'mobile_app', + timestamp: new Date(0).toISOString(), +}); + +// What the SDK copies onto every event while ATT is authorized. +const authorizedFields = (extra: Record = {}) => ({ + idfa: IDFA, + idfv: 'IDFV-TEST', + att_status: 3, + advertiser_tracking_enabled: true, + ...extra, +}); + +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; }); + 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)); // initializeQueue settles + 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(); +}; + +/** Neither leak: tracking host only with an IDFA and authorized; never an IDFA on ingest. */ +const expectNoLeak = () => { + for (const s of sent) { + if (s.url === TRACKING) { + expect(s.body.properties.idfa).toBe(IDFA); + } else { + expect(s.body.properties.idfa).toBeUndefined(); + } + } +}; + +beforeEach(async () => { + await (AsyncStorage as any).clear(); + sent = []; + liveStatus = 3; + providerCalls = 0; + trackingHostFails = false; + installFetch(); +}); + +afterEach(() => { + jest.restoreAllMocks(); +}); + +describe('host chosen from the live ATT status at send time', () => { + test('authorized + IDFA → tracking host, IDFA kept', async () => { + const client = newClient(); + const res = await client.sendEvent(makePayload('purchase', authorizedFields({ value: 5 }))); + expect(res.success).toBe(true); + expect(sent).toHaveLength(1); + expect(sent[0].url).toBe(TRACKING); + expect(sent[0].body.properties.idfa).toBe(IDFA); + expect(sent[0].body.properties.att_status).toBe(3); + expect(sent[0].body.properties.advertiser_tracking_enabled).toBe(true); + }); + + test.each([ + ['denied', 2], + ['restricted', 1], + ['not determined', 0], + ])('%s + stale IDFA → ingest, IDFA and tracking-only fields removed', async (_name, status) => { + liveStatus = status; + const client = newClient(); + const res = await client.sendEvent(makePayload('app_install', authorizedFields({ alart: 'applovin_user_1', value: 5 }))); + expect(res.success).toBe(true); + expect(sent).toHaveLength(1); + expect(sent[0].url).toBe(INGEST); + const props = sent[0].body.properties; + expect(props.idfa).toBeUndefined(); + expect(props.alart).toBeUndefined(); + // The event no longer claims tracking is allowed. + expect(props.att_status).toBe(status); + expect(props.advertiser_tracking_enabled).toBe(false); + // Everything else is kept. + expect(props.idfv).toBe('IDFV-TEST'); + expect(props.value).toBe(5); + }); + + test('status unknown (native read failed) + stale IDFA → ingest, IDFA removed', async () => { + liveStatus = undefined; + const client = newClient(); + await client.sendEvent(makePayload('purchase', authorizedFields())); + expect(sent[0].url).toBe(INGEST); + expect(sent[0].body.properties.idfa).toBeUndefined(); + expect(sent[0].body.properties.advertiser_tracking_enabled).toBe(false); + }); + + test('the stored event is not changed by the strip (a later authorized send keeps the IDFA)', async () => { + liveStatus = 2; + const client = newClient(); + const payload = makePayload('purchase', authorizedFields()); + await client.sendEvent(payload); + expect(payload.eventData!.idfa).toBe(IDFA); + }); + + test('no IDFA → ingest, and no native status read', async () => { + const client = newClient(); + await client.sendEvent(makePayload('screen', { screen: 'home', att_status: 2, advertiser_tracking_enabled: false })); + expect(sent[0].url).toBe(INGEST); + expect(sent[0].body.properties.att_status).toBe(2); + expect(providerCalls).toBe(0); + }); +}); + +describe('queue', () => { + test('queued while authorized, sent after tracking was turned off → ingest, no IDFA, later events not held', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, makePayload('purchase', authorizedFields({ value: 9 }))); + liveStatus = 2; // user turns tracking off in Settings + await enqueueQuiet(q, makePayload('screen', { att_status: 2, advertiser_tracking_enabled: false })); + await flushNow(q); + + expect(q.getStats().queueSize).toBe(0); + expect(sent.map((s) => s.url)).toEqual([INGEST, INGEST]); + expect(sent[0].body.event).toBe('purchase'); + expect(sent[0].body.properties.value).toBe(9); + expectNoLeak(); + }); + + test('mixed batch, not authorized: nothing goes to the tracking host, no IDFA on ingest', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, makePayload('a', authorizedFields())); + await enqueueQuiet(q, makePayload('b', { screen: 'home' })); + await enqueueQuiet(q, makePayload('c', authorizedFields())); + liveStatus = 1; + await flushNow(q); + + expect(q.getStats().queueSize).toBe(0); + expect(sent.map((s) => s.body.event)).toEqual(['a', 'b', 'c']); + expect(sent.every((s) => s.url === INGEST)).toBe(true); + expectNoLeak(); + }); + + test('mixed batch, authorized: IDFA events to the tracking host, the rest to ingest', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, makePayload('a', authorizedFields())); + await enqueueQuiet(q, makePayload('b', { screen: 'home' })); + await enqueueQuiet(q, makePayload('c', authorizedFields())); + await flushNow(q); + + expect(q.getStats().queueSize).toBe(0); + expect(sent.map((s) => [s.body.event, s.url])).toEqual([['a', TRACKING], ['b', INGEST], ['c', TRACKING]]); + expectNoLeak(); + }); + + test('a tracking-host request that keeps failing does not hold later events', async () => { + // Authorized, but the tracking host fails every time (a block we cannot see, DNS, a + // zone rule). The ingest host works. + trackingHostFails = true; + const q = await newQueue(newClient()); + await enqueueQuiet(q, makePayload('purchase', authorizedFields({ value: 3 }))); + await enqueueQuiet(q, makePayload('later_1', { screen: 'a' })); + await enqueueQuiet(q, makePayload('later_2', { screen: 'b' })); + + for (let i = 0; i < 4 && q.getStats().queueSize > 0; i++) await flushNow(q); + + expect(q.getStats().queueSize).toBe(0); + const delivered = sent.filter((s) => s.url === INGEST).map((s) => s.body.event); + expect(delivered).toEqual(['purchase', 'later_1', 'later_2']); + // Delivered without the IDFA, same eventId (ingest de-duplicates a lost answer). + const purchase = sent.find((s) => s.url === INGEST && s.body.event === 'purchase')!; + expect(purchase.body.properties.idfa).toBeUndefined(); + expect(purchase.body.properties.value).toBe(3); + expect(purchase.body.eventId).toBe('evt_purchase'); + expectNoLeak(); + }); + + test('a real outage (both hosts down) keeps the event with its IDFA; delivered to the tracking host once back', async () => { + const q = await newQueue(newClient()); + await enqueueQuiet(q, makePayload('purchase', authorizedFields())); + (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 < 4; i++) await flushNow(q); + expect(q.getStats().queueSize).toBe(1); + expect((q as any).queue[0].payload.eventData.idfa).toBe(IDFA); + + sent = []; + installFetch(); + await flushNow(q); + expect(q.getStats().queueSize).toBe(0); + expect(sent.map((s) => s.url)).toEqual([TRACKING]); + expect(sent[0].body.properties.idfa).toBe(IDFA); + }); +}); + +// SDK wiring: the live status comes from the native module at send time on iOS; Android +// keeps its delivery exactly as before. +const sdkVariants: Array<[string, () => any]> = [ + ['bare React Native', () => new DatalyrSDK()], + ['Expo', () => new DatalyrSDKExpo()], +]; + +describe.each(sdkVariants)('%s SDK', (_variant, createSDK) => { + let native: any; + const resetManagers = async () => { + const { networkStatusManager } = require('../src/network-status'); + networkStatusManager.destroy(); + await attributionManager.clearAttributionData(); + (attributionManager as any).initialized = false; + (attributionManager as any).isFirstLaunch = false; + await journeyManager.clearJourney(); + }; + + beforeEach(async () => { + await resetManagers(); + (AppState as any).addEventListener = () => ({ remove: () => {} }); + jest.spyOn(AdvertiserInfoBridge, 'getAdvertiserInfo').mockImplementation(async () => native); + }); + + const init = async (sdk: any) => { + await sdk.initialize({ apiKey: 'dk_test', flushInterval: 999999, enableAutoEvents: false, enableWebToAppAttribution: false }); + }; + + test('iOS: event built while authorized, tracking turned off before the send → ingest without the IDFA', async () => { + native = { idfa: IDFA, idfv: 'IDFV-TEST', att_status: 3, advertiser_tracking_enabled: true }; + const sdk = createSDK(); + try { + await init(sdk); + const q = (sdk as any).eventQueue; + q.isOnline = false; + await sdk.track('purchase', { value: 1 }); + // Settings → tracking off. The app's cached advertiser info still says authorized. + native = { idfv: 'IDFV-TEST', att_status: 2, advertiser_tracking_enabled: false }; + liveStatus = 2; + sent = []; + q.isOnline = true; + q.retryNotBefore = 0; + await q.flush(); + + const purchase = sent.filter((s) => s.body.event === '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); + expect(q.getStats().queueSize).toBe(0); + } finally { + sdk.destroy(); + } + }); + + test('Android: unchanged (GAID kept, ingest host, no extra native reads per send)', async () => { + const original = Platform.OS; + (Platform as any).OS = 'android'; + native = { gaid: 'GAID-TEST', att_status: 3, advertiser_tracking_enabled: true }; + const sdk = createSDK(); + try { + await init(sdk); + const reads = (AdvertiserInfoBridge.getAdvertiserInfo as jest.Mock).mock.calls.length; + sent = []; + await sdk.track('purchase', { value: 1 }); + await (sdk as any).eventQueue.flush(); + const purchase = sent.filter((s) => s.body.event === '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(purchase[0].body.properties.advertiser_tracking_enabled).toBe(true); + expect((AdvertiserInfoBridge.getAdvertiserInfo as jest.Mock).mock.calls.length).toBe(reads); + } finally { + sdk.destroy(); + (Platform as any).OS = original; + } + }); +});