Skip to content

Commit

Permalink
feat: migrate to use web_exp_id for web experiment device_id bucketing (
Browse files Browse the repository at this point in the history
  • Loading branch information
tyiuhc authored Jan 10, 2025
1 parent d7c167f commit 6c7c3ba
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 20 deletions.
35 changes: 17 additions & 18 deletions packages/experiment-tag/src/experiment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,24 +59,23 @@ export const initializeExperiment = async (
user = {};
}

// create new user if it does not exist, or it does not have device_id or web_exp_id
if (Object.keys(user).length === 0 || !user.device_id || !user.web_exp_id) {
if (!user.device_id || !user.web_exp_id) {
// if user has device_id, migrate it to web_exp_id
if (user.device_id) {
user.web_exp_id = user.device_id;
} else if (user.web_exp_id) {
user.device_id = user.web_exp_id;
} else {
const uuid = UUID();
// both IDs are set for backwards compatibility, to be removed in future update
user = { device_id: uuid, web_exp_id: uuid };
}
globalScope.localStorage.setItem(
experimentStorageName,
JSON.stringify(user),
);
}
// if web_exp_id does not exist:
// 1. if device_id exists, migrate device_id to web_exp_id and remove device_id
// 2. if device_id does not exist, create a new web_exp_id
// 3. if both device_id and web_exp_id exist, remove device_id
if (!user.web_exp_id) {
user.web_exp_id = user.device_id || UUID();
delete user.device_id;
globalScope.localStorage.setItem(
experimentStorageName,
JSON.stringify(user),
);
} else if (user.web_exp_id && user.device_id) {
delete user.device_id;
globalScope.localStorage.setItem(
experimentStorageName,
JSON.stringify(user),
);
}

const urlParams = getUrlParams();
Expand Down
3 changes: 1 addition & 2 deletions packages/experiment-tag/test/experiment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,11 @@ describe('initializeExperiment', () => {
test('should initialize experiment with empty user', () => {
initializeExperiment(stringify(apiKey), JSON.stringify([]));
expect(ExperimentClient.prototype.setUser).toHaveBeenCalledWith({
device_id: 'mock',
web_exp_id: 'mock',
});
expect(mockGlobal.localStorage.setItem).toHaveBeenCalledWith(
'EXP_1',
JSON.stringify({ device_id: 'mock', web_exp_id: 'mock' }),
JSON.stringify({ web_exp_id: 'mock' }),
);
});

Expand Down

0 comments on commit 6c7c3ba

Please sign in to comment.