debian-mirror-gitlab/app/assets/javascripts/experimentation/utils.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

53 lines
2 KiB
JavaScript
Raw Normal View History

2022-01-26 12:08:38 +05:30
// This file only applies to use of experiments through https://gitlab.com/gitlab-org/ruby/gems/gitlab-experiment
import { get, mapValues, pick } from 'lodash';
2021-06-08 01:23:25 +05:30
import { DEFAULT_VARIANT, CANDIDATE_VARIANT, TRACKING_CONTEXT_SCHEMA } from './constants';
2021-04-17 20:07:23 +05:30
2021-11-11 11:23:49 +05:30
function getExperimentsData() {
2021-12-11 22:18:48 +05:30
// Pull from deprecated window.gon.experiment
const experimentsFromGon = get(window, ['gon', 'experiment'], {});
// Pull from preferred window.gl.experiments
const experimentsFromGl = get(window, ['gl', 'experiments'], {});
2022-01-26 12:08:38 +05:30
// Bandaid to allow-list only the properties which the current gitlab_experiment
// context schema suppports, since we most often use this data to create that
// Snowplow context.
2021-12-11 22:18:48 +05:30
// See TRACKING_CONTEXT_SCHEMA for current version (1-0-0)
// https://gitlab.com/gitlab-org/iglu/-/blob/master/public/schemas/com.gitlab/gitlab_experiment/jsonschema/1-0-0
2022-01-26 12:08:38 +05:30
return mapValues({ ...experimentsFromGon, ...experimentsFromGl }, (xp) => {
return pick(xp, ['experiment', 'key', 'variant', 'migration_keys']);
});
}
2021-12-11 22:18:48 +05:30
2022-01-26 12:08:38 +05:30
function createGitlabExperimentContext(experimentData) {
return { schema: TRACKING_CONTEXT_SCHEMA, data: experimentData };
2021-11-11 11:23:49 +05:30
}
2021-04-17 20:07:23 +05:30
export function getExperimentData(experimentName) {
2021-11-11 11:23:49 +05:30
return getExperimentsData()[experimentName];
2021-04-17 20:07:23 +05:30
}
2021-11-11 11:23:49 +05:30
export function getAllExperimentContexts() {
2022-01-26 12:08:38 +05:30
return Object.values(getExperimentsData()).map(createGitlabExperimentContext);
2021-06-08 01:23:25 +05:30
}
2022-01-26 12:08:38 +05:30
export function isExperimentVariant(experimentName, variantName = CANDIDATE_VARIANT) {
2021-04-17 20:07:23 +05:30
return getExperimentData(experimentName)?.variant === variantName;
}
2021-04-29 21:17:54 +05:30
export function getExperimentVariant(experimentName) {
return getExperimentData(experimentName)?.variant || DEFAULT_VARIANT;
}
2021-12-11 22:18:48 +05:30
export function experiment(experimentName, { use, control, candidate, ...variants }) {
2021-04-29 21:17:54 +05:30
const variant = getExperimentVariant(experimentName);
switch (variant) {
case DEFAULT_VARIANT:
2021-12-11 22:18:48 +05:30
return (use || control).call();
2021-04-29 21:17:54 +05:30
case CANDIDATE_VARIANT:
2021-12-11 22:18:48 +05:30
return (variants.try || candidate).call();
2021-04-29 21:17:54 +05:30
default:
return variants[variant].call();
}
}