groupingStore.tsx 17 KB

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