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 @@ -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.
Expand Down
19 changes: 18 additions & 1 deletion src/event-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}`);
Expand Down
89 changes: 78 additions & 11 deletions src/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number | undefined>;

/** 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;

Expand Down Expand Up @@ -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<string, unknown> | 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<string, unknown> | 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<string, unknown> = { ...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<HttpResponse> {
return this.sendWithRetry(payload, 0);
async sendEvent(payload: EventPayload, options?: SendOptions): Promise<HttpResponse> {
const route = await this.routeFor(payload, options);
const response = await this.sendWithRetry(route.payload, 0, route.url);
return route.viaTrackingHost ? { ...response, viaTrackingHost: true } : response;
}

/**
Expand All @@ -117,7 +184,7 @@ export class HttpClient {
/**
* Send request with exponential backoff retry
*/
private async sendWithRetry(payload: EventPayload, retryCount: number): Promise<HttpResponse> {
private async sendWithRetry(payload: EventPayload, retryCount: number, url: string): Promise<HttpResponse> {
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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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) {
Expand Down
17 changes: 17 additions & 0 deletions src/sdk-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down Expand Up @@ -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<number | undefined> {
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<void> {
try {
Expand Down
3 changes: 3 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading