Skip to content
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

RHOAIENG-9232 Create useTrackUser #3024

Merged
merged 1 commit into from
Aug 12, 2024
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
16 changes: 14 additions & 2 deletions frontend/src/concepts/analyticsTracking/segmentIOUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ export const firePageEvent = (): void => {
}
};

// Stuff that gets send over as traits on an identify call. Must not include (anonymous) user Id.
type IdentifyTraits = {
isAdmin: boolean;
canCreateProjects: boolean;
clusterID: string;
};

/*
* This fires a call to associate further processing with the passed (anonymous) userId
* in the properties.
Expand All @@ -94,8 +101,13 @@ export const fireIdentifyEvent = (properties: IdentifyEventProperties): void =>
const clusterID = window.clusterID ?? '';
if (DEV_MODE) {
/* eslint-disable-next-line no-console */
console.log(`Identify event triggered`);
console.log(`Identify event triggered: ${JSON.stringify(properties)}`);
} else if (window.analytics) {
window.analytics.identify(properties.anonymousID, { clusterID });
const traits: IdentifyTraits = {
clusterID,
isAdmin: properties.isAdmin,
canCreateProjects: properties.canCreateProjects,
};
window.analytics.identify(properties.anonymousID, traits);
}
};
3 changes: 3 additions & 0 deletions frontend/src/concepts/analyticsTracking/trackingProperties.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ export type ODHSegmentKey = {
};

export type IdentifyEventProperties = {
isAdmin: boolean;
anonymousID?: string;
userId?: string;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

userId isn't used anywhere. Should this be removed? I also thought that we shouldn't include identifiable information in events.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It could indeed be removed from this PR. UserId would be the web-user-id for the sandbox case.

canCreateProjects: boolean;
};

export const enum TrackingOutcome {
Expand Down
30 changes: 15 additions & 15 deletions frontend/src/concepts/analyticsTracking/useSegmentTracking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from 'react';
import { useAppContext } from '~/app/AppContext';
import { useAppSelector } from '~/redux/hooks';
import { fireIdentifyEvent, firePageEvent } from '~/concepts/analyticsTracking/segmentIOUtils';
import { useTrackUser } from '~/concepts/analyticsTracking/useTrackUser';
import { useWatchSegmentKey } from './useWatchSegmentKey';
import { initSegment } from './initSegment';

Expand All @@ -10,28 +11,27 @@ export const useSegmentTracking = (): void => {
const { dashboardConfig } = useAppContext();
const username = useAppSelector((state) => state.user);
const clusterID = useAppSelector((state) => state.clusterID);
const [userProps, uPropsLoaded] = useTrackUser(username);

React.useEffect(() => {
if (segmentKey && loaded && !loadError && username && clusterID) {
const computeUserId = async () => {
const anonymousIDBuffer = await crypto.subtle.digest(
'SHA-1',
new TextEncoder().encode(username),
);
const anonymousIDArray = Array.from(new Uint8Array(anonymousIDBuffer));
return anonymousIDArray.map((b) => b.toString(16).padStart(2, '0')).join('');
};

if (segmentKey && loaded && !loadError && username && clusterID && uPropsLoaded) {
window.clusterID = clusterID;
initSegment({
segmentKey,
enabled: !dashboardConfig.spec.dashboardConfig.disableTracking,
}).then(() => {
computeUserId().then((userId) => {
fireIdentifyEvent({ anonymousID: userId });
firePageEvent();
});
fireIdentifyEvent(userProps);
pilhuhn marked this conversation as resolved.
Show resolved Hide resolved
firePageEvent();
});
}
}, [clusterID, loadError, loaded, segmentKey, username, dashboardConfig]);
}, [
clusterID,
loadError,
loaded,
segmentKey,
username,
dashboardConfig,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove dashboardConfig from the list of dependencies because it's too broad.
Assign dashboardConfig.spec.dashboardConfig.disableTracking to a local variable and use it as a dependency instead.

userProps,
uPropsLoaded,
]);
};
50 changes: 50 additions & 0 deletions frontend/src/concepts/analyticsTracking/useTrackUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React from 'react';
import { useUser } from '~/redux/selectors';
import { useAccessReview } from '~/api';
import { AccessReviewResourceAttributes } from '~/k8sTypes';
import { IdentifyEventProperties } from '~/concepts/analyticsTracking/trackingProperties';

export const useTrackUser = (username?: string): [IdentifyEventProperties, boolean] => {
const { isAdmin } = useUser();
const [anonymousId, setAnonymousId] = React.useState<string | undefined>(undefined);

const [loaded, setLoaded] = React.useState(false);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unnecessary to track this loaded as a separate state.
Compute it as !!anonymousId && acLoaded

const createReviewResource: AccessReviewResourceAttributes = {
group: 'project.openshift.io',
resource: 'projectrequests',
verb: 'create',
};
const [allowCreate, acLoaded] = useAccessReview(createReviewResource);

React.useEffect(() => {
const computeAnonymousUserId = async () => {
const anonymousIDBuffer = await crypto.subtle.digest(
'SHA-1',
new TextEncoder().encode(username),
);
const anonymousIDArray = Array.from(new Uint8Array(anonymousIDBuffer));
const aId = anonymousIDArray.map((b) => b.toString(16).padStart(2, '0')).join('');
return aId;
};

if (!anonymousId) {
computeAnonymousUserId().then((val) => {
setAnonymousId(val);
});
}
if (acLoaded && anonymousId) {
setLoaded(true);
}
}, [username, anonymousId, acLoaded]);
Comment on lines +30 to +38
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If username changes, you aren't recomputing the anonymous id. Although I don't think username should change and you are only going to compute the anonymous id once. But should you recompute?

If you don't care to recompute based on username changes, then you can remove all hook dependencies.

Suggested change
if (!anonymousId) {
computeAnonymousUserId().then((val) => {
setAnonymousId(val);
});
}
if (acLoaded && anonymousId) {
setLoaded(true);
}
}, [username, anonymousId, acLoaded]);
computeAnonymousUserId().then((val) => {
setAnonymousId(val);
});
// compute anonymousId only once
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The usename is set at login. So I don't think it will ever change during one session.


const props: IdentifyEventProperties = React.useMemo(
() => ({
isAdmin,
canCreateProjects: allowCreate,
anonymousID: anonymousId,
}),
[isAdmin, allowCreate, anonymousId],
);

return [props, loaded];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return [props, loaded];
return [props, acLoaded && !!anonymousId];

};
Loading