logExperiment.tsx 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import * as Sentry from '@sentry/react';
  2. import {Client} from 'sentry/api';
  3. import {experimentConfig, unassignedValue} from 'sentry/data/experimentConfig';
  4. import ConfigStore from 'sentry/stores/configStore';
  5. import type {ExperimentKey} from 'sentry/types/experiments';
  6. import {ExperimentType} from 'sentry/types/experiments';
  7. import type {Organization} from 'sentry/types/organization';
  8. import {defined} from 'sentry/utils';
  9. import localStorage from 'sentry/utils/localStorage';
  10. // the local storage key that stores which experiments we've logged
  11. const SENTRY_EXPERIMENTS_KEY = 'logged-sentry-experiments';
  12. const unitNameMap = {
  13. organization: 'org_id',
  14. user: 'user_id',
  15. } as const;
  16. type Options = {
  17. /**
  18. * The experiment key
  19. */
  20. key: ExperimentKey;
  21. /**
  22. * The organization for org based experiments
  23. */
  24. organization?: Organization;
  25. };
  26. /**
  27. * Log exposure to an experiment.
  28. *
  29. * Generally you will want to call this just before the logic to determine the
  30. * variant or exposure of a particular experiment.
  31. */
  32. export default async function logExperiment({key, organization}: Options) {
  33. // Never log experiments for super users
  34. const user = ConfigStore.get('user');
  35. if (user.isSuperuser) {
  36. return;
  37. }
  38. const config = experimentConfig[key];
  39. if (config === undefined) {
  40. return;
  41. }
  42. const {type, parameter} = config;
  43. const assignment =
  44. type === ExperimentType.ORGANIZATION
  45. ? organization?.experiments?.[key]
  46. : type === ExperimentType.USER
  47. ? // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  48. user.experiments?.[key]
  49. : null;
  50. // Nothing to log if there is no assignment
  51. if (!defined(assignment)) {
  52. return;
  53. }
  54. // Do not log if the assignment matches the unassigned group constant
  55. if (assignment === unassignedValue) {
  56. return;
  57. }
  58. const unitId =
  59. type === ExperimentType.ORGANIZATION
  60. ? Number(organization?.id)
  61. : type === ExperimentType.USER
  62. ? Number(user.id)
  63. : null;
  64. // if the value of this experiment matches the stored value, we can
  65. // skip calling log_exposure
  66. if (getExperimentLogged(key) === unitId) {
  67. return;
  68. }
  69. const data = {
  70. experiment_name: key,
  71. unit_name: unitNameMap[type],
  72. unit_id: unitId,
  73. params: {[parameter]: assignment},
  74. };
  75. const client = new Client({baseUrl: ''});
  76. try {
  77. await client.requestPromise('/_experiment/log_exposure/', {
  78. method: 'POST',
  79. data,
  80. });
  81. // update local storage with the new experiment we've logged
  82. setExperimentLogged(key, unitId);
  83. } catch (error) {
  84. Sentry.withScope(scope => {
  85. scope.setExtra('data', data);
  86. scope.setExtra('error', error);
  87. Sentry.captureException(new Error('Could not log experiment'));
  88. });
  89. }
  90. }
  91. const getExperimentsLogged = () => {
  92. try {
  93. const localStorageExperiments = localStorage.getItem(SENTRY_EXPERIMENTS_KEY);
  94. const jsonData: unknown = JSON.parse(localStorageExperiments || '{}');
  95. if (typeof jsonData === 'object' && !Array.isArray(jsonData) && jsonData !== null) {
  96. return jsonData;
  97. }
  98. } catch (err) {
  99. // some sort of malformed json
  100. Sentry.captureException(err);
  101. }
  102. // by default, return an empty config
  103. return {};
  104. };
  105. const getExperimentLogged = (key: string) => {
  106. const experimentData = getExperimentsLogged();
  107. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  108. return experimentData[key];
  109. };
  110. const setExperimentLogged = (key: string, unitId: number | null) => {
  111. // shouldn't be null but need to make TS happy
  112. if (unitId === null) {
  113. return;
  114. }
  115. const experimentData = {...getExperimentsLogged(), [key]: unitId};
  116. localStorage.setItem(SENTRY_EXPERIMENTS_KEY, JSON.stringify(experimentData));
  117. };