groupingStore.tsx 16 KB

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