Skip to content

feat: Ability to programmatically disable tracking #1067

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 29, 2025
Merged
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
14 changes: 13 additions & 1 deletion packages/core/src/analytics.ts
Original file line number Diff line number Diff line change
@@ -115,6 +115,10 @@ export class SegmentClient {
* Observable to know when the client is fully initialized and ready to send events to destination
*/
readonly isReady = new Observable<boolean>(false);
/**
* Access or subscribe to client enabled
*/
readonly enabled: Watchable<boolean> & Settable<boolean>;
/**
* Access or subscribe to client context
*/
@@ -247,6 +251,12 @@ export class SegmentClient {
onChange: this.store.deepLinkData.onChange,
};

this.enabled = {
get: this.store.enabled.get,
set: this.store.enabled.set,
onChange: this.store.enabled.onChange,
};

// add segment destination plugin unless
// asked not to via configuration.
if (this.config.autoAddSegmentDestination === true) {
@@ -476,7 +486,9 @@ export class SegmentClient {
async process(incomingEvent: SegmentEvent, enrichment?: EnrichmentClosure) {
const event = this.applyRawEventData(incomingEvent);
event.enrichment = enrichment;

if (this.enabled.get() === false) {
return;
}
if (this.isReady.value) {
return this.startTimelineProcessing(event);
} else {
47 changes: 47 additions & 0 deletions packages/core/src/storage/sovranStorage.ts
Original file line number Diff line number Diff line change
@@ -40,6 +40,7 @@ type Data = {
userInfo: UserInfoState;
filters: DestinationFilters;
pendingEvents: SegmentEvent[];
enabled: boolean;
};

const INITIAL_VALUES: Data = {
@@ -54,6 +55,7 @@ const INITIAL_VALUES: Data = {
traits: undefined,
},
pendingEvents: [],
enabled: true,
};

const isEverythingReady = (state: ReadinessStore) =>
@@ -185,6 +187,9 @@ export class SovranStorage implements Storage {
Settable<SegmentEvent[]> &
Queue<SegmentEvent, SegmentEvent[]>;

readonly enabledStore: Store<{ enabled: boolean }>;
readonly enabled: Watchable<boolean> & Settable<boolean>;

constructor(config: StorageConfig) {
this.storeId = config.storeId;
this.storePersistor = config.storePersistor;
@@ -195,6 +200,7 @@ export class SovranStorage implements Storage {
hasRestoredUserInfo: false,
hasRestoredFilters: false,
hasRestoredPendingEvents: false,
hasRestoredEnabled: false,
});

const markAsReadyGenerator = (key: keyof ReadinessStore) => () => {
@@ -490,6 +496,47 @@ export class SovranStorage implements Storage {
this.deepLinkStore.subscribe(callback),
};

this.enabledStore = createStore(
{ enabled: INITIAL_VALUES.enabled },
{
persist: {
storeId: `${this.storeId}-enabled`,
persistor: this.storePersistor,
saveDelay: this.storePersistorSaveDelay,
onInitialized: markAsReadyGenerator('hasRestoredEnabled'),
},
}
);
// Accessor object for enabled
this.enabled = {
get: createGetter(
() => {
const state = this.enabledStore.getState();
return state.enabled;
},
async () => {
const value = await this.enabledStore.getState(true);
return value.enabled;
}
),

onChange: (callback: (value: boolean) => void) => {
return this.enabledStore.subscribe((store) => {
callback(store.enabled);
});
},

set: async (value: boolean | ((prev: boolean) => boolean)) => {
const { enabled } = await this.enabledStore.dispatch((state) => {
const newEnabled =
value instanceof Function ? value(state.enabled) : value;
return { enabled: newEnabled };
});
return enabled;
},
};


this.fixAnonymousId();
}

3 changes: 3 additions & 0 deletions packages/core/src/storage/types.ts
Original file line number Diff line number Diff line change
@@ -59,6 +59,7 @@ export interface ReadinessStore {
hasRestoredUserInfo: boolean;
hasRestoredFilters: boolean;
hasRestoredPendingEvents: boolean;
hasRestoredEnabled: boolean;
}

/**
@@ -91,6 +92,8 @@ export interface Storage {
readonly pendingEvents: Watchable<SegmentEvent[]> &
Settable<SegmentEvent[]> &
Queue<SegmentEvent, SegmentEvent[]>;

readonly enabled: Watchable<boolean> & Settable<boolean>;
}
export type DeepLinkData = {
referring_application: string;
20 changes: 20 additions & 0 deletions packages/core/src/test-helpers/mockSegmentStore.ts
Original file line number Diff line number Diff line change
@@ -24,6 +24,7 @@ import { createGetter } from '../storage/helpers';

export type StoreData = {
isReady: boolean;
enabled: boolean;
context?: DeepPartial<Context>;
settings: SegmentAPIIntegrations;
consentSettings?: SegmentAPIConsentSettings;
@@ -36,6 +37,7 @@ export type StoreData = {

const INITIAL_VALUES: StoreData = {
isReady: true,
enabled: true,
context: undefined,
settings: {
[SEGMENT_DESTINATION_KEY]: {},
@@ -90,6 +92,7 @@ export class MockSegmentStore implements Storage {
userInfo: createCallbackManager<UserInfoState>(),
deepLinkData: createCallbackManager<DeepLinkData>(),
pendingEvents: createCallbackManager<SegmentEvent[]>(),
enabled: createCallbackManager<boolean>(),
};

readonly isReady = {
@@ -103,6 +106,23 @@ export class MockSegmentStore implements Storage {
},
};

readonly enabled = {
get: createMockStoreGetter(() => {
return this.data.enabled;
}),
onChange: (_callback: (value: boolean) => void) => {
return () => {
return;
};
},
set: async (value: boolean | ((prev: boolean) => boolean)) => {
this.data.enabled =
value instanceof Function ? value(this.data.enabled ?? true) : value;
this.callbacks.enabled.run(this.data.enabled);
return this.data.enabled;
},
};

readonly context: Watchable<DeepPartial<Context> | undefined> &
Settable<DeepPartial<Context>> = {
get: createMockStoreGetter(() => ({ ...this.data.context })),
1 change: 1 addition & 0 deletions packages/core/src/test-helpers/setupSegmentClient.ts
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ export const createTestClient = (
) => {
const store = new MockSegmentStore({
isReady: true,
enabled: true,
...storeData,
});


Unchanged files with check annotations Beta

},
};
const store = new MockSegmentStore({

Check warning on line 176 in packages/core/src/__tests__/internal/checkInstalledVersion.test.ts

GitHub Actions / build-and-test

'store' is already declared in the upper scope on line 22 column 9
context: {
...currentContext,
...injectedContextByPlugins,
Object.getPrototypeOf(anotherClient),
'getEndpointForSettings'
);
expect(anotherClient['getEndpointForSettings']()).toBe(

Check warning on line 305 in packages/core/src/__tests__/internal/fetchSettings.test.ts

GitHub Actions / build-and-test

["getEndpointForSettings"] is better written in dot notation
`${expectedBaseURL}projects/${config.writeKey}/settings`
);
expect(spy).toHaveBeenCalled();
Object.getPrototypeOf(anotherClient),
'getEndpointForSettings'
);
expect(anotherClient['getEndpointForSettings']()).toBe(

Check warning on line 332 in packages/core/src/__tests__/internal/fetchSettings.test.ts

GitHub Actions / build-and-test

["getEndpointForSettings"] is better written in dot notation
`${expectedBaseURL}projects/${config.writeKey}/settings`
);
expect(spy).toHaveBeenCalled();
Object.getPrototypeOf(anotherClient),
'getEndpointForSettings'
);
expect(anotherClient['getEndpointForSettings']()).toBe(

Check warning on line 359 in packages/core/src/__tests__/internal/fetchSettings.test.ts

GitHub Actions / build-and-test

["getEndpointForSettings"] is better written in dot notation
`${expectedBaseURL}/projects/${config.writeKey}/settings`
);
expect(spy).toHaveBeenCalled();
'getEndpointForSettings'
);
// Expect the private method to throw an error
expect(anotherClient['getEndpointForSettings']()).toBe(

Check warning on line 387 in packages/core/src/__tests__/internal/fetchSettings.test.ts

GitHub Actions / build-and-test

["getEndpointForSettings"] is better written in dot notation
`${settingsCDN}/${config.writeKey}/settings`
);
expect(spy).toHaveBeenCalled();
'getEndpointForSettings'
);
const expected = `https://${cdnProxy}`;
expect(anotherClient['getEndpointForSettings']()).toBe(expected);

Check warning on line 415 in packages/core/src/__tests__/internal/fetchSettings.test.ts

GitHub Actions / build-and-test

["getEndpointForSettings"] is better written in dot notation
expect(spy).toHaveBeenCalled();
}
);
Object.getPrototypeOf(anotherClient),
'getEndpointForSettings'
);
expect(anotherClient['getEndpointForSettings']()).toBe(

Check warning on line 432 in packages/core/src/__tests__/internal/fetchSettings.test.ts

GitHub Actions / build-and-test

["getEndpointForSettings"] is better written in dot notation
`${settingsCDN}/${config.writeKey}/settings`
);
expect(spy).toHaveBeenCalled();
expect(appStateChangeListener).toBeDefined();
appStateChangeListener!(to);

Check warning on line 64 in packages/core/src/__tests__/internal/handleAppStateChange.test.ts

GitHub Actions / build-and-test

Forbidden non-null assertion
// Since the calls to process lifecycle events are not awaitable we have to await for ticks here
await new Promise(process.nextTick);
await new Promise(process.nextTick);
it('stamps basic data: timestamp and messageId for pending events when not ready', async () => {
const client = new SegmentClient(clientArgs);
jest.spyOn(client.isReady, 'value', 'get').mockReturnValue(false);
// @ts-ignore

Check warning on line 41 in packages/core/src/__tests__/methods/process.test.ts

GitHub Actions / build-and-test

Do not use "@ts-ignore" because it alters compilation errors
const timeline = client.timeline;
jest.spyOn(timeline, 'process');
};
// While not ready only timestamp and messageId should be defined
// @ts-ignore

Check warning on line 56 in packages/core/src/__tests__/methods/process.test.ts

GitHub Actions / build-and-test

Do not use "@ts-ignore" because it alters compilation errors
const pendingEvents = client.store.pendingEvents.get();
expect(pendingEvents.length).toBe(1);
const pendingEvent = pendingEvents[0];