Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 35 additions & 0 deletions ios/DatalyrNativeModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -59,6 +90,10 @@ public class DatalyrNativeModule: Module {
}
}

if let startStatus = DatalyrProcessStartATT.shared.value {
result["att_status_at_process_start"] = startStatus
}

promise.resolve(result)
}

Expand Down
24 changes: 20 additions & 4 deletions src/event-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}
}

Expand Down
51 changes: 46 additions & 5 deletions src/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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<boolean> {
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
Expand All @@ -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 };
Expand All @@ -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<string, unknown> = { ...data };
for (const key of TRACKING_ONLY_KEYS) delete stripped[key];
Expand Down
41 changes: 41 additions & 0 deletions src/native/DatalyrNativeBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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<number | undefined> | 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<number | undefined> {
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 = {
Expand Down
48 changes: 46 additions & 2 deletions src/sdk-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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;
};
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -1170,7 +1175,46 @@ export class DatalyrSDKCore {
private async liveTrackingStatus(): Promise<number | undefined> {
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<string>(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<void> {
if (Platform.OS !== 'ios') return;
const key = this.u.STORAGE_KEYS.ATT_ID_WITHHELD;
try {
const grantId = await this.u.Storage.getItem<string>(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. */
Expand Down
2 changes: 2 additions & 0 deletions src/utils-expo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
2 changes: 2 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading