groupingStore.tsx 17 KB

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