eventSearch.tsx 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import {useCallback, useMemo} from 'react';
  2. import orderBy from 'lodash/orderBy';
  3. import {fetchTagValues} from 'sentry/actionCreators/tags';
  4. import {
  5. SearchQueryBuilder,
  6. type SearchQueryBuilderProps,
  7. } from 'sentry/components/searchQueryBuilder';
  8. import type {FilterKeySection} from 'sentry/components/searchQueryBuilder/types';
  9. import {parseQueryBuilderValue} from 'sentry/components/searchQueryBuilder/utils';
  10. import {joinQuery, Token} from 'sentry/components/searchSyntax/parser';
  11. import {t} from 'sentry/locale';
  12. import type {Group, Tag, TagCollection} from 'sentry/types/group';
  13. import {
  14. FieldKind,
  15. getFieldDefinition,
  16. ISSUE_EVENT_PROPERTY_FIELDS,
  17. } from 'sentry/utils/fields';
  18. import useApi from 'sentry/utils/useApi';
  19. import {useLocation} from 'sentry/utils/useLocation';
  20. import useOrganization from 'sentry/utils/useOrganization';
  21. import usePageFilters from 'sentry/utils/usePageFilters';
  22. import {Dataset} from 'sentry/views/alerts/rules/metric/types';
  23. import {ALL_EVENTS_EXCLUDED_TAGS} from 'sentry/views/issueDetails/groupEvents';
  24. import {useGroupTags} from 'sentry/views/issueDetails/groupTags/useGroupTags';
  25. import {
  26. mergeAndSortTagValues,
  27. useHasStreamlinedUI,
  28. } from 'sentry/views/issueDetails/utils';
  29. import {makeGetIssueTagValues} from 'sentry/views/issueList/utils/getIssueTagValues';
  30. interface EventSearchProps {
  31. environments: string[];
  32. group: Group;
  33. handleSearch: (value: string) => void;
  34. query: string;
  35. className?: string;
  36. queryBuilderProps?: Partial<SearchQueryBuilderProps>;
  37. }
  38. export function useEventQuery({group}: {group: Group}): string {
  39. const {selection} = usePageFilters();
  40. const location = useLocation();
  41. const environments = selection.environments;
  42. const {query: locationQuery} = location.query;
  43. let eventQuery = '';
  44. if (Array.isArray(locationQuery)) {
  45. eventQuery = locationQuery.join(' ');
  46. } else if (typeof locationQuery === 'string') {
  47. eventQuery = locationQuery;
  48. }
  49. const {data = []} = useGroupTags({
  50. groupId: group.id,
  51. environment: environments,
  52. });
  53. const filterKeys = useEventSearchFilterKeys(data);
  54. const parsedQuery = useMemo(
  55. () =>
  56. parseQueryBuilderValue(eventQuery, getFieldDefinition, {
  57. filterKeys,
  58. }) ?? [],
  59. [eventQuery, filterKeys]
  60. );
  61. // Removes invalid tokens from an issue stream query in an attempt to convert it to an event query.
  62. // For example: "is:unresolved browser.name:firefox" -> "browser.name:firefox"
  63. // Note: This is _probably_ not accounting for MANY invalid filters which could come in from the
  64. // issue stream. Will likely have to refine this in the future.
  65. const validQuery = parsedQuery.filter(token => {
  66. if (token.type === Token.FREE_TEXT) {
  67. return false;
  68. }
  69. if (token.type === Token.FILTER && !filterKeys.hasOwnProperty(token.key.text)) {
  70. return false;
  71. }
  72. return true;
  73. });
  74. return joinQuery(validQuery, false, true);
  75. }
  76. function useEventSearchFilterKeys(data) {
  77. const filterKeys = useMemo<TagCollection>(() => {
  78. const tags = [
  79. ...data.map(tag => ({...tag, kind: FieldKind.TAG})),
  80. ...ISSUE_EVENT_PROPERTY_FIELDS.map(tag => ({
  81. key: tag,
  82. name: tag,
  83. kind: FieldKind.EVENT_FIELD,
  84. })),
  85. ].filter(tag => !ALL_EVENTS_EXCLUDED_TAGS.includes(tag.key));
  86. return tags.reduce<TagCollection>((acc, tag) => {
  87. acc[tag.key] = tag;
  88. return acc;
  89. }, {});
  90. }, [data]);
  91. return filterKeys;
  92. }
  93. function getFilterKeySections(tags: TagCollection): FilterKeySection[] {
  94. const allTags: Tag[] = Object.values(tags).filter(
  95. tag => !ALL_EVENTS_EXCLUDED_TAGS.includes(tag.key)
  96. );
  97. const eventFields = orderBy(
  98. allTags.filter(tag => tag.kind === FieldKind.EVENT_FIELD),
  99. ['key']
  100. ).map(tag => tag.key);
  101. const eventTags = orderBy(
  102. allTags.filter(tag => tag.kind === FieldKind.TAG),
  103. ['totalValues', 'key'],
  104. ['desc', 'asc']
  105. ).map(tag => tag.key);
  106. return [
  107. {
  108. value: FieldKind.EVENT_FIELD,
  109. label: t('Event Filters'),
  110. children: eventFields,
  111. },
  112. {
  113. value: FieldKind.TAG,
  114. label: t('Event Tags'),
  115. children: eventTags,
  116. },
  117. ];
  118. }
  119. export function EventSearch({
  120. className,
  121. query,
  122. group,
  123. environments,
  124. handleSearch,
  125. queryBuilderProps = {},
  126. }: EventSearchProps) {
  127. const api = useApi();
  128. const organization = useOrganization();
  129. const hasStreamlinedUI = useHasStreamlinedUI();
  130. const {data = []} = useGroupTags({
  131. groupId: group.id,
  132. environment: environments,
  133. });
  134. const filterKeys = useEventSearchFilterKeys(data);
  135. const tagValueLoader = useCallback(
  136. async (key: string, search: string) => {
  137. const orgSlug = organization.slug;
  138. const projectIds = [group.project.id];
  139. const [eventsDatasetValues, issuePlatformDatasetValues] = await Promise.all([
  140. fetchTagValues({
  141. api,
  142. orgSlug,
  143. tagKey: key,
  144. search,
  145. projectIds,
  146. dataset: Dataset.ERRORS,
  147. }),
  148. fetchTagValues({
  149. api,
  150. orgSlug,
  151. tagKey: key,
  152. search,
  153. projectIds,
  154. dataset: Dataset.ISSUE_PLATFORM,
  155. }),
  156. ]);
  157. return mergeAndSortTagValues(eventsDatasetValues, issuePlatformDatasetValues);
  158. },
  159. [api, group.project.id, organization.slug]
  160. );
  161. const getTagValues = useMemo(
  162. () => makeGetIssueTagValues(tagValueLoader),
  163. [tagValueLoader]
  164. );
  165. const filterKeySections = useMemo(() => getFilterKeySections(filterKeys), [filterKeys]);
  166. return (
  167. <SearchQueryBuilder
  168. initialQuery={query}
  169. onSearch={handleSearch}
  170. filterKeys={filterKeys}
  171. filterKeySections={filterKeySections}
  172. getTagValues={getTagValues}
  173. placeholder={hasStreamlinedUI ? t('Filter events...') : t('Search events...')}
  174. label={hasStreamlinedUI ? t('Filter events...') : t('Search events')}
  175. searchSource="issue_events_tab"
  176. className={className}
  177. showUnsubmittedIndicator
  178. {...queryBuilderProps}
  179. />
  180. );
  181. }