Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add autocomplete of metrics attributes #623

Open
wants to merge 5 commits into
base: warren/metrics-mvp
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions packages/app/src/SearchInputV2.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default function SearchInputV2({
connectionId,
enableHotkey,
onSubmit,
additionalSuggestions,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this works for now, though I wonder if the v1 pattern of having a separate metrics tag filter input would be cleaner? We can leave it as a follow up.

https://github.com/hyperdxio/hyperdx/blob/main/packages/app/src/MetricTagFilterInput.tsx

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like that idea. Will add a ticket to follow up on this and the other suggestions. Thanks!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New ticket created: HDX-1410

...props
}: {
database?: string;
Expand All @@ -29,6 +30,7 @@ export default function SearchInputV2({
language?: 'sql' | 'lucene';
enableHotkey?: boolean;
onSubmit?: () => void;
additionalSuggestions?: string[];
} & UseControllerProps<any>) {
const {
field: { onChange, value },
Expand All @@ -49,11 +51,19 @@ export default function SearchInputV2({

const autoCompleteOptions = useMemo(() => {
const _columns = (fields ?? []).filter(c => c.jsType !== null);
return _columns.map(c => ({
const baseOptions = _columns.map(c => ({
value: c.path.join('.'),
label: `${c.path.join('.')} (${c.jsType})`,
}));
}, [fields]);

const suggestionOptions =
additionalSuggestions?.map(column => ({
value: column,
label: column,
})) ?? [];

return [...baseOptions, ...suggestionOptions];
}, [fields, additionalSuggestions]);

const [parsedEnglishQuery, setParsedEnglishQuery] = useState<string>('');

Expand Down
32 changes: 31 additions & 1 deletion packages/app/src/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { formatDate } from '../utils';
import { formatAttributeClause, formatDate } from '../utils';

describe('utils', () => {
it('12h utc', () => {
Expand Down Expand Up @@ -43,3 +43,33 @@ describe('utils', () => {
).toEqual('Jan 1 12:00:00.000');
});
});

describe('formatAttributeClause', () => {
it('should format SQL attribute clause correctly', () => {
expect(
formatAttributeClause('ResourceAttributes', 'service', 'nginx', true),
).toBe("ResourceAttributes['service']='nginx'");

expect(formatAttributeClause('metadata', 'environment', 'prod', true)).toBe(
"metadata['environment']='prod'",
);

expect(formatAttributeClause('data', 'user-id', 'abc-123', true)).toBe(
"data['user-id']='abc-123'",
);
});

it('should format lucene attribute clause correctly', () => {
expect(formatAttributeClause('attrs', 'service', 'nginx', false)).toBe(
'attrs.service:"nginx"',
);

expect(
formatAttributeClause('metadata', 'environment', 'prod', false),
).toBe('metadata.environment:"prod"');

expect(formatAttributeClause('data', 'user-id', 'abc-123', false)).toBe(
'data.user-id:"abc-123"',
);
});
});
15 changes: 3 additions & 12 deletions packages/app/src/components/ContextSidePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { useDebouncedValue } from '@mantine/hooks';
import { SQLInlineEditorControlled } from '@/components/SQLInlineEditor';
import WhereLanguageControlled from '@/components/WhereLanguageControlled';
import SearchInputV2 from '@/SearchInputV2';
import { formatAttributeClause } from '@/utils';

import { DBSqlRowTable } from './DBRowTable';

Expand Down Expand Up @@ -118,17 +119,6 @@ export default function ContextSubpanel({
return isSql ? `${original} AND ${addition}` : `${original} ${addition}`;
}

// Helper function to format resource attribute clause
function formatResourceAttributeClause(
field: string,
value: string,
isSql: boolean,
): string {
return isSql
? `ResourceAttributes['${field}'] = '${value}'`
: `ResourceAttributes.${field}:"${value}"`;
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just moving this function into utils so it can be used in other places as well.

// Main function to generate WHERE clause based on context
function getWhereClause(contextBy: ContextBy): string {
const isSql = originalLanguage === 'sql';
Expand All @@ -142,7 +132,8 @@ export default function ContextSubpanel({
return combineWhereClauses(originalWhere, debouncedWhere.trim(), isSql);
}

const attributeClause = formatResourceAttributeClause(
const attributeClause = formatAttributeClause(
'ResourceAttributes',
mapping.field,
mapping.value,
isSql,
Expand Down
15 changes: 12 additions & 3 deletions packages/app/src/components/DBEditTimeChartForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import { SQLInlineEditorControlled } from '@/components/SQLInlineEditor';
import { TimePicker } from '@/components/TimePicker';
import { IS_DEV } from '@/config';
import { GranularityPickerControlled } from '@/GranularityPicker';
import { useFetchMetricResourceAttrs } from '@/hooks/useFetchMetricResourceAttrs';
import SearchInputV2 from '@/SearchInputV2';
import { getFirstTimestampValueExpression, useSource } from '@/source';
import { parseTimeQuery } from '@/timeQuery';
Expand Down Expand Up @@ -130,16 +131,23 @@ function ChartSeriesEditor({
);

const metricType = watch(`${namePrefix}metricType`);

const selectedSourceId = watch('source');
const { data: tableSource } = useSource({ id: selectedSourceId });

// HACK: switch table name based on metric type
const tableName =
tableSource?.kind === SourceKind.Metric
? getMetricTableName(tableSource, metricType)
: _tableName;

const { data: attributeKeys } = useFetchMetricResourceAttrs({
databaseName,
tableName,
metricType,
metricName: watch(`${namePrefix}metricName`),
tableSource,
isSql: aggConditionLanguage === 'sql',
});

return (
<>
<Divider
Expand Down Expand Up @@ -181,7 +189,6 @@ function ChartSeriesEditor({
metricType={metricType}
setMetricName={value => {
setValue(`${namePrefix}metricName`, value);
// HACK: harcoded valueExpression
setValue(`${namePrefix}valueExpression`, 'Value');
}}
setMetricType={value => setValue(`${namePrefix}metricType`, value)}
Expand Down Expand Up @@ -213,6 +220,7 @@ function ChartSeriesEditor({
onLanguageChange={lang =>
setValue(`${namePrefix}aggConditionLanguage`, lang)
}
additionalSuggestions={attributeKeys}
language="sql"
onSubmit={onSubmit}
/>
Expand All @@ -229,6 +237,7 @@ function ChartSeriesEditor({
language="lucene"
placeholder="Search your events w/ Lucene ex. column:foo"
onSubmit={onSubmit}
additionalSuggestions={attributeKeys}
/>
)}
{showGroupBy && (
Expand Down
41 changes: 10 additions & 31 deletions packages/app/src/components/SQLInlineEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ type SQLInlineEditorProps = {
disableKeywordAutocomplete?: boolean;
connectionId: string | undefined;
enableHotkey?: boolean;
additionalSuggestions?: string[];
};

const styleTheme = EditorView.baseTheme({
Expand Down Expand Up @@ -132,6 +133,7 @@ export default function SQLInlineEditor({
disableKeywordAutocomplete,
connectionId,
enableHotkey,
additionalSuggestions = [],
}: SQLInlineEditorProps) {
const { data: fields } = useAllFields(
{
Expand All @@ -156,30 +158,30 @@ export default function SQLInlineEditor({

const updateAutocompleteColumns = useCallback(
(viewRef: EditorView) => {
const keywords =
filteredFields?.map(column => {
const keywords = [
...(filteredFields?.map(column => {
if (column.path.length > 1) {
return `${column.path[0]}['${column.path[1]}']`;
}
return column.path[0];
}) ?? [];
}) ?? []),
...additionalSuggestions,
];

viewRef.dispatch({
effects: compartmentRef.current.reconfigure(
sql({
defaultTable: table ?? '',
// schema, // FIXME: maybe we want to use schema. need to figure out the identifier issue
dialect: SQLDialect.define({
keywords:
keywords.join(' ') +
(disableKeywordAutocomplete ? '' : AUTOCOMPLETE_LIST_STRING),
// identifierQuotes: '`',
}),
}),
),
});
},
[filteredFields, table],
[filteredFields, table, additionalSuggestions],
);

useEffect(() => {
Expand Down Expand Up @@ -275,31 +277,6 @@ export default function SQLInlineEditor({
onCreateEditor={view => {
updateAutocompleteColumns(view);
}}
// onUpdate={update => {
// // console.log(
// // 'update',
// // update,
// // update.view.hasFocus,
// // update.focusChanged,
// // ref.current,
// // );
// // Always open completion window as much as possible
// console.log(
// 'update',
// update,
// update.focusChanged,
// update.view.hasFocus,
// ref.current?.view?.hasFocus,
// );
// if (
// update.focusChanged &&
// update.view.hasFocus &&
// ref.current?.view
// ) {
// console.log('startCompletion');
// startCompletion(ref.current?.view);
// }
// }}
basicSetup={{
lineNumbers: false,
foldGutter: false,
Expand All @@ -326,6 +303,7 @@ export function SQLInlineEditorControlled({
placeholder,
filterField,
connectionId,
additionalSuggestions,
...props
}: Omit<SQLInlineEditorProps, 'value' | 'onChange'> & UseControllerProps<any>) {
const { field } = useController(props);
Expand All @@ -339,6 +317,7 @@ export function SQLInlineEditorControlled({
table={table}
value={field.value || props.defaultValue}
connectionId={connectionId}
additionalSuggestions={additionalSuggestions}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This adds the ability to arbitrarily add suggestions to autocomplete that aren't already based on a source. I didn't see a way to do this, but correct me if I'm wrong!

{...props}
/>
);
Expand Down
Loading