tokenizeSearch.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import {escapeDoubleQuotes} from 'sentry/utils';
  2. const ALLOWED_WILDCARD_FIELDS = ['span.description'];
  3. export const EMPTY_OPTION_VALUE = '(empty)' as const;
  4. export enum TokenType {
  5. OPERATOR,
  6. FILTER,
  7. FREE_TEXT,
  8. }
  9. export type Token = {
  10. type: TokenType;
  11. value: string;
  12. key?: string;
  13. };
  14. function isOp(t: Token) {
  15. return t.type === TokenType.OPERATOR;
  16. }
  17. function isBooleanOp(value: string) {
  18. return ['OR', 'AND'].includes(value.toUpperCase());
  19. }
  20. function isParen(token: Token, character: '(' | ')') {
  21. return (
  22. token !== undefined &&
  23. isOp(token) &&
  24. ['(', ')'].includes(token.value) &&
  25. token.value === character
  26. );
  27. }
  28. // TODO(epurkhiser): This is legacy from before the existence of
  29. // searchSyntax/parser. We should absolutely replace the internals of this API
  30. // with `parseSearch`.
  31. export class MutableSearch {
  32. tokens: Token[];
  33. /**
  34. * Creates a `MutableSearch` from a key-value mapping of field:value.
  35. * This construct doesn't support conditions like `OR` and `AND` or
  36. * parentheses, so it's only useful for simple queries.
  37. * @param params
  38. * @returns {MutableSearch}
  39. */
  40. static fromQueryObject(params: {
  41. [key: string]: string | number | undefined;
  42. }): MutableSearch {
  43. const query = new MutableSearch('');
  44. Object.entries(params).forEach(([key, value]) => {
  45. if (!value) {
  46. return;
  47. }
  48. if (value === EMPTY_OPTION_VALUE) {
  49. query.addFilterValue('!has', key);
  50. } else {
  51. query.addFilterValue(
  52. key,
  53. value.toString(),
  54. !ALLOWED_WILDCARD_FIELDS.includes(key)
  55. );
  56. }
  57. });
  58. return query;
  59. }
  60. /**
  61. * Creates a MutableSearch from a string query
  62. */
  63. constructor(query: string);
  64. /**
  65. * Creates a mutable search query from a list of query parts
  66. */
  67. constructor(queries: string[]);
  68. constructor(tokensOrQuery: string[] | string) {
  69. const strTokens = Array.isArray(tokensOrQuery)
  70. ? tokensOrQuery
  71. : splitSearchIntoTokens(tokensOrQuery);
  72. this.tokens = [];
  73. for (let token of strTokens) {
  74. let tokenState = TokenType.FREE_TEXT;
  75. if (isBooleanOp(token)) {
  76. this.addOp(token.toUpperCase());
  77. continue;
  78. }
  79. if (token.startsWith('(')) {
  80. const parenMatch = token.match(/^\(+/g);
  81. if (parenMatch) {
  82. parenMatch[0].split('').map(paren => this.addOp(paren));
  83. token = token.replace(/^\(+/g, '');
  84. }
  85. }
  86. // Traverse the token and check if it's a filter condition or free text
  87. for (let i = 0, len = token.length; i < len; i++) {
  88. const char = token[i];
  89. if (i === 0 && (char === '"' || char === ':')) {
  90. break;
  91. }
  92. // We may have entered a filter condition
  93. if (char === ':') {
  94. const nextChar = token[i + 1] || '';
  95. if ([':', ' '].includes(nextChar)) {
  96. tokenState = TokenType.FREE_TEXT;
  97. } else {
  98. tokenState = TokenType.FILTER;
  99. }
  100. break;
  101. }
  102. }
  103. let trailingParen = '';
  104. if (token.endsWith(')') && !token.includes('(')) {
  105. const parenMatch = token.match(/\)+$/g);
  106. if (parenMatch) {
  107. trailingParen = parenMatch[0];
  108. token = token.replace(/\)+$/g, '');
  109. }
  110. }
  111. if (tokenState === TokenType.FREE_TEXT && token.length) {
  112. this.addFreeText(token);
  113. } else if (tokenState === TokenType.FILTER) {
  114. this.addStringFilter(token, false);
  115. }
  116. if (trailingParen !== '') {
  117. trailingParen.split('').map(paren => this.addOp(paren));
  118. }
  119. }
  120. }
  121. formatString() {
  122. const formattedTokens: string[] = [];
  123. for (const token of this.tokens) {
  124. switch (token.type) {
  125. case TokenType.FILTER:
  126. if (token.value === '' || token.value === null) {
  127. formattedTokens.push(`${token.key}:""`);
  128. } else if (/[\s\(\)\\"]/g.test(token.value)) {
  129. formattedTokens.push(`${token.key}:"${escapeDoubleQuotes(token.value)}"`);
  130. } else {
  131. formattedTokens.push(`${token.key}:${token.value}`);
  132. }
  133. break;
  134. case TokenType.FREE_TEXT:
  135. if (/[\s\(\)\\"]/g.test(token.value)) {
  136. formattedTokens.push(`"${escapeDoubleQuotes(token.value)}"`);
  137. } else {
  138. formattedTokens.push(token.value);
  139. }
  140. break;
  141. default:
  142. formattedTokens.push(token.value);
  143. }
  144. }
  145. return formattedTokens.join(' ').trim();
  146. }
  147. addStringFilter(filter: string, shouldEscape = true) {
  148. const [key, value] = parseFilter(filter);
  149. this.addFilterValues(key, [value], shouldEscape);
  150. return this;
  151. }
  152. addFilterValues(key: string, values: string[], shouldEscape = true) {
  153. for (const value of values) {
  154. this.addFilterValue(key, value, shouldEscape);
  155. }
  156. return this;
  157. }
  158. addFilterValue(key: string, value: string, shouldEscape = true) {
  159. // Filter values that we insert through the UI can contain special characters
  160. // that need to escaped. User entered filters should not be escaped.
  161. const escaped = shouldEscape ? escapeFilterValue(value) : value;
  162. const token: Token = {type: TokenType.FILTER, key, value: escaped};
  163. this.tokens.push(token);
  164. }
  165. setFilterValues(key: string, values: string[], shouldEscape = true) {
  166. this.removeFilter(key);
  167. this.addFilterValues(key, values, shouldEscape);
  168. return this;
  169. }
  170. get filters() {
  171. type Filters = Record<string, string[]>;
  172. const reducer = (acc: Filters, token: Token) => ({
  173. ...acc,
  174. [token.key!]: [...(acc[token.key!] ?? []), token.value],
  175. });
  176. return this.tokens
  177. .filter(t => t.type === TokenType.FILTER)
  178. .reduce<Filters>(reducer, {});
  179. }
  180. getFilterValues(key: string) {
  181. return this.filters[key] ?? [];
  182. }
  183. getFilterKeys() {
  184. return Object.keys(this.filters);
  185. }
  186. hasFilter(key: string): boolean {
  187. return this.getFilterValues(key).length > 0;
  188. }
  189. removeFilter(key: string) {
  190. const removeErroneousAndOrOps = () => {
  191. let toRemove = -1;
  192. do {
  193. if (toRemove >= 0) {
  194. this.tokens.splice(toRemove, 1);
  195. toRemove = -1;
  196. }
  197. for (let i = 0; i < this.tokens.length; i++) {
  198. const token = this.tokens[i];
  199. const prev = this.tokens[i - 1];
  200. const next = this.tokens[i + 1];
  201. if (isOp(token) && isBooleanOp(token.value)) {
  202. if (prev === undefined || isOp(prev) || next === undefined || isOp(next)) {
  203. // Want to avoid removing `(term) OR (term)` and `term OR (term)`
  204. if (
  205. prev &&
  206. next &&
  207. (isParen(prev, ')') || !isOp(prev)) &&
  208. (isParen(next, '(') || !isOp(next))
  209. ) {
  210. continue;
  211. }
  212. toRemove = i;
  213. break;
  214. }
  215. }
  216. }
  217. } while (toRemove >= 0);
  218. };
  219. this.tokens = this.tokens.filter(token => token.key !== key);
  220. // Remove any AND/OR operators that have become erroneous due to filtering out tokens
  221. removeErroneousAndOrOps();
  222. // Now the really complicated part: removing parens that only have one element in them.
  223. // Since parens are themselves tokens, this gets tricky. In summary, loop through the
  224. // tokens until we find the innermost open paren. Then forward search through the rest of the tokens
  225. // to see if that open paren corresponds to a closed paren with one or fewer items inside.
  226. // If it does, delete those parens, and loop again until there are no more parens to delete.
  227. let parensToDelete: number[] = [];
  228. const cleanParens = (_, idx: number) => !parensToDelete.includes(idx);
  229. do {
  230. if (parensToDelete.length) {
  231. this.tokens = this.tokens.filter(cleanParens);
  232. }
  233. parensToDelete = [];
  234. for (let i = 0; i < this.tokens.length; i++) {
  235. const token = this.tokens[i];
  236. if (!isOp(token) || token.value !== '(') {
  237. continue;
  238. }
  239. let alreadySeen = false;
  240. for (let j = i + 1; j < this.tokens.length; j++) {
  241. const nextToken = this.tokens[j];
  242. if (isOp(nextToken) && nextToken.value === '(') {
  243. // Continue down to the nested parens. We can skip i forward since we know
  244. // everything between i and j is NOT an open paren.
  245. i = j - 1;
  246. break;
  247. } else if (!isOp(nextToken)) {
  248. if (alreadySeen) {
  249. // This has more than one term, no need to delete
  250. break;
  251. }
  252. alreadySeen = true;
  253. } else if (isOp(nextToken) && nextToken.value === ')') {
  254. // We found another paren with zero or one terms inside. Delete the pair.
  255. parensToDelete = [i, j];
  256. break;
  257. }
  258. }
  259. if (parensToDelete.length > 0) {
  260. break;
  261. }
  262. }
  263. } while (parensToDelete.length > 0);
  264. // Now that all erroneous parens are removed we need to remove dangling OR/AND operators.
  265. // I originally removed all the dangling properties in a single loop, but that meant that
  266. // cases like `a OR OR b` would remove both operators, when only one should be removed. So
  267. // instead, we loop until we find an operator to remove, then go back to the start and loop
  268. // again.
  269. removeErroneousAndOrOps();
  270. return this;
  271. }
  272. removeFilterValue(key: string, value: string) {
  273. const values = this.getFilterValues(key);
  274. if (Array.isArray(values) && values.length) {
  275. this.setFilterValues(
  276. key,
  277. values.filter(item => item !== value)
  278. );
  279. }
  280. return this;
  281. }
  282. addFreeText(value: string) {
  283. const token: Token = {type: TokenType.FREE_TEXT, value: formatQuery(value)};
  284. this.tokens.push(token);
  285. return this;
  286. }
  287. addOp(value: string) {
  288. const token: Token = {type: TokenType.OPERATOR, value};
  289. this.tokens.push(token);
  290. return this;
  291. }
  292. get freeText(): string[] {
  293. return this.tokens.filter(t => t.type === TokenType.FREE_TEXT).map(t => t.value);
  294. }
  295. set freeText(values: string[]) {
  296. this.tokens = this.tokens.filter(t => t.type !== TokenType.FREE_TEXT);
  297. for (const v of values) {
  298. this.addFreeText(v);
  299. }
  300. }
  301. copy() {
  302. const q = new MutableSearch([]);
  303. q.tokens = [...this.tokens];
  304. return q;
  305. }
  306. isEmpty() {
  307. return this.tokens.length === 0;
  308. }
  309. }
  310. /**
  311. * Splits search strings into tokens for parsing by tokenizeSearch.
  312. *
  313. * Should stay in sync with src.sentry.search.utils:split_query_into_tokens
  314. */
  315. function splitSearchIntoTokens(query: string) {
  316. const queryChars = Array.from(query);
  317. const tokens: string[] = [];
  318. let token = '';
  319. let endOfPrevWord = '';
  320. let quoteType = '';
  321. let quoteEnclosed = false;
  322. for (let idx = 0; idx < queryChars.length; idx++) {
  323. const char = queryChars[idx];
  324. const nextChar = queryChars.length - 1 > idx ? queryChars[idx + 1] : null;
  325. token += char;
  326. if (nextChar !== null && !isSpace(char) && isSpace(nextChar)) {
  327. endOfPrevWord = char;
  328. }
  329. if (isSpace(char) && !quoteEnclosed && endOfPrevWord !== ':' && !isSpace(token)) {
  330. tokens.push(token.trim());
  331. token = '';
  332. }
  333. if (["'", '"'].includes(char) && (!quoteEnclosed || quoteType === char)) {
  334. quoteEnclosed = !quoteEnclosed;
  335. if (quoteEnclosed) {
  336. quoteType = char;
  337. }
  338. }
  339. if (quoteEnclosed && char === '\\' && nextChar === quoteType) {
  340. token += nextChar;
  341. idx++;
  342. }
  343. }
  344. const trimmedToken = token.trim();
  345. if (trimmedToken !== '') {
  346. tokens.push(trimmedToken);
  347. }
  348. return tokens;
  349. }
  350. /**
  351. * Checks if the string is only spaces
  352. */
  353. function isSpace(s: string) {
  354. return s.trim() === '';
  355. }
  356. /**
  357. * Splits a filter on ':' and removes enclosing quotes if present, and returns
  358. * both sides of the split as strings.
  359. */
  360. function parseFilter(filter: string) {
  361. const idx = filter.indexOf(':');
  362. const key = removeSurroundingQuotes(filter.slice(0, idx));
  363. const value = removeSurroundingQuotes(filter.slice(idx + 1));
  364. return [key, value];
  365. }
  366. function removeSurroundingQuotes(text: string) {
  367. const length = text.length;
  368. if (length <= 1) {
  369. return text;
  370. }
  371. let left = 0;
  372. for (; left <= length / 2; left++) {
  373. if (text.charAt(left) !== '"') {
  374. break;
  375. }
  376. }
  377. let right = length - 1;
  378. for (; right >= length / 2; right--) {
  379. if (text.charAt(right) !== '"' || text.charAt(right - 1) === '\\') {
  380. break;
  381. }
  382. }
  383. return text.slice(left, right + 1);
  384. }
  385. /**
  386. * Strips enclosing quotes and parens from a query, if present.
  387. */
  388. function formatQuery(query: string) {
  389. return query.replace(/^["\(]+|["\)]+$/g, '');
  390. }
  391. /**
  392. * Some characters have special meaning in a filter value. So when they are
  393. * directly added as a value, we have to escape them to mean the literal.
  394. */
  395. export function escapeFilterValue(value: string) {
  396. // TODO(txiao): The types here are definitely wrong.
  397. // Need to dig deeper to see where exactly it's wrong.
  398. //
  399. // astericks (*) is used for wildcard searches
  400. return typeof value === 'string' ? value.replace(/([\*])/g, '\\$1') : value;
  401. }