groupingStore.tsx 18 KB

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