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

fix(instantsearch.js): fix user token not being set in time for the first query #6377

Merged
merged 18 commits into from
Oct 23, 2024
Merged
2 changes: 1 addition & 1 deletion bundlesize.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
},
{
"path": "./packages/instantsearch.js/dist/instantsearch.development.js",
"maxSize": "180.25 kB"
"maxSize": "180.50 kB"
},
{
"path": "packages/react-instantsearch-core/dist/umd/ReactInstantSearchCore.min.js",
Expand Down
15 changes: 15 additions & 0 deletions packages/instantsearch.js/src/lib/utils/uuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Create UUID according to
* https://www.ietf.org/rfc/rfc4122.txt.
*
* @returns Generated UUID.
*/
export function createUUID(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
/* eslint-disable no-bitwise */
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
/* eslint-enable */
return v.toString(16);
});
}
134 changes: 117 additions & 17 deletions packages/instantsearch.js/src/middlewares/createInsightsMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
find,
safelyRunOnBrowser,
} from '../lib/utils';
import { createUUID } from '../lib/utils/uuid';

import type {
InsightsClient,
Expand Down Expand Up @@ -50,6 +51,8 @@ export type InsightsClientWithGlobals = InsightsClient & {

export type CreateInsightsMiddleware = typeof createInsightsMiddleware;

type TokenType = 'authenticated' | 'default';

export function createInsightsMiddleware<
TInsightsClient extends ProvidedInsightsClient
>(props: InsightsProps<TInsightsClient> = {}): InternalMiddleware {
Expand All @@ -61,6 +64,7 @@ export function createInsightsMiddleware<
$$automatic = false,
} = props;

let currentTokenType: TokenType | undefined;
let potentialInsightsClient: ProvidedInsightsClient = _insightsClient;

if (!_insightsClient && _insightsClient !== null) {
Expand Down Expand Up @@ -111,6 +115,8 @@ export function createInsightsMiddleware<
'could not extract Algolia credentials from searchClient in insights middleware.'
);

let queuedInitParams: Partial<InsightsMethodMap['init'][0]> | undefined =
undefined;
let queuedUserToken: string | undefined = undefined;
let queuedAuthenticatedUserToken: string | undefined = undefined;
let userTokenBeforeInit: string | undefined = undefined;
Expand All @@ -129,9 +135,10 @@ export function createInsightsMiddleware<
// At this point, even though `search-insights` is not loaded yet,
// we still want to read the token from the queue.
// Otherwise, the first search call will be fired without the token.
[queuedUserToken, queuedAuthenticatedUserToken] = [
[queuedUserToken, queuedAuthenticatedUserToken, queuedInitParams] = [
'setUserToken',
'setAuthenticatedUserToken',
'init',
].map((key) => {
const [, value] =
find(queue.slice().reverse(), ([method]) => method === key) || [];
Expand Down Expand Up @@ -192,11 +199,29 @@ export function createInsightsMiddleware<
instantSearchInstance.emit('error', new Error(errorMessage));
}
},
// eslint-disable-next-line complexity
shaejaz marked this conversation as resolved.
Show resolved Hide resolved
started() {
insightsClient('addAlgoliaAgent', 'insights-middleware');

helper = instantSearchInstance.mainHelper!;

const { queue: queueAtStart } = insightsClient;

if (Array.isArray(queueAtStart)) {
[queuedUserToken, queuedAuthenticatedUserToken] = [
'setUserToken',
'setAuthenticatedUserToken',
shaejaz marked this conversation as resolved.
Show resolved Hide resolved
].map((key) => {
const [, value] =
find(
queueAtStart.slice().reverse(),
([method]) => method === key
) || [];

return value;
});
}

initialParameters = {
userToken: (helper.state as PlainSearchParameters).userToken,
clickAnalytics: helper.state.clickAnalytics,
Expand All @@ -217,7 +242,9 @@ export function createInsightsMiddleware<

const setUserTokenToSearch = (
userToken?: string | number,
immediate = false
tokenType?: TokenType,
immediate = false,
unsetAuthenticatedUserToken = false
) => {
const normalizedUserToken = normalizeUserToken(userToken);

Expand All @@ -237,6 +264,19 @@ export function createInsightsMiddleware<
if (existingToken && existingToken !== userToken) {
instantSearchInstance.scheduleSearch();
}

currentTokenType = tokenType;
}

// the authenticated user token cannot be overridden by a user or anonymous token
// for instant search query requests
if (
currentTokenType &&
currentTokenType === 'authenticated' &&
tokenType === 'default' &&
!unsetAuthenticatedUserToken
) {
return;
}

// Delay the token application to the next render cycle
Expand All @@ -247,19 +287,16 @@ export function createInsightsMiddleware<
}
};

const anonymousUserToken = getInsightsAnonymousUserTokenInternal();
if (anonymousUserToken) {
// When `aa('init', { ... })` is called, it creates an anonymous user token in cookie.
// We can set it as userToken.
setUserTokenToSearch(anonymousUserToken, true);
}

function setUserToken(
token: string | number,
userToken?: string | number,
authenticatedUserToken?: string | number
) {
setUserTokenToSearch(token, true);
setUserTokenToSearch(
token,
authenticatedUserToken ? 'authenticated' : 'default',
true
);

if (userToken) {
insightsClient('setUserToken', userToken);
Expand All @@ -269,13 +306,58 @@ export function createInsightsMiddleware<
}
}

let anonymousUserToken: string | undefined = undefined;
const anonymousTokenFromInsights =
getInsightsAnonymousUserTokenInternal();
if (anonymousTokenFromInsights) {
// When `aa('init', { ... })` is called, it creates an anonymous user token in cookie.
// We can set it as userToken on instantsearch and insights. If it's not set as an insights
// userToken before a sendEvent, insights automatically generates a new anonymous token,
// causing a state change and an unnecessary query on instantsearch.
anonymousUserToken = anonymousTokenFromInsights;
} else {
const token = `anonymous-${createUUID()}`;
anonymousUserToken = token;
}

let authenticatedUserTokenFromInit: string | undefined;
let userTokenFromInit: string | undefined;

// By the time the first query is sent, the token would not be set by the insights
// onChange callbacks. It is explicitly being set here so that the first query
// has the initial tokens set and inturn a second query isn't automatically made
// when the onChange callback actually changes the state.
if (insightsInitParams) {
shaejaz marked this conversation as resolved.
Show resolved Hide resolved
if (insightsInitParams.authenticatedUserToken) {
authenticatedUserTokenFromInit =
insightsInitParams.authenticatedUserToken;
} else if (insightsInitParams.userToken) {
userTokenFromInit = insightsInitParams.userToken;
}
}

// We consider the `userToken` or `authenticatedUserToken` before an
// `init` call of higher importance than one from the queue.
// `init` call of higher importance than one from the queue and ones set
// from the init props to be higher than that.
const tokenFromInit =
authenticatedUserTokenFromInit || userTokenFromInit;
const tokenBeforeInit =
authenticatedUserTokenBeforeInit || userTokenBeforeInit;
const queuedToken = queuedAuthenticatedUserToken || queuedUserToken;
shaejaz marked this conversation as resolved.
Show resolved Hide resolved

if (tokenBeforeInit) {
if (tokenFromInit) {
setUserToken(
tokenFromInit,
userTokenFromInit,
authenticatedUserTokenFromInit
);
} else if (initialParameters.userToken) {
shaejaz marked this conversation as resolved.
Show resolved Hide resolved
setUserToken(
initialParameters.userToken,
initialParameters.userToken,
undefined
);
} else if (tokenBeforeInit) {
setUserToken(
tokenBeforeInit,
userTokenBeforeInit,
Expand All @@ -287,12 +369,30 @@ export function createInsightsMiddleware<
queuedUserToken,
queuedAuthenticatedUserToken
);
} else if (anonymousUserToken) {
setUserToken(anonymousUserToken, anonymousUserToken, undefined);
Copy link
Contributor

Choose a reason for hiding this comment

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

would like to see the setUserToken function simplified (can be separate pr) to not have three arguments


if (insightsInitParams?.useCookie || queuedInitParams?.useCookie) {
const d = new Date();
d.setTime(
d.getTime() +
(insightsInitParams?.cookieDuration ||
queuedInitParams?.cookieDuration ||
30 * 24 * 60 * 60 * 1000 * 6)
shaejaz marked this conversation as resolved.
Show resolved Hide resolved
);
const expires = `expires=${d.toUTCString()}`;
document.cookie = `_ALGOLIA=${anonymousUserToken};${expires};path=/`;
}
}

// This updates userToken which is set explicitly by `aa('setUserToken', userToken)`
insightsClient('onUserTokenChange', setUserTokenToSearch, {
immediate: true,
});
insightsClient(
'onUserTokenChange',
(token) => setUserTokenToSearch(token, 'default', true),
{
immediate: true,
}
);

// This updates userToken which is set explicitly by `aa('setAuthenticatedtUserToken', authenticatedUserToken)`
insightsClient(
Expand All @@ -301,11 +401,11 @@ export function createInsightsMiddleware<
// If we're unsetting the `authenticatedUserToken`, we revert to the `userToken`
if (!authenticatedUserToken) {
insightsClient('getUserToken', null, (_, userToken) => {
setUserTokenToSearch(userToken);
setUserTokenToSearch(userToken, 'default', true, true);
});
}

setUserTokenToSearch(authenticatedUserToken);
setUserTokenToSearch(authenticatedUserToken, 'authenticated', true);
},
{
immediate: true,
Expand Down