groupingStore.tsx 17 KB

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