groupingStore.tsx 18 KB

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