groupingStore.tsx 17 KB

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