groupingStore.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. import pick from 'lodash/pick';
  2. import {createStore} from 'reflux';
  3. import {mergeGroups} from 'sentry/actionCreators/group';
  4. import {
  5. addErrorMessage,
  6. addLoadingMessage,
  7. addSuccessMessage,
  8. } from 'sentry/actionCreators/indicator';
  9. import GroupingActions from 'sentry/actions/groupingActions';
  10. import {Client} from 'sentry/api';
  11. import {Group, Organization, Project} from 'sentry/types';
  12. import {Event} from 'sentry/types/event';
  13. import {makeSafeRefluxStore} from 'sentry/utils/makeSafeRefluxStore';
  14. import {CommonStoreDefinition} from './types';
  15. // Between 0-100
  16. const MIN_SCORE = 0.6;
  17. // @param score: {[key: string]: number}
  18. const checkBelowThreshold = (scores = {}) => {
  19. const scoreKeys = Object.keys(scores);
  20. return !scoreKeys.map(key => scores[key]).find(score => score >= MIN_SCORE);
  21. };
  22. type State = {
  23. // "Compare" button state
  24. enableFingerprintCompare: boolean;
  25. error: boolean;
  26. filteredSimilarItems: [];
  27. loading: boolean;
  28. mergeDisabled: boolean;
  29. mergeList: Array<string>;
  30. mergeState: Map<any, any>;
  31. // List of fingerprints that belong to issue
  32. mergedItems: [];
  33. mergedLinks: string;
  34. similarItems: [];
  35. similarLinks: string;
  36. // Disabled state of "Unmerge" button in "Merged" tab (for Issues)
  37. unmergeDisabled: boolean;
  38. // If "Collapse All" was just used, this will be true
  39. unmergeLastCollapsed: boolean;
  40. // Map of {[fingerprint]: Array<fingerprint, event id>} that is selected to be unmerged
  41. unmergeList: Map<any, any>;
  42. // Map of state for each fingerprint (i.e. "collapsed")
  43. unmergeState: Map<any, any>;
  44. };
  45. type ScoreMap = Record<string, number | null>;
  46. type ApiFingerprint = {
  47. id: string;
  48. latestEvent: Event;
  49. childId?: string;
  50. childLabel?: string;
  51. eventCount?: number;
  52. label?: string;
  53. lastSeen?: string;
  54. parentId?: string;
  55. parentLabel?: string;
  56. state?: string;
  57. };
  58. type ChildFingerprint = {
  59. childId: string;
  60. childLabel?: string;
  61. eventCount?: number;
  62. lastSeen?: string;
  63. latestEvent?: Event;
  64. };
  65. export type Fingerprint = {
  66. children: Array<ChildFingerprint>;
  67. eventCount: number;
  68. id: string;
  69. latestEvent: Event;
  70. label?: string;
  71. lastSeen?: string;
  72. parentId?: string;
  73. parentLabel?: string;
  74. state?: string;
  75. };
  76. type ResponseProcessors = {
  77. merged: (item: ApiFingerprint[]) => Fingerprint[];
  78. similar: (data: [Group, ScoreMap]) => {
  79. aggregate: Record<string, number>;
  80. isBelowThreshold: boolean;
  81. issue: Group;
  82. score: ScoreMap;
  83. scoresByInterface: Record<string, Array<[string, number | null]>>;
  84. };
  85. };
  86. type DataKey = keyof ResponseProcessors;
  87. type ResultsAsArrayDataMerged = Parameters<ResponseProcessors['merged']>[0];
  88. type ResultsAsArrayDataSimilar = Array<Parameters<ResponseProcessors['similar']>[0]>;
  89. type ResultsAsArray = Array<{
  90. data: ResultsAsArrayDataMerged | ResultsAsArrayDataSimilar;
  91. dataKey: DataKey;
  92. links: string | null;
  93. }>;
  94. type IdState = {
  95. busy?: boolean;
  96. checked?: boolean;
  97. collapsed?: boolean;
  98. };
  99. type InternalDefinition = {
  100. api: Client;
  101. };
  102. interface GroupingStoreDefinition
  103. extends CommonStoreDefinition<State>,
  104. InternalDefinition {
  105. getInitialState(): State;
  106. init(): void;
  107. isAllUnmergedSelected(): boolean;
  108. onFetch(
  109. toFetchArray?: Array<{
  110. dataKey: DataKey;
  111. endpoint: string;
  112. queryParams?: Record<string, any>;
  113. }>
  114. ): Promise<any>;
  115. onMerge(props: {
  116. params?: {
  117. groupId: Group['id'];
  118. orgId: Organization['id'];
  119. projectId: Project['id'];
  120. };
  121. projectId?: Project['id'];
  122. query?: string;
  123. }): undefined | Promise<any>;
  124. onToggleCollapseFingerprint(fingerprint: string): void;
  125. onToggleCollapseFingerprints(): void;
  126. onToggleMerge(id: string): void;
  127. onToggleUnmerge(props: [string, string] | string): void;
  128. onUnmerge(props: {
  129. groupId: Group['id'];
  130. errorMessage?: string;
  131. loadingMessage?: string;
  132. successMessage?: string;
  133. }): void;
  134. setStateForId(
  135. map: Map<string, IdState>,
  136. idOrIds: Array<string> | string,
  137. newState: IdState
  138. ): Array<IdState>;
  139. triggerFetchState(): Pick<
  140. State,
  141. | 'similarItems'
  142. | 'filteredSimilarItems'
  143. | 'mergedItems'
  144. | 'mergedLinks'
  145. | 'similarLinks'
  146. | 'mergeState'
  147. | 'unmergeState'
  148. | 'loading'
  149. | 'error'
  150. >;
  151. triggerMergeState(): Pick<State, 'mergeState' | 'mergeDisabled' | 'mergeList'>;
  152. triggerUnmergeState(): Pick<
  153. State,
  154. | 'unmergeDisabled'
  155. | 'unmergeState'
  156. | 'unmergeList'
  157. | 'enableFingerprintCompare'
  158. | 'unmergeLastCollapsed'
  159. >;
  160. }
  161. const storeConfig: GroupingStoreDefinition = {
  162. listenables: [GroupingActions],
  163. api: new Client(),
  164. init() {
  165. const state = this.getInitialState();
  166. Object.entries(state).forEach(([key, value]) => {
  167. this[key] = value;
  168. });
  169. },
  170. getInitialState() {
  171. return {
  172. // List of fingerprints that belong to issue
  173. mergedItems: [],
  174. // Map of {[fingerprint]: Array<fingerprint, event id>} that is selected to be unmerged
  175. unmergeList: new Map(),
  176. // Map of state for each fingerprint (i.e. "collapsed")
  177. unmergeState: new Map(),
  178. // Disabled state of "Unmerge" button in "Merged" tab (for Issues)
  179. unmergeDisabled: true,
  180. // If "Collapse All" was just used, this will be true
  181. unmergeLastCollapsed: false,
  182. // "Compare" button state
  183. enableFingerprintCompare: false,
  184. similarItems: [],
  185. filteredSimilarItems: [],
  186. similarLinks: '',
  187. mergeState: new Map(),
  188. mergeList: [],
  189. mergedLinks: '',
  190. mergeDisabled: false,
  191. loading: true,
  192. error: false,
  193. };
  194. },
  195. setStateForId(map, idOrIds, newState) {
  196. const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
  197. return ids.map(id => {
  198. const state = (map.has(id) && map.get(id)) || {};
  199. const mergedState = {...state, ...newState};
  200. map.set(id, mergedState);
  201. return mergedState;
  202. });
  203. },
  204. isAllUnmergedSelected() {
  205. const lockedItems =
  206. (Array.from(this.unmergeState.values()) as Array<IdState>).filter(
  207. ({busy}) => busy
  208. ) || [];
  209. return (
  210. this.unmergeList.size ===
  211. this.mergedItems.filter(({latestEvent}) => !!latestEvent).length -
  212. lockedItems.length
  213. );
  214. },
  215. // Fetches data
  216. onFetch(toFetchArray) {
  217. const requests = toFetchArray || this.toFetchArray;
  218. // Reset state and trigger update
  219. this.init();
  220. this.triggerFetchState();
  221. const promises = requests.map(
  222. ({endpoint, queryParams, dataKey}) =>
  223. new Promise((resolve, reject) => {
  224. this.api.request(endpoint, {
  225. method: 'GET',
  226. data: queryParams,
  227. success: (data, _, resp) => {
  228. resolve({
  229. dataKey,
  230. data,
  231. links: resp ? resp.getResponseHeader('Link') : null,
  232. });
  233. },
  234. error: err => {
  235. const error = err.responseJSON?.detail || true;
  236. reject(error);
  237. },
  238. });
  239. })
  240. );
  241. const responseProcessors: ResponseProcessors = {
  242. merged: items => {
  243. const newItemsMap: Record<string, Fingerprint> = {};
  244. const newItems: Fingerprint[] = [];
  245. items.forEach(item => {
  246. if (!newItemsMap[item.id]) {
  247. const newItem = {
  248. eventCount: 0,
  249. children: [],
  250. // lastSeen and latestEvent properties are correct
  251. // since the server returns items in
  252. // descending order of lastSeen
  253. ...item,
  254. };
  255. // Check for locked items
  256. this.setStateForId(this.unmergeState, item.id, {
  257. busy: item.state === 'locked',
  258. });
  259. newItemsMap[item.id] = newItem;
  260. newItems.push(newItem);
  261. }
  262. const newItem = newItemsMap[item.id];
  263. const {childId, childLabel, eventCount, lastSeen, latestEvent} = item;
  264. if (eventCount) {
  265. newItem.eventCount += eventCount;
  266. }
  267. if (childId) {
  268. newItem.children.push({
  269. childId,
  270. childLabel,
  271. lastSeen,
  272. latestEvent,
  273. eventCount,
  274. });
  275. }
  276. });
  277. return newItems;
  278. },
  279. similar: ([issue, scoreMap]) => {
  280. // Hide items with a low scores
  281. const isBelowThreshold = checkBelowThreshold(scoreMap);
  282. // List of scores indexed by interface (i.e., exception and message)
  283. // Note: for v2, the interface is always "similarity". When v2 is
  284. // rolled out we can get rid of this grouping entirely.
  285. const scoresByInterface = Object.keys(scoreMap)
  286. .map(scoreKey => [scoreKey, scoreMap[scoreKey]])
  287. .reduce((acc, [scoreKey, score]) => {
  288. // v1 layout: '<interface>:...'
  289. const [interfaceName] = String(scoreKey).split(':');
  290. if (!acc[interfaceName]) {
  291. acc[interfaceName] = [];
  292. }
  293. acc[interfaceName].push([scoreKey, score]);
  294. return acc;
  295. }, {});
  296. // Aggregate score by interface
  297. const aggregate = Object.keys(scoresByInterface)
  298. .map(interfaceName => [interfaceName, scoresByInterface[interfaceName]])
  299. .reduce((acc, [interfaceName, allScores]) => {
  300. // `null` scores means feature was not present in both issues, do not
  301. // include in aggregate
  302. const scores = allScores.filter(([, score]) => score !== null);
  303. const avg = scores.reduce((sum, [, score]) => sum + score, 0) / scores.length;
  304. acc[interfaceName] = avg;
  305. return acc;
  306. }, {});
  307. return {
  308. issue,
  309. score: scoreMap,
  310. scoresByInterface,
  311. aggregate,
  312. isBelowThreshold,
  313. };
  314. },
  315. };
  316. if (toFetchArray) {
  317. this.toFetchArray = toFetchArray;
  318. }
  319. return Promise.all(promises).then(
  320. resultsArray => {
  321. (resultsArray as ResultsAsArray).forEach(({dataKey, data, links}) => {
  322. const items =
  323. dataKey === 'similar'
  324. ? (data as ResultsAsArrayDataSimilar).map(responseProcessors[dataKey])
  325. : responseProcessors[dataKey](data as ResultsAsArrayDataMerged);
  326. this[`${dataKey}Items`] = items;
  327. this[`${dataKey}Links`] = links;
  328. });
  329. this.loading = false;
  330. this.error = false;
  331. this.triggerFetchState();
  332. },
  333. () => {
  334. this.loading = false;
  335. this.error = true;
  336. this.triggerFetchState();
  337. }
  338. );
  339. },
  340. // Toggle merge checkbox
  341. onToggleMerge(id) {
  342. let checked = false;
  343. // Don't do anything if item is busy
  344. const state = this.mergeState.has(id) ? this.mergeState.get(id) : undefined;
  345. if (state?.busy === true) {
  346. return;
  347. }
  348. if (this.mergeList.includes(id)) {
  349. this.mergeList = this.mergeList.filter(item => item !== id);
  350. } else {
  351. this.mergeList = [...this.mergeList, id];
  352. checked = true;
  353. }
  354. this.setStateForId(this.mergeState, id, {
  355. checked,
  356. });
  357. this.triggerMergeState();
  358. },
  359. // Toggle unmerge check box
  360. onToggleUnmerge([fingerprint, eventId]) {
  361. let checked = false;
  362. // Uncheck an item to unmerge
  363. const state = this.unmergeState.get(fingerprint);
  364. if (state?.busy === true) {
  365. return;
  366. }
  367. if (this.unmergeList.has(fingerprint)) {
  368. this.unmergeList.delete(fingerprint);
  369. } else {
  370. this.unmergeList.set(fingerprint, eventId);
  371. checked = true;
  372. }
  373. // Update "checked" state for row
  374. this.setStateForId(this.unmergeState, fingerprint, {
  375. checked,
  376. });
  377. // Unmerge should be disabled if 0 or all items are selected, or if there's
  378. // only one item to select
  379. this.unmergeDisabled =
  380. this.mergedItems.size <= 1 ||
  381. this.unmergeList.size === 0 ||
  382. this.isAllUnmergedSelected();
  383. this.enableFingerprintCompare = this.unmergeList.size === 2;
  384. this.triggerUnmergeState();
  385. },
  386. onUnmerge({groupId, loadingMessage, successMessage, errorMessage}) {
  387. const ids = Array.from(this.unmergeList.keys()) as Array<string>;
  388. return new Promise((resolve, reject) => {
  389. if (this.isAllUnmergedSelected()) {
  390. reject(new Error('Not allowed to unmerge ALL events'));
  391. return;
  392. }
  393. // Disable unmerge button
  394. this.unmergeDisabled = true;
  395. // Disable rows
  396. this.setStateForId(this.unmergeState, ids, {
  397. checked: false,
  398. busy: true,
  399. });
  400. this.triggerUnmergeState();
  401. addLoadingMessage(loadingMessage);
  402. this.api.request(`/issues/${groupId}/hashes/`, {
  403. method: 'DELETE',
  404. query: {
  405. id: ids,
  406. },
  407. success: () => {
  408. addSuccessMessage(successMessage);
  409. // Busy rows after successful Unmerge
  410. this.setStateForId(this.unmergeState, ids, {
  411. checked: false,
  412. busy: true,
  413. });
  414. this.unmergeList.clear();
  415. },
  416. error: () => {
  417. addErrorMessage(errorMessage);
  418. this.setStateForId(this.unmergeState, ids, {
  419. checked: true,
  420. busy: false,
  421. });
  422. },
  423. complete: () => {
  424. this.unmergeDisabled = false;
  425. resolve(this.triggerUnmergeState());
  426. },
  427. });
  428. });
  429. },
  430. // For cross-project views, we need to pass projectId instead of
  431. // depending on router params (since we will only have orgId in that case)
  432. onMerge({params, query, projectId}) {
  433. if (!params) {
  434. return undefined;
  435. }
  436. const ids = this.mergeList;
  437. this.mergeDisabled = true;
  438. this.setStateForId(this.mergeState, ids as Array<string>, {
  439. busy: true,
  440. });
  441. this.triggerMergeState();
  442. const promise = new Promise(resolve => {
  443. // Disable merge button
  444. const {orgId, groupId} = params;
  445. mergeGroups(
  446. this.api,
  447. {
  448. orgId,
  449. projectId: projectId || params.projectId,
  450. itemIds: [...ids, groupId] as Array<number>,
  451. query,
  452. },
  453. {
  454. success: data => {
  455. if (data?.merge?.parent) {
  456. this.trigger({
  457. mergedParent: data.merge.parent,
  458. });
  459. }
  460. // Hide rows after successful merge
  461. this.setStateForId(this.mergeState, ids as Array<string>, {
  462. checked: false,
  463. busy: true,
  464. });
  465. this.mergeList = [];
  466. },
  467. error: () => {
  468. this.setStateForId(this.mergeState, ids as Array<string>, {
  469. checked: true,
  470. busy: false,
  471. });
  472. },
  473. complete: () => {
  474. this.mergeDisabled = false;
  475. resolve(this.triggerMergeState());
  476. },
  477. }
  478. );
  479. });
  480. return promise;
  481. },
  482. // Toggle collapsed state of all fingerprints
  483. onToggleCollapseFingerprints() {
  484. this.setStateForId(
  485. this.unmergeState,
  486. this.mergedItems.map(({id}) => id),
  487. {
  488. collapsed: !this.unmergeLastCollapsed,
  489. }
  490. );
  491. this.unmergeLastCollapsed = !this.unmergeLastCollapsed;
  492. this.trigger({
  493. unmergeLastCollapsed: this.unmergeLastCollapsed,
  494. unmergeState: this.unmergeState,
  495. });
  496. },
  497. onToggleCollapseFingerprint(fingerprint) {
  498. const collapsed =
  499. this.unmergeState.has(fingerprint) && this.unmergeState.get(fingerprint).collapsed;
  500. this.setStateForId(this.unmergeState, fingerprint, {collapsed: !collapsed});
  501. this.trigger({
  502. unmergeState: this.unmergeState,
  503. });
  504. },
  505. triggerFetchState() {
  506. const state = {
  507. similarItems: this.similarItems.filter(({isBelowThreshold}) => !isBelowThreshold),
  508. filteredSimilarItems: this.similarItems.filter(
  509. ({isBelowThreshold}) => isBelowThreshold
  510. ),
  511. ...pick(this, [
  512. 'mergedItems',
  513. 'mergedLinks',
  514. 'similarLinks',
  515. 'mergeState',
  516. 'unmergeState',
  517. 'loading',
  518. 'error',
  519. 'enableFingerprintCompare',
  520. 'unmergeList',
  521. ]),
  522. };
  523. this.trigger(state);
  524. return state;
  525. },
  526. triggerUnmergeState() {
  527. const state = pick(this, [
  528. 'unmergeDisabled',
  529. 'unmergeState',
  530. 'unmergeList',
  531. 'enableFingerprintCompare',
  532. 'unmergeLastCollapsed',
  533. ]);
  534. this.trigger(state);
  535. return state;
  536. },
  537. triggerMergeState() {
  538. const state = pick(this, ['mergeDisabled', 'mergeState', 'mergeList']);
  539. this.trigger(state);
  540. return state;
  541. },
  542. getState(): State {
  543. return this.state;
  544. },
  545. };
  546. const GroupingStore = createStore(makeSafeRefluxStore(storeConfig));
  547. export default GroupingStore;