groupingStore.tsx 18 KB

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