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
aerugo
github_2023
others
2
n7space
SteelPh0enix
@@ -0,0 +1,43 @@ +/// Handle to an event. +/// +/// Handle is used in the system to access an event. +use crate::aerugo::error::RuntimeError; +use crate::event::Event; + +/// Event handle. +#[derive(Copy, Clone)] +pub struct EventHandle { + /// Reference to the event. + _event: &'static Event, +} + +impl EventHandle { + /// Emits an immediate event. + /// + /// Returns `RuntimeError` in case of an error, `Ok(())` otherwise. + #[inline(always)] + pub fn emit(&self) -> Result<(), RuntimeError> { + todo!() + } + + /// Emits an event that is delayed in time + /// + /// * `event` - Event to emit. + /// * `delay` - Delay amount. + /// + /// Returns `RuntimeError` in case of an error, `Ok(())` otherwise. + #[inline(always)] + pub fn emit_delayed(&self, _delay: f64) -> Result<(), RuntimeError> {
I'm not sure if using `f64` as time unit is a good choice. That should be a separate type (i've seen `enum`s used for this kind of thing), because as it is right now, i have no idea what time unit is used. Also, floating-point operations should generally be avoided on MCUs, if possible. In our case it's not a big deal, because SAMV71 provides FPU, but there's plenty of MCUs without FPU, which would require a software floating-point support, which could tank the overall performance.
aerugo
github_2023
others
2
n7space
Lurkerpas
@@ -0,0 +1,141 @@ +//! System control and interface for the user to interact with it. + +pub mod error; + +mod configuration; + +pub use self::configuration::TaskletConfiguration; + +use bare_metal::CriticalSection; + +use crate::api::{InitApi, RuntimeApi}; +use crate::boolean_condition::{BooleanConditionSet, BooleanConditionStorage}; +use crate::event::{EventHandle, EventStorage}; +use crate::execution_monitoring::ExecutionStats; +use crate::message_queue::MessageQueueStorage; +use crate::peripherals::Peripherals; +use crate::queue::QueueHandle; +use crate::task::{TaskHandle, TaskId}; +use crate::tasklet::TaskletStorage; + +/// System structure. +pub struct Aerugo {} + +impl Aerugo { + /// Creates new system instance. + pub const fn new() -> Self { + Aerugo {} + } + + /// Starts system scheduler. + pub fn start_scheduler(&self) -> ! { + todo!() + } +} + +impl InitApi for Aerugo { + fn create_tasklet<T, C>( + &'static self, + _config: Self::TaskConfig, + _storage: &'static TaskletStorage<T, C>, + ) -> Result<(), Self::Error> { + todo!() + } + + fn create_message_queue<T, const N: usize>( + &'static self, + _storage: &'static MessageQueueStorage<T, N>, + ) -> Result<(), Self::Error> { + todo!() + } + + fn create_event(&'static self, _storage: &'static EventStorage) -> Result<(), Self::Error> { + todo!() + } + + fn create_boolean_condition( + &'static self, + _storage: &'static BooleanConditionStorage, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_queue<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _queue: &QueueHandle<T>, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_event<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _event: &EventHandle, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_conditions<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _conditions: BooleanConditionSet, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_cyclic<T>(
cyclic execution? period?
aerugo
github_2023
others
2
n7space
Lurkerpas
@@ -0,0 +1,141 @@ +//! System control and interface for the user to interact with it. + +pub mod error; + +mod configuration; + +pub use self::configuration::TaskletConfiguration; + +use bare_metal::CriticalSection; + +use crate::api::{InitApi, RuntimeApi}; +use crate::boolean_condition::{BooleanConditionSet, BooleanConditionStorage}; +use crate::event::{EventHandle, EventStorage}; +use crate::execution_monitoring::ExecutionStats; +use crate::message_queue::MessageQueueStorage; +use crate::peripherals::Peripherals; +use crate::queue::QueueHandle; +use crate::task::{TaskHandle, TaskId}; +use crate::tasklet::TaskletStorage; + +/// System structure. +pub struct Aerugo {} + +impl Aerugo { + /// Creates new system instance. + pub const fn new() -> Self { + Aerugo {} + } + + /// Starts system scheduler. + pub fn start_scheduler(&self) -> ! { + todo!() + } +} + +impl InitApi for Aerugo { + fn create_tasklet<T, C>( + &'static self, + _config: Self::TaskConfig, + _storage: &'static TaskletStorage<T, C>, + ) -> Result<(), Self::Error> { + todo!() + } + + fn create_message_queue<T, const N: usize>( + &'static self, + _storage: &'static MessageQueueStorage<T, N>, + ) -> Result<(), Self::Error> { + todo!() + } + + fn create_event(&'static self, _storage: &'static EventStorage) -> Result<(), Self::Error> { + todo!() + } + + fn create_boolean_condition( + &'static self, + _storage: &'static BooleanConditionStorage, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_queue<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _queue: &QueueHandle<T>, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_event<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _event: &EventHandle, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_conditions<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _conditions: BooleanConditionSet, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_cyclic<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _period: f64,
Still looks like a float used for time....
aerugo
github_2023
others
2
n7space
Lurkerpas
@@ -0,0 +1,135 @@ +/// System initialization API. +/// +/// This API is used for the system initialization, before the scheduler is started. +use crate::boolean_condition::{BooleanConditionSet, BooleanConditionStorage}; +use crate::event::{EventHandle, EventStorage}; +use crate::message_queue::MessageQueueStorage; +use crate::peripherals::Peripherals; +use crate::queue::QueueHandle; +use crate::task::TaskHandle; +use crate::tasklet::TaskletStorage; + +/// System initialization API +pub trait InitApi: ErrorType + TaskConfigType { + /// Creates new tasklet in the system. + /// + /// * `T` - Type of the data processed by the tasklet. + /// * `C` - Type of the structure with tasklet context data. + /// + /// * `config` - Tasklet creation configuration + /// * `storage` - Static memory storage where the tasklet should be allocated. + /// + /// Returns `Error` in case of an error, `Ok(())` otherwise. + fn create_tasklet<T, C>( + &'static self, + config: Self::TaskConfig, + storage: &'static TaskletStorage<T, C>, + ) -> Result<(), Self::Error>; + + /// Creates new message queue in the system. + /// + /// * `T` - Type of the data stored in the queue. + /// * `N` - Size of the queue. + /// + /// * `storage` - Static memory storage where the queue should be allocated. + /// + /// Returns `Error` in case of an error, `Ok(())` otherwise. + fn create_message_queue<T, const N: usize>( + &'static self, + storage: &'static MessageQueueStorage<T, N>, + ) -> Result<(), Self::Error>; + + /// Creates new event in the system. + /// + /// * `storage` - Static memory storage where the event should be allocated. + /// + /// Returns `Error` in case of an error, `Ok(())` otherwise. + fn create_event(&'static self, storage: &'static EventStorage) -> Result<(), Self::Error>; + + /// Creates new boolean condition in the system. + /// + /// * `storage` - Static memory storage where the condition should be allocated. + /// + /// Returns `Error` in case of an error, `Ok(())` otherwise. + fn create_boolean_condition( + &'static self, + storage: &'static BooleanConditionStorage, + ) -> Result<(), Self::Error>; + + /// Subscribes tasklet to the queue. + /// + /// * `T` - Type of the data. + /// + /// * `tasklet` - Handle to the target tasklet. + /// * `queue` - Handle to the target queue. + /// + /// Returns `Error` in case of an error, `Ok(())` otherwise. + fn subscribe_tasklet_to_queue<T>( + &'static self, + tasklet: &TaskHandle<T>, + queue: &QueueHandle<T>, + ) -> Result<(), Self::Error>; + + /// Subscribes tasklet to the event. + /// + /// * `tasklet` - Handle to the target tasklet. + /// * `event` - Target event ID. + /// + /// Returns `Error` in case of an error, `Ok(())` otherwise. + fn subscribe_tasklet_to_event<T>( + &'static self, + tasklet: &TaskHandle<T>, + event: &EventHandle, + ) -> Result<(), Self::Error>; + + /// Subscribes tasklet to the set of conditions. + /// + /// * `tasklet` - Handle to the target tasklet. + /// * `condition` - Set of conditions. + /// + /// Returns `Error` in case of an error, `Ok(())` otherwise. + fn subscribe_tasklet_to_conditions<T>( + &'static self, + tasklet: &TaskHandle<T>, + conditions: BooleanConditionSet, + ) -> Result<(), Self::Error>; + + /// Subscribes tasklet to the cyclic execution. + /// + /// * `tasklet` - Handle to the target tasklet. + /// * `period` - Time period of the execution. + /// + /// Returns `Error` in case of an error, `Ok(())` otherwise. + fn subscribe_tasklet_to_cyclic<T>( + &'static self, + tasklet: &TaskHandle<T>, + period: f64,
Still looks like a float used for time....
hyperdx
github_2023
typescript
715
hyperdxio
knudtty
@@ -0,0 +1,1302 @@ +import * as React from 'react'; +import dynamic from 'next/dynamic'; +import Head from 'next/head'; +import Link from 'next/link'; +import cx from 'classnames'; +import sub from 'date-fns/sub'; +import { + parseAsFloat, + parseAsStringEnum, + useQueryState, + useQueryStates, +} from 'nuqs'; +import { useForm } from 'react-hook-form'; +import { StringParam, useQueryParam, withDefault } from 'use-query-params'; +import { + SearchConditionLanguage, + SourceKind, + TSource, +} from '@hyperdx/common-utils/dist/types'; +import { + Anchor, + Badge, + Box, + Card, + Flex, + Grid, + Group, + Loader, + ScrollArea, + SegmentedControl, + Skeleton, + Table, + Tabs, + Text, + Tooltip, +} from '@mantine/core'; + +import { TimePicker } from '@/components/TimePicker'; + +import { ConnectionSelectControlled } from './components/ConnectionSelect'; +import { DBSqlRowTable } from './components/DBRowTable'; +import { DBTimeChart } from './components/DBTimeChart'; +import { FormatPodStatus } from './components/KubeComponents'; +import OnboardingModal from './components/OnboardingModal'; +import { useQueriedChartConfig } from './hooks/useChartConfig'; +import { + convertDateRangeToGranularityString, + convertV1ChartConfigToV2, + K8S_CPU_PERCENTAGE_NUMBER_FORMAT, + K8S_MEM_NUMBER_FORMAT, +} from './ChartUtils'; +import { useConnections } from './connection'; +import { withAppNav } from './layout'; +import MetricTagValueSelect from './MetricTagValueSelect'; +import NamespaceDetailsSidePanel from './NamespaceDetailsSidePanel'; +import NodeDetailsSidePanel from './NodeDetailsSidePanel'; +import PodDetailsSidePanel from './PodDetailsSidePanel'; +import HdxSearchInput from './SearchInput'; +import { getEventBody, useSources } from './source'; +import { parseTimeQuery, useTimeQuery } from './timeQuery'; +import { KubePhase } from './types'; +import { formatNumber, formatUptime } from './utils'; + +import 'react-modern-drawer/dist/index.css'; + +const makeId = () => Math.floor(100000000 * Math.random()).toString(36); + +const getKubePhaseNumber = (phase: string) => { + switch (phase) { + case 'running': + return KubePhase.Running; + case 'succeeded': + return KubePhase.Succeeded; + case 'pending': + return KubePhase.Pending; + case 'failed': + return KubePhase.Failed; + default: + return KubePhase.Unknown; + } +}; + +const Th = React.memo<{ + children: React.ReactNode; + style?: React.CSSProperties; + onSort?: (sortOrder: 'asc' | 'desc') => void; + sort?: 'asc' | 'desc' | null; +}>(({ children, onSort, sort, style }) => { + return ( + <Table.Th + style={style} + className={cx({ 'cursor-pointer': !!onSort }, 'text-nowrap')} + onClick={() => onSort?.(sort === 'asc' ? 'desc' : 'asc')} + > + {children} + {!!sort && ( + <i + className={`ps-1 text-slate-400 fs-8.5 bi bi-caret-${ + sort === 'asc' ? 'up-fill' : 'down-fill' + }`} + /> + )} + </Table.Th> + ); +}); + +type InfraPodsStatusTableColumn = + | 'restarts' + | 'uptime' + | 'cpuLimit' + | 'memLimit' + | 'phase'; + +const TableLoading = () => { + return ( + <Table horizontalSpacing="md" highlightOnHover> + <Table.Tbody key="table-loader"> + <Table.Tr> + <Table.Td> + <Skeleton height={8} my={6} /> + </Table.Td> + </Table.Tr> + <Table.Tr> + <Table.Td> + <Skeleton height={8} my={6} /> + </Table.Td> + </Table.Tr> + <Table.Tr> + <Table.Td> + <Skeleton height={8} my={6} /> + </Table.Td> + </Table.Tr> + <Table.Tr> + <Table.Td> + <Skeleton height={8} my={6} /> + </Table.Td> + </Table.Tr> + </Table.Tbody> + </Table> + ); +}; + +export const InfraPodsStatusTable = ({ + dateRange, + metricSource, + where, +}: { + dateRange: [Date, Date]; + metricSource: TSource; + where: string; +}) => { + const [phaseFilter, setPhaseFilter] = React.useState('running'); + const [sortState, setSortState] = React.useState<{ + column: InfraPodsStatusTableColumn; + order: 'asc' | 'desc'; + }>({ + column: 'restarts', + order: 'desc', + }); + + const groupBy = ['k8s.pod.name', 'k8s.namespace.name', 'k8s.node.name']; + const { data, isError, isLoading } = useQueriedChartConfig( + convertV1ChartConfigToV2( + { + series: [ + { + table: 'metrics', + field: 'k8s.pod.phase - Gauge', + type: 'table', + aggFn: 'last_value', + where, + groupBy, + ...(sortState.column === 'phase' && { + sortOrder: sortState.order, + }), + }, + { + table: 'metrics', + field: 'k8s.container.restarts - Gauge', + type: 'table', + aggFn: 'last_value', + where, + groupBy, + ...(sortState.column === 'restarts' && { + sortOrder: sortState.order, + }), + }, + { + table: 'metrics', + field: 'k8s.pod.uptime - Sum', + type: 'table', + aggFn: 'sum', + where, + groupBy, + ...(sortState.column === 'uptime' && { + sortOrder: sortState.order, + }), + }, + { + table: 'metrics', + field: 'k8s.pod.cpu.utilization - Gauge', + type: 'table', + aggFn: 'avg', + where, + groupBy, + }, + { + table: 'metrics', + field: 'k8s.pod.cpu_limit_utilization - Gauge', + type: 'table', + aggFn: 'avg', + where, + groupBy, + ...(sortState.column === 'cpuLimit' && { + sortOrder: sortState.order, + }), + }, + { + table: 'metrics', + field: 'k8s.pod.memory.usage - Gauge', + type: 'table', + aggFn: 'avg', + where, + groupBy, + }, + { + table: 'metrics', + field: 'k8s.pod.memory_limit_utilization - Gauge', + type: 'table', + aggFn: 'avg', + where, + groupBy, + ...(sortState.column === 'memLimit' && { + sortOrder: sortState.order, + }), + }, + ], + dateRange, + seriesReturnType: 'column', + }, + { + metric: metricSource, + }, + ), + ); + + // TODO: Use useTable + const podsList = React.useMemo(() => { + if (!data) { + return []; + } + + return data.data + .map((row: any) => {
I know there's some funky keys below for row, but is there some way to avoid using 'any' here?
hyperdx
github_2023
typescript
715
hyperdxio
knudtty
@@ -0,0 +1,1302 @@ +import * as React from 'react'; +import dynamic from 'next/dynamic'; +import Head from 'next/head'; +import Link from 'next/link'; +import cx from 'classnames'; +import sub from 'date-fns/sub'; +import { + parseAsFloat, + parseAsStringEnum, + useQueryState, + useQueryStates, +} from 'nuqs'; +import { useForm } from 'react-hook-form'; +import { StringParam, useQueryParam, withDefault } from 'use-query-params'; +import { + SearchConditionLanguage, + SourceKind, + TSource, +} from '@hyperdx/common-utils/dist/types'; +import { + Anchor, + Badge, + Box, + Card, + Flex, + Grid, + Group, + Loader, + ScrollArea, + SegmentedControl, + Skeleton, + Table, + Tabs, + Text, + Tooltip, +} from '@mantine/core'; + +import { TimePicker } from '@/components/TimePicker'; + +import { ConnectionSelectControlled } from './components/ConnectionSelect'; +import { DBSqlRowTable } from './components/DBRowTable'; +import { DBTimeChart } from './components/DBTimeChart'; +import { FormatPodStatus } from './components/KubeComponents'; +import OnboardingModal from './components/OnboardingModal'; +import { useQueriedChartConfig } from './hooks/useChartConfig'; +import { + convertDateRangeToGranularityString, + convertV1ChartConfigToV2, + K8S_CPU_PERCENTAGE_NUMBER_FORMAT, + K8S_MEM_NUMBER_FORMAT, +} from './ChartUtils'; +import { useConnections } from './connection'; +import { withAppNav } from './layout'; +import MetricTagValueSelect from './MetricTagValueSelect'; +import NamespaceDetailsSidePanel from './NamespaceDetailsSidePanel'; +import NodeDetailsSidePanel from './NodeDetailsSidePanel'; +import PodDetailsSidePanel from './PodDetailsSidePanel'; +import HdxSearchInput from './SearchInput'; +import { getEventBody, useSources } from './source'; +import { parseTimeQuery, useTimeQuery } from './timeQuery'; +import { KubePhase } from './types'; +import { formatNumber, formatUptime } from './utils'; + +import 'react-modern-drawer/dist/index.css'; + +const makeId = () => Math.floor(100000000 * Math.random()).toString(36); + +const getKubePhaseNumber = (phase: string) => { + switch (phase) { + case 'running': + return KubePhase.Running; + case 'succeeded': + return KubePhase.Succeeded; + case 'pending': + return KubePhase.Pending; + case 'failed': + return KubePhase.Failed; + default: + return KubePhase.Unknown; + } +}; + +const Th = React.memo<{ + children: React.ReactNode; + style?: React.CSSProperties; + onSort?: (sortOrder: 'asc' | 'desc') => void; + sort?: 'asc' | 'desc' | null; +}>(({ children, onSort, sort, style }) => { + return ( + <Table.Th + style={style} + className={cx({ 'cursor-pointer': !!onSort }, 'text-nowrap')} + onClick={() => onSort?.(sort === 'asc' ? 'desc' : 'asc')} + > + {children} + {!!sort && ( + <i + className={`ps-1 text-slate-400 fs-8.5 bi bi-caret-${ + sort === 'asc' ? 'up-fill' : 'down-fill' + }`} + /> + )} + </Table.Th> + ); +}); + +type InfraPodsStatusTableColumn = + | 'restarts' + | 'uptime' + | 'cpuLimit' + | 'memLimit' + | 'phase'; + +const TableLoading = () => { + return ( + <Table horizontalSpacing="md" highlightOnHover> + <Table.Tbody key="table-loader"> + <Table.Tr> + <Table.Td> + <Skeleton height={8} my={6} /> + </Table.Td> + </Table.Tr> + <Table.Tr> + <Table.Td> + <Skeleton height={8} my={6} /> + </Table.Td> + </Table.Tr> + <Table.Tr> + <Table.Td> + <Skeleton height={8} my={6} /> + </Table.Td> + </Table.Tr> + <Table.Tr> + <Table.Td> + <Skeleton height={8} my={6} /> + </Table.Td> + </Table.Tr> + </Table.Tbody> + </Table> + ); +}; + +export const InfraPodsStatusTable = ({ + dateRange, + metricSource, + where, +}: { + dateRange: [Date, Date]; + metricSource: TSource; + where: string; +}) => { + const [phaseFilter, setPhaseFilter] = React.useState('running'); + const [sortState, setSortState] = React.useState<{ + column: InfraPodsStatusTableColumn; + order: 'asc' | 'desc'; + }>({ + column: 'restarts', + order: 'desc', + }); + + const groupBy = ['k8s.pod.name', 'k8s.namespace.name', 'k8s.node.name']; + const { data, isError, isLoading } = useQueriedChartConfig( + convertV1ChartConfigToV2( + { + series: [ + { + table: 'metrics', + field: 'k8s.pod.phase - Gauge', + type: 'table', + aggFn: 'last_value', + where, + groupBy, + ...(sortState.column === 'phase' && { + sortOrder: sortState.order, + }), + }, + { + table: 'metrics', + field: 'k8s.container.restarts - Gauge', + type: 'table', + aggFn: 'last_value', + where, + groupBy, + ...(sortState.column === 'restarts' && { + sortOrder: sortState.order, + }), + }, + { + table: 'metrics', + field: 'k8s.pod.uptime - Sum', + type: 'table', + aggFn: 'sum', + where, + groupBy, + ...(sortState.column === 'uptime' && { + sortOrder: sortState.order, + }), + }, + { + table: 'metrics', + field: 'k8s.pod.cpu.utilization - Gauge', + type: 'table', + aggFn: 'avg', + where, + groupBy, + }, + { + table: 'metrics', + field: 'k8s.pod.cpu_limit_utilization - Gauge', + type: 'table', + aggFn: 'avg', + where, + groupBy, + ...(sortState.column === 'cpuLimit' && { + sortOrder: sortState.order, + }), + }, + { + table: 'metrics', + field: 'k8s.pod.memory.usage - Gauge', + type: 'table', + aggFn: 'avg', + where, + groupBy, + }, + { + table: 'metrics', + field: 'k8s.pod.memory_limit_utilization - Gauge', + type: 'table', + aggFn: 'avg', + where, + groupBy, + ...(sortState.column === 'memLimit' && { + sortOrder: sortState.order, + }), + }, + ], + dateRange, + seriesReturnType: 'column', + }, + { + metric: metricSource, + }, + ), + ); + + // TODO: Use useTable + const podsList = React.useMemo(() => { + if (!data) { + return []; + } + + return data.data + .map((row: any) => { + return { + id: makeId(), + name: row["arrayElement(ResourceAttributes, 'k8s.pod.name')"], + namespace: + row["arrayElement(ResourceAttributes, 'k8s.namespace.name')"], + node: row["arrayElement(ResourceAttributes, 'k8s.node.name')"], + restarts: row['last_value(k8s.container.restarts)'], + uptime: row['sum(k8s.pod.uptime)'], + cpuAvg: row['avg(k8s.pod.cpu.utilization)'], + cpuLimitUtilization: row['avg(k8s.pod.cpu_limit_utilization)'], + memAvg: row['avg(k8s.pod.memory.usage)'], + memLimitUtilization: row['avg(k8s.pod.memory_limit_utilization)'], + phase: row['last_value(k8s.pod.phase)'], + }; + }) + .filter(pod => { + if (phaseFilter === 'all') { + return true; + } + return pod.phase === getKubePhaseNumber(phaseFilter); + }); + }, [data, phaseFilter]); + + const getLink = React.useCallback((podName: string) => { + const searchParams = new URLSearchParams(window.location.search); + searchParams.set('podName', `${podName}`); + return window.location.pathname + '?' + searchParams.toString(); + }, []); + + const getThSortProps = (column: InfraPodsStatusTableColumn) => ({ + onSort: (order: 'asc' | 'desc') => { + setSortState({ + column, + order, + }); + }, + sort: sortState.column === column ? sortState.order : null, + }); + + return ( + <Card p="md"> + <Card.Section p="md" py="xs" withBorder> + <Group align="center" justify="space-between"> + Pods + <SegmentedControl + size="xs" + value={phaseFilter} + onChange={setPhaseFilter} + data={[ + { label: 'Running', value: 'running' }, + { label: 'Succeeded', value: 'succeeded' }, + { label: 'Pending', value: 'pending' }, + { label: 'Failed', value: 'failed' }, + { label: 'All', value: 'all' }, + ]} + /> + </Group> + </Card.Section> + <Card.Section> + <ScrollArea + viewportProps={{ + style: { maxHeight: 300 }, + }} + > + {isLoading ? ( + <TableLoading /> + ) : isError ? ( + <div className="p-4 text-center text-slate-500 fs-8"> + Unable to load pod metrics + </div> + ) : podsList.length === 0 ? ( + <div className="p-4 text-center text-slate-500 fs-8">
This shows up pretty dark, maybe make it consistent with the message for the latest warning table? ![image](https://github.com/user-attachments/assets/de53ed7c-07e0-49e4-afad-8574253ad577)
hyperdx
github_2023
typescript
713
hyperdxio
wrn14897
@@ -467,6 +463,37 @@ export type Field = { jsType: JSDataType | null; }; +export type TableConnection = { + databaseName: string; + tableName: string; + connectionId: string; +}; + +export function isTableConnection(obj: any): obj is TableConnection {
`any` is dangerous. if its used to tell the obj is array or not, I'd do ``` export function isTableConnection( obj: TableConnection | TableConnection[], ): obj is TableConnection { return ( !Array.isArray(obj) && typeof obj?.databaseName === 'string' && typeof obj?.tableName === 'string' && typeof obj?.connectionId === 'string' ); } ``` also the name is a bit confusing.`isSingleTableConnection` would be a bit more clear
hyperdx
github_2023
typescript
713
hyperdxio
wrn14897
@@ -38,16 +38,15 @@ export default function SearchInputV2({ const ref = useRef<HTMLInputElement>(null); - const { data: fields } = useAllFields( - { - databaseName: database ?? '', - tableName: table ?? '', - connectionId: connectionId ?? '', - }, - { - enabled: !!database && !!table && !!connectionId, - }, - ); + const tableConnections = + _tableConnections === undefined + ? [] + : isTableConnection(_tableConnections) + ? [_tableConnections] + : _tableConnections; + const { data: fields } = useAllFields(tableConnections, {
can you explain more why do we want to accept either a single TableConnection or an array of them? Can't we just do array?
hyperdx
github_2023
typescript
713
hyperdxio
wrn14897
@@ -36,26 +41,39 @@ export function useColumns( } export function useAllFields( - { - databaseName, - tableName, - connectionId, - }: { - databaseName: string; - tableName: string; - connectionId: string; - }, + _tableConnections: TableConnection | TableConnection[], options?: Partial<UseQueryOptions<Field[]>>, ) { - const metadata = getMetadata(); + const tableConnections = isTableConnection(_tableConnections) + ? [_tableConnections] + : _tableConnections; return useQuery<Field[]>({ - queryKey: ['useMetadata.useAllFields', { databaseName, tableName }], + queryKey: [ + 'useMetadata.useAllFields', + ...tableConnections.map(tc => ({ ...tc })), + ], queryFn: async () => { - return metadata.getAllFields({ - databaseName, - tableName, - connectionId, - }); + const metadata = getMetadata();
we better leave the metadata (caching singleton) init outside the function so its not reinit for every queryFn calls
hyperdx
github_2023
typescript
713
hyperdxio
wrn14897
@@ -36,26 +41,39 @@ export function useColumns( } export function useAllFields( - { - databaseName, - tableName, - connectionId, - }: { - databaseName: string; - tableName: string; - connectionId: string; - }, + _tableConnections: TableConnection | TableConnection[], options?: Partial<UseQueryOptions<Field[]>>, ) { - const metadata = getMetadata(); + const tableConnections = isTableConnection(_tableConnections) + ? [_tableConnections] + : _tableConnections; return useQuery<Field[]>({ - queryKey: ['useMetadata.useAllFields', { databaseName, tableName }], + queryKey: [ + 'useMetadata.useAllFields', + ...tableConnections.map(tc => ({ ...tc })), + ], queryFn: async () => { - return metadata.getAllFields({ - databaseName, - tableName, - connectionId, - }); + const metadata = getMetadata(); + const fields2d = await Promise.all( + tableConnections.map(tc => metadata.getAllFields(tc)), + ); + + // skip deduplication if not possible + if (fields2d.length === 1) return fields2d[0]; + + // deduplicate common fields + const fields = []; + const set = new Set<string>(); + for (const _fields of fields2d) { + for (const field of _fields) { + const key = `${field.path.join('.')}_${field.jsType?.toString()}`;
can just use `objectHash` ``` const _key = objectHash.sha1(field) ```
hyperdx
github_2023
typescript
713
hyperdxio
wrn14897
@@ -886,9 +906,7 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) { render={({ field }) => field.value === 'sql' ? ( <SQLInlineEditorControlled - connectionId={defaultSource?.connection} - database={defaultDatabaseName} - table={defaultTableName} + tableConnection={tableConnections}
imo, its confusing we pass tableConnections as `tableConnection` prop
hyperdx
github_2023
typescript
713
hyperdxio
wrn14897
@@ -506,6 +511,28 @@ function DBDashboardPage({ presetConfig }: { presetConfig?: Dashboard }) { const { data: sources } = useSources(); const [highlightedTileId] = useQueryState('highlightedTileId'); + const tableConnections = useMemo(() => { + if (!dashboard) return []; + const tc: TableConnection[] = []; + + for (const { config } of dashboard.tiles) { + const source = sources?.find(v => v.id === config.source); + if (!source) continue; + // TODO: will need to update this when we allow for multiple metrics per chart
theoretically, we can go through each select to pull the table name, right? fwiw, there will be only 3 tables total for a single source (you can find them in `source.metricTables`)
hyperdx
github_2023
typescript
713
hyperdxio
wrn14897
@@ -36,26 +42,27 @@ export function useColumns( } export function useAllFields( - { - databaseName, - tableName, - connectionId, - }: { - databaseName: string; - tableName: string; - connectionId: string; - }, + _tableConnections: TableConnection | TableConnection[], options?: Partial<UseQueryOptions<Field[]>>, ) { + const tableConnections = isSingleTableConnection(_tableConnections) + ? [_tableConnections] + : _tableConnections; const metadata = getMetadata(); return useQuery<Field[]>({ - queryKey: ['useMetadata.useAllFields', { databaseName, tableName }], + queryKey: [ + 'useMetadata.useAllFields', + ...tableConnections.map(tc => ({ ...tc })), + ], queryFn: async () => { - return metadata.getAllFields({ - databaseName, - tableName, - connectionId, - }); + const fields2d = await Promise.all( + tableConnections.map(tc => metadata.getAllFields(tc)), + ); + + // skip deduplication if not needed + if (fields2d.length === 1) return fields2d[0]; + + return deduplicate2dArray(fields2d);
nit: `deduplicate2dArray<Field>(fields2d)`
hyperdx
github_2023
typescript
713
hyperdxio
wrn14897
@@ -0,0 +1,107 @@ +// @ts-ignore +import { deduplicate2dArray } from '../useMetadata'; + +describe('deduplicate2dArray', () => { + // Test basic deduplication + it('should remove duplicate objects across 2D array', () => { + const input = [ + [ + { id: 1, name: 'Alice' }, + { id: 2, name: 'Bob' }, + ], + [ + { id: 1, name: 'Alice' }, + { id: 3, name: 'Charlie' }, + ], + ]; + + const result = deduplicate2dArray(input); + + expect(result).toHaveLength(3); + expect(result).toEqual([ + { id: 1, name: 'Alice' }, + { id: 2, name: 'Bob' }, + { id: 3, name: 'Charlie' }, + ]); + }); + + // Test with empty arrays + it('should handle empty 2D array', () => { + const input: number[][] = []; + + const result = deduplicate2dArray(input); + + expect(result).toHaveLength(0); + }); + + // Test with nested empty arrays + it('should handle 2D array with empty subarrays', () => { + const input = [[], [], []]; + + const result = deduplicate2dArray(input); + + expect(result).toHaveLength(0); + }); + + // Test with complex objects + it('should deduplicate complex nested objects', () => { + const input = [ + [ + { user: { id: 1, details: { name: 'Alice' } } }, + { user: { id: 2, details: { name: 'Bob' } } }, + ], + [ + { user: { id: 1, details: { name: 'Alice' } } }, + { user: { id: 3, details: { name: 'Charlie' } } }, + ], + ]; + + const result = deduplicate2dArray(input); + + expect(result).toHaveLength(3); + expect(result).toEqual([ + { user: { id: 1, details: { name: 'Alice' } } }, + { user: { id: 2, details: { name: 'Bob' } } }, + { user: { id: 3, details: { name: 'Charlie' } } }, + ]); + }); + + // Test with different types of objects + it('should work with different types of objects', () => { + const input = [ + [{ value: 'string' }, { value: 42 }], + [{ value: 'string' }, { value: true }], + ]; + + const result = deduplicate2dArray(input); + + expect(result).toHaveLength(3); + }); + + // Test order preservation + it('should preserve the order of first occurrence', () => { + const input = [ + [{ id: 1 }, { id: 2 }], + [{ id: 1 }, { id: 3 }], + [{ id: 4 }, { id: 2 }], + ]; + + const result = deduplicate2dArray(input); + + expect(result).toEqual([{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]); + }); + + // Test performance consideration (large arrays) + it('should handle large 2D arrays efficiently', () => {
Lol...like test until it timeout or what?
hyperdx
github_2023
typescript
713
hyperdxio
wrn14897
@@ -115,3 +122,21 @@ export function useGetKeyValues({ placeholderData: keepPreviousData, }); } + +function deduplicate2dArray<T extends object>(array2d: T[][]): T[] { + const array: T[] = []; + const set = new Set<string>(); + for (const _array of array2d) { + for (const elem of _array) { + const key = objectHash.sha1(elem); + if (set.has(key)) continue; + set.add(key); + array.push(elem); + } + } + return array; +} + +// export functions for testing only +export const testExports = + process.env.NODE_ENV === 'test' ? { deduplicate2dArray } : undefined;
we probably don't set the node env for unit test (also you want to use `IS_CI` flag instead). I think we can just export this function
hyperdx
github_2023
typescript
716
hyperdxio
wrn14897
@@ -458,7 +458,12 @@ export function chSqlToAliasMap( ast.columns.forEach(column => { if (column.as != null) { if (column.type === 'expr' && column.expr.type === 'column_ref') { - aliasMap[column.as] = column.expr.column.expr.value; + aliasMap[column.as] =
this hot fix is good for now. I wonder if we could find how the node-sql-parser rebuilds the sql and use that function instead
hyperdx
github_2023
others
692
hyperdxio
wrn14897
@@ -64,7 +64,7 @@ exports[`renderChartConfig should generate sql for a single histogram metric 1`] arrayElement(ExplicitBounds, BucketLowIdx - 1) + (arrayElement(ExplicitBounds, BucketLowIdx) - arrayElement(ExplicitBounds, BucketLowIdx - 1)) * IF(arrayElement(CumRates, BucketLowIdx) > arrayElement(CumRates, BucketLowIdx - 1), (Rank - arrayElement(CumRates, BucketLowIdx - 1)) / (arrayElement(CumRates, BucketLowIdx) - arrayElement(CumRates, BucketLowIdx - 1)), 0), - IF(arrayElement(CumRates, 1) > 0, arrayElement(ExplicitBounds, BucketLowIdx + 1) * (Rank / arrayElement(CumRates, BucketLowIdx)), 0) + arrayElement(ExplicitBounds, BucketLowIdx)
Trying to understand this change. Does this mean we take the bound bucket if the value exceeds the boundaries? Also wonder what would happen in the old codes?
hyperdx
github_2023
typescript
692
hyperdxio
wrn14897
@@ -608,5 +671,294 @@ describe('renderChartConfig', () => { ); expect(await queryData(maxQuery)).toMatchSnapshot('maxSum'); }); + + it('two_timestamps_bounded histogram (p50)', async () => { + /*
Thanks for adding these comments. They are extremely helpful!
hyperdx
github_2023
typescript
692
hyperdxio
wrn14897
@@ -608,5 +671,294 @@ describe('renderChartConfig', () => { ); expect(await queryData(maxQuery)).toMatchSnapshot('maxSum'); }); + + it('two_timestamps_bounded histogram (p50)', async () => { + /* + This test starts with 2 data points with bounds of [10, 30]: + t0: [0, 0, 0] + t1: [10, 10, 10] + + Since the AggregationTemporality is 2(cumulative), we need to calculate the delta between the two points: + delta: [10, 10, 10] - [0, 0, 0] = [10, 10, 10] + + Total observations: 10 + 10 + 10 = 30 + Cumulative counts: [10, 20, 30] + p50 point: + Rank = 0.5 * 30 = 15 + This falls in the second bucket (since 10 < 15 ≤ 20) + + We need to interpolate between the lower and upper bounds of the second bucket: + Lower bound: 10 + Upper bound: 30 + Position in bucket: (15 - 10) / (20 - 10) = 0.5 + Interpolated value: 10 + (30 - 10) * 0.5 = 10 + 10 = 20 + + Thus the first point value would be 0 since it's at the start of the bounds. + The second point value would be 20 since that is the median point value delta from the first point. + */ + const query = await renderChartConfig( + { + select: [ + { + aggFn: 'quantile', + level: 0.5, + metricName: 'test.two_timestamps_lower_bound', + metricType: MetricsDataType.Histogram, + valueExpression: 'Value', + }, + ], + from: metricSource.from, + where: '', + metricTables: TEST_METRIC_TABLES, + dateRange: [new Date(now), new Date(now + ms('2m'))], + granularity: '1 minute', + timestampValueExpression: metricSource.timestampValueExpression, + connection: connection.id, + }, + metadata, + ); + const res = await queryData(query); + expect(res).toMatchSnapshot(); + }); + + it('two_timestamps_bounded histogram (p90)', async () => { + /* + This test starts with 2 data points with bounds of [10, 30]: + t0: [0, 0, 0] + t1: [10, 10, 10] + + Since the AggregationTemporality is 2(cumulative), we need to calculate the delta between the two points: + delta: [10, 10, 10] - [0, 0, 0] = [10, 10, 10] + + Total observations: 10 + 10 + 10 = 30 + Cumulative counts: [10, 20, 30] + p90 point: + Rank = 0.9 * 30 = 27 + This falls in the third bucket (since 20 < 27 ≤ 30) + + We need to interpolate between the lower and upper bounds of the third bucket: + Lower bound: 30 + Upper bound: Infinity (but we use the upper bound of the previous bucket for the last bucket) + Position in bucket: (27 - 20) / (30 - 20) = 0.7 + Interpolated value: 30 (since it's in the last bucket, we return the upper bound of the previous bucket) + + Thus the first point value would be 0 since it's at the start of the bounds. + The second point value would be 30 since that is the 90th percentile point value delta from the first point. + */ + const query = await renderChartConfig( + { + select: [ + { + aggFn: 'quantile', + level: 0.9, + metricName: 'test.two_timestamps_lower_bound', + metricType: MetricsDataType.Histogram, + valueExpression: 'Value', + }, + ], + from: metricSource.from, + where: '', + metricTables: TEST_METRIC_TABLES, + dateRange: [new Date(now), new Date(now + ms('2m'))], + granularity: '1 minute', + timestampValueExpression: metricSource.timestampValueExpression, + connection: connection.id, + }, + metadata, + ); + const res = await queryData(query); + expect(res).toMatchSnapshot(); + }); + + it('two_timestamps_bounded histogram (p25)', async () => { + /* + This test starts with 2 data points with bounds of [10, 30]: + t0: [0, 0, 0] + t1: [10, 10, 10] + + Since the AggregationTemporality is 2(cumulative), we need to calculate the delta between the two points: + delta: [10, 10, 10] - [0, 0, 0] = [10, 10, 10] + + Total observations: 10 + 10 + 10 = 30 + Cumulative counts: [10, 20, 30] + p25 point: + Rank = 0.25 * 30 = 7.5 + This falls in the first bucket (since 0 < 7.5 ≤ 10) + + We need to interpolate between the lower and upper bounds of the first bucket: + Lower bound: 0 (implicit lower bound for first bucket) + Upper bound: 10 (first explicit bound) + Position in bucket: 7.5 / 10 = 0.75 + Interpolated value: 0 + 0.75 * (10 - 0) = 7.5 + + Since all observations are in the first bucket which has an upper bound of 1: + For the first bucket (≤ 0), the algorithm would interpolate, but since all values are in this bucket and it's the lowest bucket, it would return 10 + Thus the value columns in res should be [0, 10] + */ + const query = await renderChartConfig( + { + select: [ + { + aggFn: 'quantile', + level: 0.25, + metricName: 'test.two_timestamps_lower_bound', + metricType: MetricsDataType.Histogram, + valueExpression: 'Value', + }, + ], + from: metricSource.from, + where: '', + metricTables: TEST_METRIC_TABLES, + dateRange: [new Date(now), new Date(now + ms('2m'))], + granularity: '1 minute', + timestampValueExpression: metricSource.timestampValueExpression, + connection: connection.id, + }, + metadata, + ); + const res = await queryData(query); + expect(res).toMatchSnapshot(); + }); + + it('two_timestamps_lower_bound_inf histogram (p50)', async () => { + /* + This test starts with 2 data points with bounds of [1, 30]: + t0: [0, 0, 0] + t1: [10, 0, 0] + + Since the AggregationTemporality is 2(cumulative), we need to calculate the delta between the two points: + delta: [10, 0, 0] - [0, 0, 0] = [10, 0, 0] + + Total observations: 10 + 0 + 0 = 10 + Cumulative counts: [10, 10, 10] + p50 point: + Rank = 0.5 * 10 = 5 + This falls in the first bucket (since 5 < 10) + + Since all observations are in the first bucket which has an upper bound of 1: + For the first bucket (≤ 0), the algorithm would interpolate, but since all values are in this bucket and it's the lowest bucket, it would return 1 + Thus the value columns in res should be [0, 1] + */ + const query = await renderChartConfig( + { + select: [ + { + aggFn: 'quantile', + level: 0.5, + metricName: 'test.two_timestamps_lower_bound_inf', + metricType: MetricsDataType.Histogram, + valueExpression: 'Value', + }, + ], + from: metricSource.from, + where: '', + metricTables: TEST_METRIC_TABLES, + dateRange: [new Date(now), new Date(now + ms('2m'))], + granularity: '1 minute', + timestampValueExpression: metricSource.timestampValueExpression, + connection: connection.id, + }, + metadata, + ); + const res = await queryData(query); + expect(res).toMatchSnapshot(); + }); + + it('two_timestamps_upper_bound_inf histogram (p50)', async () => { + /* + This test starts with 2 data points with bounds of [0, 30]: + t0: [0, 0, 0] + t1: [0, 0, 10] + + Since the AggregationTemporality is 2(cumulative), we need to calculate the delta between the two points: + delta: [0, 0, 10] - [0, 0, 0] = [0, 0, 10] + + Total observations: 0 + 0 + 10 = 10 + Cumulative counts: [0, 0, 10] + p50 point: + Rank = 0.5 * 10 = 5 + This falls in the third bucket + + Since all observations are in the third bucket which has no upper bound (infinity): + For the third bucket (> 30), the algorithm would return the upper bound of the previous bucket, which is 30 + Thus the value columns in res should be [0, 30] + */ + const query = await renderChartConfig( + { + select: [ + { + aggFn: 'quantile', + level: 0.5, + metricName: 'test.two_timestamps_upper_bound_inf', + metricType: MetricsDataType.Histogram, + valueExpression: 'Value', + }, + ], + from: metricSource.from, + where: '', + metricTables: TEST_METRIC_TABLES, + dateRange: [new Date(now), new Date(now + ms('2m'))], + granularity: '1 minute', + timestampValueExpression: metricSource.timestampValueExpression, + connection: connection.id, + }, + metadata, + ); + const res = await queryData(query); + expect(res).toMatchSnapshot(); + }); + + // HDX-1515: Handle counter reset in histogram metric in the same way that the counter reset + // is handled for sum metrics. + it.skip('three_timestamps_bounded histogram with reset (p50)', async () => {
is this intentional?
hyperdx
github_2023
typescript
709
hyperdxio
knudtty
@@ -16,60 +16,6 @@ import { LimitedSizeQueue } from '@/utils/queue'; const router = express.Router(); -router.get('/', async (req, res, next) => {
Has this endpoint been deprecated entirely? Anything that previously used this uses clickhouseProxy now?
hyperdx
github_2023
typescript
698
hyperdxio
ernestii
@@ -10,9 +10,11 @@ import { Stack, Tabs, Text, + TextInput, Tooltip, UnstyledButton, } from '@mantine/core'; +import { IconSearch } from '@tabler/icons-react';
heck yeah
hyperdx
github_2023
typescript
698
hyperdxio
ernestii
@@ -66,6 +70,7 @@ export const FilterCheckbox = ({ // taken care by the onClick in the group, triggering here will double fire emptyFn } + indeterminate={value === 'excluded'}
nit: maybe also change the color of the checkbox when it's `excluded`?
hyperdx
github_2023
typescript
698
hyperdxio
ernestii
@@ -0,0 +1,158 @@ +import { render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { FilterGroup, type FilterGroupProps } from '../DBSearchPageFilters'; + +describe('FilterGroup', () => { + const defaultProps: FilterGroupProps = { + name: 'Test Filter', + options: [ + { value: 'zebra', label: 'zebra' }, + { value: 'apple', label: 'apple' }, + { value: 'banana', label: 'banana' }, + ], + selectedValues: { included: new Set(), excluded: new Set() }, + onChange: jest.fn(), + onClearClick: jest.fn(), + onOnlyClick: jest.fn(), + onExcludeClick: jest.fn(), + }; + + it('should sort options alphabetically by default', () => { + renderWithMantine(<FilterGroup {...defaultProps} />);
👀 noice
hyperdx
github_2023
others
698
hyperdxio
ernestii
@@ -1,11 +1,37 @@ @import './variables'; +/* stylelint-disable selector-pseudo-class-no-unknown */ .filtersPanel { width: 220px; max-height: 100%; background-color: #00000030; flex-shrink: 0; word-break: break-all; + + :global {
nit: this is probably better to move to a global 'mantine-overrides.scss' file? otherwise there might be wrong styling when SearchPage isn't imported
hyperdx
github_2023
typescript
697
hyperdxio
wrn14897
@@ -23,15 +26,27 @@ export default function DBTableChart({ queryKeyPrefix?: string; enabled?: boolean; }) { - const queriedConfig = omit(config, ['granularity']); - const { data, isLoading, isError, error } = useQueriedChartConfig( - queriedConfig, - { - placeholderData: (prev: any) => prev, - queryKey: [queryKeyPrefix, queriedConfig], + const queriedConfig = (() => { + const _config = omit(config, ['granularity']); + _config.limit = { + limit: 200, + }; + return _config; + })();
since we introduced the offset, we need to add the sorting criteria (by group-by) or the results could be incorrect. This should also address the case when group-by ordering matters, for example, counts by timestamp <img width="535" alt="image" src="https://github.com/user-attachments/assets/106b1c2d-0187-46ca-a275-28ebb0edd740" />
hyperdx
github_2023
typescript
697
hyperdxio
wrn14897
@@ -31,6 +31,9 @@ export default function DBTableChart({ _config.limit = { limit: 200, }; + if (_config.groupBy && typeof _config.groupBy === 'string') { + _config.orderBy = _config.groupBy;
eventually, we probably want to let users to specify the orderBy (like which fields + asc/desc)
hyperdx
github_2023
typescript
699
hyperdxio
teeohhem
@@ -63,6 +70,41 @@ export default function DBRowSidePanelHeader({ [bodyExpanded, mainContent], ); + const headerRef = useRef<HTMLDivElement>(null); + const [headerHeight, setHeaderHeight] = useState(0); + useEffect(() => { + if (!headerRef.current) return;
nit: DRY `const el = headerRef.current`
hyperdx
github_2023
typescript
699
hyperdxio
teeohhem
@@ -63,6 +70,41 @@ export default function DBRowSidePanelHeader({ [bodyExpanded, mainContent], ); + const headerRef = useRef<HTMLDivElement>(null); + const [headerHeight, setHeaderHeight] = useState(0); + useEffect(() => { + if (!headerRef.current) return; + + const updateHeight = () => { + if (headerRef.current) {
not sure you need this safeguard since the null check is on the first line. Since the ResizeObserver only "works" when an element is in the DOM and is resized, I think it's a safe assumption that it's not null.
hyperdx
github_2023
typescript
699
hyperdxio
teeohhem
@@ -63,6 +70,41 @@ export default function DBRowSidePanelHeader({ [bodyExpanded, mainContent], ); + const headerRef = useRef<HTMLDivElement>(null); + const [headerHeight, setHeaderHeight] = useState(0); + useEffect(() => { + if (!headerRef.current) return; + + const updateHeight = () => { + if (headerRef.current) { + const newHeight = headerRef.current.offsetHeight; + setHeaderHeight(newHeight); + } + }; + + updateHeight(); + + // Set up a resize observer to detect height changes + const resizeObserver = new ResizeObserver(_ => { + updateHeight(); + });
nit: ``` const resizeObserver = new ResizeObserver(updateHeight); ```
hyperdx
github_2023
typescript
699
hyperdxio
teeohhem
@@ -63,6 +70,41 @@ export default function DBRowSidePanelHeader({ [bodyExpanded, mainContent], ); + const headerRef = useRef<HTMLDivElement>(null); + const [headerHeight, setHeaderHeight] = useState(0); + useEffect(() => { + if (!headerRef.current) return; + + const updateHeight = () => { + if (headerRef.current) { + const newHeight = headerRef.current.offsetHeight; + setHeaderHeight(newHeight); + } + }; + + updateHeight(); + + // Set up a resize observer to detect height changes + const resizeObserver = new ResizeObserver(_ => { + updateHeight(); + }); + + if (headerRef.current) {
You return immediately if the ref isn't valid already
hyperdx
github_2023
typescript
699
hyperdxio
teeohhem
@@ -63,6 +70,41 @@ export default function DBRowSidePanelHeader({ [bodyExpanded, mainContent], ); + const headerRef = useRef<HTMLDivElement>(null); + const [headerHeight, setHeaderHeight] = useState(0); + useEffect(() => { + if (!headerRef.current) return; + + const updateHeight = () => { + if (headerRef.current) { + const newHeight = headerRef.current.offsetHeight; + setHeaderHeight(newHeight); + } + }; + + updateHeight(); + + // Set up a resize observer to detect height changes + const resizeObserver = new ResizeObserver(_ => { + updateHeight(); + }); + + if (headerRef.current) { + resizeObserver.observe(headerRef.current); + } + + // Clean up the observer on component unmount + return () => { + if (headerRef.current) {
same here
hyperdx
github_2023
typescript
699
hyperdxio
teeohhem
@@ -97,16 +139,40 @@ export default function DBRowSidePanelHeader({ p="xs" mt="sm" style={{ - maxHeight: 120, + maxHeight: expandSidebarHeader ? maxBoxHeight : undefined, overflow: 'auto', overflowWrap: 'break-word', }} + ref={headerRef} > - <Flex align="baseline" gap={2} mb="xs"> - <Text size="xs" c="gray.4"> - {mainContentHeader} - </Text> - <EditButton sourceId={sourceId} /> + <Flex justify="space-between" mb="xs"> + <Flex align="baseline" gap={2}> + <Text size="xs" c="gray.4"> + {mainContentHeader} + </Text> + <EditButton sourceId={sourceId} /> + </Flex> + {/* Toggles expanded sidebar header*/} + {headerHeight >= maxBoxHeight && ( + <Button + size="compact-xs" + variant="subtle" + color="gray.3" + onClick={() => + setUserPreference({ + ...userPreferences, + expandSidebarHeader: !expandSidebarHeader, + }) + } + > + {/* TODO: Only show expand button when maxHeight = 120? */} + {expandSidebarHeader ? ( + <i className="bi bi-arrows-angle-expand" /> + ) : ( + <i className="bi bi-arrows-angle-contract" />
wait aren't these backwards? Am I reading this correctly? if `expandSidebarHeader` is true wouldn't you show the contract icon?
hyperdx
github_2023
typescript
699
hyperdxio
teeohhem
@@ -97,16 +139,40 @@ export default function DBRowSidePanelHeader({ p="xs" mt="sm" style={{ - maxHeight: 120, + maxHeight: expandSidebarHeader ? maxBoxHeight : undefined,
Isn't this backwards too? If expandSidebarHeader is true, shouldn't max height be undefined?
hyperdx
github_2023
typescript
690
hyperdxio
wrn14897
@@ -16,6 +17,25 @@ import { IS_MTVIEWS_ENABLED } from '@/config'; import { buildMTViewSelectQuery } from '@/hdxMTViews'; import { getMetadata } from '@/metadata'; +export const replaceBracketQuery = (query: any) => { + // sql-formatter throw error when query include brackets, ex: ResourceAttributes['telemetry.sdk.language'] + // feel free to remove this parser once formatter support clickhouse dialect. + if (!_.isString(query)) return query; + // Replace key[value] to arrayElement(key, value) + // edge case: + // `key`[value], from lucene key.value + // key[number value], from array + // key[value1.value2._value3] + return query.replace( + /`?(\w+)`?\[(?:'([^']+)'|(\d+))\]/g, + (match, key, strValue, numValue) => { + return numValue !== undefined + ? `arrayElement(${key}, ${numValue})` // No quotes for numbers + : `arrayElement(${key}, '${strValue}')`; // Keep quotes for strings
I think this hurts the sql readability. Ideally we can make the formatter work with bracket
hyperdx
github_2023
typescript
690
hyperdxio
wrn14897
@@ -0,0 +1,462 @@ +// custom dialect ref: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/dialect.md#custom-dialect-configuration-experimental
Have we checked this dialect is clickhouse compatible? I'd love us to maintain this going forward and contribute to the upstream later :)
hyperdx
github_2023
typescript
693
hyperdxio
teeohhem
@@ -0,0 +1,133 @@ +import { useEffect, useState } from 'react'; +import { UseFormGetValues, UseFormSetValue } from 'react-hook-form'; +import { z } from 'zod'; + +export const SearchConfigSchema = z.object({ + select: z.string(), + source: z.string(), + where: z.string(), + whereLanguage: z.enum(['sql', 'lucene']), + orderBy: z.string(), + filters: z.array( + z.union([ + z.object({ + type: z.literal('sql_ast'), + operator: z.enum(['=', '<', '>', '>=', '<=', '!=']), + left: z.string(), + right: z.string(), + }), + z.object({ + type: z.enum(['sql', 'lucene']), + condition: z.string(), + }), + ]), + ), +}); + +export type SearchConfigFromSchema = z.infer<typeof SearchConfigSchema>; + +/// Interface for all suggestion engines +interface ISuggestionEngine { + /// detect if a suggestion should be generated + detect(input: string): boolean; + /// message to display to user + userMessage(key: string): string; + /// return corrected text + correct(input: string): string; +} + +// Detects and corrects a double quote to a single quote +class DoubleQuoteSuggestion implements ISuggestionEngine { + detect(input: string): boolean { + let inSingleQuote = false; + for (let i = 0; i < input.length; i++) { + const char = input[i]; + if (char === "'") { + inSingleQuote = !inSingleQuote; + } else if (char === '"') { + if (inSingleQuote) continue; + return true; + } + } + return false; + } + + userMessage(key: string): string { + return `ClickHouse does not support double quotes (") but they were detected in ${key.toUpperCase()}. Switch to single quotes?`; + } + + correct(input: string): string { + let inSingleQuote = false; + let correctedText = ''; + for (let i = 0; i < input.length; i++) { + switch (input[i]) { + case "'": + inSingleQuote = !inSingleQuote; + correctedText += input[i]; + break; + case '"': + correctedText += inSingleQuote ? '"' : "'"; + break; + default: + correctedText += input[i]; + break; + } + } + + return correctedText; + } +} + +// Array of all suggestion engines. Expected to handle cases for select, where, and orderBy +const suggestionEngines = [new DoubleQuoteSuggestion()]; + +export type Suggestion = { + userMessage: string; + action: () => void; +}; + +export function useSqlSuggestions({ + setValue, + getValues, + hasQueryError, +}: { + setValue: UseFormSetValue<SearchConfigFromSchema>; + getValues: UseFormGetValues<SearchConfigFromSchema>; + hasQueryError: boolean; +}): Suggestion[] | null { + const [suggestions, setSuggestions] = useState<Suggestion[] | null>(null); + const [toggle, setToggle] = useState(false); + const refresh = () => setToggle(!toggle); + + useEffect(() => { + if (!hasQueryError) { + setSuggestions(null); + return; + } + + const fields: ('select' | 'where' | 'orderBy')[] = [ + 'select', + 'where', + 'orderBy', + ]; + const suggestions: Suggestion[] = []; + for (const se of suggestionEngines) { + for (const field of fields) { + if (field === 'where' && getValues('whereLanguage') !== 'sql') continue;
nit: you could probably just move this to above the loop since this only supports sql suggestions. Can probably just simplify it to ```if (getValues('whereLanguage') == 'sql') return;``` Select and GroupBy conditions don't have any quotes at all, so we probably shouldn't be sending them through the rec engine here.
hyperdx
github_2023
typescript
693
hyperdxio
teeohhem
@@ -0,0 +1,133 @@ +import { useEffect, useState } from 'react'; +import { UseFormGetValues, UseFormSetValue } from 'react-hook-form'; +import { z } from 'zod'; + +export const SearchConfigSchema = z.object({ + select: z.string(), + source: z.string(), + where: z.string(), + whereLanguage: z.enum(['sql', 'lucene']), + orderBy: z.string(), + filters: z.array( + z.union([ + z.object({ + type: z.literal('sql_ast'), + operator: z.enum(['=', '<', '>', '>=', '<=', '!=']), + left: z.string(), + right: z.string(), + }), + z.object({ + type: z.enum(['sql', 'lucene']), + condition: z.string(), + }), + ]), + ), +}); + +export type SearchConfigFromSchema = z.infer<typeof SearchConfigSchema>; + +/// Interface for all suggestion engines +interface ISuggestionEngine { + /// detect if a suggestion should be generated + detect(input: string): boolean; + /// message to display to user + userMessage(key: string): string; + /// return corrected text + correct(input: string): string; +} + +// Detects and corrects a double quote to a single quote +class DoubleQuoteSuggestion implements ISuggestionEngine { + detect(input: string): boolean { + let inSingleQuote = false; + for (let i = 0; i < input.length; i++) { + const char = input[i]; + if (char === "'") { + inSingleQuote = !inSingleQuote; + } else if (char === '"') { + if (inSingleQuote) continue; + return true; + } + } + return false; + } + + userMessage(key: string): string { + return `ClickHouse does not support double quotes (") but they were detected in ${key.toUpperCase()}. Switch to single quotes?`; + } + + correct(input: string): string { + let inSingleQuote = false; + let correctedText = ''; + for (let i = 0; i < input.length; i++) { + switch (input[i]) { + case "'": + inSingleQuote = !inSingleQuote; + correctedText += input[i]; + break; + case '"': + correctedText += inSingleQuote ? '"' : "'"; + break; + default: + correctedText += input[i]; + break; + } + } + + return correctedText; + } +} + +// Array of all suggestion engines. Expected to handle cases for select, where, and orderBy +const suggestionEngines = [new DoubleQuoteSuggestion()]; + +export type Suggestion = { + userMessage: string; + action: () => void; +}; + +export function useSqlSuggestions({ + setValue, + getValues, + hasQueryError, +}: { + setValue: UseFormSetValue<SearchConfigFromSchema>; + getValues: UseFormGetValues<SearchConfigFromSchema>; + hasQueryError: boolean; +}): Suggestion[] | null { + const [suggestions, setSuggestions] = useState<Suggestion[] | null>(null); + const [toggle, setToggle] = useState(false); + const refresh = () => setToggle(!toggle); + + useEffect(() => { + if (!hasQueryError) { + setSuggestions(null); + return; + } + + const fields: ('select' | 'where' | 'orderBy')[] = [ + 'select', + 'where', + 'orderBy', + ]; + const suggestions: Suggestion[] = []; + for (const se of suggestionEngines) { + for (const field of fields) { + if (field === 'where' && getValues('whereLanguage') !== 'sql') continue; + const input = getValues(field); + if (se.detect(input)) { + suggestions.push({ + userMessage: se.userMessage(field), + action: () => { + setValue(field, se.correct(input)); + refresh(); + }, + }); + } + } + } + setSuggestions(suggestions); + }, [hasQueryError, toggle]); + + return suggestions; +}
Nice change. I would love to see some unit tests for this.
hyperdx
github_2023
typescript
693
hyperdxio
teeohhem
@@ -136,6 +142,10 @@ export function useQueriedChartConfig( refetchOnWindowFocus: false, ...options, }); + useEffect(() => { + if (options?.onError && query.isError) options.onError(query.error); + }, [query.isError]); + return query;
Just curious why you're using `useEffect` here? Seems like this would be fine..or are you just trying to make sure that onError only gets called once? ``` if (query.isError && options?.onError) { options.onError(query.error); } ```
hyperdx
github_2023
typescript
695
hyperdxio
MikeShi42
@@ -291,6 +292,14 @@ export const MemoChart = memo(function MemoChart({ const color = lineColors[i] ?? _color; + const StackedBarWithOverlap = (props: BarProps) => {
hrm this is weird, there shouldn't be a gap, do we know why there is one?
hyperdx
github_2023
typescript
694
hyperdxio
wrn14897
@@ -258,7 +258,7 @@ export default function DBDeltaChart({ with: [ { name: 'PartIds', - sql: {
something wrong with the type? because this sql supposes to be ChSql type. I wonder why TS didn't pick this up
hyperdx
github_2023
typescript
687
hyperdxio
MikeShi42
@@ -82,76 +81,81 @@ router.get( return; } - const newPath = req.params[0]; - const qparams = new URLSearchParams(req.query); - qparams.delete('hyperdx_connection_id'); - - return createProxyMiddleware({ - target: connection.host, - changeOrigin: true, - pathFilter: (path, req) => { - // TODO: allow other methods - return req.method === 'GET'; - }, - pathRewrite: { - '^/clickhouse-proxy': '', - }, - headers: { - ...(connection.username - ? { 'X-ClickHouse-User': connection.username } - : {}), - ...(connection.password - ? { 'X-ClickHouse-Key': connection.password } - : {}), - }, - on: { - proxyReq: (proxyReq, req) => { - proxyReq.path = `/${newPath}?${qparams.toString()}`; - }, - proxyRes: (proxyRes, req, res) => { - // since clickhouse v24, the cors headers * will be attached to the response by default - // which will cause the browser to block the response - if (req.headers['access-control-request-method']) { - proxyRes.headers['access-control-allow-methods'] = - req.headers['access-control-request-method']; - } - - if (req.headers['access-control-request-headers']) { - proxyRes.headers['access-control-allow-headers'] = - req.headers['access-control-request-headers']; - } - - if (req.headers.origin) { - proxyRes.headers['access-control-allow-origin'] = - req.headers.origin; - proxyRes.headers['access-control-allow-credentials'] = 'true'; - } - }, - error: (err, _req, _res) => { - 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', - }), - ); - }, - }, - // ...(config.IS_DEV && { - // logger: console, - // }), - })(req, res, next); + req._hdx_connection = { + host: connection.host, + id: connection.id, + name: connection.name, + password: connection.password, + username: connection.username, + }; + next(); } catch (e) { - console.error('Router error:', e); - res.status(500).json({ - success: false, - error: e instanceof Error ? e.message : 'Internal server error', - }); + console.error('Error fetching connection info:', e); + next(e); } }, + createProxyMiddleware({ + target: 'http://localhost:8123', // doesn't matter. it should be overridden by the router
if host is undefined, it'll fall back to this URL, which may be undesirable (ex. an instance the user is not supposed to access via firewall policy) we should probably make the `target` some sort of invalid destination just in case, or make sure the `router` fn always returns something truthy (same idea)
hyperdx
github_2023
typescript
687
hyperdxio
MikeShi42
@@ -1,10 +1,23 @@ +import { getHyperDXMetricReader } from '@hyperdx/node-opentelemetry/build/src/metrics'; +import { HostMetrics } from '@opentelemetry/host-metrics'; +import { MeterProvider, MetricReader } from '@opentelemetry/sdk-metrics'; import { serializeError } from 'serialize-error'; import * as config from '@/config'; import Server from '@/server'; import { isOperationalError } from '@/utils/errors'; import logger from '@/utils/logger'; +if (config.IS_DEV) { + // Start collecting host metrics + const meterProvider = new MeterProvider({
this doesn't seem to attach any useful identifying resource attributes either, is it because we're not using the `NodeSDK` for metrics?
hyperdx
github_2023
typescript
686
hyperdxio
wrn14897
@@ -125,7 +125,13 @@ export const SelectSQLStatementSchema = z.object({ .array( z.object({ name: z.string(), - sql: z.lazy(() => ChSqlSchema.or(ChartConfigSchema)), + + // Need to specify either a sql or chartConfig instance. To avoid + // the schema falling into an any type, the fields are separate + // and listed as optional. + sql: ChSqlSchema.optional(), + chartConfig: z.lazy(() => ChartConfigSchema).optional(),
curious the reason we use z.lazy here?
hyperdx
github_2023
typescript
686
hyperdxio
wrn14897
@@ -133,7 +133,7 @@ describe('renderChartConfig', () => { query_params: query.params, format: 'JSON', }) - .then(res => res.json<any>()); + .then(res => res.json() as any);
I don't think we need to type it here (by default its unknown)
hyperdx
github_2023
typescript
666
hyperdxio
wrn14897
@@ -734,23 +734,50 @@ function renderLimit( // CTE (Common Table Expressions) isn't exported at this time. It's only used internally // for metric SQL generation. type ChartConfigWithOptDateRangeEx = ChartConfigWithOptDateRange & { - with?: { name: string; sql: ChSql }[]; includedDataInterval?: string; }; -function renderWith( +/** + * Type guard to check if an object is a ChSql instance + * @param obj The object to check + * @returns True if the object is a ChSql instance + */ +function isChSqlInstance(obj: any): obj is ChSql { + return ( + obj != null && + typeof obj === 'object' && + 'sql' in obj && + 'params' in obj && + typeof obj.sql === 'string' && + typeof obj.params === 'object' + ); +} + +async function renderWith( chartConfig: ChartConfigWithOptDateRangeEx, metadata: Metadata, -): ChSql | undefined { +): Promise<ChSql | undefined> { const { with: withClauses } = chartConfig; - if (withClauses) { - return concatChSql( - ',', - withClauses.map(clause => chSql`${clause.name} AS (${clause.sql})`), - ); - } - - return undefined; + const renderedClauses = withClauses?.map(async withClause => { + const { name, sql } = withClause; + if (typeof sql === 'string') {
This conflicts with the change in another PR to enable aliases (https://github.com/hyperdxio/hyperdx/pull/659/files#diff-baa4dde970c49e5ffe3667e2fe8bbc58b29e3055834c734871343dbe3cd66e56R748). Maybe we can merge that PR first. There is a case we want to treat sql as a function or variable
hyperdx
github_2023
typescript
666
hyperdxio
wrn14897
@@ -734,23 +734,50 @@ function renderLimit( // CTE (Common Table Expressions) isn't exported at this time. It's only used internally // for metric SQL generation. type ChartConfigWithOptDateRangeEx = ChartConfigWithOptDateRange & { - with?: { name: string; sql: ChSql }[]; includedDataInterval?: string; }; -function renderWith( +/** + * Type guard to check if an object is a ChSql instance + * @param obj The object to check + * @returns True if the object is a ChSql instance + */ +function isChSqlInstance(obj: any): obj is ChSql { + return ( + obj != null && + typeof obj === 'object' && + 'sql' in obj && + 'params' in obj && + typeof obj.sql === 'string' && + typeof obj.params === 'object' + ); +}
claude? I got a similar results Lol. I realized once the `ChSqlSchema` is defined. we can just use zod to do the validation
hyperdx
github_2023
typescript
666
hyperdxio
wrn14897
@@ -734,23 +734,50 @@ function renderLimit( // CTE (Common Table Expressions) isn't exported at this time. It's only used internally // for metric SQL generation. type ChartConfigWithOptDateRangeEx = ChartConfigWithOptDateRange & { - with?: { name: string; sql: ChSql }[]; includedDataInterval?: string; }; -function renderWith( +/** + * Type guard to check if an object is a ChSql instance + * @param obj The object to check + * @returns True if the object is a ChSql instance + */ +function isChSqlInstance(obj: any): obj is ChSql { + return ( + obj != null && + typeof obj === 'object' && + 'sql' in obj && + 'params' in obj && + typeof obj.sql === 'string' && + typeof obj.params === 'object' + ); +} + +async function renderWith( chartConfig: ChartConfigWithOptDateRangeEx, metadata: Metadata, -): ChSql | undefined { +): Promise<ChSql | undefined> { const { with: withClauses } = chartConfig; - if (withClauses) { - return concatChSql( - ',', - withClauses.map(clause => chSql`${clause.name} AS (${clause.sql})`), - ); - } - - return undefined; + const renderedClauses = withClauses?.map(async withClause => { + const { name, sql } = withClause; + if (typeof sql === 'string') { + return chSql`${name} AS (${chSql`${{ UNSAFE_RAW_SQL: sql }}`})`;
better not to use `UNSAFE_RAW_SQL` if possible. I wonder in this case we want to do `${{ identifier: sql }}`
hyperdx
github_2023
typescript
666
hyperdxio
wrn14897
@@ -734,23 +734,50 @@ function renderLimit( // CTE (Common Table Expressions) isn't exported at this time. It's only used internally // for metric SQL generation. type ChartConfigWithOptDateRangeEx = ChartConfigWithOptDateRange & { - with?: { name: string; sql: ChSql }[]; includedDataInterval?: string; }; -function renderWith( +/** + * Type guard to check if an object is a ChSql instance + * @param obj The object to check + * @returns True if the object is a ChSql instance + */ +function isChSqlInstance(obj: any): obj is ChSql { + return ( + obj != null && + typeof obj === 'object' && + 'sql' in obj && + 'params' in obj && + typeof obj.sql === 'string' && + typeof obj.params === 'object' + ); +} + +async function renderWith( chartConfig: ChartConfigWithOptDateRangeEx, metadata: Metadata, -): ChSql | undefined { +): Promise<ChSql | undefined> { const { with: withClauses } = chartConfig; - if (withClauses) { - return concatChSql( - ',', - withClauses.map(clause => chSql`${clause.name} AS (${clause.sql})`), - ); - } - - return undefined; + const renderedClauses = withClauses?.map(async withClause => { + const { name, sql } = withClause; + if (typeof sql === 'string') { + return chSql`${name} AS (${chSql`${{ UNSAFE_RAW_SQL: sql }}`})`; + } else if (isChSqlInstance(sql)) { + return chSql`${name} AS (${sql})`; + } else { + return chSql`${name} AS (${await renderChartConfig(
better to verify if sql is a valid chart config and throw if nothing matches
hyperdx
github_2023
typescript
666
hyperdxio
wrn14897
@@ -341,9 +344,24 @@ export const _ChartConfigSchema = z.object({ metricTables: MetricTableSchema.optional(), }); +export const CteExpressions = z.object({ + with: z + .array( + z.object({ + name: z.string(), + sql: z + .string() + .or(SelectSQLStatementSchema) + .or(_ChartConfigSchema) + .or(z.custom<ChSql>()),
does this do any validation? I suspect we want to infer ChSql from the zod schema instead. Like ``` const ChSqlSchema = z.object({ sql: z.string(), params: z.record(z.any()), }); export type ChSql = z.infer<typeof ChSqlSchema>; ```
hyperdx
github_2023
typescript
666
hyperdxio
wrn14897
@@ -737,21 +735,49 @@ type ChartConfigWithOptDateRangeEx = ChartConfigWithOptDateRange & { includedDataInterval?: string; }; -function renderWith( +async function renderWith( chartConfig: ChartConfigWithOptDateRangeEx, metadata: Metadata, -): ChSql | undefined { +): Promise<ChSql | undefined> { const { with: withClauses } = chartConfig; if (withClauses) { return concatChSql( ',', - withClauses.map(clause => { - if (clause.isSubquery === false) { - return chSql`(${clause.sql}) AS ${{ Identifier: clause.name }}`; - } - // Can not use identifier here - return chSql`${clause.name} AS (${clause.sql})`; - }), + await Promise.all( + withClauses.map(async clause => { + // The sql logic can be specified as either a string, ChSql instance or a + // chart config object. + let resolvedSql: ChSql; + if (typeof clause.sql === 'string') { + resolvedSql = chSql`${{ Identifier: clause.sql }}`; + } else if (clause.sql && 'sql' in clause.sql) { + resolvedSql = clause.sql; + } else if ( + clause.sql && + ('select' in clause.sql || 'connection' in clause.sql)
style: not a blocker. this isn't very readable imo. I wonder if we could split fields for `with` like ``` { name: string; sql?: string; chSql?: ChSql; chartConfig?: ChartConfig; } ```
hyperdx
github_2023
typescript
666
hyperdxio
wrn14897
@@ -737,21 +735,49 @@ type ChartConfigWithOptDateRangeEx = ChartConfigWithOptDateRange & { includedDataInterval?: string; }; -function renderWith( +async function renderWith( chartConfig: ChartConfigWithOptDateRangeEx, metadata: Metadata, -): ChSql | undefined { +): Promise<ChSql | undefined> { const { with: withClauses } = chartConfig; if (withClauses) { return concatChSql( ',', - withClauses.map(clause => { - if (clause.isSubquery === false) { - return chSql`(${clause.sql}) AS ${{ Identifier: clause.name }}`; - } - // Can not use identifier here - return chSql`${clause.name} AS (${clause.sql})`; - }), + await Promise.all( + withClauses.map(async clause => { + // The sql logic can be specified as either a string, ChSql instance or a + // chart config object. + let resolvedSql: ChSql; + if (typeof clause.sql === 'string') { + resolvedSql = chSql`${{ Identifier: clause.sql }}`; + } else if (clause.sql && 'sql' in clause.sql) { + resolvedSql = clause.sql; + } else if ( + clause.sql && + ('select' in clause.sql || 'connection' in clause.sql) + ) { + resolvedSql = await renderChartConfig( + { + ...clause.sql, + connection: chartConfig.connection, + timestampValueExpression: + chartConfig.timestampValueExpression || '',
I feel this should be passed from the 'with', no?
hyperdx
github_2023
typescript
666
hyperdxio
wrn14897
@@ -102,6 +102,12 @@ export const LimitSchema = z.object({ limit: z.number().optional(), offset: z.number().optional(), }); + +export const ChSqlSchema = z.object({ + sql: z.string(), + params: z.record(z.string(), z.any()), +});
👍
hyperdx
github_2023
typescript
675
hyperdxio
MikeShi42
@@ -1106,7 +1106,7 @@ export async function renderChartConfig( return concatChSql(' ', [ chSql`${withClauses?.sql ? chSql`WITH ${withClauses}` : ''}`, - chSql`SELECT ${select}`, + chSql`SELECT ${select?.sql ? select : '*'}`,
this feels pretty dangerous, we should fail loudly instead of silently adding '*' IMO, this logic is used everywhere in our app.
hyperdx
github_2023
typescript
675
hyperdxio
MikeShi42
@@ -494,7 +494,7 @@ export const renderAlertTemplate = async ({ displayType: DisplayType.Search, dateRange: [startTime, endTime], from: source.from, - select: savedSearch.select ?? source.defaultTableSelectExpression, + select: savedSearch.select || source.defaultTableSelectExpression || '*',
ah that's great, imo we should not fall back to '*' here but the `||` fix is great
hyperdx
github_2023
typescript
673
hyperdxio
wrn14897
@@ -36,6 +36,17 @@ export function RowOverviewPanel({ const resourceAttributes = firstRow?.__hdx_resource_attributes ?? EMPTY_OBJ; const eventAttributes = firstRow?.__hdx_event_attributes ?? EMPTY_OBJ; + const dataAttributes = + source.kind === 'log'
style: can use `SourceKind` enum
hyperdx
github_2023
typescript
673
hyperdxio
wrn14897
@@ -36,6 +36,17 @@ export function RowOverviewPanel({ const resourceAttributes = firstRow?.__hdx_resource_attributes ?? EMPTY_OBJ; const eventAttributes = firstRow?.__hdx_event_attributes ?? EMPTY_OBJ; + const dataAttributes = + source.kind === 'log' + ? firstRow?.['LogAttributes'] && + Object.keys(firstRow['LogAttributes']).length > 0 + ? { LogAttributes: firstRow['LogAttributes'] } + : {} + : firstRow?.['SpanAttributes'] && + Object.keys(firstRow['SpanAttributes']).length > 0 + ? { SpanAttributes: firstRow['SpanAttributes'] } + : {};
we should use `eventAttributesExpression` from source instead of hard-coded attribute here
hyperdx
github_2023
typescript
673
hyperdxio
wrn14897
@@ -49,17 +60,24 @@ export function RowOverviewPanel({ ); const isHttpRequest = useMemo(() => { - return eventAttributes?.['http.url'] != null; - }, [eventAttributes]); + const attributes = + dataAttributes?.LogAttributes || dataAttributes?.SpanAttributes; + return attributes?.['http.url'] != null; + }, [dataAttributes]); const filteredEventAttributes = useMemo(() => { + const attributes = + dataAttributes?.LogAttributes || dataAttributes?.SpanAttributes; if (isHttpRequest) { - return pickBy(eventAttributes, (value, key) => { - return !key.startsWith('http.'); - }); + return { + [dataAttributes?.LogAttributes ? 'LogAttributes' : 'SpanAttributes']:
Same thing here
hyperdx
github_2023
typescript
673
hyperdxio
wrn14897
@@ -25,6 +25,10 @@ export function RowOverviewPanel({ const { onPropertyAddClick, generateSearchUrl } = useContext(RowSidePanelContext); + const eventAttributesExpr = + source.eventAttributesExpression ?? + (source.kind === SourceKind.Log ? 'LogAttributes' : 'SpanAttributes');
Not sure if we want to use the hard-coded values. can we bypass it if the attribute expression isn't specified?
hyperdx
github_2023
typescript
673
hyperdxio
wrn14897
@@ -49,17 +59,23 @@ export function RowOverviewPanel({ ); const isHttpRequest = useMemo(() => { - return eventAttributes?.['http.url'] != null; - }, [eventAttributes]); + const attributes = + eventAttributesExpr && dataAttributes?.[eventAttributesExpr]; + return attributes?.['http.url'] != null;
I want to point out this is trace specific attribute (https://github.com/open-telemetry/opentelemetry-js/blob/eaebf765d8408b29264af5c50e51ce494781455e/semantic-conventions/src/trace/SemanticAttributes.ts#L91). I'd suggest to import these attributes from semantic convention library
hyperdx
github_2023
typescript
659
hyperdxio
wrn14897
@@ -746,7 +745,12 @@ function renderWith( if (withClauses) { return concatChSql( ',', - withClauses.map(clause => chSql`${clause.name} AS (${clause.sql})`), + withClauses.map(clause => { + if (clause.isSubquery) { + return chSql`${{ Identifier: clause.name }} AS (${clause.sql})`; + } + return chSql`(${clause.sql}) AS ${{ Identifier: clause.name }}`;
using with variable to bypass alias is quite clever! 🤯
hyperdx
github_2023
typescript
659
hyperdxio
wrn14897
@@ -115,6 +115,23 @@ export const SelectSQLStatementSchema = z.object({ havingLanguage: SearchConditionLanguageSchema.optional(), orderBy: SortSpecificationListSchema.optional(), limit: LimitSchema.optional(), + with: z + .array( + z.object({ + name: z.string(), + sql: z.object({ + sql: z.string(), + params: z.record(z.string(), z.any()), + }), + // If true, it'll render as WITH ident AS (subquery) + // If false, it'll be a "variable" ex. WITH (sql) AS ident + // where sql can be any expression, ex. a constant string + // see: https://clickhouse.com/docs/sql-reference/statements/select/with#syntax + // default assume true + isSubquery: z.boolean().optional(),
style: maybe we can call it `isVariable`
hyperdx
github_2023
typescript
659
hyperdxio
wrn14897
@@ -531,7 +531,14 @@ export class CustomSchemaSQLSerializerV2 extends SQLSerializer { throw new Error('Unsupported column type for prefix match'); } - throw new Error(`Column not found: ${field}`); + // It might be an alias, let's just try the column + // TODO: Verify aliases
I'm not sure if this would cause weird behaviors (things like sql injection). Also, the error message is different if users search with an unexisting field. I think we can ticket it and move on. I just want to keep it on the radar.
hyperdx
github_2023
typescript
668
hyperdxio
wrn14897
@@ -426,10 +428,12 @@ export class Metadata { query: sql.sql, query_params: sql.params, connectionId: chartConfig.connection, - clickhouse_settings: { - max_rows_to_read: DEFAULT_SAMPLE_SIZE, - read_overflow_mode: 'break', - }, + clickhouse_settings: !disableRowLimit
I'm a bit worried about the performance impact. I wonder if we want to enable caching for this method (using `this.cache.getOrFetch`). Besides, I wish the column type is `LowCardinality`
hyperdx
github_2023
typescript
664
hyperdxio
MikeShi42
@@ -445,5 +446,9 @@ export type Field = { jsType: JSDataType | null; }; +const __LOCAL_CACHE__ = new MetadataCache();
i think it's okay if we just name this normally (ex. `cache`)
hyperdx
github_2023
typescript
664
hyperdxio
MikeShi42
@@ -13,7 +13,7 @@ import type { ChartConfigWithDateRange } from '@/types'; const DEFAULT_SAMPLE_SIZE = 1e6; -class MetadataCache {
extra export?
hyperdx
github_2023
typescript
658
hyperdxio
wrn14897
@@ -2,4 +2,7 @@ import { getMetadata as _getMetadata } from '@hyperdx/common-utils/dist/metadata import { getClickhouseClient } from '@/clickhouse'; -export const getMetadata = () => _getMetadata(getClickhouseClient()); +const _metadata = _getMetadata(getClickhouseClient()); + +// TODO: Get rid of this function and directly consume singleton +export const getMetadata = () => _metadata;
the reason this is not a singleton because the client host might be set in the local mode (https://github.com/hyperdxio/hyperdx/blob/53f150685bf1100a18e154bc369a9b5448d9523e/packages/app/src/clickhouse.ts#L27-L40)
hyperdx
github_2023
typescript
658
hyperdxio
wrn14897
@@ -0,0 +1,497 @@ +import { useCallback, useEffect, useRef, useState } from 'react';
I assume these are c+p
hyperdx
github_2023
typescript
658
hyperdxio
wrn14897
@@ -1,25 +1,20 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +// ================================ +// NOTE: +// This file should only hold functions that relate to the clickhouse client +// not specific querying/functionality logic +// please move app-specific functions elsewhere in the app
Thanks for adding the comment
hyperdx
github_2023
typescript
657
hyperdxio
LYHuang
@@ -32,19 +79,66 @@ export function useQueriedChartConfig( console.log('mtViewDDL:', mtViewDDL); query = await renderMTViewConfig(); } - if (query == null) { - query = await renderChartConfig(config, getMetadata()); + + const queries: ChSql[] = await Promise.all( + splitChartConfigs(config).map(c => renderChartConfig(c, getMetadata())), + ); + + const resultSets = await Promise.all( + queries.map(async query => { + const resp = await clickhouseClient.query<'JSON'>({ + query: query.sql, + query_params: query.params, + format: 'JSON', + abort_signal: signal, + connectionId: config.connection, + }); + return resp.json<any>(); + }), + ); + + if (resultSets.length === 1) { + return resultSets[0]; } + // join resultSets + else if (resultSets.length > 1) { + const metaSet = new Map<string, { name: string; type: string }>(); + const tsBucketMap = new Map<string, Record<string, string | number>>(); + for (const resultSet of resultSets) { + // set up the meta data + if (Array.isArray(resultSet.meta)) { + for (const meta of resultSet.meta) { + const key = meta.name; + if (!metaSet.has(key)) { + metaSet.set(key, meta); + } + } + } - const resultSet = await clickhouseClient.query<'JSON'>({ - query: query.sql, - query_params: query.params, - format: 'JSON', - abort_signal: signal, - connectionId: config.connection, - }); + const timestampColumn = inferTimestampColumn(resultSet.meta ?? []); + if (timestampColumn == null) { + throw new Error('No timestamp column');
Are we also care the case when there is only one resultSet and `resultSet.meta` is missing `timestampColumn`?
hyperdx
github_2023
typescript
657
hyperdxio
MikeShi42
@@ -13,6 +15,49 @@ import { IS_MTVIEWS_ENABLED } from '@/config'; import { buildMTViewSelectQuery } from '@/hdxMTViews'; import { getMetadata } from '@/metadata'; +export const isMetric = (config: ChartConfigWithOptDateRange) => + config.metricTables != null; + +// TODO: apply this to all chart configs +export const setChartSelectsAlias = (config: ChartConfigWithOptDateRange) => { + if (Array.isArray(config.select)) { + if (isMetric(config)) { + return { + ...config, + select: config.select.map(s => ({ + ...s, + alias: `${s.aggFn}(${s.metricName})`, + })), + }; + } + return { + ...config, + select: config.select.map(s => ({ + ...s, + alias: `${s.aggFn}(${s.valueExpression})`, + })), + }; + } + return config; +}; + +export const splitChartConfigs = (config: ChartConfigWithOptDateRange) => { + // only split metric queries for now
what other queries would we want to do this on?
hyperdx
github_2023
typescript
657
hyperdxio
MikeShi42
@@ -13,6 +15,49 @@ import { IS_MTVIEWS_ENABLED } from '@/config'; import { buildMTViewSelectQuery } from '@/hdxMTViews'; import { getMetadata } from '@/metadata'; +export const isMetric = (config: ChartConfigWithOptDateRange) => + config.metricTables != null; + +// TODO: apply this to all chart configs +export const setChartSelectsAlias = (config: ChartConfigWithOptDateRange) => { + if (Array.isArray(config.select)) { + if (isMetric(config)) { + return { + ...config, + select: config.select.map(s => ({ + ...s, + alias: `${s.aggFn}(${s.metricName})`, + })), + }; + } + return {
why are we adding this to non-metrics queries? it's currently breaking the row side panel and it's not clear to me why we need this
hyperdx
github_2023
typescript
657
hyperdxio
MikeShi42
@@ -13,6 +15,49 @@ import { IS_MTVIEWS_ENABLED } from '@/config'; import { buildMTViewSelectQuery } from '@/hdxMTViews'; import { getMetadata } from '@/metadata'; +export const isMetric = (config: ChartConfigWithOptDateRange) => + config.metricTables != null; + +// TODO: apply this to all chart configs
why do we want to overwrite all aliases?
hyperdx
github_2023
typescript
555
hyperdxio
MikeShi42
@@ -1,440 +1,5 @@ -import { - ChSql, - chSql, - ColumnMeta, - convertCHDataTypeToJSType, - filterColumnMetaByType, - JSDataType, - sendQuery, - tableExpr, -} from '@/clickhouse'; +import { getMetadata as _getMetadata } from '@hyperdx/common-utils/dist/metadata'; -import { - ChartConfigWithDateRange, - renderChartConfig, -} from './renderChartConfig'; +import { getClickhouseClient } from '@/clickhouse'; -const DEFAULT_SAMPLE_SIZE = 1e6; - -class MetadataCache { - private cache = new Map<string, any>(); - - // this should be getOrUpdate... or just query to follow react query - get<T>(key: string): T | undefined { - return this.cache.get(key); - } - - async getOrFetch<T>(key: string, query: () => Promise<T>): Promise<T> { - const value = this.get(key) as T | undefined; - if (value != null) { - return value; - } - - // Request a lock - let newValue!: T; - await navigator.locks.request(`MedataCache.${key}`, async lock => { - newValue = await query(); - this.cache.set(key, newValue); - }); - - return newValue; - } - - set<T>(key: string, value: T) { - return this.cache.set(key, value); - } - - // TODO: This needs to be async, and use tanstack query on frontend for cache - // TODO: Implement locks for refreshing - // TODO: Shard cache by time -} - -export type TableMetadata = { - database: string; - name: string; - uuid: string; - engine: string; - is_temporary: number; - data_paths: string[]; - metadata_path: string; - metadata_modification_time: string; - metadata_version: number; - create_table_query: string; - engine_full: string; - as_select: string; - partition_key: string; - sorting_key: string; - primary_key: string; - sampling_key: string; - storage_policy: string; - total_rows: string; - total_bytes: string; - total_bytes_uncompressed: string; - parts: string; - active_parts: string; - total_marks: string; - comment: string; -}; - -export class Metadata { - private cache = new MetadataCache(); - - private static async queryTableMetadata({ - database, - table, - cache, - connectionId, - }: { - database: string; - table: string; - cache: MetadataCache; - connectionId: string; - }) { - return cache.getOrFetch(`${database}.${table}.metadata`, async () => { - const sql = chSql`SELECT * FROM system.tables where database = ${{ String: database }} AND name = ${{ String: table }}`; - const json = await sendQuery<'JSON'>({ - query: sql.sql, - query_params: sql.params, - connectionId, - }).then(res => res.json<TableMetadata>()); - return json.data[0]; - }); - } - - async getColumns({ - databaseName, - tableName, - connectionId, - }: { - databaseName: string; - tableName: string; - connectionId: string; - }) { - return this.cache.getOrFetch<ColumnMeta[]>( - `${databaseName}.${tableName}.columns`, - async () => { - const sql = chSql`DESCRIBE ${tableExpr({ database: databaseName, table: tableName })}`; - const columns = await sendQuery<'JSON'>({ - query: sql.sql, - query_params: sql.params, - connectionId, - }) - .then(res => res.json()) - .then(d => d.data); - return columns as ColumnMeta[]; - }, - ); - } - - async getMaterializedColumnsLookupTable({ - databaseName, - tableName, - connectionId, - }: { - databaseName: string; - tableName: string; - connectionId: string; - }) { - const columns = await this.getColumns({ - databaseName, - tableName, - connectionId, - }); - - // Build up materalized fields lookup table - return new Map( - columns - .filter( - c => - c.default_type === 'MATERIALIZED' || c.default_type === 'DEFAULT', - ) - .map(c => [c.default_expression, c.name]), - ); - } - - async getColumn({ - databaseName, - tableName, - column, - matchLowercase = false, - connectionId, - }: { - databaseName: string; - tableName: string; - column: string; - matchLowercase?: boolean; - connectionId: string; - }): Promise<ColumnMeta | undefined> { - const tableColumns = await this.getColumns({ - databaseName, - tableName, - connectionId, - }); - - return tableColumns.filter(c => { - if (matchLowercase) { - return c.name.toLowerCase() === column.toLowerCase(); - } - - return c.name === column; - })[0]; - } - - async getMapKeys({ - databaseName, - tableName, - column, - maxKeys = 1000, - connectionId, - }: { - databaseName: string; - tableName: string; - column: string; - maxKeys?: number; - connectionId: string; - }) { - const cachedKeys = this.cache.get<string[]>( - `${databaseName}.${tableName}.${column}.keys`, - ); - - if (cachedKeys != null) { - return cachedKeys; - } - - const colMeta = await this.getColumn({ - databaseName, - tableName, - column, - connectionId, - }); - - if (colMeta == null) { - throw new Error( - `Column ${column} not found in ${databaseName}.${tableName}`, - ); - } - - let strategy: 'groupUniqArrayArray' | 'lowCardinalityKeys' = - 'groupUniqArrayArray'; - if (colMeta.type.startsWith('Map(LowCardinality(String)')) { - strategy = 'lowCardinalityKeys'; - } - - let sql: ChSql; - if (strategy === 'groupUniqArrayArray') { - sql = chSql`SELECT groupUniqArrayArray(${{ Int32: maxKeys }})(${{ - Identifier: column, - }}) as keysArr - FROM ${tableExpr({ database: databaseName, table: tableName })}`; - } else { - sql = chSql`SELECT DISTINCT lowCardinalityKeys(arrayJoin(${{ - Identifier: column, - }}.keys)) as key - FROM ${tableExpr({ database: databaseName, table: tableName })} - LIMIT ${{ - Int32: maxKeys, - }}`; - } - - return this.cache.getOrFetch<string[]>( - `${databaseName}.${tableName}.${column}.keys`, - async () => { - const keys = await sendQuery<'JSON'>({ - query: sql.sql, - query_params: sql.params, - connectionId, - clickhouse_settings: { - max_rows_to_read: DEFAULT_SAMPLE_SIZE, - read_overflow_mode: 'break', - }, - }) - .then(res => res.json<Record<string, unknown>>()) - .then(d => { - let output: string[]; - if (strategy === 'groupUniqArrayArray') { - output = d.data[0].keysArr as string[]; - } else { - output = d.data.map(row => row.key) as string[]; - } - - return output.filter(r => r); - }); - return keys; - }, - ); - } - - async getMapValues({ - databaseName, - tableName, - column, - key, - maxValues = 20, - connectionId, - }: { - databaseName: string; - tableName: string; - column: string; - key?: string; - maxValues?: number; - connectionId: string; - }) { - const cachedValues = this.cache.get<string[]>( - `${databaseName}.${tableName}.${column}.${key}.values`, - ); - - if (cachedValues != null) { - return cachedValues; - } - - const sql = key - ? chSql` - SELECT DISTINCT ${{ - Identifier: column, - }}[${{ String: key }}] as value - FROM ${tableExpr({ database: databaseName, table: tableName })} - WHERE value != '' - LIMIT ${{ - Int32: maxValues, - }} - ` - : chSql` - SELECT DISTINCT ${{ - Identifier: column, - }} as value - FROM ${tableExpr({ database: databaseName, table: tableName })} - WHERE value != '' - LIMIT ${{ - Int32: maxValues, - }} - `; - - return this.cache.getOrFetch<string[]>( - `${databaseName}.${tableName}.${column}.${key}.values`, - async () => { - const values = await sendQuery<'JSON'>({ - query: sql.sql, - query_params: sql.params, - connectionId, - clickhouse_settings: { - max_rows_to_read: DEFAULT_SAMPLE_SIZE, - read_overflow_mode: 'break', - }, - }) - .then(res => res.json<Record<string, unknown>>()) - .then(d => d.data.map(row => row.value as string)); - return values; - }, - ); - } - - async getAllFields({ - databaseName, - tableName, - connectionId, - }: { - databaseName: string; - tableName: string; - connectionId: string; - }) { - const fields: Field[] = []; - const columns = await this.getColumns({ - databaseName, - tableName, - connectionId, - }); - - for (const c of columns) { - fields.push({ - path: [c.name], - type: c.type, - jsType: convertCHDataTypeToJSType(c.type), - }); - } - - const mapColumns = filterColumnMetaByType(columns, [JSDataType.Map]) ?? []; - - await Promise.all( - mapColumns.map(async column => { - const keys = await this.getMapKeys({ - databaseName, - tableName, - column: column.name, - connectionId, - }); - - const match = column.type.match(/Map\(.+,\s*(.+)\)/); - const chType = match?.[1] ?? 'String'; // default to string ? - - for (const key of keys) { - fields.push({ - path: [column.name, key], - type: chType, - jsType: convertCHDataTypeToJSType(chType), - }); - } - }), - ); - - return fields; - } - - async getTableMetadata({ - databaseName, - tableName, - connectionId, - }: { - databaseName: string; - tableName: string; - connectionId: string; - }) { - const tableMetadata = await Metadata.queryTableMetadata({ - cache: this.cache, - database: databaseName, - table: tableName, - connectionId, - }); - - return tableMetadata; - } - - async getKeyValues({ - chartConfig, - keys, - limit = 20, - }: { - chartConfig: ChartConfigWithDateRange; - keys: string[]; - limit?: number; - }) { - const sql = await renderChartConfig({ - ...chartConfig, - select: keys - .map((k, i) => `groupUniqArray(${limit})(${k}) AS param${i}`) - .join(', '), - }); - - const json = await sendQuery<'JSON'>({ - query: sql.sql, - query_params: sql.params, - connectionId: chartConfig.connection, - clickhouse_settings: { - max_rows_to_read: DEFAULT_SAMPLE_SIZE, - read_overflow_mode: 'break', - }, - }).then(res => res.json<any>()); - - return Object.entries(json.data[0]).map(([key, value]) => ({ - key: keys[parseInt(key.replace('param', ''))], - value: (value as string[])?.filter(Boolean), // remove nulls - })); - } -} - -export type Field = { - path: string[]; - type: string; - jsType: JSDataType | null; -}; - -export const metadata = new Metadata(); +export const getMetadata = () => _getMetadata(getClickhouseClient());
why did we change this from a singleton? aren't we creating a ton of new metadata objects without reason?
hyperdx
github_2023
typescript
656
hyperdxio
LYHuang
@@ -57,11 +61,59 @@ export function RowOverviewPanel({ return eventAttributes; }, [eventAttributes, isHttpRequest]); + const exceptionValues = useMemo(() => { + const parsedEvents = + firstRow?.__hdx_events_exception_attributes ?? EMPTY_OBJ; + const stacktrace = + parsedEvents?.['exception.stacktrace'] || + parsedEvents?.['exception.parsed_stacktrace']; + + return [ + { + stacktrace: JSON.parse(stacktrace ?? '[]'), + type: parsedEvents?.['exception.type'], + value: + typeof parsedEvents?.['exception.message'] !== 'string' + ? JSON.stringify(parsedEvents?.['exception.message']) + : parsedEvents?.['exception.message'], + mechanism: parsedEvents?.['exception.mechanism'], + }, + ]; + }, [firstRow]); + + const hasException = useMemo(() => { + return ( + Object.keys(firstRow?.__hdx_events_exception_attributes ?? {}).length > 0 + ); + }, [firstRow?.__hdx_events_exception_attributes]); + + const mainContentColumn = getEventBody(source); + const mainContent = isString(firstRow?.['__hdx_body']) + ? firstRow['__hdx_body'] + : firstRow?.['__hdx_body'] !== undefined + ? JSON.stringify(firstRow['__hdx_body']) + : undefined;
if `firstRow['__hdx_body'] = null`, it will return string `null`, unless that is what we want. ``` const mainContent = isString(firstRow?.['__hdx_body']) ? firstRow['__hdx_body'] : firstRow?.['__hdx_body'] !=null // so null and undefined will all pass ? JSON.stringify(firstRow['__hdx_body']) : undefined; ```
hyperdx
github_2023
typescript
656
hyperdxio
LYHuang
@@ -0,0 +1,677 @@ +import React, { useMemo } from 'react'; +import cx from 'classnames'; +import { ErrorBoundary } from 'react-error-boundary'; +import { Button, Text, Tooltip } from '@mantine/core'; +import { Group, Loader } from '@mantine/core'; +import { ColumnDef, Row, Table as TanstackTable } from '@tanstack/react-table'; + +import { StacktraceFrame as TStacktraceFrame } from '@/types'; +import { FormatTime } from '@/useFormatTime'; +import { useSourceMappedFrame } from '@/useSourceMappedFrame'; + +import { Table, TableCellButton } from './Table'; + +import styles from '../../styles/LogSidePanel.module.scss'; + +// https://github.com/TanStack/table/discussions/3192#discussioncomment-3873093 +export const UNDEFINED_WIDTH = 99999; + +export const parseEvents = (__events?: string) => { + try { + return JSON.parse(__events || '[]')[0].fields.reduce( + (acc: any, field: any) => { + try { + acc[field.key] = JSON.parse(field.value); + } catch (e) { + acc[field.key] = field.value; + } + return acc; + }, + {}, + ); + } catch (e) { + return null; + } +}; + +export const getFirstFrame = (frames?: TStacktraceFrame[]) => { + if (!frames || !frames.length) { + return null; + } + + return ( + frames.find(frame => frame.in_app) ?? + frames.find(frame => !!frame.function || !!frame.filename) ?? + frames[0] + ); +}; + +export const StacktraceFrame = ({ + filename, + function: functionName, + lineno, + colno, + isLoading, +}: { + filename: string; + function?: string; + lineno: number; + colno: number; + isLoading?: boolean; +}) => { + return ( + <Group gap="xs" display="inline-flex"> + <div + className="text-slate-200 fs-8" + style={{ + opacity: isLoading ? 0.8 : 1, + filter: isLoading ? 'blur(1px)' : 'none', + }} + > + {filename} + <span className="text-slate-400"> + :{lineno}:{colno} + </span> + <span className="text-slate-400">{' in '}</span> + {functionName && ( + <span + style={{ + background: '#ffffff10', + padding: '0 4px', + borderRadius: 4, + }} + > + {functionName} + </span> + )} + </div> + {isLoading && <Loader size="xs" color="gray" />} + </Group> + ); +}; + +export type StacktraceBreadcrumbCategory = + | 'ui.click' + | 'fetch' + | 'xhr' + | 'console' + | 'navigation' + | string; + +export type StacktraceBreadcrumb = { + type?: string; + level?: string; + event_id?: string; + category?: StacktraceBreadcrumbCategory; + message?: string; + data?: { [key: string]: any }; + timestamp: number; +}; + +export const CollapsibleSection = ({ + title, + children, + initiallyCollapsed, +}: { + title: string; + children: React.ReactNode; + initiallyCollapsed?: boolean; +}) => { + const [collapsed, setCollapsed] = React.useState(initiallyCollapsed ?? false); + + return ( + <div className="my-3"> + <div + className={`d-flex align-items-center mb-1 text-white-hover w-50`} + role="button" + onClick={() => setCollapsed(!collapsed)} + > + <i className={`bi bi-chevron-${collapsed ? 'right' : 'down'} me-2`}></i> + <div className="fs-7 text-slate-200">{title}</div> + </div> + {collapsed ? null : <div className="mb-4">{children}</div>} + </div> + ); +}; + +export const SectionWrapper: React.FC< + React.PropsWithChildren<{ title?: React.ReactNode }> +> = ({ children, title }) => ( + <div className={styles.panelSectionWrapper}> + {title && <div className={styles.panelSectionWrapperTitle}>{title}</div>} + {children} + </div> +); + +/** + * Stacktrace elements + */ +export const StacktraceValue = ({ + label, + value, +}: { + label: React.ReactNode; + value: React.ReactNode; +}) => { + return ( + <div + style={{ + paddingRight: 20, + marginRight: 12, + borderRight: '1px solid #ffffff20', + }} + > + <div className="text-slate-400">{label}</div> + <div className="fs-7">{value}</div> + </div> + ); +}; + +const StacktraceRowExpandButton = ({ + onClick, + isOpen, +}: { + onClick: VoidFunction; + isOpen: boolean; +}) => { + return ( + <TableCellButton + label="" + biIcon={isOpen ? 'chevron-up' : 'chevron-down'} + onClick={onClick} + /> + ); +}; + +export const StacktraceRow = ({ + row, + table, +}: { + row: Row<TStacktraceFrame>; + table: TanstackTable<TStacktraceFrame>; +}) => { + const tableMeta = table.options.meta as { + firstFrameIndex?: number; + }; + + const [lineContextOpen, setLineContextOpen] = React.useState( + row.index === tableMeta.firstFrameIndex, + ); + + const handleToggleContext = React.useCallback(() => { + setLineContextOpen(!lineContextOpen); + }, [lineContextOpen]); + + const frame = row.original; + + const { isLoading, enrichedFrame } = useSourceMappedFrame(frame); + + const augmentedFrame = enrichedFrame ?? frame; + const hasContext = !!augmentedFrame.context_line; + + return ( + <> + <div + className={cx( + 'w-100 py-2 px-4 d-flex justify-content-between align-items-center', + { [styles.stacktraceRowInteractive]: hasContext }, + )} + onClick={handleToggleContext} + > + <div> + {!augmentedFrame.in_app && ( + <Tooltip + label="in_app: false" + position="top" + withArrow + color="gray" + > + <i + className="bi bi-box-seam text-slate-400 me-2" + title="in_app: false" + /> + </Tooltip> + )} + {augmentedFrame && ( + <StacktraceFrame + colno={augmentedFrame.colno} + filename={augmentedFrame.filename} + lineno={augmentedFrame.lineno} + function={augmentedFrame.function} + isLoading={isLoading} + /> + )} + </div> + {hasContext && ( + <StacktraceRowExpandButton + onClick={handleToggleContext} + isOpen={lineContextOpen} + /> + )} + </div> + + {lineContextOpen && hasContext && ( + <pre className={styles.lineContext}> + {augmentedFrame.pre_context?.map((line, i) => ( + <div key={line + i}> + <span className={styles.lineContextLineNo}> + {(augmentedFrame.lineno ?? 0) - + (augmentedFrame.pre_context?.length ?? 0) + + i} + </span> + {line} + </div> + ))} + {augmentedFrame.context_line && ( + <div className={styles.lineContextCurrentLine}> + <span className={styles.lineContextLineNo}> + {augmentedFrame.lineno} + </span> + {augmentedFrame.context_line} + </div> + )} + {augmentedFrame.post_context?.map((line, i) => ( + <div key={line + i}> + <span className={styles.lineContextLineNo}> + {augmentedFrame.lineno + i + 1} + </span> + {line} + </div> + ))} + </pre> + )} + </> + ); +}; + +export const stacktraceColumns: ColumnDef<TStacktraceFrame>[] = [ + { + accessorKey: 'filename', + cell: StacktraceRow, + }, +]; + +/** + * Breadcrumbs + */ + +const Url = ({ url }: { url?: string }) => ( + <span className="text-slate-300" title={url}> + {url} + </span> +); + +const StatusChip = React.memo(({ status }: { status?: number }) => { + if (!status) { + return null; + } + const className = + status >= 500 + ? 'text-danger bg-danger' + : status >= 400 + ? 'text-warning bg-warning' + : 'text-success bg-success'; + return ( + <span + className={`badge lh-base rounded-5 bg-opacity-10 fw-normal ${className}`} + > + {status} + </span> + ); +}); + +const LevelChip = React.memo(({ level }: { level?: string }) => { + if (!level) { + return null; + } + const className = level.includes('error') + ? 'text-danger bg-danger' + : level.includes('warn') || level.includes('warning') + ? 'text-warning bg-warning' + : 'text-slate-300 bg-grey'; + + return ( + <span + className={`badge lh-base rounded-5 bg-opacity-10 fw-normal ${className}`} + > + {level} + </span> + ); +}); + +export const breadcrumbColumns: ColumnDef<StacktraceBreadcrumb>[] = [ + { + accessorKey: 'category', + header: 'Category', + size: 180, + cell: ({ row }) => ( + <span className="text-slate-300 d-flex align-items-center gap-2"> + {row.original.category} + {row.original.category === 'console' && ( + <LevelChip level={row.original.level} /> + )} + {row.original.category === 'fetch' || + row.original.category === 'xhr' ? ( + <StatusChip status={row.original.data?.status_code} /> + ) : null} + </span> + ), + }, + { + accessorKey: 'message', + header: 'Data', + size: UNDEFINED_WIDTH, + cell: ({ row }) => { + // fetch + if ( + row.original.data && + (row.original.category === 'fetch' || row.original.category === 'xhr') + ) { + const { method, url } = row.original.data; + return ( + <div className="text-truncate"> + <span>{method} </span> + <span className="text-slate-300" title={url}> + <Url url={url} /> + </span> + </div> + ); + } + + // navigation + if (row.original.category === 'navigation' && row.original.data) { + const { from, to } = row.original.data; + return ( + <div className="text-truncate"> + <span className="text-slate-300" title={from}> + <Url url={from} /> + </span> + <span>{' → '}</span> + <span className="text-slate-300" title={to}> + <Url url={to} /> + </span> + </div> + ); + } + + // console + if (row.original.category === 'console') { + const { message } = row.original; + return ( + <pre + className="text-slate-300 mb-0 text-truncate fs-8" + title={message} + > + {message} + </pre> + ); + } + + if (row.original.message) { + return <div className="text-truncate">{row.original.message}</div>; + } + + return <span className="text-slate-500">Empty</span>; + }, + }, + { + header: 'Timestamp', + size: 220, + cell: ({ row }) => ( + <span className="text-slate-500"> + <FormatTime value={row.original.timestamp * 1000} format="withMs" /> + </span> + ), + }, +]; + +export const useShowMoreRows = <T extends object>({ + rows, + maxRows = 5, +}: { + rows: T[]; + maxRows?: number; +}) => { + const [isExpanded, setIsExpanded] = React.useState(false); + + const visibleRows = React.useMemo(() => { + return isExpanded ? rows : rows.slice(0, maxRows); + }, [rows, isExpanded, maxRows]); + + const hiddenRowsCount = React.useMemo<number | null>(() => { + const length = rows.length ?? 0; + return length > maxRows ? length - maxRows : null; + }, [rows.length, maxRows]); + + const handleToggleMoreRows = React.useCallback(() => { + setIsExpanded(!isExpanded); + }, [isExpanded]); + + return { visibleRows, hiddenRowsCount, handleToggleMoreRows, isExpanded }; +}; + +export type ExceptionValues = { + type: string; + value: string; + mechanism?: { + type: string; + handled: boolean; + data?: { + // TODO: Are these fields dynamic? + function?: string; + handler?: string; + target?: string; + }; + }; + stacktrace?: { + frames: TStacktraceFrame[]; + }; +}[]; + +export const ExceptionSubpanel = ({ + logData, + breadcrumbs, + exceptionValues, +}: { + logData?: any; + breadcrumbs?: StacktraceBreadcrumb[]; + exceptionValues: ExceptionValues; +}) => { + const firstException = exceptionValues[0]; + + const shouldShowSourceMapFtux = useMemo(() => { + return firstException?.stacktrace?.frames?.some( + f => + f.filename.startsWith('http://') || f.filename.startsWith('https://'), + ); + }, [firstException?.stacktrace?.frames]); + + const stacktraceFrames = useMemo(() => { + if (!firstException?.stacktrace?.frames) { + return []; + } + return firstException?.stacktrace.frames.slice().reverse(); + }, [firstException]);
nit: prob use `firstException?.stacktrace?.frames` at here.
hyperdx
github_2023
typescript
652
hyperdxio
MikeShi42
@@ -118,6 +120,14 @@ function getConfig(source: TSource, traceId: string) { }, ] : []), + ...(alias.SpanAttributes
I think it's preferable in general performance-wise for us to specifically pull out the values `http.url`, etc. This in theory will also help if we do things like materialized columns on those values and whatnot.
hyperdx
github_2023
typescript
652
hyperdxio
MikeShi42
@@ -391,19 +404,24 @@ export function DBTraceWaterfallChartContainer({ const start = startOffset - minOffset; const end = start + tookMs; - const body = result.Body; - const serviceName = result.ServiceName; - const type = result.type; + const { Body: body, ServiceName: serviceName, id, type } = result; - const id = result.id; + // Extract HTTP-related logic + const eventAttributes = result.SpanAttributes || {}; + const hasHttpAttributes =
Just realizing, I think we want to condition this on spanKind client? that way it's only shown for HTTP requests from a client (since servers should be handled elsewhere in the logic iirc)
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -816,36 +816,51 @@ function translateMetricChartConfig( whereLanguage: 'sql', }; } else if (metricType === MetricsDataType.Sum && metricName) { + const time_bucket_col = '`__hdx_time_bucket2`'; + const value_high_col = '`__hdx_value_high`'; + const value_high_prev_col = '`__hdx_value_high_prev`'; + const time_expr = timeBucketExpr({ + interval: chartConfig.granularity || 'auto', + timestampValueExpression: + chartConfig.timestampValueExpression || 'TimeUnix', + dateRange: chartConfig.dateRange, + alias: '__hdx_time_bucket2', + }); return { ...restChartConfig, with: [ { name: 'RawSum', - sql: chSql`SELECT *, - any(Value) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevValue, - any(AttributesHash) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributesHash, - IF(AggregationTemporality = 1, - Value,IF(Value - PrevValue < 0 AND AttributesHash = PrevAttributesHash, Value, - IF(AttributesHash != PrevAttributesHash, 0, Value - PrevValue))) as Rate + sql: chSql`SELECT ${time_expr}, AttributesHash, last_value(a.Value) AS ${value_high_col}, + any(${value_high_col}) OVER(PARTITION BY AttributesHash ORDER BY ${time_bucket_col} ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS ${value_high_prev_col}, + ${value_high_col} - ${value_high_prev_col} AS Value, any(ResourceAttributes) AS ResourceAttributes, any(ResourceSchemaUrl) AS ResourceSchemaUrl, + any(ScopeName) AS ScopeName, any(ScopeVersion) AS ScopeVersion, any(ScopeAttributes) AS ScopeAttributes, any(ScopeDroppedAttrCount) AS ScopeDroppedAttrCount, + any(ScopeSchemaUrl) AS ScopeSchemaUrl, any(ServiceName) AS ServiceName, any(MetricName) AS MetricName, any(MetricDescription) AS MetricDescription, + any(MetricUnit) AS MetricUnit, any(Attributes) AS Attributes, any(StartTimeUnix) AS StartTimeUnix, any(Flags) AS Flags, any(AggregationTemporality) AS AggregationTemporality, + any(IsMonotonic) AS IsMonotonic FROM ( - SELECT *, - cityHash64(mapConcat(ScopeAttributes, ResourceAttributes, Attributes)) AS AttributesHash + SELECT SUM(Rate) OVER (PARTITION BY AttributesHash ORDER BY AttributesHash, TimeUnix ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Value, * + FROM ( + SELECT *, cityHash64(mapConcat(ScopeAttributes, ResourceAttributes, Attributes)) AS AttributesHash, + any(AttributesHash) OVER (ORDER BY AttributesHash, TimeUnix ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributesHash, + any(Value) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevValue, + IF(AggregationTemporality = 1, Value, + IF(Value - PrevValue < 0 AND AttributesHash = PrevAttributesHash, Value, + IF(AttributesHash != PrevAttributesHash, 0, Value - PrevValue))) AS Rate FROM ${renderFrom({ from: { ...from, tableName: metricTables[MetricsDataType.Sum] } })} - WHERE MetricName = '${metricName}' - ORDER BY AttributesHash, TimeUnix ASC - ) `, - }, - ], - select: [ - { - ..._select, - valueExpression: 'Rate', + WHERE MetricName = '${metricName}') + ORDER BY AttributesHash, TimeUnix) a + GROUP BY AttributesHash, ${time_bucket_col} + ORDER BY AttributesHash, ${time_bucket_col} + `,
style: this sql is a bit hard to read. I wonder if we could do multiple CTEs and also break each select fields into one line
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -104,28 +104,32 @@ describe('renderChartConfig', () => { const generatedSql = await renderChartConfig(config, mockMetadata); const actual = parameterizedQueryToSql(generatedSql); expect(actual).toBe( - 'WITH RawSum AS (SELECT *,\n' + - ' any(Value) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevValue,\n' + - ' any(AttributesHash) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributesHash,\n' + - ' IF(AggregationTemporality = 1,\n' + - ' Value,IF(Value - PrevValue < 0 AND AttributesHash = PrevAttributesHash, Value,\n' + - ' IF(AttributesHash != PrevAttributesHash, 0, Value - PrevValue))) as Rate\n' + + 'WITH RawSum AS (SELECT toStartOfInterval(toDateTime(TimeUnix), INTERVAL 5 minute) AS `__hdx_time_bucket2`, AttributesHash, last_value(a.Value) AS `__hdx_value_high`,\n' +
I suspect we don't need a unit test for this given the integration tests cover most of the use cases
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -816,36 +816,51 @@ function translateMetricChartConfig( whereLanguage: 'sql', }; } else if (metricType === MetricsDataType.Sum && metricName) { + const time_bucket_col = '`__hdx_time_bucket2`'; + const value_high_col = '`__hdx_value_high`'; + const value_high_prev_col = '`__hdx_value_high_prev`'; + const time_expr = timeBucketExpr({ + interval: chartConfig.granularity || 'auto', + timestampValueExpression: + chartConfig.timestampValueExpression || 'TimeUnix', + dateRange: chartConfig.dateRange, + alias: '__hdx_time_bucket2', + }); return { ...restChartConfig, with: [ { name: 'RawSum', - sql: chSql`SELECT *, - any(Value) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevValue, - any(AttributesHash) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributesHash, - IF(AggregationTemporality = 1, - Value,IF(Value - PrevValue < 0 AND AttributesHash = PrevAttributesHash, Value, - IF(AttributesHash != PrevAttributesHash, 0, Value - PrevValue))) as Rate + sql: chSql`SELECT ${time_expr}, AttributesHash, last_value(a.Value) AS ${value_high_col}, + any(${value_high_col}) OVER(PARTITION BY AttributesHash ORDER BY ${time_bucket_col} ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS ${value_high_prev_col}, + ${value_high_col} - ${value_high_prev_col} AS Value, any(ResourceAttributes) AS ResourceAttributes, any(ResourceSchemaUrl) AS ResourceSchemaUrl, + any(ScopeName) AS ScopeName, any(ScopeVersion) AS ScopeVersion, any(ScopeAttributes) AS ScopeAttributes, any(ScopeDroppedAttrCount) AS ScopeDroppedAttrCount, + any(ScopeSchemaUrl) AS ScopeSchemaUrl, any(ServiceName) AS ServiceName, any(MetricName) AS MetricName, any(MetricDescription) AS MetricDescription, + any(MetricUnit) AS MetricUnit, any(Attributes) AS Attributes, any(StartTimeUnix) AS StartTimeUnix, any(Flags) AS Flags, any(AggregationTemporality) AS AggregationTemporality, + any(IsMonotonic) AS IsMonotonic FROM ( - SELECT *, - cityHash64(mapConcat(ScopeAttributes, ResourceAttributes, Attributes)) AS AttributesHash + SELECT SUM(Rate) OVER (PARTITION BY AttributesHash ORDER BY AttributesHash, TimeUnix ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Value, * + FROM ( + SELECT *, cityHash64(mapConcat(ScopeAttributes, ResourceAttributes, Attributes)) AS AttributesHash, + any(AttributesHash) OVER (ORDER BY AttributesHash, TimeUnix ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributesHash, + any(Value) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevValue, + IF(AggregationTemporality = 1, Value, + IF(Value - PrevValue < 0 AND AttributesHash = PrevAttributesHash, Value, + IF(AttributesHash != PrevAttributesHash, 0, Value - PrevValue))) AS Rate FROM ${renderFrom({ from: { ...from, tableName: metricTables[MetricsDataType.Sum] } })} - WHERE MetricName = '${metricName}' - ORDER BY AttributesHash, TimeUnix ASC - ) `, - }, - ], - select: [ - { - ..._select, - valueExpression: 'Rate', + WHERE MetricName = '${metricName}') + ORDER BY AttributesHash, TimeUnix) a
style: maybe we can rename this sub table to something other than 'a'
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -816,36 +816,51 @@ function translateMetricChartConfig( whereLanguage: 'sql', }; } else if (metricType === MetricsDataType.Sum && metricName) { + const time_bucket_col = '`__hdx_time_bucket2`'; + const value_high_col = '`__hdx_value_high`'; + const value_high_prev_col = '`__hdx_value_high_prev`'; + const time_expr = timeBucketExpr({ + interval: chartConfig.granularity || 'auto', + timestampValueExpression: + chartConfig.timestampValueExpression || 'TimeUnix', + dateRange: chartConfig.dateRange, + alias: '__hdx_time_bucket2', + }); return { ...restChartConfig, with: [ { name: 'RawSum', - sql: chSql`SELECT *, - any(Value) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevValue, - any(AttributesHash) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributesHash, - IF(AggregationTemporality = 1, - Value,IF(Value - PrevValue < 0 AND AttributesHash = PrevAttributesHash, Value, - IF(AttributesHash != PrevAttributesHash, 0, Value - PrevValue))) as Rate + sql: chSql`SELECT ${time_expr}, AttributesHash, last_value(a.Value) AS ${value_high_col},
My understanding of this query is we compute rates and sum them into accumulative values, and then compute rates again. I wonder if its more efficient to use accumulative values at the beginning (if `AggregationTemporality` is 1, then adding values up) given most of sum metrics are likely to be accumulative
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -816,36 +816,80 @@ function translateMetricChartConfig( whereLanguage: 'sql', }; } else if (metricType === MetricsDataType.Sum && metricName) { + const time_bucket_col = '`__hdx_time_bucket2`'; + const value_high_col = '`__hdx_value_high`'; + const value_high_prev_col = '`__hdx_value_high_prev`'; + const time_expr = timeBucketExpr({
style: we use camel-case across the ts codebase :)
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -816,36 +816,80 @@ function translateMetricChartConfig( whereLanguage: 'sql', }; } else if (metricType === MetricsDataType.Sum && metricName) { + const time_bucket_col = '`__hdx_time_bucket2`'; + const value_high_col = '`__hdx_value_high`'; + const value_high_prev_col = '`__hdx_value_high_prev`'; + const time_expr = timeBucketExpr({ + interval: chartConfig.granularity || 'auto', + timestampValueExpression: + chartConfig.timestampValueExpression || 'TimeUnix', + dateRange: chartConfig.dateRange, + alias: '__hdx_time_bucket2',
nit: can be `time_bucket_col`
hyperdx
github_2023
others
650
hyperdxio
wrn14897
@@ -21,15 +21,41 @@ Array [ ] `; +exports[`renderChartConfig Query Metrics calculates min_rate/max_rate correctly for sum metrics: maxSum 1`] = `
🔥 🔥 🔥
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -430,12 +430,23 @@ describe('renderChartConfig', () => { expect(await queryData(query)).toMatchSnapshot(); }); - // FIXME: here are the expected values - // [0, 1, 8, 8, 15, 15, 23, 25, 25, 67] - // [0, 2, 9, 9, 24, 34, 44, 66, 66, 158] - // min -> [15, 52] - // max -> [24, 134] - it.skip('calculates min_rate/max_rate correctly for sum metrics', async () => { + it('calculates min_rate/max_rate correctly for sum metrics', async () => { + // Based on the data inserted in the fixture, the expected stream of values
Thanks for adding more context here
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -816,36 +816,80 @@ function translateMetricChartConfig( whereLanguage: 'sql', }; } else if (metricType === MetricsDataType.Sum && metricName) { + const time_bucket_col = '`__hdx_time_bucket2`'; + const value_high_col = '`__hdx_value_high`'; + const value_high_prev_col = '`__hdx_value_high_prev`'; + const time_expr = timeBucketExpr({ + interval: chartConfig.granularity || 'auto', + timestampValueExpression: + chartConfig.timestampValueExpression || 'TimeUnix', + dateRange: chartConfig.dateRange, + alias: '__hdx_time_bucket2', + }); return { ...restChartConfig, with: [ { - name: 'RawSum', - sql: chSql`SELECT *, - any(Value) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevValue, - any(AttributesHash) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributesHash, - IF(AggregationTemporality = 1, - Value,IF(Value - PrevValue < 0 AND AttributesHash = PrevAttributesHash, Value, - IF(AttributesHash != PrevAttributesHash, 0, Value - PrevValue))) as Rate - FROM ( - SELECT *, - cityHash64(mapConcat(ScopeAttributes, ResourceAttributes, Attributes)) AS AttributesHash + name: 'Source', + sql: chSql` + SELECT + *, + cityHash64(mapConcat(ScopeAttributes, ResourceAttributes, Attributes)) AS AttributesHash, + any(AttributesHash) OVER (ORDER BY AttributesHash, TimeUnix ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributesHash, + any(Value) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevValue, + IF(AggregationTemporality = 1, Value, + IF(Value - PrevValue < 0 AND AttributesHash = PrevAttributesHash, Value, + IF(AttributesHash != PrevAttributesHash, 0, Value - PrevValue))) AS Rate FROM ${renderFrom({ from: { ...from, tableName: metricTables[MetricsDataType.Sum] } })} - WHERE MetricName = '${metricName}' - ORDER BY AttributesHash, TimeUnix ASC - ) `, + WHERE MetricName = '${metricName}'`,
I think we want to do the time range filtering here so db won't scan the whole table (`TimeUnix` is the partition key)
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -443,23 +445,23 @@ async function timeFilterExpr({ ); } + const startTimeCond = includedDataInterval + ? chSql`toStartOfInterval(fromUnixTimestamp64Milli(${{ Int64: startTime }}), INTERVAL ${includedDataInterval}) - INTERVAL ${includedDataInterval}` + : chSql`fromUnixTimestamp64Milli(${{ Int64: startTime }})`; + + const endTimeCond = includedDataInterval + ? chSql`toStartOfInterval(fromUnixTimestamp64Milli(${{ Int64: endTime }}), INTERVAL ${includedDataInterval}) + INTERVAL ${includedDataInterval}` + : chSql`fromUnixTimestamp64Milli(${{ Int64: endTime }})`;
style: do you think it would be slightly cleaner if we pass the extended date range instead? since I'd imagine this is only used for metrics
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -872,36 +876,95 @@ async function translateMetricChartConfig( timestampValueExpression: timeBucketCol, }; } else if (metricType === MetricsDataType.Sum && metricName) { + const timeBucketCol = '__hdx_time_bucket2'; + const valueHighCol = '`__hdx_value_high`'; + const valueHighPrevCol = '`__hdx_value_high_prev`'; + const timeExpr = timeBucketExpr({ + interval: chartConfig.granularity || 'auto', + timestampValueExpression: + chartConfig.timestampValueExpression || 'TimeUnix',
style: can use `DEFAULT_METRIC_TABLE_TIME_COLUMN`
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -872,36 +876,95 @@ async function translateMetricChartConfig( timestampValueExpression: timeBucketCol, }; } else if (metricType === MetricsDataType.Sum && metricName) { + const timeBucketCol = '__hdx_time_bucket2'; + const valueHighCol = '`__hdx_value_high`'; + const valueHighPrevCol = '`__hdx_value_high_prev`'; + const timeExpr = timeBucketExpr({ + interval: chartConfig.granularity || 'auto', + timestampValueExpression: + chartConfig.timestampValueExpression || 'TimeUnix', + dateRange: chartConfig.dateRange, + alias: timeBucketCol, + }); + + // Render the where clause to limit data selection on the source CTE but also search forward/back one + // bucket window to ensure that there is enough data to compute a reasonable value on the ends of the
do we need to extend both ends or only the start ?
hyperdx
github_2023
typescript
650
hyperdxio
wrn14897
@@ -872,36 +876,95 @@ async function translateMetricChartConfig( timestampValueExpression: timeBucketCol, }; } else if (metricType === MetricsDataType.Sum && metricName) { + const timeBucketCol = '__hdx_time_bucket2'; + const valueHighCol = '`__hdx_value_high`'; + const valueHighPrevCol = '`__hdx_value_high_prev`'; + const timeExpr = timeBucketExpr({ + interval: chartConfig.granularity || 'auto', + timestampValueExpression: + chartConfig.timestampValueExpression || 'TimeUnix', + dateRange: chartConfig.dateRange, + alias: timeBucketCol, + }); + + // Render the where clause to limit data selection on the source CTE but also search forward/back one + // bucket window to ensure that there is enough data to compute a reasonable value on the ends of the + // series. + const where = await renderWhere( + { + ...chartConfig, + from: { + ...from, + tableName: metricTables[MetricsDataType.Gauge], + }, + filters: [ + { + type: 'sql', + condition: `MetricName = '${metricName}'`, + }, + ], + includedDataInterval: + chartConfig.granularity === 'auto' && + Array.isArray(chartConfig.dateRange) + ? convertDateRangeToGranularityString(chartConfig.dateRange, 60) + : chartConfig.granularity, + }, + metadata, + ); + return { ...restChartConfig, with: [ { - name: 'RawSum', - sql: chSql`SELECT *, - any(Value) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevValue, - any(AttributesHash) OVER (ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevAttributesHash, - IF(AggregationTemporality = 1, - Value,IF(Value - PrevValue < 0 AND AttributesHash = PrevAttributesHash, Value, - IF(AttributesHash != PrevAttributesHash, 0, Value - PrevValue))) as Rate - FROM ( - SELECT *, - cityHash64(mapConcat(ScopeAttributes, ResourceAttributes, Attributes)) AS AttributesHash + name: 'Source', + sql: chSql` + SELECT + *, + cityHash64(mapConcat(ScopeAttributes, ResourceAttributes, Attributes)) AS AttributesHash, + IF(AggregationTemporality = 1, + SUM(Value) OVER (PARTITION BY AttributesHash ORDER BY AttributesHash, TimeUnix ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), + deltaSum(Value) OVER (PARTITION BY AttributesHash ORDER BY AttributesHash, TimeUnix ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
double check this still handles counter reset. it's very clean and I'm kinda surprised
hyperdx
github_2023
typescript
626
hyperdxio
wrn14897
@@ -61,6 +65,8 @@ export default function SessionSubpanel({ start: Date; end: Date; initialTs?: number; + where?: string; + whereLanguage?: 'sql' | 'lucene';
style: can use `SearchConditionLanguage`
hyperdx
github_2023
typescript
648
hyperdxio
teeohhem
@@ -142,6 +145,17 @@ const Line = React.memo( // mounting it for potentially hundreds of lines const { ref, hovered } = useHover<HTMLDivElement>(); + const isCollapsibleString = + isString(value) && + (value.split('\n').length > 1 || + value.length > STRING_COLLAPSE_THRESHOLD); + const collapseString = isCollapsibleString + ? (value.split('\n').length > 1 ? value.split('\n')[0] : value).substring( + 0, + COLLAPSE_STRING_SIZE, + ) + '...' + : ''; +
It would be neat if we could use mantine's Spoiler component for this: https://mantine.dev/core/spoiler/
hyperdx
github_2023
typescript
647
hyperdxio
wrn14897
@@ -167,6 +167,19 @@ export function LogTableModelForm({ connectionId={connectionId} /> </FormRow> + <FormRow
Can we move this to 'optional fields'?
hyperdx
github_2023
typescript
642
hyperdxio
teeohhem
@@ -152,7 +152,8 @@ export const SessionEventList = ({ const isNavigation = spanName === 'routeChange' || spanName === 'documentLoad'; - const isError = event.severity_text === 'error' || statusCode > 499; + const isError = + event.severity_text.toLowerCase() === 'error' || statusCode > 499;
nit: `event.severity_text?.toLowerCase()`
hyperdx
github_2023
typescript
625
hyperdxio
wrn14897
@@ -484,3 +496,41 @@ export default function SessionsPage() { } SessionsPage.getLayout = withAppNav; + +function SessionSetupInstructions() { + return ( + <> + <Stack w={500} mx="auto" mt="xl" gap="xxs"> + <i className="bi bi-laptop text-slate-600 fs-1"></i> + <Text c="gray" fw={500} size="xs"> + Instructions + </Text> + <Text c="gray"> + You can set up Session Replays when the HyperDX Otel Collector is + used. + </Text> + <Text c="gray" fw={500} mt="sm"> + 1. Create a new source with <strong>Session</strong> type + </Text> + <Text c="dimmed" size="xs"> + Go to Team Settings, click <strong>Add Source</strong> under Sources + section, and select <strong>Session</strong> as the source type. + </Text> + <Text c="gray" fw={500} mt="sm"> + 2. Choose the <strong>rrweb</strong> table + </Text> + <Text c="dimmed" size="xs"> + Select the <strong>rrweb</strong> table from the dropdown, and select + the corresponding trace source. + </Text> + + <Text c="gray" fw={500} mt="sm"> + 3. Start recording sessions + </Text> + <Text c="dimmed" size="xs"> + Install the HyperDX Browser Integration to start recording sessions.
do we want to point the doc link?
hyperdx
github_2023
typescript
625
hyperdxio
wrn14897
@@ -481,3 +493,41 @@ export default function SessionsPage() { } SessionsPage.getLayout = withAppNav; + +function SessionSetupInstructions() { + return ( + <> + <Stack w={500} mx="auto" mt="xl" gap="xxs"> + <i className="bi bi-laptop text-slate-600 fs-1"></i> + <Text c="gray" fw={500} size="xs"> + Instructions + </Text> + <Text c="gray"> + You can set up Session Replays when the HyperDX Otel Collector is
Looks good!
hyperdx
github_2023
typescript
637
hyperdxio
wrn14897
@@ -61,10 +58,45 @@ function getTableBody(tableModel: TSource) { } } -function getConfig(source: TSource, traceId: string) { +function useSortKey(source: TSource): string { + let rowSortTimestamp = source.timestampValueExpression; + const { data: sourceCols } = useColumns({
I think we want to use `useAllFields` (https://github.com/hyperdxio/hyperdx/blob/e80630c1075d381f91dde43301dfceb92b95100e/packages/app/src/hooks/useMetadata.tsx#L38) instead
hyperdx
github_2023
typescript
637
hyperdxio
wrn14897
@@ -61,10 +58,45 @@ function getTableBody(tableModel: TSource) { } } -function getConfig(source: TSource, traceId: string) { +function useSortKey(source: TSource): string { + let rowSortTimestamp = source.timestampValueExpression; + const { data: sourceCols } = useColumns({ + connectionId: source.connection, + ...source.from, + }); + const defaultSelections = new Set( + source.defaultTableSelectExpression?.split(',').map(col => { + return col.trim(); + }), + ); + for (const col of sourceCols ?? []) { + if (defaultSelections.has(col.name) && col.type.startsWith('DateTime')) {
use `jsType` for type comparison
hyperdx
github_2023
typescript
637
hyperdxio
wrn14897
@@ -61,10 +58,45 @@ function getTableBody(tableModel: TSource) { } } -function getConfig(source: TSource, traceId: string) { +function useSortKey(source: TSource): string { + let rowSortTimestamp = source.timestampValueExpression; + const { data: sourceCols } = useColumns({ + connectionId: source.connection, + ...source.from, + }); + const defaultSelections = new Set( + source.defaultTableSelectExpression?.split(',').map(col => { + return col.trim(); + }), + ); + for (const col of sourceCols ?? []) { + if (defaultSelections.has(col.name) && col.type.startsWith('DateTime')) { + rowSortTimestamp = col.name; + break; + } + } + return source.kind === SourceKind.Trace + ? source.timestampValueExpression
we still need to keep `getDisplayedTimestampValueExpression`
hyperdx
github_2023
typescript
637
hyperdxio
wrn14897
@@ -61,10 +58,45 @@ function getTableBody(tableModel: TSource) { } } -function getConfig(source: TSource, traceId: string) { +function useSortKey(source: TSource): string { + let rowSortTimestamp = source.timestampValueExpression; + const { data: sourceCols } = useColumns({ + connectionId: source.connection, + ...source.from, + }); + const defaultSelections = new Set( + source.defaultTableSelectExpression?.split(',').map(col => { + return col.trim(); + }), + ); + for (const col of sourceCols ?? []) { + if (defaultSelections.has(col.name) && col.type.startsWith('DateTime')) { + rowSortTimestamp = col.name; + break; + } + } + return source.kind === SourceKind.Trace + ? source.timestampValueExpression + : rowSortTimestamp;
we want to keep `getDisplayedTimestampValueExpression(source)` as a fallback option