repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
hyperdx
github_2023
typescript
637
hyperdxio
wrn14897
@@ -81,7 +113,7 @@ function getConfig(source: TSource, traceId: string) { alias: 'Body', }, { - valueExpression: alias.Timestamp, + valueExpression: sortKey,
is this suppose be `alias.Timestamp` ?
hyperdx
github_2023
typescript
641
hyperdxio
teeohhem
@@ -55,8 +65,16 @@ export const Tags = React.memo( (event: React.KeyboardEvent<HTMLInputElement>) => { if (event.key === 'Enter') { if (allowCreate && q.length > 0) { - onChange([...values, event.currentTarget.value]); - setQ(''); + // Check if tag already exists (case insensitive) + const newTag = event.currentTarget.value; + const tagExists = values.some( + tag => tag.toLowerCase() === newTag.toLowerCase(), + ); + + if (!tagExists) { + onChange([...values, newTag]); + setQ(''); + }
nit: If a tag exists, do we want to display an info message of some sort?
hyperdx
github_2023
typescript
641
hyperdxio
teeohhem
@@ -926,6 +1009,24 @@ function DBSearchPage() { Alerts </Button> )} + {!!savedSearch && ( + <Tags + allowCreate + values={savedSearch.tags || []} + onChange={handleUpdateTags} + > + <Button + variant="outline" + color="dark.2" + px="xs" + size="xs" + style={{ flexShrink: 0 }} + > + <i className="bi bi-tags-fill me-1"></i> + {savedSearch.tags?.length || 0} + </Button> + </Tags>
Just a note, clicking on this "x" in the input does nothing ![image](https://github.com/user-attachments/assets/d5dedbc3-3241-4a5b-9a12-0be9cf80f716)
hyperdx
github_2023
typescript
640
hyperdxio
LYHuang
@@ -554,6 +531,18 @@ function DBSearchPage() { updateInput: !isLive, }); + // If live tail is null, but time range exists, don't live tail + // If live tail is null, and time range is null, let's live tail + useEffect(() => { + if (_isLive == null && isReady) {
A little bit confuse about this part, is it try to init livetail flag become `true` when user enter the search page and does not set time range? And once the flag is set, we don't auto turn on the flag even user remove time range?
hyperdx
github_2023
typescript
640
hyperdxio
LYHuang
@@ -87,33 +29,94 @@ export function RowOverviewPanel({ return firstRow; }, [data]); - const resourceAttributes = useMemo(() => { - return firstRow[source.resourceAttributesExpression!] || {}; - }, [firstRow, source.resourceAttributesExpression]); + const resourceAttributes = firstRow?.__hdx_resource_attributes ?? EMPTY_OBJ; + const eventAttributes = firstRow?.__hdx_event_attributes ?? EMPTY_OBJ;
Not sure this is intent but there is a chance `resourceAttributes` and `eventAttributes` reference the same obj, I don't think it is safe. ``` const EMPTY_OBJ = {} const randomObj = {} const ob1 = randomObj?.key1 ?? EMPTY_OBJ const ob2 = randomObj?.key2 ?? EMPTY_OBJ; EMPTY_OBJ.random = 'random words' console.log(ob1) console.log(ob2) // output: // { random: 'random words' } // { random: 'random words' } ```
hyperdx
github_2023
typescript
640
hyperdxio
LYHuang
@@ -87,33 +29,94 @@ export function RowOverviewPanel({ return firstRow; }, [data]); - const resourceAttributes = useMemo(() => { - return firstRow[source.resourceAttributesExpression!] || {}; - }, [firstRow, source.resourceAttributesExpression]); + const resourceAttributes = firstRow?.__hdx_resource_attributes ?? EMPTY_OBJ; + const eventAttributes = firstRow?.__hdx_event_attributes ?? EMPTY_OBJ; + + const _generateSearchUrl = useCallback( + (query?: string, timeRange?: [Date, Date]) => { + return ( + generateSearchUrl?.({ + where: query, + whereLanguage: 'lucene', + }) ?? '/' + ); + }, + [generateSearchUrl],
is it ok we don't update `_generateSearchUrl` even `query` and `timeRange` change?
hyperdx
github_2023
typescript
640
hyperdxio
LYHuang
@@ -61,7 +62,10 @@ export const FilterCheckbox = ({ <Checkbox checked={!!value} size={13 as any} - onChange={e => onChange?.(e.currentTarget.checked)} + onChange={
Can we just remove `onChange` or pass `() => {}`?
hyperdx
github_2023
typescript
640
hyperdxio
LYHuang
@@ -0,0 +1,343 @@ +import React, { useMemo } from 'react'; +import Link from 'next/link'; +import { pickBy } from 'lodash'; +import CopyToClipboard from 'react-copy-to-clipboard'; +import { JSONTree } from 'react-json-tree'; +import { + Accordion, + Box, + Button, + CopyButton, + TableData, + Text, +} from '@mantine/core'; +import { notifications } from '@mantine/notifications'; + +import HyperJson from '@/components/HyperJson'; +import { Table } from '@/components/Table'; +import { + headerColumns, + networkColumns, + SectionWrapper, +} from '@/LogSidePanelElements'; +import { CollapsibleSection } from '@/LogSidePanelElements'; +import { CurlGenerator } from '@/utils/curlGenerator'; + +interface NetworkPropertyPanelProps { + eventAttributes: Record<string, any>; + onPropertyAddClick?: (key: string, value: string) => void; + generateSearchUrl: (query?: string, timeRange?: [Date, Date]) => string; +} + +// https://github.com/reduxjs/redux-devtools/blob/f11383d294c1139081f119ef08aa1169bd2ad5ff/packages/react-json-tree/src/createStylingFromTheme.ts +const JSON_TREE_THEME = { + base00: '#00000000', + base01: '#383830', + base02: '#49483e', + base03: '#75715e', + base04: '#a59f85', + base05: '#f8f8f2', + base06: '#f5f4f1', + base07: '#f9f8f5', + base08: '#f92672', + base09: '#fd971f', + base0A: '#f4bf75', + base0B: '#a6e22e', + base0C: '#a1efe4', + base0D: '#8378FF', // Value Labels + base0E: '#ae81ff', + base0F: '#cc6633', +}; + +const parseHeaders = ( + keyPrefix: string, + parsedProperties: any, +): [string, string][] => { + const reqHeaderObj: Record< + string, + string | string[] | Record<string, string> + > = pickBy(parsedProperties, (value, key) => key.startsWith(keyPrefix)); + + return Object.entries(reqHeaderObj).flatMap(([fullKey, _value]) => { + let value = _value; + try { + if (typeof _value === 'string') {
don't need `if` if we already try catch it
hyperdx
github_2023
typescript
640
hyperdxio
LYHuang
@@ -0,0 +1,343 @@ +import React, { useMemo } from 'react'; +import Link from 'next/link'; +import { pickBy } from 'lodash'; +import CopyToClipboard from 'react-copy-to-clipboard'; +import { JSONTree } from 'react-json-tree'; +import { + Accordion, + Box, + Button, + CopyButton, + TableData, + Text, +} from '@mantine/core'; +import { notifications } from '@mantine/notifications'; + +import HyperJson from '@/components/HyperJson'; +import { Table } from '@/components/Table'; +import { + headerColumns, + networkColumns, + SectionWrapper, +} from '@/LogSidePanelElements'; +import { CollapsibleSection } from '@/LogSidePanelElements'; +import { CurlGenerator } from '@/utils/curlGenerator'; + +interface NetworkPropertyPanelProps { + eventAttributes: Record<string, any>; + onPropertyAddClick?: (key: string, value: string) => void; + generateSearchUrl: (query?: string, timeRange?: [Date, Date]) => string; +} + +// https://github.com/reduxjs/redux-devtools/blob/f11383d294c1139081f119ef08aa1169bd2ad5ff/packages/react-json-tree/src/createStylingFromTheme.ts +const JSON_TREE_THEME = { + base00: '#00000000', + base01: '#383830', + base02: '#49483e', + base03: '#75715e', + base04: '#a59f85', + base05: '#f8f8f2', + base06: '#f5f4f1', + base07: '#f9f8f5', + base08: '#f92672', + base09: '#fd971f', + base0A: '#f4bf75', + base0B: '#a6e22e', + base0C: '#a1efe4', + base0D: '#8378FF', // Value Labels + base0E: '#ae81ff', + base0F: '#cc6633', +}; + +const parseHeaders = ( + keyPrefix: string, + parsedProperties: any, +): [string, string][] => { + const reqHeaderObj: Record< + string, + string | string[] | Record<string, string> + > = pickBy(parsedProperties, (value, key) => key.startsWith(keyPrefix)); + + return Object.entries(reqHeaderObj).flatMap(([fullKey, _value]) => { + let value = _value; + try { + if (typeof _value === 'string') { + value = JSON.parse(_value); + } + } catch (e) { + // ignore + } + + // Replacing _ -> - is part of the otel spec, idk why + const key = fullKey.replace(keyPrefix, '').replace('_', '-'); + + let keyVal = [[key, `${value}`]] as [string, string][]; + + if (Array.isArray(value)) { + keyVal = value.map(value => [key, `${value}`] as [string, string]); + } else if (typeof value === 'object' && Object.keys(value).length > 0) { + try { + // TODO: We actually shouldn't be re-serializing this as it may mess with the original value + keyVal = [[key, `${JSON.stringify(value)}`]] as [string, string][]; + } catch (e) { + console.error(e);
no console.log
hyperdx
github_2023
typescript
640
hyperdxio
LYHuang
@@ -0,0 +1,343 @@ +import React, { useMemo } from 'react'; +import Link from 'next/link'; +import { pickBy } from 'lodash'; +import CopyToClipboard from 'react-copy-to-clipboard'; +import { JSONTree } from 'react-json-tree'; +import { + Accordion, + Box, + Button, + CopyButton, + TableData, + Text, +} from '@mantine/core'; +import { notifications } from '@mantine/notifications'; + +import HyperJson from '@/components/HyperJson'; +import { Table } from '@/components/Table'; +import { + headerColumns, + networkColumns, + SectionWrapper, +} from '@/LogSidePanelElements'; +import { CollapsibleSection } from '@/LogSidePanelElements'; +import { CurlGenerator } from '@/utils/curlGenerator'; + +interface NetworkPropertyPanelProps { + eventAttributes: Record<string, any>; + onPropertyAddClick?: (key: string, value: string) => void; + generateSearchUrl: (query?: string, timeRange?: [Date, Date]) => string; +} + +// https://github.com/reduxjs/redux-devtools/blob/f11383d294c1139081f119ef08aa1169bd2ad5ff/packages/react-json-tree/src/createStylingFromTheme.ts +const JSON_TREE_THEME = { + base00: '#00000000', + base01: '#383830', + base02: '#49483e', + base03: '#75715e', + base04: '#a59f85', + base05: '#f8f8f2', + base06: '#f5f4f1', + base07: '#f9f8f5', + base08: '#f92672', + base09: '#fd971f', + base0A: '#f4bf75', + base0B: '#a6e22e', + base0C: '#a1efe4', + base0D: '#8378FF', // Value Labels + base0E: '#ae81ff', + base0F: '#cc6633', +}; + +const parseHeaders = ( + keyPrefix: string, + parsedProperties: any, +): [string, string][] => { + const reqHeaderObj: Record< + string, + string | string[] | Record<string, string> + > = pickBy(parsedProperties, (value, key) => key.startsWith(keyPrefix)); + + return Object.entries(reqHeaderObj).flatMap(([fullKey, _value]) => { + let value = _value; + try { + if (typeof _value === 'string') { + value = JSON.parse(_value); + } + } catch (e) { + // ignore + } + + // Replacing _ -> - is part of the otel spec, idk why + const key = fullKey.replace(keyPrefix, '').replace('_', '-'); + + let keyVal = [[key, `${value}`]] as [string, string][]; + + if (Array.isArray(value)) { + keyVal = value.map(value => [key, `${value}`] as [string, string]); + } else if (typeof value === 'object' && Object.keys(value).length > 0) { + try { + // TODO: We actually shouldn't be re-serializing this as it may mess with the original value + keyVal = [[key, `${JSON.stringify(value)}`]] as [string, string][];
if object `value` can only from parsing, we can use `_value` at here
hyperdx
github_2023
typescript
640
hyperdxio
LYHuang
@@ -0,0 +1,343 @@ +import React, { useMemo } from 'react'; +import Link from 'next/link'; +import { pickBy } from 'lodash'; +import CopyToClipboard from 'react-copy-to-clipboard'; +import { JSONTree } from 'react-json-tree'; +import { + Accordion, + Box, + Button, + CopyButton, + TableData, + Text, +} from '@mantine/core'; +import { notifications } from '@mantine/notifications'; + +import HyperJson from '@/components/HyperJson'; +import { Table } from '@/components/Table'; +import { + headerColumns, + networkColumns, + SectionWrapper, +} from '@/LogSidePanelElements'; +import { CollapsibleSection } from '@/LogSidePanelElements'; +import { CurlGenerator } from '@/utils/curlGenerator'; + +interface NetworkPropertyPanelProps { + eventAttributes: Record<string, any>; + onPropertyAddClick?: (key: string, value: string) => void; + generateSearchUrl: (query?: string, timeRange?: [Date, Date]) => string; +} + +// https://github.com/reduxjs/redux-devtools/blob/f11383d294c1139081f119ef08aa1169bd2ad5ff/packages/react-json-tree/src/createStylingFromTheme.ts +const JSON_TREE_THEME = { + base00: '#00000000', + base01: '#383830', + base02: '#49483e', + base03: '#75715e', + base04: '#a59f85', + base05: '#f8f8f2', + base06: '#f5f4f1', + base07: '#f9f8f5', + base08: '#f92672', + base09: '#fd971f', + base0A: '#f4bf75', + base0B: '#a6e22e', + base0C: '#a1efe4', + base0D: '#8378FF', // Value Labels + base0E: '#ae81ff', + base0F: '#cc6633', +}; + +const parseHeaders = ( + keyPrefix: string, + parsedProperties: any, +): [string, string][] => { + const reqHeaderObj: Record< + string, + string | string[] | Record<string, string> + > = pickBy(parsedProperties, (value, key) => key.startsWith(keyPrefix)); + + return Object.entries(reqHeaderObj).flatMap(([fullKey, _value]) => { + let value = _value; + try { + if (typeof _value === 'string') { + value = JSON.parse(_value); + } + } catch (e) { + // ignore + } + + // Replacing _ -> - is part of the otel spec, idk why + const key = fullKey.replace(keyPrefix, '').replace('_', '-'); + + let keyVal = [[key, `${value}`]] as [string, string][]; + + if (Array.isArray(value)) { + keyVal = value.map(value => [key, `${value}`] as [string, string]); + } else if (typeof value === 'object' && Object.keys(value).length > 0) { + try { + // TODO: We actually shouldn't be re-serializing this as it may mess with the original value + keyVal = [[key, `${JSON.stringify(value)}`]] as [string, string][]; + } catch (e) { + console.error(e); + } + } + + return keyVal; + }); +}; + +const generateCurl = ({ + method, + headers, + url, + body, +}: { + method?: string; + headers: Array<{ name: string; value: string }>; + url?: string; + body?: string; +}) => { + if (!url || !method) return ''; + + let curl = `curl -X ${method} '${url}'`; + headers.forEach(({ name, value }) => { + curl += `\n -H '${name}: ${value}'`; + }); + + if (body) { + curl += `\n -d '${body}'`; + } + + return curl; +}; + +export const NetworkBody = ({ + body, + theme, + emptyMessage, + notCollectedMessage, +}: { + body: any; + theme?: any; + emptyMessage?: string; + notCollectedMessage?: string; +}) => { + const valueRenderer = React.useCallback((raw: any) => { + return ( + <pre + className="d-inline text-break" + style={{ + whiteSpace: 'pre-wrap', + wordWrap: 'break-word', + }} + > + {raw} + </pre> + ); + }, []); + + const parsedBody = React.useMemo(() => { + if (typeof body !== 'string') return null; + try { + if ( + (body.startsWith('{') && body.endsWith('}')) || + (body.startsWith('[') && body.endsWith(']')) + ) { + const parsed = JSON.parse(body); + return parsed; + }
prob do `return null` at here to make result consistent
hyperdx
github_2023
typescript
635
hyperdxio
teeohhem
@@ -810,8 +846,67 @@ function translateMetricChartConfig( databaseName: '', tableName: 'RawSum', }, - where: `MetricName = '${metricName}'`, - whereLanguage: 'sql', + }; + } else if (metricType === MetricsDataType.Histogram && metricName) { + // histograms are only valid for quantile selections + const { aggFn, level, ..._selectRest } = _select as { + aggFn: string; + level?: number; + }; + + if (aggFn !== 'quantile' || level == null) { + throw new Error('quantile must be specified for histogram metrics'); + } + + return { + ...restChartConfig, + with: [ + { + name: 'HistRate', + sql: chSql`SELECT *, any(BucketCounts) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevBucketCounts, + any(CountLength) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevCountLength, + any(AttributesHash) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributesHash, + IF(AggregationTemporality = 1, + BucketCounts, + IF(AttributesHash = PrevAttributesHash AND CountLength = PrevCountLength, + arrayMap((prev, curr) -> IF(curr < prev, curr, toUInt64(toInt64(curr) - toInt64(prev))), PrevBucketCounts, BucketCounts), + BucketCounts)) as BucketRates + FROM ( + SELECT *, cityHash64(mapConcat(ScopeAttributes, ResourceAttributes, Attributes)) AS AttributesHash, + length(BucketCounts) as CountLength + FROM ${renderFrom({ from: { ...from, tableName: metricTables[MetricsDataType.Histogram] } })}) + WHERE MetricName = '${metricName}' + ORDER BY Attributes, TimeUnix ASC + `, + },
![chic-fil-a](https://github.com/user-attachments/assets/0fd125e3-dc4a-47fc-924e-381d4e2452d3)
hyperdx
github_2023
typescript
624
hyperdxio
wrn14897
@@ -189,6 +191,21 @@ export default function DBRowSidePanel({ ? source.logSourceId : undefined; + const resourceAttributes = useMemo<Record<string, string>>(() => { + const key = source.resourceAttributesExpression || 'ResourceAttributes'; + return normalizedRow?.[key] || {}; + }, [normalizedRow, source.resourceAttributesExpression]); + + const rumSessionId = useMemo(() => { + return ( + resourceAttributes['rum.sessionId'] || + resourceAttributes['process.tag.rum.sessionId'] + ); + // TODO: Add search for related session from logs[?] + }, [resourceAttributes]);
To match what we have in v1, we want to grab the session Id from the top level span. That being said, the session replay should be accessible for any spans in the same trace (log items as well) <img width="1184" alt="Screenshot 2025-02-24 at 5 11 24 PM" src="https://github.com/user-attachments/assets/50151a68-a8b9-4156-b6a7-b4b8c31cc8a8" />
hyperdx
github_2023
typescript
624
hyperdxio
wrn14897
@@ -0,0 +1,139 @@ +import { useMemo } from 'react'; +import { TSource } from '@hyperdx/common-utils/dist/types'; +import { Loader } from '@mantine/core'; + +import SessionSubpanel from '@/SessionSubpanel'; +import { useSource } from '@/source'; +import { getDisplayedTimestampValueExpression } from '@/source'; + +import { useEventsData } from './DBTraceWaterfallChart'; + +export const useSessionId = ({ + sourceId, + traceId, + dateRange, + enabled = false, +}: { + sourceId?: string; + traceId: string; + dateRange: [Date, Date]; + enabled?: boolean; +}) => { + const { data: source } = useSource({ id: sourceId }); + + const config = useMemo(() => { + if (!source) { + return; + } + return { + select: [ + { + valueExpression: getDisplayedTimestampValueExpression(source),
style: better to centralize getDisplayedTimestampValueExpression call somewhere top level. for now, I think we can use `timestampValueExpression` directly
hyperdx
github_2023
typescript
624
hyperdxio
wrn14897
@@ -0,0 +1,139 @@ +import { useMemo } from 'react'; +import { TSource } from '@hyperdx/common-utils/dist/types'; +import { Loader } from '@mantine/core'; + +import SessionSubpanel from '@/SessionSubpanel'; +import { useSource } from '@/source'; +import { getDisplayedTimestampValueExpression } from '@/source'; + +import { useEventsData } from './DBTraceWaterfallChart'; + +export const useSessionId = ({ + sourceId, + traceId, + dateRange, + enabled = false, +}: { + sourceId?: string; + traceId: string; + dateRange: [Date, Date]; + enabled?: boolean; +}) => { + const { data: source } = useSource({ id: sourceId }); + + const config = useMemo(() => { + if (!source) { + return; + } + return { + select: [ + { + valueExpression: getDisplayedTimestampValueExpression(source), + alias: 'Timestamp', + }, + { + valueExpression: `${source.resourceAttributesExpression}['rum.sessionId']`, + alias: 'rumSessionId', + }, + { + valueExpression: `${source.resourceAttributesExpression}['service.name']`, + alias: 'serviceName', + }, + { + valueExpression: `${source.parentSpanIdExpression}`, + alias: 'parentSpanId', + }, + ], + from: source.from, + timestampValueExpression: getDisplayedTimestampValueExpression(source), + limit: { limit: 10000 }, + connection: source.connection, + where: `${source.traceIdExpression} = '${traceId}'`, + whereLanguage: 'sql' as const, + }; + }, [source, traceId]); + + const { data } = useEventsData({
style: `useEventsData` seems to be used for `DBTraceWaterfallChartContainer` particularly. I think here we can just make a call using `clickhouseClient.query` like https://github.com/hyperdxio/hyperdx/blob/b66fc1464166dffaf06258f9c77094f3f9f3dd85/packages/app/src/clickhouse.ts#L244-L249
hyperdx
github_2023
typescript
634
hyperdxio
wrn14897
@@ -73,3 +80,78 @@ describe('formatAttributeClause', () => { ); }); }); + +describe('getMetricTableName', () => { + // Base source object with required properties + const createBaseSource = () => ({ + from: { + tableName: 'default_table',
nit: as I recall, the tableName is an empty string for the metrics source
hyperdx
github_2023
typescript
634
hyperdxio
wrn14897
@@ -73,3 +80,78 @@ describe('formatAttributeClause', () => { ); }); }); + +describe('getMetricTableName', () => { + // Base source object with required properties + const createBaseSource = () => ({ + from: { + tableName: 'default_table', + databaseName: 'test_db', + }, + id: 'test-id', + name: 'test-source', + timestampValueExpression: 'timestamp', + connection: 'test-connection', + kind: 'logs' as const,
nit: 'metric'?
hyperdx
github_2023
others
633
hyperdxio
MikeShi42
@@ -75,9 +85,8 @@ extensions: endpoint: :13133 service: telemetry: - # TODO: enable internal metrics - # metrics: - # address: ':8888' + metrics:
can ticket this for later but seems better if we push directly? https://opentelemetry.io/docs/collector/internal-telemetry/#configure-internal-metrics
hyperdx
github_2023
typescript
629
hyperdxio
MikeShi42
@@ -688,18 +727,119 @@ function renderLimit( return chSql`${{ Int32: chartConfig.limit.limit }}${offset}`; } -export async function renderChartConfig( +// CTE (Common Table Expressions) isn't exported at this time. It's only used internally +// for metric SQL generation. +type ChartConfigWithOptDateRateAndCte = ChartConfigWithOptDateRange & { + with?: { name: string; sql: ChSql }[]; +}; + +function renderWith( + chartConfig: ChartConfigWithOptDateRateAndCte, + metadata: Metadata, +): ChSql | undefined { + const { with: withClauses } = chartConfig; + if (withClauses) { + return concatChSql( + '', + withClauses.map(clause => chSql`WITH ${clause.name} AS (${clause.sql})`), + ); + } + + return undefined; +} + +function translateMetricChartConfig( chartConfig: ChartConfigWithOptDateRange, +): ChartConfigWithOptDateRateAndCte { + const metricTables = chartConfig.metricTables; + if (!metricTables) { + return chartConfig; + } + + // assumes all the selects are from a single metric type, for now + const { select, from, ...restChartConfig } = chartConfig; + if (!select || !Array.isArray(select)) { + throw new Error('multi select or string select on metrics not supported'); + } + + const { metricType, metricName, ..._select } = select[0]; // Initial impl only supports one metric select per chart config + if (metricType === MetricsDataType.Gauge && metricName) { + return { + ...restChartConfig, + select: [ + { + ..._select, + valueExpression: 'Value', + }, + ], + from: { + ...from, + tableName: metricTables[MetricsDataType.Gauge], + }, + where: `MetricName = '${metricName}'`, + whereLanguage: 'sql', + }; + } else if (metricType === MetricsDataType.Sum && metricName) { + return { + ...restChartConfig, + with: [ + { + name: 'RawSum', + sql: chSql`SELECT MetricName,Value,TimeUnix,Attributes,
We need to expose all the original columns here, otherwise the user won't be able to query the table for something like `GROUP BY ResourceAttrributes['host.name']`
hyperdx
github_2023
typescript
619
hyperdxio
wrn14897
@@ -262,21 +262,16 @@ export const handleSendGenericWebhook = async ( 'Content-Type': 'application/json', // default, will be overwritten if user has set otherwise ...(webhook.headers?.toJSON() ?? {}), }; - - // BODY - - let body = ''; - if (webhook.body) { - const handlebars = Handlebars.create(); - body = handlebars.compile(webhook.body, { - noEscape: true, - })({ - body: escapeJsonString(message.body), - link: escapeJsonString(message.hdxLink), - title: escapeJsonString(message.title), - }); - } - + // BODY, for v2, currently don't support custom template, use {{title}} | {{body}} | {{link}} as default template + let body = '{{title}} | {{body}} | {{link}}';
Can't we set this as a default value when creating a generic webhook? Giving it another thought, I think we should just add a 'body' field in the UI. It's kind of critical imo to empower the generic webhook. v1 design looks like <img width="701" alt="Screenshot 2025-02-18 at 9 46 16 PM" src="https://github.com/user-attachments/assets/b3ec6e94-d628-4c3d-983a-9be22984984f" />
hyperdx
github_2023
typescript
619
hyperdxio
wrn14897
@@ -262,18 +262,26 @@ export const handleSendGenericWebhook = async ( 'Content-Type': 'application/json', // default, will be overwritten if user has set otherwise ...(webhook.headers?.toJSON() ?? {}), }; - // BODY - let body = ''; - if (webhook.body) { - const handlebars = Handlebars.create(); - body = handlebars.compile(webhook.body, { - noEscape: true, - })({ - body: escapeJsonString(message.body), - link: escapeJsonString(message.hdxLink), - title: escapeJsonString(message.title), + try { + if (webhook.body) { + const handlebars = Handlebars.create(); + body = handlebars.compile(webhook.body, { + noEscape: true, + })({ + body: escapeJsonString(message.body), + link: escapeJsonString(message.hdxLink), + title: escapeJsonString(message.title), + }); + } + } catch (e) { + logger.error({ + message: 'Failed to compile generic webhook body', + error: serializeError(e), + }); + body = JSON.stringify({ + text: `${escapeJsonString(message.title)} | ${escapeJsonString(message.body)} | ${escapeJsonString(message.hdxLink)}`,
Any reason we want to set the default body here? I think aborting is more appropriate given the template is invalid
hyperdx
github_2023
typescript
619
hyperdxio
wrn14897
@@ -37,6 +46,15 @@ import { capitalizeFirstLetter } from './utils'; import styles from '../styles/TeamPage.module.scss'; +const DEFAULT_GENERIC_WEBHOOK_BODY = + '{"text": "{{title}} | {{body}} | {{link}}"}'; + +const jsonLinterWithEmptyCheck = () => (view: any) => {
can we type `view` ?
hyperdx
github_2023
typescript
619
hyperdxio
wrn14897
@@ -742,6 +764,50 @@ function CreateWebhookForm({ error={form.formState.errors.description?.message} {...form.register('description')} /> + {form.getValues('service') === 'generic' && [ + <label className=".mantine-TextInput-label" key="1"> + Webhook Body (optional) + </label>, + <div className="mb-2" key="2"> + <CodeMirror + height="100px" + extensions={[ + json(), + linter(jsonLinterWithEmptyCheck()), + placeholder( + '{\n\t"text": "{{title}} | {{body}} | {{link}}"\n}',
style: can use `DEFAULT_GENERIC_WEBHOOK_BODY` here
hyperdx
github_2023
typescript
619
hyperdxio
wrn14897
@@ -742,6 +764,50 @@ function CreateWebhookForm({ error={form.formState.errors.description?.message} {...form.register('description')} /> + {form.getValues('service') === 'generic' && [ + <label className=".mantine-TextInput-label" key="1"> + Webhook Body (optional) + </label>, + <div className="mb-2" key="2"> + <CodeMirror + height="100px" + extensions={[ + json(), + linter(jsonLinterWithEmptyCheck()), + placeholder( + '{\n\t"text": "{{title}} | {{body}} | {{link}}"\n}', + ), + ]} + theme="dark" + onChange={value => form.setValue('body', value)} + /> + </div>, + <Alert + icon={<i className="bi bi-info-circle-fill text-slate-400" />} + key="3" + className="mb-4" + color="gray" + > + <span> + Currently the body supports the following message template + variables: + </span> + <br /> + <span> + <code> + {'{{'}link{'}}'} + </code> + ,{' '} + <code> + {'{{'}title{'}}'} + </code> + ,{' '} + <code> + {'{{'}body{'}}'} + </code> + </span>
style: it would be nice if we could reuse `DEFAULT_GENERIC_WEBHOOK_BODY` so the component matches it always
hyperdx
github_2023
typescript
619
hyperdxio
wrn14897
@@ -262,18 +262,26 @@ export const handleSendGenericWebhook = async ( 'Content-Type': 'application/json', // default, will be overwritten if user has set otherwise ...(webhook.headers?.toJSON() ?? {}), }; - // BODY - let body = ''; - if (webhook.body) { - const handlebars = Handlebars.create(); - body = handlebars.compile(webhook.body, { - noEscape: true, - })({ - body: escapeJsonString(message.body), - link: escapeJsonString(message.hdxLink), - title: escapeJsonString(message.title), + try { + if (webhook.body) {
this if case is probably redundant? given the `compile` would throw
hyperdx
github_2023
typescript
619
hyperdxio
wrn14897
@@ -672,12 +693,17 @@ function CreateWebhookForm({ }); const onSubmit: SubmitHandler<WebhookForm> = async values => { + const { service, name, url, description, body } = values; try { await saveWebhook.mutateAsync({ - service: values.service, - name: values.name, - url: values.url, - description: values.description || '', + service, + name, + url, + description: description || '', + body: + service === 'generic' && !body
style: can import enum from the common-utils https://github.com/hyperdxio/hyperdx/blob/4586cc1c1bf54b00dbfcea855a0c1e19176dc237/packages/common-utils/src/types.ts#L168
hyperdx
github_2023
typescript
619
hyperdxio
wrn14897
@@ -742,6 +768,45 @@ function CreateWebhookForm({ error={form.formState.errors.description?.message} {...form.register('description')} /> + {form.getValues('service') === 'generic' && [
same here
hyperdx
github_2023
typescript
622
hyperdxio
MikeShi42
@@ -790,7 +790,7 @@ function translateMetricChartConfig( any(Attributes) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributes, IF(AggregationTemporality = 1, Value,IF(Value - PrevValue < 0 AND Attributes = PrevAttributes,Value, - IF(Attributes != PrevAttributes, 0, Value - PrevValue))) as Rate + IF(cityHash64(Attributes) != cityHash64(PrevAttributes), 0, Value - PrevValue))) as Rate
I think we want to actually run this on the subselect first, otherwise we'll be rehashing a lot more than we need to.
hyperdx
github_2023
typescript
623
hyperdxio
MikeShi42
@@ -0,0 +1,120 @@ +import { ResponseJSON } from '@clickhouse/client'; +import { chSql } from '@hyperdx/common-utils/dist/clickhouse'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { TSource } from '@hyperdx/common-utils/dist/types'; +import { useQuery } from '@tanstack/react-query'; + +import { getClickhouseClient } from '@/clickhouse'; +import { formatAttributeClause } from '@/utils'; + +const METRIC_FETCH_LIMIT = 25;
I think we should be able to safely set this into the thousands?
hyperdx
github_2023
typescript
623
hyperdxio
MikeShi42
@@ -0,0 +1,120 @@ +import { ResponseJSON } from '@clickhouse/client'; +import { chSql } from '@hyperdx/common-utils/dist/clickhouse'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { TSource } from '@hyperdx/common-utils/dist/types'; +import { useQuery } from '@tanstack/react-query'; + +import { getClickhouseClient } from '@/clickhouse'; +import { formatAttributeClause } from '@/utils'; + +const METRIC_FETCH_LIMIT = 25; + +const extractAttributeKeys = ( + attributesArr: { + ScopeAttributes?: object; + ResourceAttributes?: object; + Attributes?: object; + }[], + isSql: boolean, +) => { + try { + const resultSet = new Set<string>(); + for (const attribute of attributesArr) { + if (attribute.ScopeAttributes) { + Object.entries(attribute.ScopeAttributes).forEach(([key, value]) => { + const clause = formatAttributeClause( + 'ScopeAttributes', + key, + value, + isSql, + ); + resultSet.add(clause); + }); + } + + if (attribute.ResourceAttributes) { + Object.entries(attribute.ResourceAttributes).forEach(([key, value]) => { + const clause = formatAttributeClause( + 'ResourceAttributes', + key, + value, + isSql, + ); + resultSet.add(clause); + }); + } + + if (attribute.Attributes) { + Object.entries(attribute.Attributes).forEach(([key, value]) => { + const clause = formatAttributeClause('Attributes', key, value, isSql); + resultSet.add(clause); + }); + } + } + return Array.from(resultSet); + } catch (e) { + console.error('Error parsing metric autocompleteattributes', e); + return []; + } +}; + +interface MetricResourceAttrsProps { + databaseName: string; + tableName: string; + metricType: string; + metricName: string; + tableSource: TSource | undefined; + isSql: boolean; +} + +export const useFetchMetricResourceAttrs = ({ + databaseName, + tableName, + metricType, + metricName, + tableSource, + isSql, +}: MetricResourceAttrsProps) => { + const shouldFetch = Boolean( + databaseName && + tableName && + tableSource && + tableSource?.kind === SourceKind.Metric, + ); + return useQuery({ + queryKey: ['metric-attributes', databaseName, tableName, metricType], + queryFn: async ({ signal }) => { + if (!shouldFetch) { + return []; + } + + const clickhouseClient = getClickhouseClient(); + + const sql = chSql` + SELECT
do we want to do select distinct?
hyperdx
github_2023
typescript
623
hyperdxio
MikeShi42
@@ -0,0 +1,120 @@ +import { ResponseJSON } from '@clickhouse/client'; +import { chSql } from '@hyperdx/common-utils/dist/clickhouse'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { TSource } from '@hyperdx/common-utils/dist/types'; +import { useQuery } from '@tanstack/react-query'; + +import { getClickhouseClient } from '@/clickhouse'; +import { formatAttributeClause } from '@/utils'; + +const METRIC_FETCH_LIMIT = 25; + +const extractAttributeKeys = ( + attributesArr: { + ScopeAttributes?: object; + ResourceAttributes?: object; + Attributes?: object; + }[], + isSql: boolean, +) => { + try { + const resultSet = new Set<string>(); + for (const attribute of attributesArr) { + if (attribute.ScopeAttributes) { + Object.entries(attribute.ScopeAttributes).forEach(([key, value]) => { + const clause = formatAttributeClause( + 'ScopeAttributes', + key, + value, + isSql, + ); + resultSet.add(clause); + }); + } + + if (attribute.ResourceAttributes) { + Object.entries(attribute.ResourceAttributes).forEach(([key, value]) => { + const clause = formatAttributeClause( + 'ResourceAttributes', + key, + value, + isSql, + ); + resultSet.add(clause); + }); + } + + if (attribute.Attributes) { + Object.entries(attribute.Attributes).forEach(([key, value]) => { + const clause = formatAttributeClause('Attributes', key, value, isSql); + resultSet.add(clause); + }); + } + } + return Array.from(resultSet); + } catch (e) { + console.error('Error parsing metric autocompleteattributes', e); + return []; + } +}; + +interface MetricResourceAttrsProps { + databaseName: string; + tableName: string; + metricType: string; + metricName: string; + tableSource: TSource | undefined; + isSql: boolean; +} + +export const useFetchMetricResourceAttrs = ({ + databaseName, + tableName, + metricType, + metricName, + tableSource, + isSql, +}: MetricResourceAttrsProps) => { + const shouldFetch = Boolean( + databaseName && + tableName && + tableSource && + tableSource?.kind === SourceKind.Metric, + ); + return useQuery({ + queryKey: ['metric-attributes', databaseName, tableName, metricType], + queryFn: async ({ signal }) => { + if (!shouldFetch) { + return []; + } + + const clickhouseClient = getClickhouseClient(); + + const sql = chSql` + SELECT + ScopeAttributes, + ResourceAttributes, + Attributes + FROM ${tableName} + WHERE MetricName='${metricName}' + LIMIT ${METRIC_FETCH_LIMIT.toString()} + `; + + const result = (await clickhouseClient + .query<'JSON'>({ + query: sql.sql, + query_params: sql.params, + format: 'JSON', + abort_signal: signal, + connectionId: tableSource!.connection,
it _may_ be nice to also add a row scan limit https://github.com/hyperdxio/hyperdx/blob/4529dfe459cab43745a8d30f54442bf4ed976950/packages/common-utils/src/metadata.ts#L428-L431
hyperdx
github_2023
typescript
623
hyperdxio
MikeShi42
@@ -17,6 +17,7 @@ export default function SearchInputV2({ connectionId, enableHotkey, onSubmit, + additionalSuggestions,
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
hyperdx
github_2023
typescript
623
hyperdxio
wrn14897
@@ -0,0 +1,120 @@ +import { ResponseJSON } from '@clickhouse/client'; +import { chSql } from '@hyperdx/common-utils/dist/clickhouse'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { TSource } from '@hyperdx/common-utils/dist/types'; +import { useQuery } from '@tanstack/react-query'; + +import { getClickhouseClient } from '@/clickhouse'; +import { formatAttributeClause } from '@/utils'; + +const METRIC_FETCH_LIMIT = 25; + +const extractAttributeKeys = ( + attributesArr: { + ScopeAttributes?: object; + ResourceAttributes?: object; + Attributes?: object; + }[], + isSql: boolean, +) => { + try { + const resultSet = new Set<string>(); + for (const attribute of attributesArr) { + if (attribute.ScopeAttributes) { + Object.entries(attribute.ScopeAttributes).forEach(([key, value]) => { + const clause = formatAttributeClause( + 'ScopeAttributes', + key, + value, + isSql, + ); + resultSet.add(clause); + }); + } + + if (attribute.ResourceAttributes) { + Object.entries(attribute.ResourceAttributes).forEach(([key, value]) => { + const clause = formatAttributeClause( + 'ResourceAttributes', + key, + value, + isSql, + ); + resultSet.add(clause); + }); + } + + if (attribute.Attributes) { + Object.entries(attribute.Attributes).forEach(([key, value]) => { + const clause = formatAttributeClause('Attributes', key, value, isSql); + resultSet.add(clause); + }); + } + } + return Array.from(resultSet); + } catch (e) { + console.error('Error parsing metric autocompleteattributes', e); + return []; + } +}; + +interface MetricResourceAttrsProps { + databaseName: string; + tableName: string; + metricType: string; + metricName: string; + tableSource: TSource | undefined; + isSql: boolean; +} + +export const useFetchMetricResourceAttrs = ({ + databaseName, + tableName, + metricType, + metricName, + tableSource, + isSql, +}: MetricResourceAttrsProps) => { + const shouldFetch = Boolean( + databaseName && + tableName && + tableSource && + tableSource?.kind === SourceKind.Metric, + ); + return useQuery({ + queryKey: ['metric-attributes', databaseName, tableName, metricType], + queryFn: async ({ signal }) => { + if (!shouldFetch) { + return []; + } + + const clickhouseClient = getClickhouseClient(); + + const sql = chSql` + SELECT + ScopeAttributes, + ResourceAttributes, + Attributes + FROM ${tableName} + WHERE MetricName='${metricName}' + LIMIT ${METRIC_FETCH_LIMIT.toString()}
style: we want to parameterize query like ``` FROM ${tableExpr({ database: databaseName, table: tableName })} WHERE MetricName=${{ String: metricName }} LIMIT ${{ Int32: METRIC_FETCH_LIMIT}} ```
hyperdx
github_2023
typescript
623
hyperdxio
wrn14897
@@ -0,0 +1,120 @@ +import { ResponseJSON } from '@clickhouse/client'; +import { chSql } from '@hyperdx/common-utils/dist/clickhouse'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { TSource } from '@hyperdx/common-utils/dist/types'; +import { useQuery } from '@tanstack/react-query'; + +import { getClickhouseClient } from '@/clickhouse'; +import { formatAttributeClause } from '@/utils'; + +const METRIC_FETCH_LIMIT = 25; + +const extractAttributeKeys = ( + attributesArr: { + ScopeAttributes?: object; + ResourceAttributes?: object; + Attributes?: object; + }[], + isSql: boolean, +) => { + try { + const resultSet = new Set<string>(); + for (const attribute of attributesArr) { + if (attribute.ScopeAttributes) { + Object.entries(attribute.ScopeAttributes).forEach(([key, value]) => { + const clause = formatAttributeClause( + 'ScopeAttributes', + key, + value, + isSql, + ); + resultSet.add(clause); + }); + } + + if (attribute.ResourceAttributes) { + Object.entries(attribute.ResourceAttributes).forEach(([key, value]) => { + const clause = formatAttributeClause( + 'ResourceAttributes', + key, + value, + isSql, + ); + resultSet.add(clause); + }); + } + + if (attribute.Attributes) { + Object.entries(attribute.Attributes).forEach(([key, value]) => { + const clause = formatAttributeClause('Attributes', key, value, isSql); + resultSet.add(clause); + }); + } + } + return Array.from(resultSet); + } catch (e) { + console.error('Error parsing metric autocompleteattributes', e); + return []; + } +}; + +interface MetricResourceAttrsProps { + databaseName: string; + tableName: string; + metricType: string; + metricName: string; + tableSource: TSource | undefined; + isSql: boolean; +} + +export const useFetchMetricResourceAttrs = ({ + databaseName, + tableName, + metricType, + metricName, + tableSource, + isSql, +}: MetricResourceAttrsProps) => { + const shouldFetch = Boolean( + databaseName && + tableName && + tableSource && + tableSource?.kind === SourceKind.Metric, + ); + return useQuery({ + queryKey: ['metric-attributes', databaseName, tableName, metricType], + queryFn: async ({ signal }) => { + if (!shouldFetch) { + return []; + } + + const clickhouseClient = getClickhouseClient(); + + const sql = chSql` + SELECT + ScopeAttributes, + ResourceAttributes, + Attributes + FROM ${tableName} + WHERE MetricName='${metricName}' + LIMIT ${METRIC_FETCH_LIMIT.toString()} + `; + + const result = (await clickhouseClient + .query<'JSON'>({ + query: sql.sql, + query_params: sql.params, + format: 'JSON', + abort_signal: signal, + connectionId: tableSource!.connection, + }) + .then(res => res.json())) as ResponseJSON<{ Attributes: object }>;
``` { ScopeAttributes?: Record<string, string>; ResourceAttributes?: Record<string, string>; Attributes?: Record<string, string>; } ```
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -22,233 +27,338 @@ type SpanRow = { ParentSpanId: string; StatusCode?: string; ServiceName?: string; + SeverityText?: string; HyperDXEventType: 'span'; + type?: string; }; + +function textColor(condition: { isError: boolean; isWarn: boolean }): string { + const { isError, isWarn } = condition; + if (isError) return 'text-danger'; + if (isWarn) return 'text-warning'; + return ''; +} + +function barColor(condition: { + isError: boolean; + isWarn: boolean; + isHighlighted: boolean; +}) { + const { isError, isWarn, isHighlighted } = condition; + if (isError) return isHighlighted ? '#FF6E6E' : '#F53749'; + if (isWarn) return isHighlighted ? '#FFE38A' : '#FFC107'; + return isHighlighted ? '#A9AFB7' : '#6A7077'; +} + +function getTableBody(tableModel: TSource) { + if (tableModel?.kind === SourceKind.Trace) { + return getSpanEventBody(tableModel) ?? ''; + } else if (tableModel?.kind === SourceKind.Log) { + return tableModel.implicitColumnExpression ?? ''; + } else { + return ''; + } +} + +function getFetchConfig(source: TSource, traceId: string) { + const alias = { + Body: getTableBody(source), + Timestamp: getDisplayedTimestampValueExpression(source), + Duration: source.durationExpression + ? getDurationSecondsExpression(source) + : '', + TraceId: source.traceIdExpression ?? '', + SpanId: source.spanIdExpression ?? '', + ParentSpanId: source.parentSpanIdExpression ?? '', + StatusCode: source.statusCodeExpression ?? '', + ServiceName: source.serviceNameExpression ?? '', + SeverityText: source.severityTextExpression ?? '', + }; + let selectOption: { + valueExpression: string; + alias: string; + }[] = []; + + if (source.kind === SourceKind.Trace) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + // in Seconds, f64 holds ns precision for durations up to ~3 months + valueExpression: alias.Duration, + alias: 'Duration', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + { + valueExpression: alias.ParentSpanId, + alias: 'ParentSpanId', + }, + ...(alias.StatusCode + ? [ + { + valueExpression: alias.StatusCode, + alias: 'StatusCode', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } else if (source.kind === SourceKind.Log) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + ...(alias.SeverityText + ? [ + { + valueExpression: alias.SeverityText, + alias: 'SeverityText', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } + const config = { + select: selectOption, + from: source.from, + timestampValueExpression: alias.Timestamp, + where: `${alias.TraceId} = '${traceId}'`, + limit: { limit: 10000 }, + connection: source.connection, + }; + return { config, alias, type: source.kind }; +} + +function useFetchingData({ + config, + dateRangeStartInclusive, + dateRange, +}: { + config: {
Should we be reusing `ChartConfigSchema` types here instead of duping?
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -22,233 +27,338 @@ type SpanRow = { ParentSpanId: string; StatusCode?: string; ServiceName?: string; + SeverityText?: string; HyperDXEventType: 'span'; + type?: string; }; + +function textColor(condition: { isError: boolean; isWarn: boolean }): string { + const { isError, isWarn } = condition; + if (isError) return 'text-danger'; + if (isWarn) return 'text-warning'; + return ''; +} + +function barColor(condition: { + isError: boolean; + isWarn: boolean; + isHighlighted: boolean; +}) { + const { isError, isWarn, isHighlighted } = condition; + if (isError) return isHighlighted ? '#FF6E6E' : '#F53749'; + if (isWarn) return isHighlighted ? '#FFE38A' : '#FFC107'; + return isHighlighted ? '#A9AFB7' : '#6A7077'; +} + +function getTableBody(tableModel: TSource) { + if (tableModel?.kind === SourceKind.Trace) { + return getSpanEventBody(tableModel) ?? ''; + } else if (tableModel?.kind === SourceKind.Log) { + return tableModel.implicitColumnExpression ?? ''; + } else { + return ''; + } +} + +function getFetchConfig(source: TSource, traceId: string) { + const alias = { + Body: getTableBody(source), + Timestamp: getDisplayedTimestampValueExpression(source), + Duration: source.durationExpression + ? getDurationSecondsExpression(source) + : '', + TraceId: source.traceIdExpression ?? '', + SpanId: source.spanIdExpression ?? '', + ParentSpanId: source.parentSpanIdExpression ?? '', + StatusCode: source.statusCodeExpression ?? '', + ServiceName: source.serviceNameExpression ?? '', + SeverityText: source.severityTextExpression ?? '', + }; + let selectOption: { + valueExpression: string; + alias: string; + }[] = []; + + if (source.kind === SourceKind.Trace) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + // in Seconds, f64 holds ns precision for durations up to ~3 months + valueExpression: alias.Duration, + alias: 'Duration', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + { + valueExpression: alias.ParentSpanId, + alias: 'ParentSpanId', + }, + ...(alias.StatusCode + ? [ + { + valueExpression: alias.StatusCode, + alias: 'StatusCode', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } else if (source.kind === SourceKind.Log) { + selectOption = [
it'd be nice to DRY this out
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -202,7 +204,14 @@ export default function DBTracePanel({ <Text size="sm" c="dark.2" my="sm"> Span Details
This should reflect the correct event type name
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -202,7 +204,14 @@ export default function DBTracePanel({ <Text size="sm" c="dark.2" my="sm"> Span Details </Text> - <RowDataPanel source={traceSourceData} rowId={traceRowWhere} /> + <RowDataPanel + source={ + traceRowWhere?.type === SourceKind.Log && parentSourceData + ? parentSourceData
I think parentSourceData is a log source only if the user opened a log, but if you open a trace, then the parentSourceData would be a trace type?
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -56,7 +57,7 @@ export default function DBTracePanel({ const [traceRowWhere, setTraceRowWhere] = useQueryState( 'traceRowWhere',
not a huge fan of overloading this query param, esp if the rowWhere is for a log but put in the "traceRowWhere" - the naming wouldn't make sense. I think it might be better to introduce another query param for `logRowWhere`? We could rename this query param but it'd technically be a breaking change (technically this schema change is already a breaking change, URLs are supposed to be stable in our app).
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -22,233 +27,338 @@ type SpanRow = { ParentSpanId: string; StatusCode?: string; ServiceName?: string; + SeverityText?: string; HyperDXEventType: 'span'; + type?: string; }; + +function textColor(condition: { isError: boolean; isWarn: boolean }): string { + const { isError, isWarn } = condition; + if (isError) return 'text-danger'; + if (isWarn) return 'text-warning'; + return ''; +} + +function barColor(condition: { + isError: boolean; + isWarn: boolean; + isHighlighted: boolean; +}) { + const { isError, isWarn, isHighlighted } = condition; + if (isError) return isHighlighted ? '#FF6E6E' : '#F53749'; + if (isWarn) return isHighlighted ? '#FFE38A' : '#FFC107'; + return isHighlighted ? '#A9AFB7' : '#6A7077'; +} + +function getTableBody(tableModel: TSource) { + if (tableModel?.kind === SourceKind.Trace) { + return getSpanEventBody(tableModel) ?? ''; + } else if (tableModel?.kind === SourceKind.Log) { + return tableModel.implicitColumnExpression ?? ''; + } else { + return ''; + } +} + +function getFetchConfig(source: TSource, traceId: string) { + const alias = { + Body: getTableBody(source), + Timestamp: getDisplayedTimestampValueExpression(source), + Duration: source.durationExpression + ? getDurationSecondsExpression(source) + : '', + TraceId: source.traceIdExpression ?? '', + SpanId: source.spanIdExpression ?? '', + ParentSpanId: source.parentSpanIdExpression ?? '', + StatusCode: source.statusCodeExpression ?? '', + ServiceName: source.serviceNameExpression ?? '', + SeverityText: source.severityTextExpression ?? '', + }; + let selectOption: { + valueExpression: string; + alias: string; + }[] = []; + + if (source.kind === SourceKind.Trace) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + // in Seconds, f64 holds ns precision for durations up to ~3 months + valueExpression: alias.Duration, + alias: 'Duration', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + { + valueExpression: alias.ParentSpanId, + alias: 'ParentSpanId', + }, + ...(alias.StatusCode + ? [ + { + valueExpression: alias.StatusCode, + alias: 'StatusCode', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } else if (source.kind === SourceKind.Log) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + ...(alias.SeverityText + ? [ + { + valueExpression: alias.SeverityText, + alias: 'SeverityText', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } + const config = { + select: selectOption, + from: source.from, + timestampValueExpression: alias.Timestamp, + where: `${alias.TraceId} = '${traceId}'`, + limit: { limit: 10000 }, + connection: source.connection, + }; + return { config, alias, type: source.kind }; +} + +function useFetchingData({ + config, + dateRangeStartInclusive, + dateRange, +}: { + config: { + select: { + valueExpression: string; + alias: string; + }[]; + from: { + databaseName: string; + tableName: string; + }; + timestampValueExpression: string; + where: string; + limit: { + limit: number; + }; + connection: string; + }; + dateRangeStartInclusive: boolean; + dateRange: [Date, Date]; +}) { + const query: ChartConfigWithDateRange = useMemo(() => { + return { + ...config, + dateRange, + dateRangeStartInclusive, + orderBy: [ + { + valueExpression: config.timestampValueExpression, + ordering: 'ASC', + }, + ], + }; + }, [config, dateRange]); + return useOffsetPaginatedQuery(query); +} + function useSpansAroundFocus({
```suggestion function useEventsAroundFocus({ ```
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -22,233 +27,338 @@ type SpanRow = { ParentSpanId: string; StatusCode?: string; ServiceName?: string; + SeverityText?: string; HyperDXEventType: 'span'; + type?: string; }; + +function textColor(condition: { isError: boolean; isWarn: boolean }): string { + const { isError, isWarn } = condition; + if (isError) return 'text-danger'; + if (isWarn) return 'text-warning'; + return ''; +} + +function barColor(condition: { + isError: boolean; + isWarn: boolean; + isHighlighted: boolean; +}) { + const { isError, isWarn, isHighlighted } = condition; + if (isError) return isHighlighted ? '#FF6E6E' : '#F53749'; + if (isWarn) return isHighlighted ? '#FFE38A' : '#FFC107'; + return isHighlighted ? '#A9AFB7' : '#6A7077'; +} + +function getTableBody(tableModel: TSource) { + if (tableModel?.kind === SourceKind.Trace) { + return getSpanEventBody(tableModel) ?? ''; + } else if (tableModel?.kind === SourceKind.Log) { + return tableModel.implicitColumnExpression ?? ''; + } else { + return ''; + } +} + +function getFetchConfig(source: TSource, traceId: string) { + const alias = { + Body: getTableBody(source), + Timestamp: getDisplayedTimestampValueExpression(source), + Duration: source.durationExpression + ? getDurationSecondsExpression(source) + : '', + TraceId: source.traceIdExpression ?? '', + SpanId: source.spanIdExpression ?? '', + ParentSpanId: source.parentSpanIdExpression ?? '', + StatusCode: source.statusCodeExpression ?? '', + ServiceName: source.serviceNameExpression ?? '', + SeverityText: source.severityTextExpression ?? '', + }; + let selectOption: { + valueExpression: string; + alias: string; + }[] = []; + + if (source.kind === SourceKind.Trace) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + // in Seconds, f64 holds ns precision for durations up to ~3 months + valueExpression: alias.Duration, + alias: 'Duration', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + { + valueExpression: alias.ParentSpanId, + alias: 'ParentSpanId', + }, + ...(alias.StatusCode + ? [ + { + valueExpression: alias.StatusCode, + alias: 'StatusCode', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } else if (source.kind === SourceKind.Log) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + ...(alias.SeverityText + ? [ + { + valueExpression: alias.SeverityText, + alias: 'SeverityText', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } + const config = { + select: selectOption, + from: source.from, + timestampValueExpression: alias.Timestamp, + where: `${alias.TraceId} = '${traceId}'`, + limit: { limit: 10000 }, + connection: source.connection, + }; + return { config, alias, type: source.kind }; +} + +function useFetchingData({
nit: I think this name is too non-descriptive, additionally reads awkwardly (I think hook names are usually `use${Noun}` format) maybe `useEventsData` or something. Same goes for the config function above
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -22,233 +27,338 @@ type SpanRow = { ParentSpanId: string; StatusCode?: string; ServiceName?: string; + SeverityText?: string; HyperDXEventType: 'span'; + type?: string; }; + +function textColor(condition: { isError: boolean; isWarn: boolean }): string { + const { isError, isWarn } = condition; + if (isError) return 'text-danger'; + if (isWarn) return 'text-warning'; + return ''; +} + +function barColor(condition: { + isError: boolean; + isWarn: boolean; + isHighlighted: boolean; +}) { + const { isError, isWarn, isHighlighted } = condition; + if (isError) return isHighlighted ? '#FF6E6E' : '#F53749'; + if (isWarn) return isHighlighted ? '#FFE38A' : '#FFC107'; + return isHighlighted ? '#A9AFB7' : '#6A7077'; +} + +function getTableBody(tableModel: TSource) { + if (tableModel?.kind === SourceKind.Trace) { + return getSpanEventBody(tableModel) ?? ''; + } else if (tableModel?.kind === SourceKind.Log) { + return tableModel.implicitColumnExpression ?? ''; + } else { + return ''; + } +} + +function getFetchConfig(source: TSource, traceId: string) { + const alias = { + Body: getTableBody(source), + Timestamp: getDisplayedTimestampValueExpression(source), + Duration: source.durationExpression + ? getDurationSecondsExpression(source) + : '', + TraceId: source.traceIdExpression ?? '', + SpanId: source.spanIdExpression ?? '', + ParentSpanId: source.parentSpanIdExpression ?? '', + StatusCode: source.statusCodeExpression ?? '', + ServiceName: source.serviceNameExpression ?? '', + SeverityText: source.severityTextExpression ?? '', + }; + let selectOption: { + valueExpression: string; + alias: string; + }[] = []; + + if (source.kind === SourceKind.Trace) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + // in Seconds, f64 holds ns precision for durations up to ~3 months + valueExpression: alias.Duration, + alias: 'Duration', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + { + valueExpression: alias.ParentSpanId, + alias: 'ParentSpanId', + }, + ...(alias.StatusCode + ? [ + { + valueExpression: alias.StatusCode, + alias: 'StatusCode', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } else if (source.kind === SourceKind.Log) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + ...(alias.SeverityText + ? [ + { + valueExpression: alias.SeverityText, + alias: 'SeverityText', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } + const config = { + select: selectOption, + from: source.from, + timestampValueExpression: alias.Timestamp, + where: `${alias.TraceId} = '${traceId}'`, + limit: { limit: 10000 }, + connection: source.connection, + }; + return { config, alias, type: source.kind }; +} + +function useFetchingData({ + config, + dateRangeStartInclusive, + dateRange, +}: { + config: { + select: { + valueExpression: string; + alias: string; + }[]; + from: { + databaseName: string; + tableName: string; + }; + timestampValueExpression: string; + where: string; + limit: { + limit: number; + }; + connection: string; + }; + dateRangeStartInclusive: boolean; + dateRange: [Date, Date]; +}) { + const query: ChartConfigWithDateRange = useMemo(() => { + return { + ...config, + dateRange, + dateRangeStartInclusive, + orderBy: [ + { + valueExpression: config.timestampValueExpression, + ordering: 'ASC', + }, + ], + }; + }, [config, dateRange]); + return useOffsetPaginatedQuery(query); +} + function useSpansAroundFocus({ - traceTableModel, + tableModel, focusDate, dateRange, traceId, }: { - traceTableModel: TSource; + tableModel: TSource; focusDate: Date; dateRange: [Date, Date]; traceId: string; }) { - // Needed to reverse map alias to valueExpr for useRowWhere - const aliasMap = useMemo( - () => ({ - Body: getSpanEventBody(traceTableModel) ?? '', - Timestamp: getDisplayedTimestampValueExpression(traceTableModel), - Duration: getDurationSecondsExpression(traceTableModel), - SpanId: traceTableModel.spanIdExpression ?? '', - ParentSpanId: traceTableModel.parentSpanIdExpression ?? '', - StatusCode: traceTableModel.statusCodeExpression, - ServiceName: traceTableModel.serviceNameExpression, - }), - [traceTableModel], - ); - - const config = useMemo( - () => ({ - select: [ - { - valueExpression: aliasMap.Body, - alias: 'Body', - }, - { - valueExpression: aliasMap.Timestamp, - alias: 'Timestamp', - }, - { - // in Seconds, f64 holds ns precision for durations up to ~3 months - valueExpression: aliasMap.Duration, - alias: 'Duration', - }, - { - valueExpression: aliasMap.SpanId, - alias: 'SpanId', - }, - { - valueExpression: aliasMap.ParentSpanId, - alias: 'ParentSpanId', - }, - ...(aliasMap.StatusCode - ? [ - { - valueExpression: aliasMap.StatusCode, - alias: 'StatusCode', - }, - ] - : []), - ...(aliasMap.ServiceName - ? [ - { - valueExpression: aliasMap.ServiceName, - alias: 'ServiceName', - }, - ] - : []), - ], - from: traceTableModel.from, - timestampValueExpression: traceTableModel.timestampValueExpression, - where: `${traceTableModel.traceIdExpression} = '${traceId}'`, - limit: { limit: 10000 }, - connection: traceTableModel.connection, - }), - [traceTableModel, traceId, aliasMap], + let isFetching = false; + const { config, alias, type } = useMemo( + () => getFetchConfig(tableModel, traceId), + [tableModel, traceId], ); const { data: beforeSpanData, isFetching: isBeforeSpanFetching } = - useOffsetPaginatedQuery( - useMemo( - () => ({ - ...config, - dateRange: [dateRange[0], focusDate], - orderBy: [ - { - valueExpression: traceTableModel.timestampValueExpression, - ordering: 'ASC', - }, - ], - }), - [ - config, - focusDate, - dateRange, - traceTableModel.timestampValueExpression, - ], - ), - ); - + useFetchingData({ + config, + dateRangeStartInclusive: true, + dateRange: [dateRange[0], focusDate], + }); const { data: afterSpanData, isFetching: isAfterSpanFetching } = - useOffsetPaginatedQuery( - useMemo( - () => ({ - ...config, - dateRange: [focusDate, dateRange[1]], - dateRangeStartInclusive: false, - orderBy: [ - { - valueExpression: traceTableModel.timestampValueExpression, - ordering: 'ASC', - }, - ], - }), - [ - config, - focusDate, - dateRange, - traceTableModel.timestampValueExpression, - ], - ), - ); - - const data = useMemo(() => { - return { - meta: beforeSpanData?.meta ?? afterSpanData?.meta, - data: [ - ...(beforeSpanData?.data ?? []), - ...(afterSpanData?.data ?? []), - ].map(d => { - d.HyperDXEventType = 'span'; - return d; - }) as SpanRow[], - }; // TODO: Type useOffsetPaginatedQuery instead + useFetchingData({ + config, + dateRangeStartInclusive: false, + dateRange: [focusDate, dateRange[1]], + }); + isFetching = isFetching || isBeforeSpanFetching || isAfterSpanFetching; + const meta = beforeSpanData?.meta ?? afterSpanData?.meta; + const rowWhere = useRowWhere({ meta, aliasMap: alias }); + const rows = useMemo(() => { + // Sometimes meta has not loaded yet + // DO NOT REMOVE, useRowWhere will error if no meta + if (!meta || meta.length === 0) return []; + const concatData = [ + ...(beforeSpanData?.data ?? []), + ...(afterSpanData?.data ?? []), + ].map(d => { + d.HyperDXEventType = 'span'; + return d; + }) as SpanRow[]; + return concatData.map((cd: SpanRow) => ({ + ...cd, + id: rowWhere(omit(cd, ['HyperDXEventType'])), + type, + })); }, [afterSpanData, beforeSpanData]); - const isSearchResultsFetching = isBeforeSpanFetching || isAfterSpanFetching; - return { - data, - isFetching: isSearchResultsFetching, - aliasMap, + rows, + isFetching, }; } // TODO: Optimize with ts lookup tables export function DBTraceWaterfallChartContainer({ traceTableModel, + logTableModel, traceId, dateRange, focusDate, onClick, highlightedRowWhere, }: { traceTableModel: TSource; + logTableModel?: TSource; traceId: string; dateRange: [Date, Date]; focusDate: Date; - onClick?: (rowWhere: string) => void; + onClick?: (rowWhere: { id: string; type: string }) => void; highlightedRowWhere?: string | null; }) { - const { data, isFetching, aliasMap } = useSpansAroundFocus({ - traceTableModel, + const { rows: traceRowsData, isFetching: traceIsFetching } = + useSpansAroundFocus({ + tableModel: traceTableModel, + focusDate, + dateRange, + traceId, + }); + const { rows: logRowsData, isFetching: logIsFetching } = useSpansAroundFocus({ + // search data if logTableModel exist + // search invliad date range if no logTableModel(react hook need execute no matter what)
```suggestion // search invalid date range if no logTableModel(react hook need execute no matter what) ``` Also: you can pass in enable flags into queries, typically we expose them upwards (looks like you can pass `enable` into the second arg of `useOffsetPaginatedQuery`). If this doesn't fire a query, maybe that's something we can skip for now but if we fire a silly query we should just disable it.
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -22,233 +27,338 @@ type SpanRow = { ParentSpanId: string; StatusCode?: string; ServiceName?: string; + SeverityText?: string; HyperDXEventType: 'span'; + type?: string; }; + +function textColor(condition: { isError: boolean; isWarn: boolean }): string { + const { isError, isWarn } = condition; + if (isError) return 'text-danger'; + if (isWarn) return 'text-warning'; + return ''; +} + +function barColor(condition: { + isError: boolean; + isWarn: boolean; + isHighlighted: boolean; +}) { + const { isError, isWarn, isHighlighted } = condition; + if (isError) return isHighlighted ? '#FF6E6E' : '#F53749'; + if (isWarn) return isHighlighted ? '#FFE38A' : '#FFC107'; + return isHighlighted ? '#A9AFB7' : '#6A7077'; +} + +function getTableBody(tableModel: TSource) { + if (tableModel?.kind === SourceKind.Trace) { + return getSpanEventBody(tableModel) ?? ''; + } else if (tableModel?.kind === SourceKind.Log) { + return tableModel.implicitColumnExpression ?? ''; + } else { + return ''; + } +} + +function getFetchConfig(source: TSource, traceId: string) { + const alias = { + Body: getTableBody(source), + Timestamp: getDisplayedTimestampValueExpression(source), + Duration: source.durationExpression + ? getDurationSecondsExpression(source) + : '', + TraceId: source.traceIdExpression ?? '', + SpanId: source.spanIdExpression ?? '', + ParentSpanId: source.parentSpanIdExpression ?? '', + StatusCode: source.statusCodeExpression ?? '', + ServiceName: source.serviceNameExpression ?? '', + SeverityText: source.severityTextExpression ?? '', + }; + let selectOption: { + valueExpression: string; + alias: string; + }[] = []; + + if (source.kind === SourceKind.Trace) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + // in Seconds, f64 holds ns precision for durations up to ~3 months + valueExpression: alias.Duration, + alias: 'Duration', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + { + valueExpression: alias.ParentSpanId, + alias: 'ParentSpanId', + }, + ...(alias.StatusCode + ? [ + { + valueExpression: alias.StatusCode, + alias: 'StatusCode', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } else if (source.kind === SourceKind.Log) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + ...(alias.SeverityText + ? [ + { + valueExpression: alias.SeverityText, + alias: 'SeverityText', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } + const config = { + select: selectOption, + from: source.from, + timestampValueExpression: alias.Timestamp, + where: `${alias.TraceId} = '${traceId}'`, + limit: { limit: 10000 }, + connection: source.connection, + }; + return { config, alias, type: source.kind }; +} + +function useFetchingData({ + config, + dateRangeStartInclusive, + dateRange, +}: { + config: { + select: { + valueExpression: string; + alias: string; + }[]; + from: { + databaseName: string; + tableName: string; + }; + timestampValueExpression: string; + where: string; + limit: { + limit: number; + }; + connection: string; + }; + dateRangeStartInclusive: boolean; + dateRange: [Date, Date]; +}) { + const query: ChartConfigWithDateRange = useMemo(() => { + return { + ...config, + dateRange, + dateRangeStartInclusive, + orderBy: [ + { + valueExpression: config.timestampValueExpression, + ordering: 'ASC', + }, + ], + }; + }, [config, dateRange]); + return useOffsetPaginatedQuery(query); +} + function useSpansAroundFocus({ - traceTableModel, + tableModel, focusDate, dateRange, traceId, }: { - traceTableModel: TSource; + tableModel: TSource;
this is some inconsistency in our app but I think we're trying to use `source` instead of `model` now. so `tableSource`
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -22,233 +27,338 @@ type SpanRow = { ParentSpanId: string; StatusCode?: string; ServiceName?: string; + SeverityText?: string; HyperDXEventType: 'span'; + type?: string; }; + +function textColor(condition: { isError: boolean; isWarn: boolean }): string { + const { isError, isWarn } = condition; + if (isError) return 'text-danger'; + if (isWarn) return 'text-warning'; + return ''; +} + +function barColor(condition: { + isError: boolean; + isWarn: boolean; + isHighlighted: boolean; +}) { + const { isError, isWarn, isHighlighted } = condition; + if (isError) return isHighlighted ? '#FF6E6E' : '#F53749'; + if (isWarn) return isHighlighted ? '#FFE38A' : '#FFC107'; + return isHighlighted ? '#A9AFB7' : '#6A7077'; +} + +function getTableBody(tableModel: TSource) { + if (tableModel?.kind === SourceKind.Trace) { + return getSpanEventBody(tableModel) ?? ''; + } else if (tableModel?.kind === SourceKind.Log) { + return tableModel.implicitColumnExpression ?? ''; + } else { + return ''; + } +} + +function getFetchConfig(source: TSource, traceId: string) { + const alias = { + Body: getTableBody(source), + Timestamp: getDisplayedTimestampValueExpression(source), + Duration: source.durationExpression + ? getDurationSecondsExpression(source) + : '', + TraceId: source.traceIdExpression ?? '', + SpanId: source.spanIdExpression ?? '', + ParentSpanId: source.parentSpanIdExpression ?? '', + StatusCode: source.statusCodeExpression ?? '', + ServiceName: source.serviceNameExpression ?? '', + SeverityText: source.severityTextExpression ?? '', + }; + let selectOption: { + valueExpression: string; + alias: string; + }[] = []; + + if (source.kind === SourceKind.Trace) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + // in Seconds, f64 holds ns precision for durations up to ~3 months + valueExpression: alias.Duration, + alias: 'Duration', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + { + valueExpression: alias.ParentSpanId, + alias: 'ParentSpanId', + }, + ...(alias.StatusCode + ? [ + { + valueExpression: alias.StatusCode, + alias: 'StatusCode', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } else if (source.kind === SourceKind.Log) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + ...(alias.SeverityText + ? [ + { + valueExpression: alias.SeverityText, + alias: 'SeverityText', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } + const config = { + select: selectOption, + from: source.from, + timestampValueExpression: alias.Timestamp, + where: `${alias.TraceId} = '${traceId}'`, + limit: { limit: 10000 }, + connection: source.connection, + }; + return { config, alias, type: source.kind }; +} + +function useFetchingData({ + config, + dateRangeStartInclusive, + dateRange, +}: { + config: { + select: { + valueExpression: string; + alias: string; + }[]; + from: { + databaseName: string; + tableName: string; + }; + timestampValueExpression: string; + where: string; + limit: { + limit: number; + }; + connection: string; + }; + dateRangeStartInclusive: boolean; + dateRange: [Date, Date]; +}) { + const query: ChartConfigWithDateRange = useMemo(() => { + return { + ...config, + dateRange, + dateRangeStartInclusive, + orderBy: [ + { + valueExpression: config.timestampValueExpression, + ordering: 'ASC', + }, + ], + }; + }, [config, dateRange]); + return useOffsetPaginatedQuery(query); +} + function useSpansAroundFocus({ - traceTableModel, + tableModel, focusDate, dateRange, traceId, }: { - traceTableModel: TSource; + tableModel: TSource; focusDate: Date; dateRange: [Date, Date]; traceId: string; }) { - // Needed to reverse map alias to valueExpr for useRowWhere - const aliasMap = useMemo( - () => ({ - Body: getSpanEventBody(traceTableModel) ?? '', - Timestamp: getDisplayedTimestampValueExpression(traceTableModel), - Duration: getDurationSecondsExpression(traceTableModel), - SpanId: traceTableModel.spanIdExpression ?? '', - ParentSpanId: traceTableModel.parentSpanIdExpression ?? '', - StatusCode: traceTableModel.statusCodeExpression, - ServiceName: traceTableModel.serviceNameExpression, - }), - [traceTableModel], - ); - - const config = useMemo( - () => ({ - select: [ - { - valueExpression: aliasMap.Body, - alias: 'Body', - }, - { - valueExpression: aliasMap.Timestamp, - alias: 'Timestamp', - }, - { - // in Seconds, f64 holds ns precision for durations up to ~3 months - valueExpression: aliasMap.Duration, - alias: 'Duration', - }, - { - valueExpression: aliasMap.SpanId, - alias: 'SpanId', - }, - { - valueExpression: aliasMap.ParentSpanId, - alias: 'ParentSpanId', - }, - ...(aliasMap.StatusCode - ? [ - { - valueExpression: aliasMap.StatusCode, - alias: 'StatusCode', - }, - ] - : []), - ...(aliasMap.ServiceName - ? [ - { - valueExpression: aliasMap.ServiceName, - alias: 'ServiceName', - }, - ] - : []), - ], - from: traceTableModel.from, - timestampValueExpression: traceTableModel.timestampValueExpression, - where: `${traceTableModel.traceIdExpression} = '${traceId}'`, - limit: { limit: 10000 }, - connection: traceTableModel.connection, - }), - [traceTableModel, traceId, aliasMap], + let isFetching = false; + const { config, alias, type } = useMemo( + () => getFetchConfig(tableModel, traceId), + [tableModel, traceId], ); const { data: beforeSpanData, isFetching: isBeforeSpanFetching } = - useOffsetPaginatedQuery( - useMemo( - () => ({ - ...config, - dateRange: [dateRange[0], focusDate], - orderBy: [ - { - valueExpression: traceTableModel.timestampValueExpression, - ordering: 'ASC', - }, - ], - }), - [ - config, - focusDate, - dateRange, - traceTableModel.timestampValueExpression, - ], - ), - ); - + useFetchingData({ + config, + dateRangeStartInclusive: true, + dateRange: [dateRange[0], focusDate], + }); const { data: afterSpanData, isFetching: isAfterSpanFetching } = - useOffsetPaginatedQuery( - useMemo( - () => ({ - ...config, - dateRange: [focusDate, dateRange[1]], - dateRangeStartInclusive: false, - orderBy: [ - { - valueExpression: traceTableModel.timestampValueExpression, - ordering: 'ASC', - }, - ], - }), - [ - config, - focusDate, - dateRange, - traceTableModel.timestampValueExpression, - ], - ), - ); - - const data = useMemo(() => { - return { - meta: beforeSpanData?.meta ?? afterSpanData?.meta, - data: [ - ...(beforeSpanData?.data ?? []), - ...(afterSpanData?.data ?? []), - ].map(d => { - d.HyperDXEventType = 'span'; - return d; - }) as SpanRow[], - }; // TODO: Type useOffsetPaginatedQuery instead + useFetchingData({ + config, + dateRangeStartInclusive: false, + dateRange: [focusDate, dateRange[1]], + }); + isFetching = isFetching || isBeforeSpanFetching || isAfterSpanFetching; + const meta = beforeSpanData?.meta ?? afterSpanData?.meta; + const rowWhere = useRowWhere({ meta, aliasMap: alias }); + const rows = useMemo(() => { + // Sometimes meta has not loaded yet + // DO NOT REMOVE, useRowWhere will error if no meta + if (!meta || meta.length === 0) return []; + const concatData = [ + ...(beforeSpanData?.data ?? []), + ...(afterSpanData?.data ?? []), + ].map(d => { + d.HyperDXEventType = 'span';
wouldn't this mark every event as a span? even logs?
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -73,6 +73,7 @@ export const SelectListSchema = z.array(DerivedColumnSchema).or(z.string()); export const SortSpecificationSchema = z.intersection( RootValueExpressionSchema, z.object({ + valueExpression: z.string().optional(),
why do we need to add this?
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -22,233 +27,338 @@ type SpanRow = { ParentSpanId: string; StatusCode?: string; ServiceName?: string; + SeverityText?: string; HyperDXEventType: 'span'; + type?: string; }; + +function textColor(condition: { isError: boolean; isWarn: boolean }): string { + const { isError, isWarn } = condition; + if (isError) return 'text-danger'; + if (isWarn) return 'text-warning'; + return ''; +} + +function barColor(condition: { + isError: boolean; + isWarn: boolean; + isHighlighted: boolean; +}) { + const { isError, isWarn, isHighlighted } = condition; + if (isError) return isHighlighted ? '#FF6E6E' : '#F53749'; + if (isWarn) return isHighlighted ? '#FFE38A' : '#FFC107'; + return isHighlighted ? '#A9AFB7' : '#6A7077'; +} + +function getTableBody(tableModel: TSource) { + if (tableModel?.kind === SourceKind.Trace) { + return getSpanEventBody(tableModel) ?? ''; + } else if (tableModel?.kind === SourceKind.Log) { + return tableModel.implicitColumnExpression ?? ''; + } else { + return ''; + } +} + +function getFetchConfig(source: TSource, traceId: string) { + const alias = { + Body: getTableBody(source), + Timestamp: getDisplayedTimestampValueExpression(source), + Duration: source.durationExpression + ? getDurationSecondsExpression(source) + : '', + TraceId: source.traceIdExpression ?? '', + SpanId: source.spanIdExpression ?? '', + ParentSpanId: source.parentSpanIdExpression ?? '', + StatusCode: source.statusCodeExpression ?? '', + ServiceName: source.serviceNameExpression ?? '', + SeverityText: source.severityTextExpression ?? '', + }; + let selectOption: { + valueExpression: string; + alias: string; + }[] = []; + + if (source.kind === SourceKind.Trace) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + // in Seconds, f64 holds ns precision for durations up to ~3 months + valueExpression: alias.Duration, + alias: 'Duration', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + { + valueExpression: alias.ParentSpanId, + alias: 'ParentSpanId', + }, + ...(alias.StatusCode + ? [ + { + valueExpression: alias.StatusCode, + alias: 'StatusCode', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } else if (source.kind === SourceKind.Log) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + ...(alias.SeverityText + ? [ + { + valueExpression: alias.SeverityText, + alias: 'SeverityText', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } + const config = { + select: selectOption, + from: source.from, + timestampValueExpression: alias.Timestamp, + where: `${alias.TraceId} = '${traceId}'`, + limit: { limit: 10000 }, + connection: source.connection, + }; + return { config, alias, type: source.kind }; +} + +function useFetchingData({ + config, + dateRangeStartInclusive, + dateRange, +}: { + config: { + select: { + valueExpression: string; + alias: string; + }[]; + from: { + databaseName: string; + tableName: string; + }; + timestampValueExpression: string; + where: string; + limit: { + limit: number; + }; + connection: string; + }; + dateRangeStartInclusive: boolean; + dateRange: [Date, Date]; +}) { + const query: ChartConfigWithDateRange = useMemo(() => { + return { + ...config, + dateRange, + dateRangeStartInclusive, + orderBy: [ + { + valueExpression: config.timestampValueExpression, + ordering: 'ASC', + }, + ], + }; + }, [config, dateRange]); + return useOffsetPaginatedQuery(query); +} + function useSpansAroundFocus({ - traceTableModel, + tableModel, focusDate, dateRange, traceId, }: { - traceTableModel: TSource; + tableModel: TSource; focusDate: Date; dateRange: [Date, Date]; traceId: string; }) { - // Needed to reverse map alias to valueExpr for useRowWhere - const aliasMap = useMemo( - () => ({ - Body: getSpanEventBody(traceTableModel) ?? '', - Timestamp: getDisplayedTimestampValueExpression(traceTableModel), - Duration: getDurationSecondsExpression(traceTableModel), - SpanId: traceTableModel.spanIdExpression ?? '', - ParentSpanId: traceTableModel.parentSpanIdExpression ?? '', - StatusCode: traceTableModel.statusCodeExpression, - ServiceName: traceTableModel.serviceNameExpression, - }), - [traceTableModel], - ); - - const config = useMemo( - () => ({ - select: [ - { - valueExpression: aliasMap.Body, - alias: 'Body', - }, - { - valueExpression: aliasMap.Timestamp, - alias: 'Timestamp', - }, - { - // in Seconds, f64 holds ns precision for durations up to ~3 months - valueExpression: aliasMap.Duration, - alias: 'Duration', - }, - { - valueExpression: aliasMap.SpanId, - alias: 'SpanId', - }, - { - valueExpression: aliasMap.ParentSpanId, - alias: 'ParentSpanId', - }, - ...(aliasMap.StatusCode - ? [ - { - valueExpression: aliasMap.StatusCode, - alias: 'StatusCode', - }, - ] - : []), - ...(aliasMap.ServiceName - ? [ - { - valueExpression: aliasMap.ServiceName, - alias: 'ServiceName', - }, - ] - : []), - ], - from: traceTableModel.from, - timestampValueExpression: traceTableModel.timestampValueExpression, - where: `${traceTableModel.traceIdExpression} = '${traceId}'`, - limit: { limit: 10000 }, - connection: traceTableModel.connection, - }), - [traceTableModel, traceId, aliasMap], + let isFetching = false; + const { config, alias, type } = useMemo( + () => getFetchConfig(tableModel, traceId), + [tableModel, traceId], ); const { data: beforeSpanData, isFetching: isBeforeSpanFetching } = - useOffsetPaginatedQuery( - useMemo( - () => ({ - ...config, - dateRange: [dateRange[0], focusDate], - orderBy: [ - { - valueExpression: traceTableModel.timestampValueExpression, - ordering: 'ASC', - }, - ], - }), - [ - config, - focusDate, - dateRange, - traceTableModel.timestampValueExpression, - ], - ), - ); - + useFetchingData({ + config, + dateRangeStartInclusive: true, + dateRange: [dateRange[0], focusDate], + }); const { data: afterSpanData, isFetching: isAfterSpanFetching } = - useOffsetPaginatedQuery( - useMemo( - () => ({ - ...config, - dateRange: [focusDate, dateRange[1]], - dateRangeStartInclusive: false, - orderBy: [ - { - valueExpression: traceTableModel.timestampValueExpression, - ordering: 'ASC', - }, - ], - }), - [ - config, - focusDate, - dateRange, - traceTableModel.timestampValueExpression, - ], - ), - ); - - const data = useMemo(() => { - return { - meta: beforeSpanData?.meta ?? afterSpanData?.meta, - data: [ - ...(beforeSpanData?.data ?? []), - ...(afterSpanData?.data ?? []), - ].map(d => { - d.HyperDXEventType = 'span'; - return d; - }) as SpanRow[], - }; // TODO: Type useOffsetPaginatedQuery instead + useFetchingData({ + config, + dateRangeStartInclusive: false, + dateRange: [focusDate, dateRange[1]], + }); + isFetching = isFetching || isBeforeSpanFetching || isAfterSpanFetching; + const meta = beforeSpanData?.meta ?? afterSpanData?.meta; + const rowWhere = useRowWhere({ meta, aliasMap: alias }); + const rows = useMemo(() => { + // Sometimes meta has not loaded yet + // DO NOT REMOVE, useRowWhere will error if no meta + if (!meta || meta.length === 0) return []; + const concatData = [ + ...(beforeSpanData?.data ?? []), + ...(afterSpanData?.data ?? []), + ].map(d => { + d.HyperDXEventType = 'span'; + return d; + }) as SpanRow[]; + return concatData.map((cd: SpanRow) => ({ + ...cd, + id: rowWhere(omit(cd, ['HyperDXEventType'])), + type, + })); }, [afterSpanData, beforeSpanData]); - const isSearchResultsFetching = isBeforeSpanFetching || isAfterSpanFetching; - return { - data, - isFetching: isSearchResultsFetching, - aliasMap, + rows, + isFetching, }; } // TODO: Optimize with ts lookup tables export function DBTraceWaterfallChartContainer({ traceTableModel, + logTableModel, traceId, dateRange, focusDate, onClick, highlightedRowWhere, }: { traceTableModel: TSource; + logTableModel?: TSource; traceId: string; dateRange: [Date, Date]; focusDate: Date; - onClick?: (rowWhere: string) => void; + onClick?: (rowWhere: { id: string; type: string }) => void; highlightedRowWhere?: string | null; }) { - const { data, isFetching, aliasMap } = useSpansAroundFocus({ - traceTableModel, + const { rows: traceRowsData, isFetching: traceIsFetching } = + useSpansAroundFocus({ + tableModel: traceTableModel, + focusDate, + dateRange, + traceId, + }); + const { rows: logRowsData, isFetching: logIsFetching } = useSpansAroundFocus({ + // search data if logTableModel exist + // search invliad date range if no logTableModel(react hook need execute no matter what) + tableModel: logTableModel || traceTableModel, focusDate, - dateRange, + dateRange: logTableModel ? dateRange : [dateRange[1], dateRange[0]], traceId, }); - const rowWhere = useRowWhere({ meta: data?.meta, aliasMap }); - - const rows = useMemo( - () => - data?.meta != null && data.meta.length > 0 // Sometimes meta has not loaded yet - ? data?.data?.map(row => { - return { - ...row, - id: rowWhere(omit(row, ['HyperDXEventType'])), - }; - }) - : undefined, - [data, rowWhere], - ); + const isFetching = traceIsFetching || logIsFetching; + const rows = [...traceRowsData, ...logRowsData]; + + rows.sort((a, b) => { + const aDate = TimestampNano.fromString(a.Timestamp); + const bDate = TimestampNano.fromString(b.Timestamp); + const secDiff = aDate.getTimeT() - bDate.getTimeT(); + if (secDiff === 0) { + return aDate.getNano() - bDate.getNano(); + } else { + return secDiff; + } + }); // 3 Edge-cases // 1. No spans, just logs (ex. sampling) // 2. Spans, but with missing spans inbetween (ex. missing intermediary spans) // 3. Spans, with multiple root nodes (ex. somehow disjoint traces fe/be) - const spanIds = useMemo(() => { - return new Set( - rows - ?.filter(result => result.HyperDXEventType === 'span') - .map(result => result.SpanId) ?? [], - ); - }, [rows]); - // Parse out a DAG of spans - type Node = SpanRow & { id: string; children: SpanRow[] }; + type Node = SpanRow & { id: string; parentId: string; children: SpanRow[] }; const rootNodes: Node[] = []; - const nodes: { [SpanId: string]: any } = {}; + const parentSpanIdsMap = new Map(); + const nodesMap = new Map(); + for (const { ParentSpanId, SpanId } of rows ?? []) { + if (ParentSpanId && SpanId) parentSpanIdsMap.set(SpanId, ParentSpanId); + } + let logSpanCount = -1; for (const result of rows ?? []) { + const { type, HyperDXEventType, SpanId } = result; + // ignore everything without spanId + if (!SpanId) continue; + if (type === SourceKind.Log) logSpanCount += 1; + + // log have dupelicate span id, tag it with -log-couunt + const nodeSpanId = + type === SourceKind.Log ? `${SpanId}-log-${logSpanCount}` : SpanId; + const nodeParentSpanId = + type === SourceKind.Log ? SpanId : parentSpanIdsMap.get(SpanId) || ''; + const curNode = { ...result, children: [], // In case we were created already previously, inherit the children built so far - ...(result.HyperDXEventType === 'span' ? nodes[result.SpanId] : {}), + ...(result.HyperDXEventType === 'span' ? nodesMap.get(nodeSpanId) : {}), }; - if (result.HyperDXEventType === 'span') { - nodes[result.SpanId] = curNode; + if (!nodesMap.has(nodeSpanId)) { + nodesMap.set(nodeSpanId, curNode); } - if ( - result.HyperDXEventType === 'span' && - // If there's no parent defined, or if the parent doesn't exist, we're a root - (result.ParentSpanId === '' || !spanIds.has(result.ParentSpanId)) - ) { + const isRootNode =
I believe this can be a lot more readable if we do the direct boolean expression which I believe is: ``` const isRootNode = HyperDXEventType === 'span' && type !== SourceKind.Log && !nodeParentSpanId; ```
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -22,233 +27,338 @@ type SpanRow = { ParentSpanId: string; StatusCode?: string; ServiceName?: string; + SeverityText?: string; HyperDXEventType: 'span'; + type?: string; }; + +function textColor(condition: { isError: boolean; isWarn: boolean }): string { + const { isError, isWarn } = condition; + if (isError) return 'text-danger'; + if (isWarn) return 'text-warning'; + return ''; +} + +function barColor(condition: { + isError: boolean; + isWarn: boolean; + isHighlighted: boolean; +}) { + const { isError, isWarn, isHighlighted } = condition; + if (isError) return isHighlighted ? '#FF6E6E' : '#F53749'; + if (isWarn) return isHighlighted ? '#FFE38A' : '#FFC107'; + return isHighlighted ? '#A9AFB7' : '#6A7077'; +} + +function getTableBody(tableModel: TSource) { + if (tableModel?.kind === SourceKind.Trace) { + return getSpanEventBody(tableModel) ?? ''; + } else if (tableModel?.kind === SourceKind.Log) { + return tableModel.implicitColumnExpression ?? ''; + } else { + return ''; + } +} + +function getFetchConfig(source: TSource, traceId: string) { + const alias = { + Body: getTableBody(source), + Timestamp: getDisplayedTimestampValueExpression(source), + Duration: source.durationExpression + ? getDurationSecondsExpression(source) + : '', + TraceId: source.traceIdExpression ?? '', + SpanId: source.spanIdExpression ?? '', + ParentSpanId: source.parentSpanIdExpression ?? '', + StatusCode: source.statusCodeExpression ?? '', + ServiceName: source.serviceNameExpression ?? '', + SeverityText: source.severityTextExpression ?? '', + }; + let selectOption: { + valueExpression: string; + alias: string; + }[] = []; + + if (source.kind === SourceKind.Trace) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + // in Seconds, f64 holds ns precision for durations up to ~3 months + valueExpression: alias.Duration, + alias: 'Duration', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + { + valueExpression: alias.ParentSpanId, + alias: 'ParentSpanId', + }, + ...(alias.StatusCode + ? [ + { + valueExpression: alias.StatusCode, + alias: 'StatusCode', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } else if (source.kind === SourceKind.Log) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + ...(alias.SeverityText + ? [ + { + valueExpression: alias.SeverityText, + alias: 'SeverityText', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } + const config = { + select: selectOption, + from: source.from, + timestampValueExpression: alias.Timestamp, + where: `${alias.TraceId} = '${traceId}'`, + limit: { limit: 10000 }, + connection: source.connection, + }; + return { config, alias, type: source.kind }; +} + +function useFetchingData({ + config, + dateRangeStartInclusive, + dateRange, +}: { + config: { + select: { + valueExpression: string; + alias: string; + }[]; + from: { + databaseName: string; + tableName: string; + }; + timestampValueExpression: string; + where: string; + limit: { + limit: number; + }; + connection: string; + }; + dateRangeStartInclusive: boolean; + dateRange: [Date, Date]; +}) { + const query: ChartConfigWithDateRange = useMemo(() => { + return { + ...config, + dateRange, + dateRangeStartInclusive, + orderBy: [ + { + valueExpression: config.timestampValueExpression, + ordering: 'ASC', + }, + ], + }; + }, [config, dateRange]); + return useOffsetPaginatedQuery(query); +} + function useSpansAroundFocus({ - traceTableModel, + tableModel, focusDate, dateRange, traceId, }: { - traceTableModel: TSource; + tableModel: TSource; focusDate: Date; dateRange: [Date, Date]; traceId: string; }) { - // Needed to reverse map alias to valueExpr for useRowWhere - const aliasMap = useMemo( - () => ({ - Body: getSpanEventBody(traceTableModel) ?? '', - Timestamp: getDisplayedTimestampValueExpression(traceTableModel), - Duration: getDurationSecondsExpression(traceTableModel), - SpanId: traceTableModel.spanIdExpression ?? '', - ParentSpanId: traceTableModel.parentSpanIdExpression ?? '', - StatusCode: traceTableModel.statusCodeExpression, - ServiceName: traceTableModel.serviceNameExpression, - }), - [traceTableModel], - ); - - const config = useMemo( - () => ({ - select: [ - { - valueExpression: aliasMap.Body, - alias: 'Body', - }, - { - valueExpression: aliasMap.Timestamp, - alias: 'Timestamp', - }, - { - // in Seconds, f64 holds ns precision for durations up to ~3 months - valueExpression: aliasMap.Duration, - alias: 'Duration', - }, - { - valueExpression: aliasMap.SpanId, - alias: 'SpanId', - }, - { - valueExpression: aliasMap.ParentSpanId, - alias: 'ParentSpanId', - }, - ...(aliasMap.StatusCode - ? [ - { - valueExpression: aliasMap.StatusCode, - alias: 'StatusCode', - }, - ] - : []), - ...(aliasMap.ServiceName - ? [ - { - valueExpression: aliasMap.ServiceName, - alias: 'ServiceName', - }, - ] - : []), - ], - from: traceTableModel.from, - timestampValueExpression: traceTableModel.timestampValueExpression, - where: `${traceTableModel.traceIdExpression} = '${traceId}'`, - limit: { limit: 10000 }, - connection: traceTableModel.connection, - }), - [traceTableModel, traceId, aliasMap], + let isFetching = false; + const { config, alias, type } = useMemo( + () => getFetchConfig(tableModel, traceId), + [tableModel, traceId], ); const { data: beforeSpanData, isFetching: isBeforeSpanFetching } = - useOffsetPaginatedQuery( - useMemo( - () => ({ - ...config, - dateRange: [dateRange[0], focusDate], - orderBy: [ - { - valueExpression: traceTableModel.timestampValueExpression, - ordering: 'ASC', - }, - ], - }), - [ - config, - focusDate, - dateRange, - traceTableModel.timestampValueExpression, - ], - ), - ); - + useFetchingData({ + config, + dateRangeStartInclusive: true, + dateRange: [dateRange[0], focusDate], + }); const { data: afterSpanData, isFetching: isAfterSpanFetching } = - useOffsetPaginatedQuery( - useMemo( - () => ({ - ...config, - dateRange: [focusDate, dateRange[1]], - dateRangeStartInclusive: false, - orderBy: [ - { - valueExpression: traceTableModel.timestampValueExpression, - ordering: 'ASC', - }, - ], - }), - [ - config, - focusDate, - dateRange, - traceTableModel.timestampValueExpression, - ], - ), - ); - - const data = useMemo(() => { - return { - meta: beforeSpanData?.meta ?? afterSpanData?.meta, - data: [ - ...(beforeSpanData?.data ?? []), - ...(afterSpanData?.data ?? []), - ].map(d => { - d.HyperDXEventType = 'span'; - return d; - }) as SpanRow[], - }; // TODO: Type useOffsetPaginatedQuery instead + useFetchingData({ + config, + dateRangeStartInclusive: false, + dateRange: [focusDate, dateRange[1]], + }); + isFetching = isFetching || isBeforeSpanFetching || isAfterSpanFetching; + const meta = beforeSpanData?.meta ?? afterSpanData?.meta; + const rowWhere = useRowWhere({ meta, aliasMap: alias }); + const rows = useMemo(() => { + // Sometimes meta has not loaded yet + // DO NOT REMOVE, useRowWhere will error if no meta + if (!meta || meta.length === 0) return []; + const concatData = [ + ...(beforeSpanData?.data ?? []), + ...(afterSpanData?.data ?? []), + ].map(d => { + d.HyperDXEventType = 'span'; + return d; + }) as SpanRow[]; + return concatData.map((cd: SpanRow) => ({ + ...cd, + id: rowWhere(omit(cd, ['HyperDXEventType'])), + type, + })); }, [afterSpanData, beforeSpanData]); - const isSearchResultsFetching = isBeforeSpanFetching || isAfterSpanFetching; - return { - data, - isFetching: isSearchResultsFetching, - aliasMap, + rows, + isFetching, }; } // TODO: Optimize with ts lookup tables export function DBTraceWaterfallChartContainer({ traceTableModel, + logTableModel, traceId, dateRange, focusDate, onClick, highlightedRowWhere, }: { traceTableModel: TSource; + logTableModel?: TSource; traceId: string; dateRange: [Date, Date]; focusDate: Date; - onClick?: (rowWhere: string) => void; + onClick?: (rowWhere: { id: string; type: string }) => void; highlightedRowWhere?: string | null; }) { - const { data, isFetching, aliasMap } = useSpansAroundFocus({ - traceTableModel, + const { rows: traceRowsData, isFetching: traceIsFetching } = + useSpansAroundFocus({ + tableModel: traceTableModel, + focusDate, + dateRange, + traceId, + }); + const { rows: logRowsData, isFetching: logIsFetching } = useSpansAroundFocus({ + // search data if logTableModel exist + // search invliad date range if no logTableModel(react hook need execute no matter what) + tableModel: logTableModel || traceTableModel, focusDate, - dateRange, + dateRange: logTableModel ? dateRange : [dateRange[1], dateRange[0]], traceId, }); - const rowWhere = useRowWhere({ meta: data?.meta, aliasMap }); - - const rows = useMemo( - () => - data?.meta != null && data.meta.length > 0 // Sometimes meta has not loaded yet - ? data?.data?.map(row => { - return { - ...row, - id: rowWhere(omit(row, ['HyperDXEventType'])), - }; - }) - : undefined, - [data, rowWhere], - ); + const isFetching = traceIsFetching || logIsFetching; + const rows = [...traceRowsData, ...logRowsData]; + + rows.sort((a, b) => { + const aDate = TimestampNano.fromString(a.Timestamp); + const bDate = TimestampNano.fromString(b.Timestamp); + const secDiff = aDate.getTimeT() - bDate.getTimeT(); + if (secDiff === 0) { + return aDate.getNano() - bDate.getNano(); + } else { + return secDiff; + } + }); // 3 Edge-cases // 1. No spans, just logs (ex. sampling) // 2. Spans, but with missing spans inbetween (ex. missing intermediary spans) // 3. Spans, with multiple root nodes (ex. somehow disjoint traces fe/be) - const spanIds = useMemo(() => { - return new Set( - rows - ?.filter(result => result.HyperDXEventType === 'span') - .map(result => result.SpanId) ?? [], - ); - }, [rows]); - // Parse out a DAG of spans - type Node = SpanRow & { id: string; children: SpanRow[] }; + type Node = SpanRow & { id: string; parentId: string; children: SpanRow[] }; const rootNodes: Node[] = []; - const nodes: { [SpanId: string]: any } = {}; + const parentSpanIdsMap = new Map();
it's not clear to me what this map is being used for, on line 333 could we not pull the parent span id from the row itself?
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -22,233 +27,338 @@ type SpanRow = { ParentSpanId: string; StatusCode?: string; ServiceName?: string; + SeverityText?: string; HyperDXEventType: 'span'; + type?: string; }; + +function textColor(condition: { isError: boolean; isWarn: boolean }): string { + const { isError, isWarn } = condition; + if (isError) return 'text-danger'; + if (isWarn) return 'text-warning'; + return ''; +} + +function barColor(condition: { + isError: boolean; + isWarn: boolean; + isHighlighted: boolean; +}) { + const { isError, isWarn, isHighlighted } = condition; + if (isError) return isHighlighted ? '#FF6E6E' : '#F53749'; + if (isWarn) return isHighlighted ? '#FFE38A' : '#FFC107'; + return isHighlighted ? '#A9AFB7' : '#6A7077'; +} + +function getTableBody(tableModel: TSource) { + if (tableModel?.kind === SourceKind.Trace) { + return getSpanEventBody(tableModel) ?? ''; + } else if (tableModel?.kind === SourceKind.Log) { + return tableModel.implicitColumnExpression ?? ''; + } else { + return ''; + } +} + +function getFetchConfig(source: TSource, traceId: string) { + const alias = { + Body: getTableBody(source), + Timestamp: getDisplayedTimestampValueExpression(source), + Duration: source.durationExpression + ? getDurationSecondsExpression(source) + : '', + TraceId: source.traceIdExpression ?? '', + SpanId: source.spanIdExpression ?? '', + ParentSpanId: source.parentSpanIdExpression ?? '', + StatusCode: source.statusCodeExpression ?? '', + ServiceName: source.serviceNameExpression ?? '', + SeverityText: source.severityTextExpression ?? '', + }; + let selectOption: { + valueExpression: string; + alias: string; + }[] = []; + + if (source.kind === SourceKind.Trace) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + // in Seconds, f64 holds ns precision for durations up to ~3 months + valueExpression: alias.Duration, + alias: 'Duration', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + { + valueExpression: alias.ParentSpanId, + alias: 'ParentSpanId', + }, + ...(alias.StatusCode + ? [ + { + valueExpression: alias.StatusCode, + alias: 'StatusCode', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } else if (source.kind === SourceKind.Log) { + selectOption = [ + { + valueExpression: alias.Body, + alias: 'Body', + }, + { + valueExpression: alias.Timestamp, + alias: 'Timestamp', + }, + { + valueExpression: alias.SpanId, + alias: 'SpanId', + }, + ...(alias.SeverityText + ? [ + { + valueExpression: alias.SeverityText, + alias: 'SeverityText', + }, + ] + : []), + ...(alias.ServiceName + ? [ + { + valueExpression: alias.ServiceName, + alias: 'ServiceName', + }, + ] + : []), + ]; + } + const config = { + select: selectOption, + from: source.from, + timestampValueExpression: alias.Timestamp, + where: `${alias.TraceId} = '${traceId}'`, + limit: { limit: 10000 }, + connection: source.connection, + }; + return { config, alias, type: source.kind }; +} + +function useFetchingData({ + config, + dateRangeStartInclusive, + dateRange, +}: { + config: { + select: { + valueExpression: string; + alias: string; + }[]; + from: { + databaseName: string; + tableName: string; + }; + timestampValueExpression: string; + where: string; + limit: { + limit: number; + }; + connection: string; + }; + dateRangeStartInclusive: boolean; + dateRange: [Date, Date]; +}) { + const query: ChartConfigWithDateRange = useMemo(() => { + return { + ...config, + dateRange, + dateRangeStartInclusive, + orderBy: [ + { + valueExpression: config.timestampValueExpression, + ordering: 'ASC', + }, + ], + }; + }, [config, dateRange]); + return useOffsetPaginatedQuery(query); +} + function useSpansAroundFocus({ - traceTableModel, + tableModel, focusDate, dateRange, traceId, }: { - traceTableModel: TSource; + tableModel: TSource; focusDate: Date; dateRange: [Date, Date]; traceId: string; }) { - // Needed to reverse map alias to valueExpr for useRowWhere - const aliasMap = useMemo( - () => ({ - Body: getSpanEventBody(traceTableModel) ?? '', - Timestamp: getDisplayedTimestampValueExpression(traceTableModel), - Duration: getDurationSecondsExpression(traceTableModel), - SpanId: traceTableModel.spanIdExpression ?? '', - ParentSpanId: traceTableModel.parentSpanIdExpression ?? '', - StatusCode: traceTableModel.statusCodeExpression, - ServiceName: traceTableModel.serviceNameExpression, - }), - [traceTableModel], - ); - - const config = useMemo( - () => ({ - select: [ - { - valueExpression: aliasMap.Body, - alias: 'Body', - }, - { - valueExpression: aliasMap.Timestamp, - alias: 'Timestamp', - }, - { - // in Seconds, f64 holds ns precision for durations up to ~3 months - valueExpression: aliasMap.Duration, - alias: 'Duration', - }, - { - valueExpression: aliasMap.SpanId, - alias: 'SpanId', - }, - { - valueExpression: aliasMap.ParentSpanId, - alias: 'ParentSpanId', - }, - ...(aliasMap.StatusCode - ? [ - { - valueExpression: aliasMap.StatusCode, - alias: 'StatusCode', - }, - ] - : []), - ...(aliasMap.ServiceName - ? [ - { - valueExpression: aliasMap.ServiceName, - alias: 'ServiceName', - }, - ] - : []), - ], - from: traceTableModel.from, - timestampValueExpression: traceTableModel.timestampValueExpression, - where: `${traceTableModel.traceIdExpression} = '${traceId}'`, - limit: { limit: 10000 }, - connection: traceTableModel.connection, - }), - [traceTableModel, traceId, aliasMap], + let isFetching = false; + const { config, alias, type } = useMemo( + () => getFetchConfig(tableModel, traceId), + [tableModel, traceId], ); const { data: beforeSpanData, isFetching: isBeforeSpanFetching } = - useOffsetPaginatedQuery( - useMemo( - () => ({ - ...config, - dateRange: [dateRange[0], focusDate], - orderBy: [ - { - valueExpression: traceTableModel.timestampValueExpression, - ordering: 'ASC', - }, - ], - }), - [ - config, - focusDate, - dateRange, - traceTableModel.timestampValueExpression, - ], - ), - ); - + useFetchingData({ + config, + dateRangeStartInclusive: true, + dateRange: [dateRange[0], focusDate], + }); const { data: afterSpanData, isFetching: isAfterSpanFetching } = - useOffsetPaginatedQuery( - useMemo( - () => ({ - ...config, - dateRange: [focusDate, dateRange[1]], - dateRangeStartInclusive: false, - orderBy: [ - { - valueExpression: traceTableModel.timestampValueExpression, - ordering: 'ASC', - }, - ], - }), - [ - config, - focusDate, - dateRange, - traceTableModel.timestampValueExpression, - ], - ), - ); - - const data = useMemo(() => { - return { - meta: beforeSpanData?.meta ?? afterSpanData?.meta, - data: [ - ...(beforeSpanData?.data ?? []), - ...(afterSpanData?.data ?? []), - ].map(d => { - d.HyperDXEventType = 'span'; - return d; - }) as SpanRow[], - }; // TODO: Type useOffsetPaginatedQuery instead + useFetchingData({ + config, + dateRangeStartInclusive: false, + dateRange: [focusDate, dateRange[1]], + }); + isFetching = isFetching || isBeforeSpanFetching || isAfterSpanFetching; + const meta = beforeSpanData?.meta ?? afterSpanData?.meta; + const rowWhere = useRowWhere({ meta, aliasMap: alias }); + const rows = useMemo(() => { + // Sometimes meta has not loaded yet + // DO NOT REMOVE, useRowWhere will error if no meta + if (!meta || meta.length === 0) return []; + const concatData = [ + ...(beforeSpanData?.data ?? []), + ...(afterSpanData?.data ?? []), + ].map(d => { + d.HyperDXEventType = 'span'; + return d; + }) as SpanRow[]; + return concatData.map((cd: SpanRow) => ({ + ...cd, + id: rowWhere(omit(cd, ['HyperDXEventType'])), + type, + })); }, [afterSpanData, beforeSpanData]); - const isSearchResultsFetching = isBeforeSpanFetching || isAfterSpanFetching; - return { - data, - isFetching: isSearchResultsFetching, - aliasMap, + rows, + isFetching, }; } // TODO: Optimize with ts lookup tables export function DBTraceWaterfallChartContainer({ traceTableModel, + logTableModel, traceId, dateRange, focusDate, onClick, highlightedRowWhere, }: { traceTableModel: TSource; + logTableModel?: TSource; traceId: string; dateRange: [Date, Date]; focusDate: Date; - onClick?: (rowWhere: string) => void; + onClick?: (rowWhere: { id: string; type: string }) => void; highlightedRowWhere?: string | null; }) { - const { data, isFetching, aliasMap } = useSpansAroundFocus({ - traceTableModel, + const { rows: traceRowsData, isFetching: traceIsFetching } = + useSpansAroundFocus({ + tableModel: traceTableModel, + focusDate, + dateRange, + traceId, + }); + const { rows: logRowsData, isFetching: logIsFetching } = useSpansAroundFocus({ + // search data if logTableModel exist + // search invliad date range if no logTableModel(react hook need execute no matter what) + tableModel: logTableModel || traceTableModel, focusDate, - dateRange, + dateRange: logTableModel ? dateRange : [dateRange[1], dateRange[0]], traceId, }); - const rowWhere = useRowWhere({ meta: data?.meta, aliasMap }); - - const rows = useMemo( - () => - data?.meta != null && data.meta.length > 0 // Sometimes meta has not loaded yet - ? data?.data?.map(row => { - return { - ...row, - id: rowWhere(omit(row, ['HyperDXEventType'])), - }; - }) - : undefined, - [data, rowWhere], - ); + const isFetching = traceIsFetching || logIsFetching; + const rows = [...traceRowsData, ...logRowsData]; + + rows.sort((a, b) => { + const aDate = TimestampNano.fromString(a.Timestamp); + const bDate = TimestampNano.fromString(b.Timestamp); + const secDiff = aDate.getTimeT() - bDate.getTimeT(); + if (secDiff === 0) { + return aDate.getNano() - bDate.getNano(); + } else { + return secDiff; + } + }); // 3 Edge-cases // 1. No spans, just logs (ex. sampling) // 2. Spans, but with missing spans inbetween (ex. missing intermediary spans) // 3. Spans, with multiple root nodes (ex. somehow disjoint traces fe/be) - const spanIds = useMemo(() => { - return new Set( - rows - ?.filter(result => result.HyperDXEventType === 'span') - .map(result => result.SpanId) ?? [], - ); - }, [rows]); - // Parse out a DAG of spans - type Node = SpanRow & { id: string; children: SpanRow[] }; + type Node = SpanRow & { id: string; parentId: string; children: SpanRow[] }; const rootNodes: Node[] = []; - const nodes: { [SpanId: string]: any } = {}; + const parentSpanIdsMap = new Map(); + const nodesMap = new Map(); + for (const { ParentSpanId, SpanId } of rows ?? []) { + if (ParentSpanId && SpanId) parentSpanIdsMap.set(SpanId, ParentSpanId); + } + let logSpanCount = -1; for (const result of rows ?? []) { + const { type, HyperDXEventType, SpanId } = result; + // ignore everything without spanId + if (!SpanId) continue; + if (type === SourceKind.Log) logSpanCount += 1; + + // log have dupelicate span id, tag it with -log-couunt + const nodeSpanId =
is this id used anywhere? is it effectively just random and never used further?
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -121,7 +141,9 @@ export default function DBTracePanel({ </Flex> <Group gap="sm"> <Text size="sm" c="gray.4"> - Trace Source + {parentSourceData?.kind === SourceKind.Log + ? 'Trace Source' + : 'Correlate Log Source'}
```suggestion : 'Correlated Log Source'} ```
hyperdx
github_2023
typescript
605
hyperdxio
MikeShi42
@@ -43,20 +42,41 @@ export default function DBTracePanel({ }, }); - const { data: traceSourceData, isLoading: isTraceSourceLoading } = useSource({ - id: watch('source'), - }); + const { data: childSourceData, isLoading: isChildSourceDataLoading } = + useSource({ + id: watch('source'), + }); const { data: parentSourceData, isLoading: isParentSourceDataLoading } = useSource({ id: parentSourceId, }); + const logSourceData =
Not 100% sure of the logic here but I'm pretty sure this is still causing a bug. If I'm searching from the trace table, and I open the Trace panel, logs do not show up. We should be using `traceSourceId` and `logSourceId` to pull up the correlated source.
hyperdx
github_2023
typescript
616
hyperdxio
MikeShi42
@@ -144,7 +166,7 @@ export function useSessions( ], from: traceSource.from, dateRange, - where: `mapContains(${traceSource.resourceAttributesExpression}, 'rum.sessionId')`, + where: `mapContains(${traceSource.resourceAttributesExpression}, 'rum.sessionId') AND ${whereClauseSQL}`,
It seems like we're better off if we use the `filters` param for the `mapContains` statement and then pass in the user input into `where` and that way we don't have to hack some weird stuff on top?
hyperdx
github_2023
typescript
616
hyperdxio
MikeShi42
@@ -89,7 +93,25 @@ export function useSessions( if (!traceSource || !sessionSource) { return []; } - // TODO: we + + let whereClauseSQL = `1=1`;
no need for fix, just a note in the future: I know we do this pattern a lot in v1, but it'd be nice in v2 if we started cleaning that up and just conditionally rendering the SQL statement since we aren't using the same SQL formatter as before.
hyperdx
github_2023
typescript
616
hyperdxio
MikeShi42
@@ -529,7 +529,7 @@ async function renderWhereExpression({ return chSql`${{ UNSAFE_RAW_SQL: _condition }}`; } -async function renderWhere( +export async function renderWhere(
let's not export this :)
hyperdx
github_2023
typescript
612
hyperdxio
MikeShi42
@@ -700,6 +700,17 @@ function CreateWebhookForm({ <form onSubmit={form.handleSubmit(onSubmit)}> <Stack mt="sm"> <Text>Create Webhook</Text> + <Radio.Group + name="service"
do we need to register this to the form to persist?
hyperdx
github_2023
typescript
610
hyperdxio
teeohhem
@@ -641,10 +646,39 @@ export function MetricTableModelForm({ setValue: UseFormSetValue<TSource>; }) { const databaseName = watch(`from.databaseName`, DEFAULT_DATABASE); - const tableName = watch(`from.tableName`); const connectionId = watch(`connection`); - const [showOptionalFields, setShowOptionalFields] = useState(false); + useEffect(() => { + setValue('timestampValueExpression', ''); + const { unsubscribe } = watch(async (value, { name, type }) => { + try { + if (name && type === 'change') { + const [prefix, suffix] = name.split('.'); + if (prefix === 'metricTables') { + const tableName = + value?.metricTables?.[suffix as keyof typeof value.metricTables]; + const metricType = suffix as MetricsDataType; + const isValid = await isValidMetricTable({ + databaseName, + tableName, + connectionId, + metricType, + }); + if (!isValid) { + notifications.show({ + color: 'red', + message: `${tableName} is not a valid OTEL ${metricType} schema.`, + }); + } + } + } + } catch (e) { + console.error(e);
nit: Should probably toast here with `e.message`
hyperdx
github_2023
typescript
610
hyperdxio
MikeShi42
@@ -641,10 +646,43 @@ export function MetricTableModelForm({ setValue: UseFormSetValue<TSource>; }) { const databaseName = watch(`from.databaseName`, DEFAULT_DATABASE); - const tableName = watch(`from.tableName`); const connectionId = watch(`connection`); - const [showOptionalFields, setShowOptionalFields] = useState(false); + useEffect(() => { + setValue('timestampValueExpression', '');
can we set this to TimeUnix or StartTimeUnix?
hyperdx
github_2023
typescript
601
hyperdxio
wrn14897
@@ -105,15 +128,28 @@ router.get( } }, error: (err, _req, _res) => { - console.error(err); + console.error('Proxy error:', err); + res.writeHead(500, { + 'Content-Type': 'application/json', + }); + res.end( + JSON.stringify({ + success: false, + error: err.message || 'Failed to connect to ClickHouse server', + }), + );
style: can simplify this ``` res.status(500).json({ success: false, error: err.message ?? 'Failed to connect to ClickHouse server' }); ```
hyperdx
github_2023
typescript
598
hyperdxio
wrn14897
@@ -14,7 +14,7 @@ export const Source = mongoose.model<ISource>( { kind: { type: String, - enum: ['log', 'trace'], + enum: ['log', 'trace', 'metric'],
style: can we do `enum: Object.values(SourceKind)` ?
hyperdx
github_2023
typescript
598
hyperdxio
wrn14897
@@ -396,6 +396,7 @@ export enum SourceKind { Log = 'log',
Can you run `yarn changeset` and commit the changeset? since we need to bump this pkg version
hyperdx
github_2023
typescript
598
hyperdxio
wrn14897
@@ -536,6 +537,243 @@ export function TraceTableModelForm({ ); } +export function MetricTableModelForm({ + control, + watch, + setValue, +}: { + control: Control<TSource>; + watch: UseFormWatch<TSource>; + setValue: UseFormSetValue<TSource>; +}) { + const databaseName = watch(`from.databaseName`, DEFAULT_DATABASE); + const tableName = watch(`from.tableName`); + const connectionId = watch(`connection`); + + const [showOptionalFields, setShowOptionalFields] = useState(false); + + return ( + <> + <Stack gap="sm"> + <FormRow label={'Server Connection'}> + <ConnectionSelectControlled control={control} name={`connection`} /> + </FormRow> + <FormRow label={'Database'}> + <DatabaseSelectControlled + connectionId={connectionId} + control={control} + name={`from.databaseName`} + /> + </FormRow> + <Divider /> + <FormRow label={'Metric Type'}> + <Select + data={[{ value: 'gauge', label: 'Gauge' }]} + defaultValue="gauge" + placeholder="Select metric type" + allowDeselect={false} + /> + </FormRow> + <FormRow label={'Table'}> + <DBTableSelectControlled + connectionId={connectionId} + database={databaseName} + control={control} + name={`from.tableName`} + rules={{ required: 'Table is required' }} + /> + </FormRow> + <FormRow label={'Timestamp Column'}> + <SQLInlineEditorControlled + connectionId={connectionId} + database={databaseName} + table={tableName} + control={control} + name="timestampValueExpression" + placeholder="TimeUnix" + disableKeywordAutocomplete + /> + </FormRow> + <FormRow + label={'Default Select'} + helpText="Default columns selected in search results (this can be customized per search later)" + > + <SQLInlineEditorControlled + database={databaseName} + table={tableName} + control={control} + name="defaultTableSelectExpression" + placeholder="TimeUnix, MetricName, Value, ServiceName" + connectionId={connectionId} + /> + </FormRow>
I suspect we don't need the default select for metrics
hyperdx
github_2023
typescript
598
hyperdxio
wrn14897
@@ -536,6 +537,243 @@ export function TraceTableModelForm({ ); } +export function MetricTableModelForm({ + control, + watch, + setValue, +}: { + control: Control<TSource>; + watch: UseFormWatch<TSource>; + setValue: UseFormSetValue<TSource>; +}) { + const databaseName = watch(`from.databaseName`, DEFAULT_DATABASE); + const tableName = watch(`from.tableName`); + const connectionId = watch(`connection`); + + const [showOptionalFields, setShowOptionalFields] = useState(false); + + return ( + <> + <Stack gap="sm"> + <FormRow label={'Server Connection'}> + <ConnectionSelectControlled control={control} name={`connection`} /> + </FormRow> + <FormRow label={'Database'}> + <DatabaseSelectControlled + connectionId={connectionId} + control={control} + name={`from.databaseName`} + /> + </FormRow> + <Divider /> + <FormRow label={'Metric Type'}> + <Select + data={[{ value: 'gauge', label: 'Gauge' }]} + defaultValue="gauge" + placeholder="Select metric type" + allowDeselect={false} + /> + </FormRow> + <FormRow label={'Table'}> + <DBTableSelectControlled + connectionId={connectionId} + database={databaseName} + control={control} + name={`from.tableName`} + rules={{ required: 'Table is required' }} + /> + </FormRow> + <FormRow label={'Timestamp Column'}> + <SQLInlineEditorControlled + connectionId={connectionId} + database={databaseName} + table={tableName} + control={control} + name="timestampValueExpression" + placeholder="TimeUnix" + disableKeywordAutocomplete + /> + </FormRow> + <FormRow + label={'Default Select'} + helpText="Default columns selected in search results (this can be customized per search later)" + > + <SQLInlineEditorControlled + database={databaseName} + table={tableName} + control={control} + name="defaultTableSelectExpression" + placeholder="TimeUnix, MetricName, Value, ServiceName, Attributes" + connectionId={connectionId} + /> + </FormRow> + <FormRow + label={'Metric Name Column'} + helpText="Column containing the name of the metric being measured" + > + <SQLInlineEditorControlled + connectionId={connectionId} + database={databaseName} + table={tableName} + control={control} + name="metricNameExpression" + placeholder="MetricName" + /> + </FormRow> + <FormRow label={'Gauge Value Column'}> + <SQLInlineEditorControlled + connectionId={connectionId} + database={databaseName} + table={tableName} + control={control} + name="valueExpression" + placeholder="Value" + /> + </FormRow> + <Box> + {!showOptionalFields && ( + <Anchor + underline="always" + onClick={() => setShowOptionalFields(true)} + size="xs" + c="gray.4" + > + <Text me="sm" span> + <i className="bi bi-gear" /> + </Text> + Configure Optional Fields + </Anchor> + )} + {showOptionalFields && ( + <Button + onClick={() => setShowOptionalFields(false)} + size="xs" + variant="subtle" + color="gray.4" + > + Hide Optional Fields + </Button> + )} + </Box> + </Stack> + <Stack + gap="sm" + style={{ + display: showOptionalFields ? 'flex' : 'none', + }} + > + <Divider /> + <FormRow + label={'Service Name Column'} + helpText="Column containing the service name associated with the metric" + > + <SQLInlineEditorControlled + connectionId={connectionId} + database={databaseName} + table={tableName} + control={control} + name="serviceNameExpression" + placeholder="ServiceName" + /> + </FormRow> + <FormRow + label={'Resource Attributes Column'} + helpText="Column containing resource attributes/tags associated with the metric" + > + <SQLInlineEditorControlled + connectionId={connectionId} + database={databaseName} + table={tableName} + control={control} + name="resourceAttributesExpression" + placeholder="ResourceAttributes" + /> + </FormRow> + <FormRow + label={'Metric Unit Column'} + helpText="Column containing the unit of measurement for the metric" + > + <SQLInlineEditorControlled + connectionId={connectionId} + database={databaseName} + table={tableName} + control={control} + name="metricUnitExpression" + placeholder="MetricUnit" + /> + </FormRow> + <FormRow + label={'Metric Flag Column'} + helpText="Column containing flags or markers associated with the metric" + > + <SQLInlineEditorControlled + connectionId={connectionId} + database={databaseName} + table={tableName} + control={control} + name="flagsExpression" + placeholder="Flags" + /> + </FormRow> + <FormRow + label={'Event Attributes Expression'} + helpText="Column containing additional attributes/dimensions for the metric" + > + <SQLInlineEditorControlled + connectionId={connectionId} + database={databaseName} + table={tableName} + control={control} + name="eventAttributesExpression" + placeholder="Attributes" + /> + </FormRow> + </Stack> + </> + ); +} + +function TableModelForm({ + control, + watch, + setValue, + kind, +}: { + control: Control<TSource>; + watch: UseFormWatch<TSource>; + setValue: UseFormSetValue<TSource>; + kind: SourceKind; +}) { + switch (kind) { + case SourceKind.Log: + return ( + <LogTableModelForm + control={control} + watch={watch} + setValue={setValue} + /> + ); + case SourceKind.Trace: + return ( + <TraceTableModelForm + control={control} + watch={watch} + setValue={setValue} + /> + ); + case SourceKind.Metric: + return ( + <MetricTableModelForm + control={control} + watch={watch} + setValue={setValue} + /> + ); + case SourceKind.Session:
The session reuses the same clickhouse log exporter, which means it should be able to share `LogTableModelForm` component
hyperdx
github_2023
typescript
599
hyperdxio
ernestii
@@ -1,112 +1,150 @@ import type { Row } from '@clickhouse/client'; +import { ClickhouseClient } from '@hyperdx/common-utils/dist/clickhouse'; +import { getMetadata } from '@hyperdx/common-utils/dist/metadata'; +import { renderChartConfig } from '@hyperdx/common-utils/dist/renderChartConfig'; import opentelemetry, { SpanStatusCode } from '@opentelemetry/api'; import express from 'express'; -import { isNumber, parseInt } from 'lodash'; +import { parseInt } from 'lodash'; import { serializeError } from 'serialize-error'; +import { z } from 'zod'; +import { validateRequest } from 'zod-express-middleware'; -import * as clickhouse from '@/clickhouse'; -import { getTeam } from '@/controllers/team'; +import { getConnectionById } from '@/controllers/connection'; +import { getNonNullUserWithTeam } from '@/middleware/auth'; +import { Source } from '@/models/source'; import logger from '@/utils/logger'; +import { objectIdSchema } from '@/utils/zod'; const router = express.Router(); -router.get('/', async (req, res, next) => { - try { - const teamId = req.user?.team; - const { endTime, q, startTime } = req.query; - if (teamId == null) { - return res.sendStatus(403); - } - const startTimeNum = parseInt(startTime as string); - const endTimeNum = parseInt(endTime as string); - if (!isNumber(startTimeNum) || !isNumber(endTimeNum)) { - return res.sendStatus(400); - } +router.get( + '/:sessionId/rrweb', + validateRequest({ + params: z.object({ + sessionId: z.string(), + }), + query: z.object({ + sourceId: objectIdSchema, + startTime: z.string().regex(/^\d+$/, 'Must be an integer string'),
super nit: I think zod should support converting to number natively with coerce: ``` z.coerce.number() ```
hyperdx
github_2023
typescript
594
hyperdxio
MikeShi42
@@ -389,6 +389,11 @@ export const RawLogTable = memo( const [scrolledToHighlightedLine, setScrolledToHighlightedLine] = useState(false); + // Reset scroll state when highlighted line changes or when table data changes + useEffect(() => { + setScrolledToHighlightedLine(false); + }, [highlightedLineId, dedupedRows]);
I'm not totally following this bug fix, I'm assuming the suspected root cause is that the `highlightedLineId` is updated from one value to another but because the `scrolledToHighlightedLine` doesn't get reset, we don't scroll to that new line id properly. I'm assuming in that case, we should probably just have this effect run on `highlightedLineId` change (though I'm also a bit worried about bugs, it might be better to force the parent to re-create the entire component via `key`). The issue I can see with the current implementation is that if a user initiates a scroll on the results table which triggers a refresh, when the table has a `highlightedLineId` but already scrolled to it previously, that will reset the `scrolledToHighlightedLine` state and have it rescroll back. I have not tested if this actually happens yet though.
hyperdx
github_2023
typescript
594
hyperdxio
MikeShi42
@@ -0,0 +1,267 @@ +import { useMemo, useState } from 'react'; +import { sq } from 'date-fns/locale'; +import ms from 'ms'; +import { useForm } from 'react-hook-form'; +import { + ChartConfigWithDateRange, + TSource, +} from '@hyperdx/common-utils/dist/types'; +import { Badge, Flex, Group, SegmentedControl } from '@mantine/core'; +import { useDebouncedValue } from '@mantine/hooks'; + +import { SQLInlineEditorControlled } from '@/components/SQLInlineEditor'; +import WhereLanguageControlled from '@/components/WhereLanguageControlled'; +import SearchInputV2 from '@/SearchInputV2'; + +import { DBSqlRowTable } from './DBRowTable'; + +enum ContextBy { + All = 'all', + Custom = 'custom', + Host = 'host', + Node = 'k8s.node.name', + Pod = 'k8s.pod.name', + Service = 'service', +} + +interface ContextSubpanelProps { + source: TSource; + dbSqlRowTableConfig: ChartConfigWithDateRange | undefined; + rowData: Record<string, any>; + rowId: string | undefined; +} + +export default function ContextSubpanel({ + source, + dbSqlRowTableConfig, + rowData, + rowId, +}: ContextSubpanelProps) { + const QUERY_KEY_PREFIX = 'context'; + const { Timestamp: origTimestamp } = rowData; + const { + where: originalWhere = '', + whereLanguage: originalLanguage = 'lucene', + } = dbSqlRowTableConfig ?? {}; + const [range, setRange] = useState<number>(ms('30s')); + const [contextBy, setContextBy] = useState<ContextBy>(ContextBy.All); + const { control, watch } = useForm({ + defaultValues: { + where: '', + whereLanguage: originalLanguage ?? ('lucene' as 'lucene' | 'sql'), + }, + }); + + const formWhere = watch('where'); + const [debouncedWhere] = useDebouncedValue(formWhere, 1000); + + const date = useMemo(() => new Date(origTimestamp), [origTimestamp]); + + const newDateRange = useMemo( + (): [Date, Date] => [ + new Date(date.getTime() - range / 2), + new Date(date.getTime() + range / 2), + ], + [date, range], + ); + + /* Functions to help generate WHERE clause based on + which Context the user chooses (All, Host, Node, etc...). + Since we support lucene and sql, we need to format the condition + based on the language + */ + const { + 'k8s.node.name': k8sNodeName, + 'k8s.pod.name': k8sPodName, + 'host.name': host, + 'service.name': service, + } = rowData.ResourceAttributes ?? {}; + + const CONTEXT_MAPPING = { + [ContextBy.All]: { + field: '', + value: originalWhere, + }, + [ContextBy.Custom]: { + field: '', + value: debouncedWhere, + }, + [ContextBy.Service]: { + field: 'service.name', + value: service, + }, + [ContextBy.Host]: { + field: 'host.name', + value: host, + }, + [ContextBy.Pod]: { + field: 'k8s.pod.name', + value: k8sPodName, + }, + [ContextBy.Node]: { + field: 'k8s.node.name', + value: k8sNodeName, + }, + } as const; + + // Helper function to combine WHERE clauses + function combineWhereClauses(
nit: i'm not sure if using `filters` would be appropriate here, but it'd be nice to just call out that `filters` is the right pattern in case anyone stumbles upon this and wants to duplicate this pattern without realizing they might benefit from `filters`
hyperdx
github_2023
others
597
hyperdxio
teeohhem
@@ -115,5 +116,11 @@ services: restart: on-failure networks: - internal + healthcheck: + # "clickhouse", "client", "-u ${CLICKHOUSE_USER}", "--password ${CLICKHOUSE_PASSWORD}", "-q 'SELECT 1'" + test: wget --no-verbose --tries=1 http://127.0.0.1:8123/ping || exit 1 + interval: 10s
Do we want the interval to be that high? I imagine if they're all started around the same time, we could get away with a shorter timeframe.
hyperdx
github_2023
typescript
595
hyperdxio
MikeShi42
@@ -724,31 +731,34 @@ export function TableSourceForm({ render={({ field: { onChange, value } }) => ( <Radio.Group value={value} - onChange={v => onChange(v as 'log' | 'trace')} + onChange={v => onChange(v)} withAsterisk > <Group> - <Radio value="log" label="Log" /> - <Radio value="trace" label="Trace" /> + <Radio value={SourceKind.Log} label="Log" /> + <Radio value={SourceKind.Trace} label="Trace" /> + {IS_SESSIONS_ENABLED && (
is the intent that we'll follow up with a session model/source form later?
hyperdx
github_2023
others
586
hyperdxio
MikeShi42
@@ -29,11 +29,29 @@ processors: # 25% of limit up to 2G spike_limit_mib: 512 check_interval: 5s +connectors: + routing/logs: + default_pipelines: [logs/out-default] + error_mode: ignore + table: + - statement: route() where IsMatch(attributes["rum.sessionId"], ".*")
Do we want to match based on something a bit more robust to the session replay event itself? Like the scope name being `rum.rr-web` or attributes like `rr-web.event`? I'm just thinking it's possible in the future we'll have logs that will have that rum.sessionId attribute fwiw I'm fine if this is ticketed up for later
hyperdx
github_2023
typescript
582
hyperdxio
wrn14897
@@ -158,7 +158,9 @@ export default function DBRowSidePanel({ } const mainContentColumn = getEventBody(source); - const mainContent: string | undefined = normalizedRow?.['__hdx_body']; + const mainContent: string | undefined = normalizedRow?.['__hdx_body'] + ? JSON.stringify(normalizedRow['__hdx_body'])
style: I know we are using these aliases on the frontend. we should create an enum for them. Another issue here is the `JSON.stringify` generates incorrect results on a string, right? (like adding extra quotes). I think we want to do this for the object type only
hyperdx
github_2023
typescript
582
hyperdxio
wrn14897
@@ -693,7 +693,8 @@ function mergeSelectWithPrimaryAndPartitionKey( .split(',') .map(k => extractColumnReference(k.trim())) .filter((k): k is string => k != null && k.length > 0); - const primaryKeyArr = primaryKeys.split(',').map(k => k.trim()); + const primaryKeyArr =
good call on this. this doesn't rule out the string with spaces. how about ``` primaryKeys.trim() !== "" ? primaryKeys.split(',').map(k => k.trim()) : []; ```
hyperdx
github_2023
typescript
582
hyperdxio
wrn14897
@@ -207,50 +226,74 @@ export abstract class SQLSerializer implements Serializer { `(${column} ${isNegatedField ? '!' : ''}= CAST(?, 'Float64'))`, [term], ); + } else if (propertyType === 'json') {
style: can use `JSDataType` enum
hyperdx
github_2023
typescript
582
hyperdxio
wrn14897
@@ -299,6 +343,12 @@ export abstract class SQLSerializer implements Serializer { `(?? ${isNegatedField ? '!' : ''}= CAST(?, 'Float64'))`, [column, term], ); + } else if (propertyType === 'json') { + const shoudUseTokenBf = isImplicitField;
I know it's probably c + p. `shoudUseTokenBf` is misleading here since json type field doesn't have a tokenbf index. we can just do `ILIKE` for now
hyperdx
github_2023
typescript
582
hyperdxio
wrn14897
@@ -476,7 +549,8 @@ export class CustomSchemaSQLSerializerV2 extends SQLSerializer { return { column: this.implicitColumnExpression, - propertyType: 'string' as const, + columnJSON: undefined, + propertyType: JSDataType.String as const,
nit: no need for `as const`
hyperdx
github_2023
typescript
582
hyperdxio
wrn14897
@@ -66,6 +67,52 @@ export default function useRowWhere({ value, chType, ]); + case JSDataType.JSON: + // Handle case for whole json object, ex: json + return SqlString.format(`lower(hex(MD5(toString(?))))=?`, [ + SqlString.raw(valueExpr), + MD5(value).toString(), + ]); + case JSDataType.Dynamic: + // Handle case for json element, ex: json.c + + // Currently we can't distinguish null or 'null' + if (value === 'null') { + return SqlString.format(`isNull(??)`, SqlString.raw(column)); + } + if ( + value.length > 1000 || + column.length > 1000 || + columJsonSplit.length >= 8 + ) { + throw new Error( + 'Search value/object key too large, or nested too many level', + ); + }
curious about the reason to set up this cap
hyperdx
github_2023
typescript
582
hyperdxio
wrn14897
@@ -66,6 +67,52 @@ export default function useRowWhere({ value, chType, ]); + case JSDataType.JSON: + // Handle case for whole json object, ex: json + return SqlString.format(`lower(hex(MD5(toString(?))))=?`, [ + SqlString.raw(valueExpr), + MD5(value).toString(), + ]); + case JSDataType.Dynamic: + // Handle case for json element, ex: json.c + + // Currently we can't distinguish null or 'null' + if (value === 'null') { + return SqlString.format(`isNull(??)`, SqlString.raw(column)); + } + if ( + value.length > 1000 || + column.length > 1000 || + columJsonSplit.length >= 8 + ) { + throw new Error( + 'Search value/object key too large, or nested too many level', + ); + } + if (columJsonSplit.length >= 2) { + // case for json.a, really bad implementation + // reason doing this because at CH + // {json: {a: [1,2,3]}} + // json -> '{"a": ["1","2","3"]}}', json.a -> [1,2,3] + // update this once there is new version + let jsonExtractTemplate = `simpleJSONExtractRaw(toString(?), ?)`; + for (let i = 2; i < columJsonSplit.length; i++) { + jsonExtractTemplate = + 'simpleJSONExtractRaw(' + jsonExtractTemplate + ', ?)'; + }
what do you think if we throw here without implementing the hack temporarily? since I'd image this query could take a significant performance hit (string casting and parsing json for each depth)
hyperdx
github_2023
typescript
582
hyperdxio
wrn14897
@@ -158,7 +158,16 @@ export default function DBRowSidePanel({ } const mainContentColumn = getEventBody(source); - const mainContent: string | undefined = normalizedRow?.['__hdx_body']; + let mainContentTypeCheck = normalizedRow?.['__hdx_body'] + ? normalizedRow['__hdx_body'] + : undefined; + if ( + mainContentTypeCheck !== undefined && + typeof mainContentTypeCheck !== 'string' + ) { + mainContentTypeCheck = JSON.stringify(mainContentTypeCheck); + } + const mainContent: string | undefined = mainContentTypeCheck;
style: we can simplify this chunk (also using `isString` from lodash) ``` const mainContent = isString(normalizedRow?.['__hdx_body']) ? normalizedRow['__hdx_body'] : normalizedRow?.['__hdx_body'] !== undefined ? JSON.stringify(normalizedRow['__hdx_body']) : undefined; ```
hyperdx
github_2023
typescript
582
hyperdxio
wrn14897
@@ -66,6 +66,32 @@ export default function useRowWhere({ value, chType, ]); + case JSDataType.JSON: + // Handle case for whole json object, ex: json + return SqlString.format(`lower(hex(MD5(toString(?))))=?`, [ + SqlString.raw(valueExpr), + MD5(value).toString(), + ]); + case JSDataType.Dynamic: + // Handle case for json element, ex: json.c + + // Currently we can't distinguish null or 'null' + if (value === 'null') { + return SqlString.format(`isNull(??)`, SqlString.raw(column)); + } + if (value.length > 1000 || column.length > 1000) { + throw new Error('Search value/object key too large.'); + } + // TODO: update when JSON type have new version + // will not work for array/object dyanmic data + return SqlString.format(`toString(?)=?`, [ + SqlString.raw(valueExpr), + // data other than array/object will alwayas return with dobule quote + // remove dobule qoute to seach correctly + value[0] === '"' && value[value.length - 1] === '"' + ? value.slice(1, -1) + : value,
do we get the extra quotes due to JSON.stringify?
hyperdx
github_2023
typescript
528
hyperdxio
MikeShi42
@@ -564,10 +564,15 @@ function ClickhousePage() { color="gray.4" variant="subtle" onClick={() => { + // Clears the min/max latency filters that are used to filter the query results setLatencyFilter({ latencyMin: null, latencyMax: null, }); + // Updates the visual display of the time picker + setDisplayedTimeInputValue(DEFAULT_INTERVAL);
I suspect `onSearch` should do this already, did it not work with just `onSearch` alone? The logic is a bit tricky to trace but [this useEffect](https://github.com/hyperdxio/hyperdx/blob/990e62ce0408d9c86a28405424fac13076ca6336/packages/app/src/timeQuery.ts#L500) should update it, and it's triggered by [the callback above the effect](https://github.com/hyperdxio/hyperdx/blob/990e62ce0408d9c86a28405424fac13076ca6336/packages/app/src/timeQuery.ts#L494)
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -1,24 +1,58 @@ -import { differenceBy, uniq } from 'lodash'; +import { differenceBy, groupBy, uniq } from 'lodash'; import { z } from 'zod'; -import { DashboardWithoutIdSchema, Tile } from '@/common/commonTypes'; +import { DashboardWithoutIdSchema } from '@/common/commonTypes'; import type { ObjectId } from '@/models'; import Alert from '@/models/alert'; import Dashboard from '@/models/dashboard'; -import { tagsSchema } from '@/utils/zod'; export async function getDashboards(teamId: ObjectId) { - const dashboards = await Dashboard.find({ + const _dashboards = await Dashboard.find({ team: teamId, }); + + const alertsByTileId = groupBy( + await Alert.find({ + dashboard: { $in: _dashboards.map(d => d._id) },
we should also add `team: teamId` filter to lock the query
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -1,24 +1,58 @@ -import { differenceBy, uniq } from 'lodash'; +import { differenceBy, groupBy, uniq } from 'lodash'; import { z } from 'zod'; -import { DashboardWithoutIdSchema, Tile } from '@/common/commonTypes'; +import { DashboardWithoutIdSchema } from '@/common/commonTypes'; import type { ObjectId } from '@/models'; import Alert from '@/models/alert'; import Dashboard from '@/models/dashboard'; -import { tagsSchema } from '@/utils/zod'; export async function getDashboards(teamId: ObjectId) { - const dashboards = await Dashboard.find({ + const _dashboards = await Dashboard.find({ team: teamId, }); + + const alertsByTileId = groupBy( + await Alert.find({ + dashboard: { $in: _dashboards.map(d => d._id) }, + source: 'tile', + }),
double check we want to select all fields from the alert?
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -1,24 +1,58 @@ -import { differenceBy, uniq } from 'lodash'; +import { differenceBy, groupBy, uniq } from 'lodash'; import { z } from 'zod'; -import { DashboardWithoutIdSchema, Tile } from '@/common/commonTypes'; +import { DashboardWithoutIdSchema } from '@/common/commonTypes'; import type { ObjectId } from '@/models'; import Alert from '@/models/alert'; import Dashboard from '@/models/dashboard'; -import { tagsSchema } from '@/utils/zod'; export async function getDashboards(teamId: ObjectId) { - const dashboards = await Dashboard.find({ + const _dashboards = await Dashboard.find({ team: teamId, }); + + const alertsByTileId = groupBy( + await Alert.find({ + dashboard: { $in: _dashboards.map(d => d._id) }, + source: 'tile', + }), + 'tileId', + ); + + const dashboards = _dashboards + .map(d => d.toJSON()) + .map(d => ({ + ...d, + tiles: d.tiles.map(t => ({ + ...t, + config: { ...t.config, alert: alertsByTileId[t.id]?.[0] },
any reason we want to add `alert` field to `config` instead of adding it to the top level?
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -1,24 +1,58 @@ -import { differenceBy, uniq } from 'lodash'; +import { differenceBy, groupBy, uniq } from 'lodash'; import { z } from 'zod'; -import { DashboardWithoutIdSchema, Tile } from '@/common/commonTypes'; +import { DashboardWithoutIdSchema } from '@/common/commonTypes'; import type { ObjectId } from '@/models'; import Alert from '@/models/alert'; import Dashboard from '@/models/dashboard'; -import { tagsSchema } from '@/utils/zod'; export async function getDashboards(teamId: ObjectId) { - const dashboards = await Dashboard.find({ + const _dashboards = await Dashboard.find({ team: teamId, }); + + const alertsByTileId = groupBy( + await Alert.find({ + dashboard: { $in: _dashboards.map(d => d._id) }, + source: 'tile', + }), + 'tileId', + ); + + const dashboards = _dashboards + .map(d => d.toJSON()) + .map(d => ({ + ...d, + tiles: d.tiles.map(t => ({ + ...t, + config: { ...t.config, alert: alertsByTileId[t.id]?.[0] }, + })), + })); + return dashboards; } export async function getDashboard(dashboardId: string, teamId: ObjectId) { - return Dashboard.findOne({ + const _dashboard = await Dashboard.findOne({ _id: dashboardId, team: teamId, }); + + const alertsByTileId = groupBy( + await Alert.find({
perf: can fire `Dashboard.findOne` and `Alert.find` concurrently
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -1,24 +1,58 @@ -import { differenceBy, uniq } from 'lodash'; +import { differenceBy, groupBy, uniq } from 'lodash'; import { z } from 'zod'; -import { DashboardWithoutIdSchema, Tile } from '@/common/commonTypes'; +import { DashboardWithoutIdSchema } from '@/common/commonTypes'; import type { ObjectId } from '@/models'; import Alert from '@/models/alert'; import Dashboard from '@/models/dashboard'; -import { tagsSchema } from '@/utils/zod'; export async function getDashboards(teamId: ObjectId) { - const dashboards = await Dashboard.find({ + const _dashboards = await Dashboard.find({ team: teamId, }); + + const alertsByTileId = groupBy( + await Alert.find({ + dashboard: { $in: _dashboards.map(d => d._id) }, + source: 'tile', + }), + 'tileId', + ); + + const dashboards = _dashboards + .map(d => d.toJSON()) + .map(d => ({ + ...d, + tiles: d.tiles.map(t => ({ + ...t, + config: { ...t.config, alert: alertsByTileId[t.id]?.[0] }, + })), + })); + return dashboards; } export async function getDashboard(dashboardId: string, teamId: ObjectId) { - return Dashboard.findOne({ + const _dashboard = await Dashboard.findOne({ _id: dashboardId, team: teamId, }); + + const alertsByTileId = groupBy( + await Alert.find({ + dashboard: dashboardId, + source: 'tile',
better to add `team: teamId` filter
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -29,13 +63,27 @@ export async function createDashboard( ...dashboard, team: teamId, }).save(); + + // Create related alerts + for (const tile of dashboard.tiles) { + if (!tile.config.alert) { + await Alert.findOneAndUpdate( + { + dashboard: newDashboard._id, + tileId: tile.id, + source: 'tile', + team: teamId, + }, + { ...tile.config.alert }, + { new: true, upsert: true }, + ); + } + }
hmm...maybe we don't want to create an alert here (SRP). I wonder if we should fire a request at the modal level instead
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -93,27 +110,54 @@ export async function updateDashboardAndAlerts( team: teamId, }, { - ...dashboard, - tags: dashboard.tags && uniq(dashboard.tags), + ...updates, + tags: updates.tags && uniq(updates.tags), }, { new: true }, ); if (updatedDashboard == null) { throw new Error('Could not update dashboard'); } - // Delete related alerts - const deletedTileIds = differenceBy( - oldDashboard?.tiles || [], - updatedDashboard?.tiles || [], - 'id', - ).map(c => c.id); + // Update related alerts
style: I'd suggest to move all alerting mutation codes from here to another controller
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -48,41 +96,10 @@ export async function deleteDashboardAndAlerts( export async function updateDashboard(
we should write a few more integration tests for cases of updating dashboard
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -93,27 +110,54 @@ export async function updateDashboardAndAlerts( team: teamId, }, { - ...dashboard, - tags: dashboard.tags && uniq(dashboard.tags), + ...updates, + tags: updates.tags && uniq(updates.tags), }, { new: true }, ); if (updatedDashboard == null) { throw new Error('Could not update dashboard'); } - // Delete related alerts - const deletedTileIds = differenceBy( - oldDashboard?.tiles || [], - updatedDashboard?.tiles || [], - 'id', - ).map(c => c.id); + // Update related alerts + // - Delete + const newAlertIds = updates.tiles?.map(t => t.config.alert?._id);
perf: can use set here. also do we want to filter out nullish cases?
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -93,27 +110,54 @@ export async function updateDashboardAndAlerts( team: teamId, }, { - ...dashboard, - tags: dashboard.tags && uniq(dashboard.tags), + ...updates, + tags: updates.tags && uniq(updates.tags), }, { new: true }, ); if (updatedDashboard == null) { throw new Error('Could not update dashboard'); } - // Delete related alerts - const deletedTileIds = differenceBy( - oldDashboard?.tiles || [], - updatedDashboard?.tiles || [], - 'id', - ).map(c => c.id); + // Update related alerts + // - Delete + const newAlertIds = updates.tiles?.map(t => t.config.alert?._id); + const deletedAlertIds: string[] = []; - if (deletedTileIds?.length > 0) { - await Alert.deleteMany({ - dashboard: dashboardId, - tileId: { $in: deletedTileIds }, - }); + if (oldDashboard.tiles) { + for (const tile of oldDashboard.tiles) { + if ( + tile.config.alert?._id && + !newAlertIds?.includes(tile.config.alert._id) + ) { + deletedAlertIds.push(tile.config.alert._id.toString()); + } + } + + if (deletedAlertIds?.length > 0) { + await Alert.deleteMany({ + dashboard: dashboardId,
safer to add teamId filter here
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -93,27 +110,54 @@ export async function updateDashboardAndAlerts( team: teamId, }, { - ...dashboard, - tags: dashboard.tags && uniq(dashboard.tags), + ...updates, + tags: updates.tags && uniq(updates.tags), }, { new: true }, ); if (updatedDashboard == null) { throw new Error('Could not update dashboard'); } - // Delete related alerts - const deletedTileIds = differenceBy( - oldDashboard?.tiles || [], - updatedDashboard?.tiles || [], - 'id', - ).map(c => c.id); + // Update related alerts + // - Delete + const newAlertIds = updates.tiles?.map(t => t.config.alert?._id); + const deletedAlertIds: string[] = []; - if (deletedTileIds?.length > 0) { - await Alert.deleteMany({ - dashboard: dashboardId, - tileId: { $in: deletedTileIds }, - }); + if (oldDashboard.tiles) { + for (const tile of oldDashboard.tiles) { + if ( + tile.config.alert?._id && + !newAlertIds?.includes(tile.config.alert._id) + ) { + deletedAlertIds.push(tile.config.alert._id.toString()); + } + } + + if (deletedAlertIds?.length > 0) { + await Alert.deleteMany({ + dashboard: dashboardId, + _id: { $in: deletedAlertIds }, + }); + } + } + + // - Update / Create + if (updates.tiles) { + for (const tile of updates.tiles) { + if (tile.config.alert) { + await Alert.findOneAndUpdate(
perf: can run this concurrently
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -346,6 +347,7 @@ export const SavedChartConfigSchema = z.intersection( z.object({ name: z.string(), source: z.string(), + alert: AlertSchemaBase.optional(),
isn't this supposed to be `AlertSchema` ?
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -122,6 +123,53 @@ export const getAlertById = async ( }); }; +export const getDashboardAlerts = async ( + dashboardIds: string[] | null, + teamId: ObjectId, +) => {
style: imo, its not very readable when the 1st arg is null. I'd create two methods `getTeamDashboardAlertsByTile(teamId: ObjectId)` and `getDashboardAlertsByTile(teamId: ObjectId, dashboardId: string)`. we don't need to support the array case.
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -192,6 +192,20 @@ const Tile = forwardRef( [chart.config.source, setRowId, setRowSource], ); + const alert = chart.config.alert; + const alertIndicatorColor = useMemo(() => { + if (!alert) { + return 'transparent'; + } + if (alert.state === 'OK') {
nit: can use `AlertState`
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -122,6 +123,59 @@ export const getAlertById = async ( }); }; +export const getTeamDashboardAlertsByTile = async (teamId: ObjectId) => { + const alerts = await Alert.find({ + source: 'tile',
nit: realized this can be `AlertSource.TILE`
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -96,27 +102,42 @@ export async function updateDashboardAndAlerts( team: teamId, }, { - ...dashboard, - tags: dashboard.tags && uniq(dashboard.tags), + ...updates, + tags: updates.tags && uniq(updates.tags), }, { new: true }, ); if (updatedDashboard == null) { throw new Error('Could not update dashboard'); } - // Delete related alerts - const deletedTileIds = differenceBy( - oldDashboard?.tiles || [], - updatedDashboard?.tiles || [], - 'id', - ).map(c => c.id); - - if (deletedTileIds?.length > 0) { - await Alert.deleteMany({ - dashboard: dashboardId, - tileId: { $in: deletedTileIds }, - }); + // Update related alerts + // - Delete + const newAlertIds = new Set( + updates.tiles?.map(t => t.config.alert?.id).filter(Boolean), + ); + const deletedAlertIds: string[] = []; + + if (oldDashboard.tiles) { + for (const tile of oldDashboard.tiles) { + const alertId = tile.config.alert?.id?.toString();
nit: isn't `id` already string type?
hyperdx
github_2023
typescript
562
hyperdxio
wrn14897
@@ -122,6 +123,59 @@ export const getAlertById = async ( }); }; +export const getTeamDashboardAlertsByTile = async (teamId: ObjectId) => { + const alerts = await Alert.find({ + source: 'tile', + team: teamId, + }); + return groupBy(alerts, 'tileId'); +}; + +export const getDashboardAlertsByTile = async ( + teamId: ObjectId, + dashboardId: ObjectId | string, +) => { + const alerts = await Alert.find({ + dashboard: dashboardId, + source: 'tile', + team: teamId, + }); + return groupBy(alerts, 'tileId'); +}; + +export const createOrUpdateDashboardAlerts = async ( + dashboardId: ObjectId | string, + teamId: ObjectId, + alertsByTile: Record<string, AlertInput>, +) => { + return Promise.all( + Object.entries(alertsByTile).map(async ([tileId, alert]) => { + return await Alert.findOneAndUpdate(
nit: this `async` and `await` seem redundant
hyperdx
github_2023
typescript
572
hyperdxio
wrn14897
@@ -0,0 +1,101 @@ +import { dateParser, parseTimeRangeInput } from '../utils'; + +describe('dateParser', () => {
great tests! I wonder if we also want to bump `chrono-node` for bug fixes
hyperdx
github_2023
typescript
563
hyperdxio
wrn14897
@@ -64,6 +72,7 @@ export type SavedSearch = z.infer<typeof SavedSearchSchema>; export const SavedChartConfigSchema = z.any(); export const TileSchema = z.object({ + name: z.string().optional(),
Is this correct? `name` should be within `config` field, right?
hyperdx
github_2023
typescript
563
hyperdxio
wrn14897
@@ -67,6 +67,26 @@ export type AlertChannelType = 'webhook'; export type Alert = z.infer<typeof AlertSchema>; +export enum AlertState { + ALERT = 'ALERT', + DISABLED = 'DISABLED', + INSUFFICIENT_DATA = 'INSUFFICIENT_DATA', + OK = 'OK', +} + +export type AlertHistory = { + counts: number; + createdAt: string; + lastValues: { startTime: string; count: number }[]; + state: AlertState; +};
should be able to import these from `common-utils` pkg
hyperdx
github_2023
typescript
561
hyperdxio
wrn14897
@@ -38,7 +38,7 @@ export const SavedSearchSchema = z.object({ name: z.string(), select: z.string(), where: z.string(), - whereLanguage: z.string().optional(), + whereLanguage: z.union([z.literal('sql'), z.literal('lucene')]).optional(),
should use `common-utils`
hyperdx
github_2023
typescript
561
hyperdxio
wrn14897
@@ -15,8 +16,7 @@ import { } from '@mantine/core'; import { notifications } from '@mantine/notifications'; -import { type Alert, AlertSchema } from '@/commonTypes'; -import { SQLInlineEditorControlled } from '@/components/SQLInlineEditor'; +import { type Alert, AlertSchema, SavedSearch } from '@/commonTypes';
`common-utils` (https://github.com/hyperdxio/hyperdx/pull/564)
hyperdx
github_2023
typescript
561
hyperdxio
wrn14897
@@ -77,3 +78,49 @@ export const AlertChannelForm = ({ return null; }; + +export const getAlertReferenceLines = ({ + thresholdType, + threshold, + // TODO: zScore +}: { + thresholdType: 'above' | 'below'; + threshold: number; +}) => ( + <> + {threshold != null && thresholdType === 'below' && ( + <ReferenceArea + y1={0} + y2={threshold} + ifOverflow="extendDomain" + fill="red" + strokeWidth={0} + fillOpacity={0.05} + /> + )} + {threshold != null && thresholdType === 'above' && (
nit: can use `AlertThresholdType` enum https://github.com/hyperdxio/hyperdx/blob/85002c3546f9a85aab19951344131ace88d9e39e/packages/common-utils/src/types.ts#L176