groupingStore.tsx 17 KB

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