Compare commits

...

4 Commits

Author SHA1 Message Date
Vinícius Lourenço
c3036ee9a0 chore(web): mark fire-and-forget analytics promises in AppRoutes 2026-11-20 22:42:02 -03:00
Vinícius Lourenço
394e984137 test(web): cover Sentry replay integration options 2026-11-20 22:41:52 -03:00
Vinícius Lourenço
15fbd8b2b5 perf(web): load PostHog only when analytics are enabled 2026-11-20 22:35:55 -03:00
Vinícius Lourenço
60ac8a570e perf(web): load Sentry session replay after init 2026-11-20 22:35:54 -03:00
5 changed files with 233 additions and 39 deletions

View File

@@ -27,10 +27,15 @@ import { ChatSupportState, useChatSupport } from 'hooks/useChatSupport';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { StatusCodes } from 'http-status-codes';
import {
getLoadedPostHog,
loadPostHog,
resetPostHog,
withPostHog,
} from 'lib/analytics/posthog';
import { IS_PROD } from 'lib/env';
import { getCurrentLocation, navigate, subscribe } from 'lib/router/navigation';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import posthog from 'posthog-js';
import { useAppContext } from 'providers/App/App';
import { IUser } from 'providers/App/types';
import { LicenseStatus } from 'types/api/licensesV3/getActive';
@@ -126,11 +131,11 @@ function App(): JSX.Element {
};
if (email) {
logEvent('Email Identified', identifyPayload, 'identify');
void logEvent('Email Identified', identifyPayload, 'identify');
}
if (domain) {
logEvent('Domain Identified', groupTraits, 'group');
void logEvent('Domain Identified', groupTraits, 'group');
}
if (window && window.Appcues) {
window.Appcues.identify(id, {
@@ -145,26 +150,28 @@ function App(): JSX.Element {
});
}
posthog?.identify(id, {
email,
name: displayName,
orgName,
deployment_name: hostNameParts[0],
data_region: hostNameParts[1],
deployment_url: hostname,
company_domain: domain,
source: 'signoz-ui',
isPaidUser: !!trialInfo?.trialConvertedToSubscription,
});
void withPostHog((posthog) => {
posthog.identify(id, {
email,
name: displayName,
orgName,
deployment_name: hostNameParts[0],
data_region: hostNameParts[1],
deployment_url: hostname,
company_domain: domain,
source: 'signoz-ui',
isPaidUser: !!trialInfo?.trialConvertedToSubscription,
});
posthog?.group('company', orgId, {
name: orgName,
deployment_name: hostNameParts[0],
data_region: hostNameParts[1],
deployment_url: hostname,
company_domain: domain,
source: 'signoz-ui',
isPaidUser: !!trialInfo?.trialConvertedToSubscription,
posthog.group('company', orgId, {
name: orgName,
deployment_name: hostNameParts[0],
data_region: hostNameParts[1],
deployment_url: hostname,
company_domain: domain,
source: 'signoz-ui',
isPaidUser: !!trialInfo?.trialConvertedToSubscription,
});
});
}
},
@@ -302,16 +309,7 @@ function App(): JSX.Element {
useEffect(() => {
if (isCloudUser || isEnterpriseSelfHostedUser) {
if (
window.signozBootData?.settings?.posthog?.enabled &&
window.signozBootData?.settings?.posthog?.key
) {
posthog.init(window.signozBootData.settings.posthog.key, {
api_host: window.signozBootData.settings.posthog.apiHost,
ui_host: window.signozBootData.settings.posthog.uiHost,
person_profiles: 'identified_only', // or 'always' to create profiles for anonymous users as well
});
}
void loadPostHog();
if (
!isSentryInitialized &&
@@ -327,10 +325,6 @@ function App(): JSX.Element {
// Kept for the `transaction` tag used in routing, even though
// tracing is disabled. Ref: https://github.com/SigNoz/platform-pod/issues/2393#issuecomment-4603658055
Sentry.browserTracingIntegration(),
Sentry.replayIntegration({
maskAllText: false,
blockAllMedia: false,
}),
],
tracesSampleRate: 0, // Ref: https://github.com/SigNoz/platform-pod/issues/2393#issuecomment-4603658055
replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
@@ -369,7 +363,7 @@ function App(): JSX.Element {
return null;
}
const sessionReplayUrl = posthog.get_session_replay_url?.({
const sessionReplayUrl = getLoadedPostHog()?.get_session_replay_url?.({
withTimestamp: true,
});
if (sessionReplayUrl) {
@@ -384,10 +378,14 @@ function App(): JSX.Element {
});
setIsSentryInitialized(true);
import('lib/analytics/sentryReplay')
.then(({ addSentryReplay }) => addSentryReplay())
.catch(() => undefined);
}
} else {
posthog.reset();
Sentry.close();
void resetPostHog();
void Sentry.close();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isCloudUser, isEnterpriseSelfHostedUser]);

View File

@@ -0,0 +1,118 @@
import type { Posthog } from 'types/generated/webSettings';
const mockInit = jest.fn();
const mockIdentify = jest.fn();
const mockReset = jest.fn();
jest.mock('posthog-js', () => ({
__esModule: true,
default: {
init: mockInit,
identify: mockIdentify,
reset: mockReset,
},
}));
const ENABLED: Posthog = {
enabled: true,
key: 'phc_test',
apiHost: 'https://ph.example.com',
uiHost: 'https://ui.example.com',
};
function setPostHogSettings(posthog: Posthog): void {
window.signozBootData = {
settings: {
appcues: { enabled: false },
posthog,
pylon: { enabled: false },
sentry: { enabled: false },
},
};
}
describe('posthog loader', () => {
let loader: typeof import('../posthog');
beforeEach(async () => {
jest.resetModules();
loader = await import('../posthog');
setPostHogSettings(ENABLED);
});
afterEach(() => {
window.signozBootData = undefined;
});
it.each([
['disabled', { ...ENABLED, enabled: false }],
['missing a key', { ...ENABLED, key: undefined }],
])('never loads posthog-js when it is %s', async (_, settings) => {
setPostHogSettings(settings);
const callback = jest.fn();
expect(loader.loadPostHog()).toBeUndefined();
await loader.withPostHog(callback);
await loader.resetPostHog();
expect(callback).not.toHaveBeenCalled();
expect(mockInit).not.toHaveBeenCalled();
expect(mockReset).not.toHaveBeenCalled();
expect(loader.getLoadedPostHog()).toBeUndefined();
});
it('initializes once with the boot settings', async () => {
const first = loader.loadPostHog();
const second = loader.loadPostHog();
expect(second).toBe(first);
await first;
expect(mockInit).toHaveBeenCalledTimes(1);
expect(mockInit).toHaveBeenCalledWith('phc_test', {
api_host: 'https://ph.example.com',
ui_host: 'https://ui.example.com',
person_profiles: 'identified_only',
});
});
it('runs a call made before the module loads against the initialized instance', async () => {
const identified = loader.withPostHog((posthog) =>
posthog.identify('user-1', { role: 'ADMIN' }),
);
expect(mockIdentify).not.toHaveBeenCalled();
expect(loader.getLoadedPostHog()).toBeUndefined();
await loader.loadPostHog();
await identified;
expect(mockIdentify).toHaveBeenCalledTimes(1);
expect(mockIdentify).toHaveBeenCalledWith('user-1', { role: 'ADMIN' });
expect(mockInit.mock.invocationCallOrder[0]).toBeLessThan(
mockIdentify.mock.invocationCallOrder[0],
);
expect(loader.getLoadedPostHog()).toBeDefined();
});
it('does not reset an instance that was never requested', async () => {
await loader.resetPostHog();
expect(mockReset).not.toHaveBeenCalled();
});
it('resets after the pending load finishes', async () => {
const loading = loader.loadPostHog();
const reset = loader.resetPostHog();
expect(mockReset).not.toHaveBeenCalled();
await loading;
await reset;
expect(mockReset).toHaveBeenCalledTimes(1);
expect(mockInit.mock.invocationCallOrder[0]).toBeLessThan(
mockReset.mock.invocationCallOrder[0],
);
});
});

View File

@@ -0,0 +1,25 @@
import { addIntegration, replayIntegration } from '@sentry/react';
import { addSentryReplay } from '../sentryReplay';
jest.mock('@sentry/react', () => ({
addIntegration: jest.fn(),
replayIntegration: jest.fn(),
}));
describe('addSentryReplay', () => {
it('adds the replay integration with text and media unmasked', () => {
const integration = { name: 'Replay' };
jest
.mocked(replayIntegration)
.mockReturnValue(integration as ReturnType<typeof replayIntegration>);
addSentryReplay();
expect(replayIntegration).toHaveBeenCalledWith({
maskAllText: false,
blockAllMedia: false,
});
expect(addIntegration).toHaveBeenCalledWith(integration);
});
});

View File

@@ -0,0 +1,43 @@
import type { PostHog } from 'posthog-js';
let loading: Promise<PostHog | undefined> | undefined;
let loaded: PostHog | undefined;
export function loadPostHog(): Promise<PostHog | undefined> | undefined {
const settings = window.signozBootData?.settings?.posthog;
if (!settings?.enabled || !settings.key) {
return undefined;
}
const { key, apiHost, uiHost } = settings;
loading ??= import('posthog-js')
.then(({ default: posthog }) => {
posthog.init(key, {
api_host: apiHost,
ui_host: uiHost,
person_profiles: 'identified_only', // or 'always' to create profiles for anonymous users as well
});
loaded = posthog;
return posthog;
})
.catch(() => undefined);
return loading;
}
export async function withPostHog(
callback: (posthog: PostHog) => void,
): Promise<void> {
const posthog = await loadPostHog();
if (posthog) {
callback(posthog);
}
}
export function getLoadedPostHog(): PostHog | undefined {
return loaded;
}
export async function resetPostHog(): Promise<void> {
const posthog = await loading;
posthog?.reset();
}

View File

@@ -0,0 +1,10 @@
import { addIntegration, replayIntegration } from '@sentry/react';
export function addSentryReplay(): void {
addIntegration(
replayIntegration({
maskAllText: false,
blockAllMedia: false,
}),
);
}