mirror of
https://github.com/SigNoz/signoz.git
synced 2026-06-10 19:00:34 +01:00
Compare commits
36 Commits
feat/auth-
...
feat/test-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4dcf9ea488 | ||
|
|
8f25f2ece7 | ||
|
|
3aac04aac2 | ||
|
|
a2c6cb680d | ||
|
|
3484cbbfdd | ||
|
|
ebbd430715 | ||
|
|
d16f2d0d4d | ||
|
|
bf74f0680d | ||
|
|
6712701f22 | ||
|
|
128739f25e | ||
|
|
cd9fa0cf9c | ||
|
|
8d7fb6e270 | ||
|
|
cfe7878f94 | ||
|
|
e9fae6964d | ||
|
|
1eeff7283d | ||
|
|
db6360afaf | ||
|
|
13285a5c6a | ||
|
|
908856f73f | ||
|
|
26e9f38f94 | ||
|
|
66b86a8509 | ||
|
|
100067d8dc | ||
|
|
b883a09c78 | ||
|
|
96f2160119 | ||
|
|
1824acc860 | ||
|
|
fd9bc7c42e | ||
|
|
68d17dd164 | ||
|
|
7568a1a1e1 | ||
|
|
8c28035e6e | ||
|
|
3d9dd945f6 | ||
|
|
3b8bcdecaa | ||
|
|
4b54affb10 | ||
|
|
519c5471ba | ||
|
|
68c4b6f724 | ||
|
|
e65a1dd1ce | ||
|
|
8d2e024cb2 | ||
|
|
90cb4e99f9 |
@@ -1,5 +1,11 @@
|
||||
// TODO: Improve the styling of the query aggregation container and its components. - @YounixM , @H4ad
|
||||
|
||||
$dropdown-base-height: 250px;
|
||||
$recents-header-height: 30px;
|
||||
$recent-row-height: 36px;
|
||||
// how many recents are rendered, this caps how tall the dropdown can grow to fit them.
|
||||
$max-recents-shown: 5;
|
||||
|
||||
.code-mirror-where-clause {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
@@ -117,7 +123,23 @@
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
font-family: 'Space Mono', monospace !important;
|
||||
min-height: 200px !important;
|
||||
max-height: $dropdown-base-height !important;
|
||||
overflow-y: auto !important;
|
||||
|
||||
// Recents render at the top of the dropdown ahead of regular suggestions.
|
||||
// At the base max-height, having recents in view would crowd out the
|
||||
// suggestion list below. This loop grows the dropdown by one row's worth
|
||||
// of height for every recent present (up to $max-recents-shown), plus the
|
||||
// section header. `:has(> li:nth-of-type(N) .cm-completionIcon-recent)`
|
||||
// matches when the Nth child of <ul> is a recent — i.e. there are at
|
||||
// least N recents visible.
|
||||
@for $i from 1 through $max-recents-shown {
|
||||
&:has(> li:nth-of-type(#{$i}) .cm-completionIcon-recent) {
|
||||
max-height: $dropdown-base-height +
|
||||
$recents-header-height +
|
||||
($i * $recent-row-height) !important;
|
||||
}
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 0.3rem;
|
||||
@@ -133,6 +155,19 @@
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
completion-section {
|
||||
display: block;
|
||||
padding: 10px 12px 6px;
|
||||
font-size: 10px !important;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--l3-foreground, var(--l2-foreground));
|
||||
opacity: 0.7;
|
||||
border-bottom: 0;
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
li {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
@@ -159,11 +194,78 @@
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cm-completionDetail {
|
||||
margin-left: auto;
|
||||
font-style: normal;
|
||||
font-size: var(--periscope-font-size-small, 11px);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
&[aria-selected='true'] {
|
||||
background: var(--l3-background) !important;
|
||||
font-weight: 600 !important;
|
||||
}
|
||||
}
|
||||
|
||||
li:has(.cm-completionIcon-recent) {
|
||||
&:hover .cm-recent-delete,
|
||||
&[aria-selected='true'] .cm-recent-delete {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
li .cm-completionLabel {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.cm-recent-delete {
|
||||
margin-left: 8px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
color: var(--l2-foreground);
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
opacity: 0.5;
|
||||
transition:
|
||||
opacity 0.12s ease,
|
||||
background-color 0.12s ease;
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
background: color-mix(in srgb, var(--l2-foreground) 18%, transparent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&::after {
|
||||
content: '↓↑ to navigate · ↵ to apply · esc to dismiss';
|
||||
display: block;
|
||||
padding: 8px 12px;
|
||||
border-top: 1px solid var(--l1-border);
|
||||
font-family: 'Space Mono', monospace;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--l2-foreground);
|
||||
opacity: 0.6;
|
||||
background: color-mix(in srgb, var(--l1-background) 50%, transparent);
|
||||
border-bottom-left-radius: 4px;
|
||||
border-bottom-right-radius: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -46,8 +46,15 @@ import {
|
||||
import { validateQuery } from 'utils/queryValidationUtils';
|
||||
import { unquote } from 'utils/stringUtils';
|
||||
|
||||
import { queryExamples } from './constants';
|
||||
import { combineInitialAndUserExpression } from './utils';
|
||||
import { getRecentQueries } from 'lib/recentQueries/getRecentQueries';
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
|
||||
import { queryExamples, SUGGESTIONS_SECTION } from './constants';
|
||||
import {
|
||||
combineInitialAndUserExpression,
|
||||
getRecentOptions,
|
||||
renderRecentDeleteButton,
|
||||
} from './utils';
|
||||
|
||||
import './QuerySearch.styles.scss';
|
||||
|
||||
@@ -1250,6 +1257,41 @@ function QuerySearch({
|
||||
};
|
||||
}
|
||||
|
||||
const signal = dataSource as SignalType;
|
||||
|
||||
function combinedSuggestions(
|
||||
context: CompletionContext,
|
||||
): CompletionResult | null {
|
||||
const fullDoc = context.state.doc.toString();
|
||||
const recentOptions = getRecentOptions(
|
||||
getRecentQueries(signal, signalSource ?? ''),
|
||||
fullDoc,
|
||||
);
|
||||
const result = autoSuggestions(context);
|
||||
|
||||
const suggestionOptions = (result?.options || []).map((opt) => ({
|
||||
...opt,
|
||||
section: SUGGESTIONS_SECTION,
|
||||
}));
|
||||
|
||||
if (recentOptions.length === 0 && suggestionOptions.length === 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
return {
|
||||
from: 0,
|
||||
to: fullDoc.length,
|
||||
options: recentOptions,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...result,
|
||||
options: [...recentOptions, ...suggestionOptions],
|
||||
};
|
||||
}
|
||||
|
||||
// Effect to handle focus state and trigger suggestions
|
||||
useEffect(() => {
|
||||
const clearTimeout = toggleSuggestions(10);
|
||||
@@ -1398,11 +1440,12 @@ function QuerySearch({
|
||||
})}
|
||||
extensions={[
|
||||
autocompletion({
|
||||
override: [autoSuggestions],
|
||||
override: [combinedSuggestions],
|
||||
defaultKeymap: true,
|
||||
closeOnBlur: true,
|
||||
activateOnTyping: true,
|
||||
maxRenderedOptions: 50,
|
||||
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
|
||||
}),
|
||||
javascript({ jsx: false, typescript: false }),
|
||||
EditorView.lineWrapping,
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
export const RECENTS_SECTION = { name: 'Recent searches', rank: 1 } as const;
|
||||
export const SUGGESTIONS_SECTION = { name: 'Suggestions', rank: 2 } as const;
|
||||
|
||||
// Custom CodeMirror Completion.type for recent-query entries. Used to discriminate
|
||||
// recents from regular autocomplete completions in renderers and event handlers.
|
||||
export const RECENT_COMPLETION_TYPE = 'recent';
|
||||
|
||||
// Max number of recents rendered in the autocomplete dropdown.
|
||||
// Do change $max-recents-shown: in QuerySearch.styles.scss if you change this.
|
||||
export const RECENTS_DISPLAY_CAP = 5;
|
||||
|
||||
export const queryExamples = [
|
||||
{
|
||||
label: 'Basic Query',
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
import { closeCompletion, startCompletion } from '@codemirror/autocomplete';
|
||||
import type { Completion } from '@codemirror/autocomplete';
|
||||
import type { EditorView } from '@uiw/react-codemirror';
|
||||
import dayjs from 'dayjs';
|
||||
import { normalizeFilterExpression } from 'lib/recentQueries/normalize';
|
||||
import * as recentQueriesStore from 'lib/recentQueries/recentQueriesStore';
|
||||
import type { RecentQueryEntry } from 'lib/recentQueries/types';
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
import 'utils/timeUtils';
|
||||
|
||||
import {
|
||||
RECENT_COMPLETION_TYPE,
|
||||
RECENTS_DISPLAY_CAP,
|
||||
RECENTS_SECTION,
|
||||
} from './constants';
|
||||
|
||||
export function combineInitialAndUserExpression(
|
||||
initial: string,
|
||||
user: string,
|
||||
@@ -38,3 +54,106 @@ export function getUserExpressionFromCombined(
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
// Filters and projects a list of recent-query entries into CodeMirror completions.
|
||||
// Entries are supplied by the caller (typically via the useRecents hook) so this
|
||||
// function stays pure and React doesn't have to re-subscribe inside CodeMirror's
|
||||
// autocomplete callback.
|
||||
export function getRecentOptions(
|
||||
entries: RecentQueryEntry[],
|
||||
fullDoc: string,
|
||||
): Completion[] {
|
||||
const normalizedDoc = normalizeFilterExpression(fullDoc);
|
||||
|
||||
const matches = entries
|
||||
.filter((e) => {
|
||||
const normalizedRecent = normalizeFilterExpression(e.filter.expression);
|
||||
if (normalizedRecent === normalizedDoc) {
|
||||
return false;
|
||||
}
|
||||
if (normalizedDoc === '') {
|
||||
return true;
|
||||
}
|
||||
return normalizedRecent.includes(normalizedDoc);
|
||||
})
|
||||
.slice(0, RECENTS_DISPLAY_CAP);
|
||||
|
||||
return matches.map((entry, index) => ({
|
||||
label: entry.filter.expression,
|
||||
type: RECENT_COMPLETION_TYPE,
|
||||
// CodeMirror sorts within a section by boost desc, then label asc. The store
|
||||
// returns entries newest-first, so we mirror that by giving the newest entry
|
||||
// the highest boost — otherwise CM falls back to alphabetical order and the
|
||||
// "most recently used" expectation breaks. Stays within the recents section
|
||||
// because section.rank keeps recents above suggestions regardless of boost.
|
||||
boost: matches.length - index,
|
||||
section: RECENTS_SECTION,
|
||||
detail: dayjs(entry.lastUsedAt).fromNow(),
|
||||
recentId: entry.id,
|
||||
recentSignal: entry.signal,
|
||||
recentSource: entry.source,
|
||||
apply: (view: EditorView): void => {
|
||||
view.dispatch({
|
||||
changes: {
|
||||
from: 0,
|
||||
to: view.state.doc.length,
|
||||
insert: entry.filter.expression,
|
||||
},
|
||||
selection: { anchor: entry.filter.expression.length },
|
||||
});
|
||||
closeCompletion(view);
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function renderRecentDeleteButton(
|
||||
completion: Completion,
|
||||
_state: unknown,
|
||||
view: EditorView | null,
|
||||
): Node | null {
|
||||
if (completion.type !== RECENT_COMPLETION_TYPE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const c = completion as Completion & {
|
||||
recentId?: string;
|
||||
recentSignal?: SignalType;
|
||||
recentSource?: string;
|
||||
};
|
||||
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'cm-recent-delete';
|
||||
btn.setAttribute('aria-label', 'Remove from recent searches');
|
||||
btn.title = 'Remove from recent searches';
|
||||
btn.textContent = '×';
|
||||
queueMicrotask(() => {
|
||||
if (btn.parentElement) {
|
||||
btn.parentElement.title = completion.label;
|
||||
}
|
||||
});
|
||||
|
||||
const stop = (e: Event): void => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
// CodeMirror's autocomplete closes the popup on pointerdown / mousedown outside
|
||||
// the editor. The delete button lives inside the popup, so we must stop those
|
||||
// events early — otherwise clicking × would dismiss the dropdown before the
|
||||
// click handler fires and the entry wouldn't actually get removed.
|
||||
btn.addEventListener('pointerdown', stop);
|
||||
btn.addEventListener('mousedown', stop);
|
||||
btn.addEventListener('click', (e) => {
|
||||
stop(e);
|
||||
if (!c.recentId || !c.recentSignal) {
|
||||
return;
|
||||
}
|
||||
recentQueriesStore.remove(c.recentId, c.recentSignal, c.recentSource ?? '');
|
||||
if (view) {
|
||||
view.focus();
|
||||
startCompletion(view);
|
||||
}
|
||||
});
|
||||
|
||||
return btn;
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ function Explorer(): JSX.Element {
|
||||
handleSetQueryData,
|
||||
redirectWithQueryBuilderData,
|
||||
} = useQueryBuilder();
|
||||
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
const { handleExplorerTabChange } = useHandleExplorerTabChange();
|
||||
const isAIAssistantEnabled = useIsAIAssistantEnabled();
|
||||
|
||||
5
frontend/src/lib/recentQueries/constants.ts
Normal file
5
frontend/src/lib/recentQueries/constants.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export const STORAGE_KEY_PREFIX = 'qb_recent_v1';
|
||||
export const STORAGE_VERSION = 1;
|
||||
// Maximum entries kept per (signal, source) bucket. Larger than the UI's
|
||||
// RECENTS_DISPLAY_CAP so deleting a visible entry surfaces an older one.
|
||||
export const MAX_ENTRIES = 10;
|
||||
51
frontend/src/lib/recentQueries/getRecentQueries.test.ts
Normal file
51
frontend/src/lib/recentQueries/getRecentQueries.test.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import * as store from './recentQueriesStore';
|
||||
import { getRecentQueries } from './getRecentQueries';
|
||||
|
||||
describe('getRecentQueries', () => {
|
||||
beforeEach(() => {
|
||||
store.useRecentQueriesStore.setState({ buckets: {} });
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('returns the entries for a (signal, source) bucket', () => {
|
||||
store.save({
|
||||
signal: 'logs',
|
||||
filter: { expression: "severity_text = 'ERROR'" },
|
||||
});
|
||||
|
||||
const entries = getRecentQueries('logs', '');
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].filter.expression).toBe("severity_text = 'ERROR'");
|
||||
});
|
||||
|
||||
it('returns an empty array for a bucket with no entries', () => {
|
||||
expect(getRecentQueries('logs', '')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('reads the latest entries on each call (non-subscribing)', () => {
|
||||
expect(getRecentQueries('logs', '')).toHaveLength(0);
|
||||
|
||||
store.save({
|
||||
signal: 'logs',
|
||||
filter: { expression: "severity_text = 'ERROR'" },
|
||||
});
|
||||
|
||||
expect(getRecentQueries('logs', '')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('partitions by signal and source', () => {
|
||||
store.save({
|
||||
signal: 'logs',
|
||||
filter: { expression: "severity_text = 'ERROR'" },
|
||||
});
|
||||
store.save({
|
||||
signal: 'metrics',
|
||||
source: 'meter',
|
||||
filter: { expression: 'cpu_usage > 80' },
|
||||
});
|
||||
|
||||
expect(getRecentQueries('logs', '')).toHaveLength(1);
|
||||
expect(getRecentQueries('metrics', 'meter')).toHaveLength(1);
|
||||
expect(getRecentQueries('metrics', '')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
14
frontend/src/lib/recentQueries/getRecentQueries.ts
Normal file
14
frontend/src/lib/recentQueries/getRecentQueries.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
|
||||
import * as store from './recentQueriesStore';
|
||||
import type { RecentQueryEntry } from './types';
|
||||
|
||||
// Non-subscribing read of recent searches for a (signal, source) bucket.
|
||||
// Deliberately not the zustand hook — subscribing would reconfigure CodeMirror
|
||||
// and close the open completion popup on every store change.
|
||||
export function getRecentQueries(
|
||||
signal: SignalType,
|
||||
source: string,
|
||||
): RecentQueryEntry[] {
|
||||
return store.list(signal, source);
|
||||
}
|
||||
100
frontend/src/lib/recentQueries/normalize.test.ts
Normal file
100
frontend/src/lib/recentQueries/normalize.test.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { normalizeFilterExpression } from './normalize';
|
||||
|
||||
describe('normalizeFilterExpression', () => {
|
||||
it('returns empty string for empty input', () => {
|
||||
expect(normalizeFilterExpression('')).toBe('');
|
||||
});
|
||||
|
||||
it('returns empty string for whitespace-only input', () => {
|
||||
expect(normalizeFilterExpression(' \t ')).toBe('');
|
||||
});
|
||||
|
||||
it('strips whitespace around operators', () => {
|
||||
expect(normalizeFilterExpression(' a = 1 ')).toBe('a=1');
|
||||
expect(normalizeFilterExpression('a = 1')).toBe('a=1');
|
||||
expect(normalizeFilterExpression('a=1')).toBe('a=1');
|
||||
});
|
||||
|
||||
it('lowercases AND / OR / NOT outside quotes', () => {
|
||||
expect(normalizeFilterExpression('A AND B OR NOT C')).toBe('AandBornotC');
|
||||
});
|
||||
|
||||
it('lowercases IN / LIKE / ILIKE / CONTAINS', () => {
|
||||
expect(normalizeFilterExpression('host IN [1, 2] AND name LIKE "foo"')).toBe(
|
||||
'hostin[1,2]andnamelike"foo"',
|
||||
);
|
||||
});
|
||||
|
||||
it('lowercases REGEXP', () => {
|
||||
expect(normalizeFilterExpression('path REGEXP "foo"')).toBe(
|
||||
'pathregexp"foo"',
|
||||
);
|
||||
expect(normalizeFilterExpression('path REGEXP "foo"')).toBe(
|
||||
normalizeFilterExpression('path regexp "foo"'),
|
||||
);
|
||||
});
|
||||
|
||||
it('lowercases HAS / HASANY / HASALL / HASTOKEN function names', () => {
|
||||
expect(normalizeFilterExpression('HAS(tags, "x")')).toBe(
|
||||
normalizeFilterExpression('has(tags, "x")'),
|
||||
);
|
||||
expect(normalizeFilterExpression('HASANY(tags, ["a","b"])')).toBe(
|
||||
normalizeFilterExpression('hasAny(tags, ["a","b"])'),
|
||||
);
|
||||
expect(normalizeFilterExpression('HASALL(tags, ["a","b"])')).toBe(
|
||||
normalizeFilterExpression('hasAll(tags, ["a","b"])'),
|
||||
);
|
||||
expect(normalizeFilterExpression('HASTOKEN(msg, "err")')).toBe(
|
||||
normalizeFilterExpression('hasToken(msg, "err")'),
|
||||
);
|
||||
});
|
||||
|
||||
it('lowercases TRUE / FALSE boolean literals', () => {
|
||||
expect(normalizeFilterExpression('active = TRUE')).toBe(
|
||||
normalizeFilterExpression('active = true'),
|
||||
);
|
||||
expect(normalizeFilterExpression('active = FALSE')).toBe(
|
||||
normalizeFilterExpression('active = false'),
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves whitespace and casing inside single-quoted strings', () => {
|
||||
expect(normalizeFilterExpression("a = 'X Y'")).toBe("a='X Y'");
|
||||
});
|
||||
|
||||
it('preserves whitespace and casing inside double-quoted strings', () => {
|
||||
expect(normalizeFilterExpression('a = "X Y"')).toBe('a="X Y"');
|
||||
});
|
||||
|
||||
it('does not lowercase keyword-looking substrings inside quotes', () => {
|
||||
expect(normalizeFilterExpression("msg = 'AND ERROR'")).toBe(
|
||||
"msg='AND ERROR'",
|
||||
);
|
||||
});
|
||||
|
||||
it('handles escaped quotes inside strings', () => {
|
||||
expect(normalizeFilterExpression("msg = 'a\\'b' AND x = 1")).toBe(
|
||||
"msg='a\\'b'andx=1",
|
||||
);
|
||||
});
|
||||
|
||||
it('treats two formattings of the same expression as identical', () => {
|
||||
const a = normalizeFilterExpression(
|
||||
'service.name = "frontend" AND severity = error',
|
||||
);
|
||||
const b = normalizeFilterExpression(
|
||||
'service.name="frontend" and severity=error',
|
||||
);
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it('preserves unquoted value casing (treats them as identifiers)', () => {
|
||||
expect(normalizeFilterExpression('status = OK')).toBe('status=OK');
|
||||
});
|
||||
|
||||
it('handles mixed quotes in one expression', () => {
|
||||
expect(normalizeFilterExpression(`a = 'X' AND b = "Y"`)).toBe(
|
||||
`a='X'andb="Y"`,
|
||||
);
|
||||
});
|
||||
});
|
||||
56
frontend/src/lib/recentQueries/normalize.ts
Normal file
56
frontend/src/lib/recentQueries/normalize.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import {
|
||||
OPERATORS,
|
||||
QUERY_BUILDER_FUNCTIONS,
|
||||
TRACE_OPERATOR_OPERATORS,
|
||||
} from 'constants/antlrQueryConstants';
|
||||
|
||||
// Reserved keywords sourced from the ANTLR grammar constants so this list stays
|
||||
// in sync with the parser. `\b` prevents partial matches inside identifiers
|
||||
// (e.g. `OR` inside `originator`). `TRUE`/`FALSE` are BOOL literals, included
|
||||
// so case variants of boolean values also dedup.
|
||||
const WORD_KEYWORDS = [
|
||||
...Object.keys(OPERATORS).filter((k) => /^[A-Z]+$/.test(k)),
|
||||
...Object.keys(TRACE_OPERATOR_OPERATORS).filter((k) => /^[A-Z]+$/.test(k)),
|
||||
...Object.values(QUERY_BUILDER_FUNCTIONS),
|
||||
'TRUE',
|
||||
'FALSE',
|
||||
];
|
||||
|
||||
const KEYWORDS_RE = new RegExp(`\\b(${WORD_KEYWORDS.join('|')})\\b`, 'gi');
|
||||
|
||||
// Matches single- or double-quoted string literals, supporting escaped quotes
|
||||
// (e.g. `'it\'s'` or `"a \" b"`). We preserve quoted spans verbatim during
|
||||
// normalisation so user-meaningful whitespace and casing inside string values
|
||||
// stays intact: `name = "Foo Bar"` must not collapse to `name="foobar"`.
|
||||
const QUOTED_RE = /'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g;
|
||||
|
||||
// Lowercases reserved keywords and strips ALL whitespace from the unquoted regions
|
||||
// of the input. Keywords are normalised so casing variants dedup; whitespace is
|
||||
// dropped so formatting variants (`a=1` vs `a = 1`) dedup too.
|
||||
function processOutsideQuotes(s: string): string {
|
||||
return s.replace(KEYWORDS_RE, (m) => m.toLowerCase()).replace(/\s+/g, '');
|
||||
}
|
||||
|
||||
// Produces a canonical form of a filter expression suitable for dedup-key derivation.
|
||||
// Walks the input alternating between unquoted regions (where we normalise keywords
|
||||
// and whitespace) and quoted regions (which we copy verbatim).
|
||||
export function normalizeFilterExpression(input: string): string {
|
||||
if (!input) {
|
||||
return '';
|
||||
}
|
||||
|
||||
let result = '';
|
||||
let lastIndex = 0;
|
||||
QUOTED_RE.lastIndex = 0;
|
||||
|
||||
let match = QUOTED_RE.exec(input);
|
||||
while (match !== null) {
|
||||
result += processOutsideQuotes(input.slice(lastIndex, match.index));
|
||||
result += match[0];
|
||||
lastIndex = QUOTED_RE.lastIndex;
|
||||
match = QUOTED_RE.exec(input);
|
||||
}
|
||||
result += processOutsideQuotes(input.slice(lastIndex));
|
||||
|
||||
return result.trim();
|
||||
}
|
||||
247
frontend/src/lib/recentQueries/recentQueriesStore.test.ts
Normal file
247
frontend/src/lib/recentQueries/recentQueriesStore.test.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
import { MAX_ENTRIES } from './constants';
|
||||
import * as store from './recentQueriesStore';
|
||||
import type { RecentQueryInput } from './recentQueriesStore';
|
||||
import type { RecentQueryEntry } from './types';
|
||||
|
||||
const baseInput = (
|
||||
overrides: Partial<RecentQueryInput> = {},
|
||||
): RecentQueryInput => ({
|
||||
signal: 'logs',
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function saveOrThrow(input: RecentQueryInput): RecentQueryEntry {
|
||||
const saved = store.save(input);
|
||||
if (!saved) {
|
||||
throw new Error('expected save to return an entry');
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
describe('recentQueries store', () => {
|
||||
beforeEach(() => {
|
||||
store.useRecentQueriesStore.setState({ buckets: {} });
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('save + list', () => {
|
||||
it('saves an entry and lists it', () => {
|
||||
store.save(baseInput());
|
||||
const entries = store.list('logs');
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].filter.expression).toBe("service.name = 'frontend'");
|
||||
expect(entries[0].id).toBeTruthy();
|
||||
expect(entries[0].lastUsedAt).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('does not save when the filter expression is empty', () => {
|
||||
const result = store.save(baseInput({ filter: { expression: '' } }));
|
||||
expect(result).toBeNull();
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not save when the filter expression is whitespace only', () => {
|
||||
const result = store.save(baseInput({ filter: { expression: ' ' } }));
|
||||
expect(result).toBeNull();
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('LRU ordering', () => {
|
||||
it('places the most recently saved entry at the front', () => {
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
store.save(baseInput({ filter: { expression: 'http.status_code >= 500' } }));
|
||||
store.save(baseInput({ filter: { expression: 'attempt = 1' } }));
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries.map((e) => e.filter.expression)).toStrictEqual([
|
||||
'attempt = 1',
|
||||
'http.status_code >= 500',
|
||||
"severity_text = 'ERROR'",
|
||||
]);
|
||||
});
|
||||
|
||||
it('re-saving an existing filter bumps it to the front', () => {
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
store.save(baseInput({ filter: { expression: 'http.status_code >= 500' } }));
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries).toHaveLength(2);
|
||||
expect(entries.map((e) => e.filter.expression)).toStrictEqual([
|
||||
"severity_text = 'ERROR'",
|
||||
'http.status_code >= 500',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dedup', () => {
|
||||
it('treats formatting variations of the same filter as one entry', () => {
|
||||
store.save(
|
||||
baseInput({
|
||||
filter: { expression: "severity_text = 'ERROR' AND attempt = 1" },
|
||||
}),
|
||||
);
|
||||
store.save(
|
||||
baseInput({
|
||||
filter: { expression: "severity_text='ERROR' and attempt=1" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('signal partitioning', () => {
|
||||
it('saves to the right bucket per signal', () => {
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'logs',
|
||||
filter: { expression: "severity_text = 'ERROR'" },
|
||||
}),
|
||||
);
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'traces',
|
||||
filter: { expression: "service.name = 'orders-api'" },
|
||||
}),
|
||||
);
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'metrics',
|
||||
filter: { expression: 'cpu_usage > 80' },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
expect(store.list('traces')).toHaveLength(1);
|
||||
expect(store.list('metrics')).toHaveLength(1);
|
||||
expect(store.list('logs')[0].filter.expression).toBe(
|
||||
"severity_text = 'ERROR'",
|
||||
);
|
||||
expect(store.list('traces')[0].filter.expression).toBe(
|
||||
"service.name = 'orders-api'",
|
||||
);
|
||||
expect(store.list('metrics')[0].filter.expression).toBe('cpu_usage > 80');
|
||||
});
|
||||
|
||||
it('does not leak between signals on dedup', () => {
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'logs',
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
}),
|
||||
);
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'traces',
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
expect(store.list('traces')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('LRU cap', () => {
|
||||
it('caps the bucket at MAX_ENTRIES and evicts the oldest', () => {
|
||||
const total = MAX_ENTRIES + 1;
|
||||
for (let i = 0; i < total; i += 1) {
|
||||
store.save(baseInput({ filter: { expression: `attempt = ${i}` } }));
|
||||
}
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries).toHaveLength(MAX_ENTRIES);
|
||||
expect(entries[0].filter.expression).toBe(`attempt = ${total - 1}`);
|
||||
expect(entries.some((e) => e.filter.expression === 'attempt = 0')).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('remove', () => {
|
||||
it('removes an entry by id', () => {
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
const saved = saveOrThrow(
|
||||
baseInput({ filter: { expression: 'http.status_code >= 500' } }),
|
||||
);
|
||||
store.remove(saved.id, 'logs');
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].filter.expression).toBe("severity_text = 'ERROR'");
|
||||
});
|
||||
|
||||
it('is a no-op when the id does not exist', () => {
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
store.remove('does-not-exist', 'logs');
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('does not touch other signals', () => {
|
||||
const logsEntry = saveOrThrow(
|
||||
baseInput({
|
||||
signal: 'logs',
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
}),
|
||||
);
|
||||
store.save(
|
||||
baseInput({
|
||||
signal: 'traces',
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
}),
|
||||
);
|
||||
|
||||
store.remove(logsEntry.id, 'logs');
|
||||
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
expect(store.list('traces')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('persistence', () => {
|
||||
it('reads back the same entries after the in-memory state is reset', () => {
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
store.save(baseInput({ filter: { expression: 'http.status_code >= 500' } }));
|
||||
|
||||
store.useRecentQueriesStore.setState({ buckets: {} });
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries.map((e) => e.filter.expression)).toStrictEqual([
|
||||
'http.status_code >= 500',
|
||||
"severity_text = 'ERROR'",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reactive subscription via zustand', () => {
|
||||
it('notifies zustand subscribers on save', () => {
|
||||
const cb = jest.fn();
|
||||
const unsubscribe = store.useRecentQueriesStore.subscribe(cb);
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
expect(cb).toHaveBeenCalledTimes(1);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it('notifies zustand subscribers on remove', () => {
|
||||
const saved = saveOrThrow(
|
||||
baseInput({ filter: { expression: "severity_text = 'ERROR'" } }),
|
||||
);
|
||||
const cb = jest.fn();
|
||||
const unsubscribe = store.useRecentQueriesStore.subscribe(cb);
|
||||
store.remove(saved.id, 'logs');
|
||||
expect(cb).toHaveBeenCalledTimes(1);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it('stops notifying after unsubscribe', () => {
|
||||
const cb = jest.fn();
|
||||
const unsubscribe = store.useRecentQueriesStore.subscribe(cb);
|
||||
unsubscribe();
|
||||
store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
|
||||
expect(cb).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
144
frontend/src/lib/recentQueries/recentQueriesStore.ts
Normal file
144
frontend/src/lib/recentQueries/recentQueriesStore.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
import get from 'api/browser/localstorage/get';
|
||||
import set from 'api/browser/localstorage/set';
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
import { create } from 'zustand';
|
||||
|
||||
import { MAX_ENTRIES, STORAGE_VERSION } from './constants';
|
||||
import { normalizeFilterExpression } from './normalize';
|
||||
import type { RecentQueriesStoreShape, RecentQueryEntry } from './types';
|
||||
import { bucketKey, makeId, normalizeSource, storageKeyFor } from './utils';
|
||||
|
||||
// Mirrors parsed localStorage so equal raw strings return the same array ref —
|
||||
// preserves Object.is for zustand selector bail-out.
|
||||
const persistedBucketCache = new Map<
|
||||
string,
|
||||
{ raw: string; parsed: RecentQueryEntry[] }
|
||||
>();
|
||||
|
||||
function loadBucketFromStorage(
|
||||
signal: SignalType,
|
||||
source: string,
|
||||
): RecentQueryEntry[] | null {
|
||||
const key = bucketKey(signal, source);
|
||||
try {
|
||||
const raw = get(storageKeyFor(signal, source));
|
||||
if (!raw) {
|
||||
persistedBucketCache.delete(key);
|
||||
return null;
|
||||
}
|
||||
const cached = persistedBucketCache.get(key);
|
||||
if (cached && cached.raw === raw) {
|
||||
return cached.parsed;
|
||||
}
|
||||
const parsedShape = JSON.parse(raw) as RecentQueriesStoreShape;
|
||||
if (
|
||||
parsedShape?.version !== STORAGE_VERSION ||
|
||||
!Array.isArray(parsedShape.entries)
|
||||
) {
|
||||
persistedBucketCache.delete(key);
|
||||
return null;
|
||||
}
|
||||
persistedBucketCache.set(key, { raw, parsed: parsedShape.entries });
|
||||
return parsedShape.entries;
|
||||
} catch {
|
||||
persistedBucketCache.delete(key);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveBucketToStorage(
|
||||
signal: SignalType,
|
||||
source: string,
|
||||
entries: RecentQueryEntry[],
|
||||
): void {
|
||||
try {
|
||||
const raw = JSON.stringify({ version: STORAGE_VERSION, entries });
|
||||
if (set(storageKeyFor(signal, source), raw)) {
|
||||
persistedBucketCache.set(bucketKey(signal, source), {
|
||||
raw,
|
||||
parsed: entries,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Ignore storage errors (e.g. quota exceeded, JSON.stringify failure).
|
||||
}
|
||||
}
|
||||
|
||||
export type RecentQueryInput = Omit<
|
||||
RecentQueryEntry,
|
||||
'id' | 'lastUsedAt' | 'source'
|
||||
> & {
|
||||
source?: string;
|
||||
};
|
||||
|
||||
type RecentQueriesState = {
|
||||
buckets: Record<string, RecentQueryEntry[]>;
|
||||
save: (entry: RecentQueryInput) => RecentQueryEntry | null;
|
||||
remove: (id: string, signal: SignalType, source?: string) => void;
|
||||
};
|
||||
|
||||
export const useRecentQueriesStore = create<RecentQueriesState>()(
|
||||
(set, get) => ({
|
||||
buckets: {},
|
||||
|
||||
save: (entry): RecentQueryEntry | null => {
|
||||
const normalized = normalizeFilterExpression(entry.filter.expression);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
const source = normalizeSource(entry.source);
|
||||
const key = bucketKey(entry.signal, source);
|
||||
|
||||
const current =
|
||||
get().buckets[key] ?? loadBucketFromStorage(entry.signal, source) ?? [];
|
||||
const filtered = current.filter(
|
||||
(e) => normalizeFilterExpression(e.filter.expression) !== normalized,
|
||||
);
|
||||
|
||||
const newEntry: RecentQueryEntry = {
|
||||
...entry,
|
||||
source,
|
||||
id: makeId(entry.signal, source, normalized),
|
||||
lastUsedAt: Date.now(),
|
||||
};
|
||||
|
||||
const next = [newEntry, ...filtered].slice(0, MAX_ENTRIES);
|
||||
set({ buckets: { ...get().buckets, [key]: next } });
|
||||
saveBucketToStorage(entry.signal, source, next);
|
||||
return newEntry;
|
||||
},
|
||||
|
||||
remove: (id, signal, source = ''): void => {
|
||||
const key = bucketKey(signal, source);
|
||||
const current = get().buckets[key] ?? loadBucketFromStorage(signal, source);
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
const next = current.filter((e) => e.id !== id);
|
||||
if (next.length === current.length) {
|
||||
return;
|
||||
}
|
||||
set({ buckets: { ...get().buckets, [key]: next } });
|
||||
saveBucketToStorage(signal, source, next);
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Plain-function wrappers for non-React callers — same pattern as useColumnStore.ts.
|
||||
export function save(entry: RecentQueryInput): RecentQueryEntry | null {
|
||||
return useRecentQueriesStore.getState().save(entry);
|
||||
}
|
||||
|
||||
export function remove(id: string, signal: SignalType, source = ''): void {
|
||||
useRecentQueriesStore.getState().remove(id, signal, source);
|
||||
}
|
||||
|
||||
// Synchronous bucket read with localStorage fallback for non-React callers.
|
||||
export function list(signal: SignalType, source = ''): RecentQueryEntry[] {
|
||||
const key = bucketKey(signal, source);
|
||||
const state = useRecentQueriesStore.getState();
|
||||
if (state.buckets[key]) {
|
||||
return state.buckets[key];
|
||||
}
|
||||
return loadBucketFromStorage(signal, source) ?? [];
|
||||
}
|
||||
126
frontend/src/lib/recentQueries/saveRecentQuery.test.ts
Normal file
126
frontend/src/lib/recentQueries/saveRecentQuery.test.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { validateQuery } from 'utils/queryValidationUtils';
|
||||
|
||||
import * as store from './recentQueriesStore';
|
||||
import { saveRecentQuery } from './saveRecentQuery';
|
||||
|
||||
jest.mock('utils/queryValidationUtils', () => ({
|
||||
validateQuery: jest.fn(),
|
||||
}));
|
||||
|
||||
const mockedValidateQuery = validateQuery as jest.MockedFunction<
|
||||
typeof validateQuery
|
||||
>;
|
||||
|
||||
const buildQuery = (overrides: Partial<IBuilderQuery>[] = [{}]): Query => ({
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
promql: [],
|
||||
clickhouse_sql: [],
|
||||
id: 'q1',
|
||||
builder: {
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
queryData: overrides.map((o, i) => ({
|
||||
queryName: `Q${i}`,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
aggregateAttribute: undefined as never,
|
||||
functions: [],
|
||||
filter: { expression: 'service.name = "frontend"' },
|
||||
groupBy: [],
|
||||
expression: `Q${i}`,
|
||||
disabled: false,
|
||||
having: [],
|
||||
limit: null,
|
||||
stepInterval: null,
|
||||
orderBy: [],
|
||||
legend: '',
|
||||
...o,
|
||||
})) as IBuilderQuery[],
|
||||
},
|
||||
});
|
||||
|
||||
describe('saveRecentQuery', () => {
|
||||
beforeEach(() => {
|
||||
store.useRecentQueriesStore.setState({ buckets: {} });
|
||||
localStorage.clear();
|
||||
mockedValidateQuery.mockReturnValue({
|
||||
isValid: true,
|
||||
message: '',
|
||||
errors: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('saves the query when validation passes', () => {
|
||||
saveRecentQuery(buildQuery());
|
||||
|
||||
const entries = store.list('logs');
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].filter.expression).toBe('service.name = "frontend"');
|
||||
});
|
||||
|
||||
it('does not save when validateQuery rejects the expression', () => {
|
||||
mockedValidateQuery.mockReturnValue({
|
||||
isValid: false,
|
||||
message: 'bad',
|
||||
errors: [],
|
||||
});
|
||||
|
||||
saveRecentQuery(buildQuery());
|
||||
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not save a builder query with an empty filter expression', () => {
|
||||
saveRecentQuery(buildQuery([{ filter: { expression: '' } }]));
|
||||
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('saves each builder query in the composite separately', () => {
|
||||
saveRecentQuery(
|
||||
buildQuery([
|
||||
{
|
||||
dataSource: DataSource.LOGS,
|
||||
filter: { expression: "service.name = 'frontend'" },
|
||||
},
|
||||
{
|
||||
dataSource: DataSource.TRACES,
|
||||
filter: { expression: "service.name = 'orders-api'" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
expect(store.list('traces')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps a single entry when the same query is run again', () => {
|
||||
saveRecentQuery(buildQuery());
|
||||
saveRecentQuery(buildQuery());
|
||||
|
||||
expect(store.list('logs')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('adds a second entry when the filter changes', () => {
|
||||
saveRecentQuery(
|
||||
buildQuery([{ filter: { expression: "severity_text = 'ERROR'" } }]),
|
||||
);
|
||||
saveRecentQuery(
|
||||
buildQuery([{ filter: { expression: 'http.status_code >= 500' } }]),
|
||||
);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('is a no-op when the query is null', () => {
|
||||
saveRecentQuery(null);
|
||||
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
48
frontend/src/lib/recentQueries/saveRecentQuery.ts
Normal file
48
frontend/src/lib/recentQueries/saveRecentQuery.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
QueryState,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
import { validateQuery } from 'utils/queryValidationUtils';
|
||||
|
||||
import * as store from './recentQueriesStore';
|
||||
|
||||
function toSignal(dataSource: IBuilderQuery['dataSource']): SignalType | null {
|
||||
if (
|
||||
dataSource === 'logs' ||
|
||||
dataSource === 'traces' ||
|
||||
dataSource === 'metrics'
|
||||
) {
|
||||
return dataSource;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Persists each builder query's filter expression as a recent search, partitioned
|
||||
// by signal (and source). Call this on an explicit Stage & Run — not on staged-query
|
||||
// changes — so page loads, navigation, and correlation redirects don't pollute recents.
|
||||
// The store dedups by normalized filter, so re-running a query just bumps it to the front.
|
||||
export function saveRecentQuery(
|
||||
query: Query | QueryState | null | undefined,
|
||||
): void {
|
||||
const queryData = query?.builder?.queryData ?? [];
|
||||
queryData.forEach((q) => {
|
||||
const expression = q.filter?.expression?.trim();
|
||||
if (!expression) {
|
||||
return;
|
||||
}
|
||||
if (!validateQuery(expression).isValid) {
|
||||
return;
|
||||
}
|
||||
const signal = toSignal(q.dataSource);
|
||||
if (!signal) {
|
||||
return;
|
||||
}
|
||||
store.save({
|
||||
signal,
|
||||
source: q.source ?? '',
|
||||
filter: q.filter ?? { expression: '' },
|
||||
});
|
||||
});
|
||||
}
|
||||
14
frontend/src/lib/recentQueries/types.ts
Normal file
14
frontend/src/lib/recentQueries/types.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { Filter, SignalType } from 'types/api/v5/queryRange';
|
||||
|
||||
export interface RecentQueryEntry {
|
||||
id: string;
|
||||
signal: SignalType;
|
||||
source: string;
|
||||
filter: Filter;
|
||||
lastUsedAt: number;
|
||||
}
|
||||
|
||||
export interface RecentQueriesStoreShape {
|
||||
version: 1;
|
||||
entries: RecentQueryEntry[];
|
||||
}
|
||||
24
frontend/src/lib/recentQueries/utils.ts
Normal file
24
frontend/src/lib/recentQueries/utils.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
|
||||
import { STORAGE_KEY_PREFIX } from './constants';
|
||||
|
||||
export function normalizeSource(source: string | undefined): string {
|
||||
return source ?? '';
|
||||
}
|
||||
|
||||
export function bucketKey(signal: SignalType, source: string): string {
|
||||
return `${signal}:${source}`;
|
||||
}
|
||||
|
||||
export function storageKeyFor(signal: SignalType, source: string): string {
|
||||
return `${STORAGE_KEY_PREFIX}:${bucketKey(signal, source)}`;
|
||||
}
|
||||
|
||||
// Same (signal, source, normalized filter) ⇒ same id ⇒ upsert.
|
||||
export function makeId(
|
||||
signal: SignalType,
|
||||
source: string,
|
||||
normalizedFilter: string,
|
||||
): string {
|
||||
return `${signal}|${source}|${normalizedFilter}`;
|
||||
}
|
||||
@@ -39,6 +39,7 @@ import { updateStepInterval } from 'hooks/queryBuilder/useStepInterval';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
|
||||
import { saveRecentQuery } from 'lib/recentQueries/saveRecentQuery';
|
||||
import { createNewBuilderItemName } from 'lib/newQueryBuilder/createNewBuilderItemName';
|
||||
import { getOperatorsBySourceAndPanelType } from 'lib/newQueryBuilder/getOperatorsBySourceAndPanelType';
|
||||
import { replaceIncorrectObjectFields } from 'lib/replaceIncorrectObjectFields';
|
||||
@@ -1025,6 +1026,11 @@ export function QueryBuilderProvider({
|
||||
);
|
||||
|
||||
const handleRunQuery = useCallback(() => {
|
||||
// Save the run query to recent searches. Tied to the explicit Stage & Run
|
||||
// gesture (not staged-query changes) so navigation and correlation redirects
|
||||
// don't pollute recents.
|
||||
saveRecentQuery(currentQuery);
|
||||
|
||||
const isExplorer =
|
||||
location.pathname === ROUTES.LOGS_EXPLORER ||
|
||||
location.pathname === ROUTES.TRACES_EXPLORER;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import dayjs from 'dayjs';
|
||||
import customParseFormat from 'dayjs/plugin/customParseFormat';
|
||||
import duration from 'dayjs/plugin/duration';
|
||||
import relativeTime from 'dayjs/plugin/relativeTime';
|
||||
import timezone from 'dayjs/plugin/timezone';
|
||||
import utc from 'dayjs/plugin/utc';
|
||||
|
||||
@@ -9,6 +10,7 @@ dayjs.extend(utc);
|
||||
dayjs.extend(customParseFormat);
|
||||
dayjs.extend(duration);
|
||||
dayjs.extend(timezone);
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
export function toUTCEpoch(time: number): number {
|
||||
const x = new Date();
|
||||
|
||||
Reference in New Issue
Block a user