repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
hyperdx
github_2023
typescript
559
hyperdxio
wrn14897
@@ -1,14 +1,28 @@ import { z } from 'zod'; import { SavedSearchSchema } from '@/common/commonTypes'; +import Alert from '@/models/alert'; import { SavedSearch } from '@/models/savedSearch'; type SavedSearchWithoutId = Omit<z.infer<typeof SavedSearchSchema>, 'id'>; -export function getSavedSearches(teamId: string) { - return SavedSearch.find({ +export async function getSavedSearches(teamId: string) { + const savedSearches = await SavedSearch.find({ team: teamId, }); + const alerts = await Promise.all( + savedSearches.map(({ _id }) => + Alert.find({ savedSearch: _id }, { __v: 0 }), + ), + );
perf: we don't need to fire multiple requests to get savedSearch alerts here. Instead, we can query all savedSearch alerts given the team id: ``` const alerts = Alert.find({ team: teamId, savedSearch: { $exists: true, $ne: null } }, { __v: 0, ONLY SELECT THINGS USED BY THE APP}) ``` We can run this alerts query and the savedSearches one concurrently. Then, we can either send an alerts lookup table or join them with saverSearches back
hyperdx
github_2023
typescript
559
hyperdxio
wrn14897
@@ -756,8 +759,18 @@ function DBSearchPage() { setValue('orderBy', defaultOrderBy); }, [inputSource, inputSourceObj, defaultOrderBy]); + const [isAlertModalOpen, { open: openAlertModal, close: closeAlertModal }] = + useDisclosure(); + return ( <Flex direction="column" h="100vh" style={{ overflow: 'hidden' }}> + {isAlertModalOpen && (
can we add a feature flag for alerting components? or using `IS_DEV` flag to expose it in dev environment only
hyperdx
github_2023
typescript
559
hyperdxio
wrn14897
@@ -1,6 +1,6 @@ import { z } from 'zod'; -import { DashboardSchema, SavedSearchSchema } from './commonTypes'; +import { AlertSchema, DashboardSchema, SavedSearchSchema } from './commonTypes';
style: we need to add `AlertSchema` to common-utils later. I'm fine to import it here in commonTypes temp
hyperdx
github_2023
typescript
559
hyperdxio
wrn14897
@@ -203,8 +203,12 @@ export const AlertIntervalSchema = z.union([ export type AlertInterval = z.infer<typeof AlertIntervalSchema>; +export const zAlertChannelType = z.literal('webhook');
we need to add a changeset to this package (for every changes)
hyperdx
github_2023
typescript
549
hyperdxio
wrn14897
@@ -0,0 +1,106 @@ +import { useMemo } from 'react'; +import { Accordion } from '@mantine/core'; + +import { TSource } from '@/commonTypes'; +import { useQueriedChartConfig } from '@/hooks/useChartConfig'; +import { getEventBody, getFirstTimestampValueExpression } from '@/source'; + +import { DBRowJsonViewer } from './DBRowJsonViewer'; + +export function useRowData({ + source, + rowId, +}: { + source: TSource; + rowId: string | undefined | null; +}) { + const eventBodyExpr = getEventBody(source); + + const searchedTraceIdExpr = source.traceIdExpression; + + const severityTextExpr = + source.severityTextExpression || source.statusCodeExpression; + + return useQueriedChartConfig( + { + connection: source.connection, + select: [ + { + valueExpression: '*', + }, + { + valueExpression: getFirstTimestampValueExpression( + source.timestampValueExpression, + ), + alias: '__hdx_timestamp', + }, + ...(eventBodyExpr + ? [ + { + valueExpression: eventBodyExpr, + alias: '__hdx_body', + }, + ] + : []), + ...(searchedTraceIdExpr + ? [ + { + valueExpression: searchedTraceIdExpr, + alias: '__hdx_trace_id', + }, + ] + : []), + ...(severityTextExpr + ? [ + { + valueExpression: severityTextExpr, + alias: '__hdx_severity_text', + }, + ] + : []), + ], + where: rowId ?? '0=1', + from: source.from, + limit: { limit: 1 }, + }, + { + queryKey: ['row_side_panel', rowId, source], + enabled: rowId != null, + }, + ); +} + +export function RowOverviewPanel({ + source, + rowId, +}: { + source: TSource; + rowId: string | undefined | null; +}) { + const { data, isLoading, isError } = useRowData({ source, rowId }); + + const firstRow = useMemo(() => { + const firstRow = { ...(data?.data?.[0] ?? {}) }; + if (!firstRow) { + return null; + } + return firstRow; + }, [data]); + + const resourceAttributes = useMemo(() => { + return firstRow['ResourceAttributes'] || {};
We should use the `resourceAttributesExpression` from the `source` model instead of hardcoding the field here
hyperdx
github_2023
typescript
549
hyperdxio
wrn14897
@@ -0,0 +1,106 @@ +import { useMemo } from 'react'; +import { Accordion } from '@mantine/core'; + +import { TSource } from '@/commonTypes'; +import { useQueriedChartConfig } from '@/hooks/useChartConfig'; +import { getEventBody, getFirstTimestampValueExpression } from '@/source'; + +import { DBRowJsonViewer } from './DBRowJsonViewer'; + +export function useRowData({ + source, + rowId, +}: { + source: TSource; + rowId: string | undefined | null; +}) { + const eventBodyExpr = getEventBody(source); + + const searchedTraceIdExpr = source.traceIdExpression; + + const severityTextExpr = + source.severityTextExpression || source.statusCodeExpression; + + return useQueriedChartConfig( + { + connection: source.connection, + select: [ + { + valueExpression: '*', + }, + { + valueExpression: getFirstTimestampValueExpression( + source.timestampValueExpression, + ), + alias: '__hdx_timestamp', + }, + ...(eventBodyExpr + ? [ + { + valueExpression: eventBodyExpr, + alias: '__hdx_body', + }, + ] + : []), + ...(searchedTraceIdExpr + ? [ + { + valueExpression: searchedTraceIdExpr, + alias: '__hdx_trace_id', + }, + ] + : []), + ...(severityTextExpr + ? [ + { + valueExpression: severityTextExpr, + alias: '__hdx_severity_text', + }, + ] + : []), + ], + where: rowId ?? '0=1', + from: source.from, + limit: { limit: 1 }, + }, + { + queryKey: ['row_side_panel', rowId, source], + enabled: rowId != null, + }, + ); +} + +export function RowOverviewPanel({ + source, + rowId, +}: { + source: TSource; + rowId: string | undefined | null; +}) { + const { data, isLoading, isError } = useRowData({ source, rowId }); + + const firstRow = useMemo(() => { + const firstRow = { ...(data?.data?.[0] ?? {}) }; + if (!firstRow) { + return null; + } + return firstRow; + }, [data]); + + const resourceAttributes = useMemo(() => { + return firstRow['ResourceAttributes'] || {}; + }, [firstRow]); + + return ( + <div> + <Accordion defaultValue={['resourceAttributes']} multiple> + <Accordion.Item value="resourceAttributes"> + <Accordion.Control>Resource Attributes</Accordion.Control>
Not for now. I wonder if we also want to show LogAttributes (Log type) and SpanAttributes (Trace type) 🤔
hyperdx
github_2023
typescript
549
hyperdxio
wrn14897
@@ -0,0 +1,122 @@ +import { useMemo } from 'react'; +import { Accordion } from '@mantine/core'; + +import { TSource } from '@/commonTypes'; +import { useQueriedChartConfig } from '@/hooks/useChartConfig'; +import { getEventBody, getFirstTimestampValueExpression } from '@/source'; + +import { DBRowJsonViewer } from './DBRowJsonViewer'; + +export function useRowData({ + source, + rowId, +}: { + source: TSource; + rowId: string | undefined | null; +}) { + const eventBodyExpr = getEventBody(source); + + const searchedTraceIdExpr = source.traceIdExpression; + + const severityTextExpr = + source.severityTextExpression || source.statusCodeExpression; + + return useQueriedChartConfig( + { + connection: source.connection, + select: [ + { + valueExpression: '*', + }, + { + valueExpression: getFirstTimestampValueExpression( + source.timestampValueExpression, + ), + alias: '__hdx_timestamp', + }, + ...(eventBodyExpr + ? [ + { + valueExpression: eventBodyExpr, + alias: '__hdx_body', + }, + ] + : []), + ...(searchedTraceIdExpr + ? [ + { + valueExpression: searchedTraceIdExpr, + alias: '__hdx_trace_id', + }, + ] + : []), + ...(severityTextExpr + ? [ + { + valueExpression: severityTextExpr, + alias: '__hdx_severity_text', + }, + ] + : []), + ], + where: rowId ?? '0=1', + from: source.from, + limit: { limit: 1 }, + }, + { + queryKey: ['row_side_panel', rowId, source], + enabled: rowId != null, + }, + ); +} + +export function RowOverviewPanel({ + source, + rowId, +}: { + source: TSource; + rowId: string | undefined | null; +}) { + const { data, isLoading, isError } = useRowData({ source, rowId }); + + const firstRow = useMemo(() => { + const firstRow = { ...(data?.data?.[0] ?? {}) }; + if (!firstRow) { + return null; + } + return firstRow; + }, [data]); + + const resourceAttributes = useMemo(() => { + return firstRow[source.resourceAttributesExpression!] || {}; + }, [firstRow, source.resourceAttributesExpression]); + + const eventAttributes = useMemo(() => { + return firstRow[source.eventAttributesExpression!] || {}; + }, [firstRow, source.eventAttributesExpression]); + + return ( + <div className="flex-grow-1 bg-body overflow-auto"> + <Accordion + defaultValue={['resourceAttributes', 'eventAttributes']} + multiple + > + <Accordion.Item value="resourceAttributes"> + <Accordion.Control>Resource Attributes</Accordion.Control> + <Accordion.Panel> + <DBRowJsonViewer data={resourceAttributes} /> + </Accordion.Panel> + </Accordion.Item> + + <Accordion.Item value="eventAttributes"> + <Accordion.Control> + {source.kind === 'log' ? 'Span' : 'Trace'} Attributes
This should be ``` {source.kind === 'log' ? 'Log' : 'Span'} ``` check out https://github.com/hyperdxio/hyperdx/blob/509256f4c9baa489c7a86f14daa4a4aa8b386942/packages/app/src/source.ts#L259-L297
hyperdx
github_2023
others
566
hyperdxio
wrn14897
@@ -41,12 +41,15 @@ dev-int-build: .PHONY: dev-int dev-int: - docker compose -p int -f ./docker-compose.ci.yml run --rm api dev:int $(FILE)
The dx should be the same (run `make dev-int FILE=blabla`)
hyperdx
github_2023
others
566
hyperdxio
wrn14897
@@ -29,50 +29,24 @@ services: - ./docker/clickhouse/local/config.xml:/etc/clickhouse-server/config.xml - ./docker/clickhouse/local/users.xml:/etc/clickhouse-server/users.xml restart: on-failure - # ports: - # - 8123:8123 # http api + ports: + - 8123:8123 # http api # - 9000:9000 # native networks: - internal db: image: mongo:5.0.14-focal command: --port 29999 - # ports: - # - 29999:29999 + ports: + - 29999:29999 networks: - internal redis: image: redis:7.0.11-alpine - # ports: - # - 6379:6379 - networks: - - internal - api:
move this out of docker (since we need to test `common-utils` together)
hyperdx
github_2023
typescript
566
hyperdxio
teeohhem
@@ -346,7 +346,7 @@ export class ClickhouseClient { } else if (isNode) { const { createClient } = await import('@clickhouse/client'); const _client = createClient({ - host: this.host, + url: this.host,
just curious about this change...related to the PR or a drive-by fix?
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,64 @@ +{{- if .Values.otel.enabled }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "hdx-oss.fullname" . }}-otel-collector + labels: + {{- include "hdx-oss.labels" . | nindent 4 }} + app: otel-collector +spec: + replicas: 1 + selector: + matchLabels: + {{- include "hdx-oss.selectorLabels" . | nindent 6 }} + app: otel-collector + template: + metadata: + labels: + {{- include "hdx-oss.selectorLabels" . | nindent 8 }} + app: otel-collector + spec: + containers: + - name: otel-collector + image: "{{ .Values.images.otelCollector.repository }}:{{ .Values.images.otelCollector.tag }}" + ports: + - containerPort: {{ .Values.otel.port }} + - containerPort: {{ .Values.otel.nativePort }} + - containerPort: {{ .Values.otel.grpcPort }} + - containerPort: {{ .Values.otel.httpPort }} + - containerPort: {{ .Values.otel.healthPort }} + env: + - name: CLICKHOUSE_SERVER_ENDPOINT + value: "{{ include "hdx-oss.fullname" . }}-clickhouse:{{ .Values.clickhouse.port }}" + - name: HYPERDX_LOG_LEVEL + value: {{ .Values.hyperdx.logLevel }} + - name: INGESTOR_API_URL + value: "http://ingestor:8002"
`INGESTOR_API_URL` is no longer used. it's deprecated
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,158 @@ +<?xml version="1.0"?> +<clickhouse> + <logger> + <level>debug</level> + <console>true</console> + <log remove="remove"/> + <errorlog remove="remove"/> + </logger> + + <listen_host>0.0.0.0</listen_host> + <http_port>8123</http_port> + <tcp_port>9000</tcp_port> + <interserver_http_host>ch-server</interserver_http_host> + <interserver_http_port>9009</interserver_http_port>
I think we can remove the interserver setup since the clickhouse is going to be a single instance
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,158 @@ +<?xml version="1.0"?> +<clickhouse> + <logger> + <level>debug</level> + <console>true</console> + <log remove="remove"/> + <errorlog remove="remove"/> + </logger> + + <listen_host>0.0.0.0</listen_host> + <http_port>8123</http_port> + <tcp_port>9000</tcp_port> + <interserver_http_host>ch-server</interserver_http_host> + <interserver_http_port>9009</interserver_http_port> + + <max_connections>4096</max_connections> + <keep_alive_timeout>64</keep_alive_timeout> + <max_concurrent_queries>100</max_concurrent_queries> + <uncompressed_cache_size>8589934592</uncompressed_cache_size> + <mark_cache_size>5368709120</mark_cache_size> + + <path>/var/lib/clickhouse/</path> + <tmp_path>/var/lib/clickhouse/tmp/</tmp_path> + <user_files_path>/var/lib/clickhouse/user_files/</user_files_path> + + <users_config>users.xml</users_config> + <default_profile>default</default_profile> + <default_database>default</default_database> + <timezone>UTC</timezone> + <mlock_executable>false</mlock_executable> + + <!-- Query log. Used only for queries with setting log_queries = 1. --> + <query_log> + <database>system</database> + <table>query_log</table> + <flush_interval_milliseconds>7500</flush_interval_milliseconds> + </query_log> + + <!-- Metric log contains rows with current values of ProfileEvents, CurrentMetrics collected with "collect_interval_milliseconds" interval. --> + <metric_log> + <database>system</database> + <table>metric_log</table> + <flush_interval_milliseconds>7500</flush_interval_milliseconds> + <collect_interval_milliseconds>1000</collect_interval_milliseconds> + </metric_log> + + <!-- + Asynchronous metric log contains values of metrics from + system.asynchronous_metrics. + --> + <asynchronous_metric_log> + <database>system</database> + <table>asynchronous_metric_log</table> + <!-- + Asynchronous metrics are updated once a minute, so there is + no need to flush more often. + --> + <flush_interval_milliseconds>7000</flush_interval_milliseconds> + </asynchronous_metric_log> + + <!-- + OpenTelemetry log contains OpenTelemetry trace spans. + --> + <opentelemetry_span_log> + <!-- + The default table creation code is insufficient, this <engine> spec + is a workaround. There is no 'event_time' for this log, but two times, + start and finish. It is sorted by finish time, to avoid inserting + data too far away in the past (probably we can sometimes insert a span + that is seconds earlier than the last span in the table, due to a race + between several spans inserted in parallel). This gives the spans a + global order that we can use to e.g. retry insertion into some external + system. + --> + <engine> + engine MergeTree + partition by toYYYYMM(finish_date) + order by (finish_date, finish_time_us, trace_id) + </engine> + <database>system</database> + <table>opentelemetry_span_log</table> + <flush_interval_milliseconds>7500</flush_interval_milliseconds> + </opentelemetry_span_log> + + + <!-- Crash log. Stores stack traces for fatal errors. + This table is normally empty. --> + <crash_log> + <database>system</database> + <table>crash_log</table> + + <partition_by /> + <flush_interval_milliseconds>1000</flush_interval_milliseconds> + </crash_log> + + <!-- Profiling on Processors level. --> + <processors_profile_log> + <database>system</database> + <table>processors_profile_log</table> + + <partition_by>toYYYYMM(event_date)</partition_by> + <flush_interval_milliseconds>7500</flush_interval_milliseconds> + </processors_profile_log> + + <!-- Uncomment if use part log. + Part log contains information about all actions with parts in MergeTree tables (creation, deletion, merges, downloads).--> + <part_log> + <database>system</database> + <table>part_log</table> + <partition_by>toYYYYMM(event_date)</partition_by> + <flush_interval_milliseconds>7500</flush_interval_milliseconds> + </part_log> + + <!-- Trace log. Stores stack traces collected by query profilers. + See query_profiler_real_time_period_ns and query_profiler_cpu_time_period_ns settings. --> + <trace_log> + <database>system</database> + <table>trace_log</table> + + <partition_by>toYYYYMM(event_date)</partition_by> + <flush_interval_milliseconds>7500</flush_interval_milliseconds> + </trace_log> + + <!-- Query thread log. Has information about all threads participated in query execution. + Used only for queries with setting log_query_threads = 1. --> + <query_thread_log> + <database>system</database> + <table>query_thread_log</table> + <partition_by>toYYYYMM(event_date)</partition_by> + <flush_interval_milliseconds>7500</flush_interval_milliseconds> + </query_thread_log> + + <!-- Query views log. Has information about all dependent views associated with a query. + Used only for queries with setting log_query_views = 1. --> + <query_views_log> + <database>system</database> + <table>query_views_log</table> + <partition_by>toYYYYMM(event_date)</partition_by> + <flush_interval_milliseconds>7500</flush_interval_milliseconds> + </query_views_log> + + <remote_servers> + <hdx_cluster> + <shard> + <replica> + <host>ch-server</host> + <port>9000</port> + </replica> + </shard> + </hdx_cluster> + </remote_servers>
can remove this `remove_servers` section as well
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,45 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "hdx-oss.fullname" . }}-mongodb + labels: + {{- include "hdx-oss.labels" . | nindent 4 }} + app: mongodb +spec: + replicas: 1 + selector: + matchLabels: + {{- include "hdx-oss.selectorLabels" . | nindent 6 }} + app: mongodb + template: + metadata: + labels: + {{- include "hdx-oss.selectorLabels" . | nindent 8 }} + app: mongodb + spec: + containers: + - name: mongodb + image: "{{ .Values.images.mongodb.repository }}:{{ .Values.images.mongodb.tag }}" + ports: + - containerPort: {{ .Values.mongodb.port }} + volumeMounts: + - name: mongodb-data + mountPath: /data/db + volumes: + - name: mongodb-data + persistentVolumeClaim: + claimName: {{ include "hdx-oss.fullname" . }}-mongodb +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "hdx-oss.fullname" . }}-mongodb + labels: + {{- include "hdx-oss.labels" . | nindent 4 }} +spec: + ports: + - port: {{ .Values.mongodb.port }} + targetPort: {{ .Values.mongodb.port }} + selector: + {{- include "hdx-oss.selectorLabels" . | nindent 4 }} + app: mongodb
Should this be `ClusterIP` type ? Theoretically, the service should be accessed internally only
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,120 @@ +{{- if .Values.clickhouse.enabled }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "hdx-oss.fullname" . }}-clickhouse + labels: + {{- include "hdx-oss.labels" . | nindent 4 }} + app: clickhouse +spec: + replicas: 1 + selector: + matchLabels: + {{- include "hdx-oss.selectorLabels" . | nindent 6 }} + app: clickhouse + template: + metadata: + labels: + {{- include "hdx-oss.selectorLabels" . | nindent 8 }} + app: clickhouse + spec: + containers: + - name: clickhouse + image: "{{ .Values.images.clickhouse.repository }}:{{ .Values.images.clickhouse.tag }}" + ports: + - containerPort: {{ .Values.clickhouse.port }} + - containerPort: {{ .Values.clickhouse.nativePort }} + env: + - name: CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT + value: "1" + volumeMounts: + - name: config + mountPath: /etc/clickhouse-server/config.xml + subPath: config.xml + - name: users + mountPath: /etc/clickhouse-server/users.xml + subPath: users.xml + - name: data + mountPath: /var/lib/clickhouse + - name: logs + mountPath: /var/log/clickhouse-server + volumes: + - name: config + configMap: + name: {{ include "hdx-oss.fullname" . }}-clickhouse-config + - name: users + configMap: + name: {{ include "hdx-oss.fullname" . }}-clickhouse-users + - name: data + emptyDir: {} + - name: logs + emptyDir: {} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "hdx-oss.fullname" . }}-clickhouse + labels: + {{- include "hdx-oss.labels" . | nindent 4 }} +spec: + ports:
Internal only
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,51 @@ +<?xml version="1.0"?> +<clickhouse> + <profiles> + <default> + <max_memory_usage>10000000000</max_memory_usage> + <use_uncompressed_cache>0</use_uncompressed_cache> + <load_balancing>in_order</load_balancing> + <log_queries>1</log_queries> + </default> + </profiles> + + <users> + <default> + <password></password> + <profile>default</profile> + <networks> + <ip>::/0</ip> + </networks> + <quota>default</quota> + </default>
Couple things I have in mind for initializing clickhouse instance: 1. Clickhouse instance should not be public 2. Lock the networks to be local or intenal network ``` <default> <password></password> <profile>default</profile> <networks> <ip>::1</ip> <ip>127.0.0.1</ip> <ip>INTERNAL SUBNET</ip> </networks> <quota>default</quota> </default> ``` 3. Maybe we want to create two separate accounts (one for `otel-colleoct` with write access, and one for `app` with readonly access). The RBAC for `app` service should look like ``` <app> <password>XXX</password> <networks> <ip>INTERNAL SUBNET</ip> </networks> <profile>readonly</profile> <quota>default</quota> <grants> <query>GRANT SHOW ON *.*</query> <query>GRANT SELECT ON system.*</query> <query>GRANT SELECT ON default.*</query> </grants> </app> ``` 3. For better DX, I wonder if we want to insert the default source for users (or how they would know the clickhouse host ?).
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,51 @@ +<?xml version="1.0"?> +<clickhouse> + <profiles> + <default> + <max_memory_usage>10000000000</max_memory_usage> + <use_uncompressed_cache>0</use_uncompressed_cache> + <load_balancing>in_order</load_balancing> + <log_queries>1</log_queries> + </default> + </profiles> + + <users> + <default> + <password></password> + <profile>default</profile> + <networks> + <ip>::/0</ip> + </networks> + <quota>default</quota> + </default> + <api> + <password>api</password> + <profile>default</profile> + <networks> + <ip>::/0</ip> + </networks> + <quota>default</quota> + </api> + <worker> + <password>worker</password> + <profile>default</profile> + <networks> + <ip>::/0</ip> + </networks> + <quota>default</quota> + </worker>
can remove this `worker` user
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,93 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "hdx-oss.fullname" . }}-app + labels: + {{- include "hdx-oss.labels" . | nindent 4 }} + app: app +spec: + replicas: 1 + selector: + matchLabels: + {{- include "hdx-oss.selectorLabels" . | nindent 6 }} + app: app + template: + metadata: + labels: + {{- include "hdx-oss.selectorLabels" . | nindent 8 }} + app: app + spec: + initContainers: + - name: wait-for-mongodb + image: busybox + command: ['sh', '-c', 'until nc -z {{ include "hdx-oss.fullname" . }}-mongodb {{ .Values.mongodb.port }}; do echo waiting for mongodb; sleep 2; done;']
oh this is interesting. learned new stuff today :)
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,93 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "hdx-oss.fullname" . }}-app + labels: + {{- include "hdx-oss.labels" . | nindent 4 }} + app: app +spec: + replicas: 1 + selector: + matchLabels: + {{- include "hdx-oss.selectorLabels" . | nindent 6 }} + app: app + template: + metadata: + labels: + {{- include "hdx-oss.selectorLabels" . | nindent 8 }} + app: app + spec: + initContainers: + - name: wait-for-mongodb + image: busybox + command: ['sh', '-c', 'until nc -z {{ include "hdx-oss.fullname" . }}-mongodb {{ .Values.mongodb.port }}; do echo waiting for mongodb; sleep 2; done;'] + containers: + - name: app + image: "{{ .Values.images.hdx.repository }}:{{ .Values.images.hdx.tag }}" + ports: + - name: app-port + containerPort: {{ .Values.hyperdx.appPort }} + - name: api-port + containerPort: {{ .Values.hyperdx.apiPort }} + envFrom: + - configMapRef: + name: {{ include "hdx-oss.fullname" . }}-app-config + env: + - name: HYPERDX_API_KEY + valueFrom: + secretKeyRef: + name: {{ include "hdx-oss.fullname" . }}-secrets + key: api-key +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "hdx-oss.fullname" . }}-app + labels: + {{- include "hdx-oss.labels" . | nindent 4 }} +spec: + type: LoadBalancer + ports: + - port: {{ .Values.hyperdx.appPort }} + targetPort: {{ .Values.hyperdx.appPort }} + name: app + selector: + {{- include "hdx-oss.selectorLabels" . | nindent 4 }} + app: app +--- +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ include "hdx-oss.fullname" . }}-app-ingress + labels: + {{- include "hdx-oss.labels" . | nindent 4 }} + annotations: + nginx.ingress.kubernetes.io/rewrite-target: /$1 + nginx.ingress.kubernetes.io/use-regex: "true" + {{- if .Values.hyperdx.ingress.tls.enabled }} + nginx.ingress.kubernetes.io/ssl-redirect: "true" + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + {{- end }} + nginx.ingress.kubernetes.io/proxy-body-size: {{ .Values.hyperdx.ingress.proxyBodySize | quote }} + nginx.ingress.kubernetes.io/proxy-connect-timeout: {{ .Values.hyperdx.ingress.proxyConnectTimeout | quote }} + nginx.ingress.kubernetes.io/proxy-send-timeout: {{ .Values.hyperdx.ingress.proxySendTimeout | quote }} + nginx.ingress.kubernetes.io/proxy-read-timeout: {{ .Values.hyperdx.ingress.proxyReadTimeout | quote }}
imo this is useful for the production deployment. we should doc the tls setup so people can deploy hyperdx to their own custom domain
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,62 @@ +{{- if .Values.otel.enabled }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "hdx-oss.fullname" . }}-otel-collector + labels: + {{- include "hdx-oss.labels" . | nindent 4 }} + app: otel-collector +spec: + replicas: 1 + selector: + matchLabels: + {{- include "hdx-oss.selectorLabels" . | nindent 6 }} + app: otel-collector + template: + metadata: + labels: + {{- include "hdx-oss.selectorLabels" . | nindent 8 }} + app: otel-collector + spec: + containers: + - name: otel-collector + image: "{{ .Values.images.otelCollector.repository }}:{{ .Values.images.otelCollector.tag }}" + ports: + - containerPort: {{ .Values.otel.port }} + - containerPort: {{ .Values.otel.nativePort }} + - containerPort: {{ .Values.otel.grpcPort }} + - containerPort: {{ .Values.otel.httpPort }} + - containerPort: {{ .Values.otel.healthPort }} + env: + - name: CLICKHOUSE_SERVER_ENDPOINT + value: "{{ include "hdx-oss.fullname" . }}-clickhouse:{{ .Values.clickhouse.port }}"
we need to change `clickhouse.port` to `clickhouse.nativePort`. Also I realized we need to inject `CLICKHOUSE_USER` and `CLICKHOUSE_PASSWORD` (with otelcollector user)
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,74 @@ +global: + imageRegistry: "" + imagePullSecrets: [] + +hyperdx: + apiKey: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + apiPort: 8000 + appPort: 3000 + appUrl: "http://localhost" + logLevel: "info" + usageStatsEnabled: true + ingress: + host: "localhost" # Production domain + proxyBodySize: "100m" + proxyConnectTimeout: "60" + proxySendTimeout: "60" + proxyReadTimeout: "60" + tls: + enabled: false + secretName: "hyperdx-tls" + +mongodb: + port: 27017 + +redis: + port: 6379 + +clickhouse: + port: 8123 + nativePort: 9000 + enabled: true + persistence: + enabled: true + dataSize: 10Gi + logSize: 5Gi + config: + users: + appUserPassword: "hyperdx" + apiUserPassword: "hyperdx" + otelUserPassword: "otelcollectorpass" + +otel: + port: 13133 + nativePort: 24225 + grpcPort: 4317 + httpPort: 4318 + healthPort: 8888 + enabled: true + +images: + hdx: + repository: hyperdx/app + tag: dev
``` hdx: repository: hyperdx/hyperdx tag: 2-beta ```
hyperdx
github_2023
others
553
hyperdxio
wrn14897
@@ -0,0 +1,74 @@ +global: + imageRegistry: "" + imagePullSecrets: [] + +hyperdx: + apiKey: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + apiPort: 8000 + appPort: 3000 + appUrl: "http://localhost" + logLevel: "info" + usageStatsEnabled: true + ingress: + host: "localhost" # Production domain + proxyBodySize: "100m" + proxyConnectTimeout: "60" + proxySendTimeout: "60" + proxyReadTimeout: "60" + tls: + enabled: false + secretName: "hyperdx-tls" + +mongodb: + port: 27017 + +redis: + port: 6379 + +clickhouse: + port: 8123 + nativePort: 9000 + enabled: true + persistence: + enabled: true + dataSize: 10Gi + logSize: 5Gi + config: + users: + appUserPassword: "hyperdx" + apiUserPassword: "hyperdx" + otelUserPassword: "otelcollectorpass" + +otel: + port: 13133 + nativePort: 24225 + grpcPort: 4317 + httpPort: 4318 + healthPort: 8888 + enabled: true + +images: + hdx: + repository: hyperdx/app + tag: dev + pullPolicy: IfNotPresent + redis: + repository: redis + tag: 7.0.11-alpine + mongodb: + repository: mongo + tag: 5.0.14-focal + otelCollector: + repository: otel/opentelemetry-collector-contrib + tag: 0.113.0
we should use hyperdx custom-built image. Or we would need to add otel-collector configmap (from `docker/otel-collector/config.yaml`) ``` otelCollector: repository: hyperdx/hyperdx-otel-collector tag: 2-beta ``` The another problem is the image uses fixed `default` clickhouse user. I will update the otel collector config build later.
hyperdx
github_2023
typescript
548
hyperdxio
LYHuang
@@ -14,21 +21,76 @@ import { } from '@/utils/logParser'; import { redisClient } from '@/utils/redis'; -import { SavedChartConfig, Tile } from './common/commonTypes'; -import { DisplayType } from './common/DisplayType'; -import * as config from './config'; -import { AlertInput } from './controllers/alerts'; -import { getTeam } from './controllers/team'; -import { findUserByEmail } from './controllers/user'; -import { mongooseConnection } from './models'; -import { AlertInterval, AlertSource, AlertThresholdType } from './models/alert'; -import Server from './server'; - const MOCK_USER = { email: 'fake@deploysentinel.com', password: 'TacoCat!2#4X', }; +const DEFAULT_LOGS_TABLE = 'default.otel_logs'; +const DEFAULT_TRACES_TABLE = 'default.otel_traces';
Do we have a plan to move all these default variable in one file? So it can be easier to ref or setup with environment variables in future.
hyperdx
github_2023
typescript
548
hyperdxio
LYHuang
@@ -52,7 +50,7 @@ const getAlerts = () => team: ITeam; savedSearch?: EnhancedSavedSearch; dashboard?: IDashboard; - }>(['team', 'savedSearch', 'savedSearch.source', 'dashboard']); + }>(['team', 'savedSearch', 'dashboard']);
`savedSearch.source` is still using in line 648: `const source = await Source.findById(alert.savedSearch.source);` Just want double check if it is fine.
hyperdx
github_2023
typescript
548
hyperdxio
LYHuang
@@ -100,10 +98,11 @@ export const buildChartLink = ({ }; export const doesExceedThreshold = ( - isThresholdTypeAbove: boolean, + thresholdType: AlertThresholdType,
Will the alert crash if customer set up an alert with unknown type?
hyperdx
github_2023
typescript
542
hyperdxio
MikeShi42
@@ -4,6 +4,7 @@ import { ObjectId } from 'mongodb'; import { z } from 'zod'; import { validateRequest } from 'zod-express-middleware'; +import { TileSchema } from '@/common/commonTypes';
nit: should we be calling these /v2/? (filename)
hyperdx
github_2023
typescript
542
hyperdxio
teeohhem
@@ -45,7 +45,7 @@ export default class Server { } async start() {
is async necessary anymore?
hyperdx
github_2023
typescript
538
hyperdxio
MikeShi42
@@ -0,0 +1,36 @@ +import { useQuery } from '@tanstack/react-query'; + +import { sendQuery } from '@/clickhouse'; +import { + ChartConfigWithDateRange, + renderChartConfig, +} from '@/renderChartConfig'; + +export function useExplainQuery(
just noting we probably want to eventually DRY out with https://github.com/hyperdxio/hyperdx/blob/83f9997c03a31c73fd7dfbf03a83d1a34909a483/packages/app/src/BenchmarkPage.tsx, but nothing important rn imo
hyperdx
github_2023
typescript
538
hyperdxio
MikeShi42
@@ -0,0 +1,36 @@ +import { useQuery } from '@tanstack/react-query'; + +import { sendQuery } from '@/clickhouse'; +import { + ChartConfigWithDateRange, + renderChartConfig, +} from '@/renderChartConfig'; + +export function useExplainQuery( + config: ChartConfigWithDateRange, + options?: { enabled?: boolean }, +) { + const { + data: explainData, + isLoading, + error, + } = useQuery({ + queryKey: ['explain', config], + queryFn: async ({ signal }) => { + const query = await renderChartConfig(config); + const response = await sendQuery<'JSONEachRow'>({ + query: `EXPLAIN ESTIMATE ${query.sql}`, + query_params: query.params, + format: 'JSONEachRow', + abort_signal: signal, + connectionId: config.connection, + }); + return response.json(); + }, + enabled: options?.enabled, + retry: false, + staleTime: 1000 * 60, + }); + + return { explainResults: explainData, isLoading, error };
more of a style note: my pref usually is to return the react hook results as-is and let the consumer rename/grab the data as it sees fit.
hyperdx
github_2023
typescript
538
hyperdxio
MikeShi42
@@ -0,0 +1,36 @@ +import { useQuery } from '@tanstack/react-query'; + +import { sendQuery } from '@/clickhouse'; +import { + ChartConfigWithDateRange, + renderChartConfig, +} from '@/renderChartConfig'; + +export function useExplainQuery( + config: ChartConfigWithDateRange, + options?: { enabled?: boolean },
another style note: I've found that keeping options as something like: https://github.com/hyperdxio/hyperdx/blob/83f9997c03a31c73fd7dfbf03a83d1a34909a483/packages/app/src/BenchmarkPage.tsx#L87 and then spreading it below It's helpful as it allows the callers to easily add more react query option overrides in the future. It helps with consistency so all hooks can support the same set of overrides more or less.
hyperdx
github_2023
typescript
538
hyperdxio
MikeShi42
@@ -761,6 +770,14 @@ export function DBSqlRowTable({ return { ...config, select, additionalKeysLength }; }, [primaryKey, partitionKey, config]); + const { + explainResults, + isLoading: isExplainLoading, + error: explainError, + } = useExplainQuery(mergedConfig ?? config, {
A pattern I've found to make components more reusable is to have the querying hooks be its own component, this way we can always pass in a config object into any component, and have it render the results that we want (similar to `SearchTotalCount` component for example, or for any of our chart components). The intent here is that if we want to show estimates elsewhere (ex in a chart editor), it'd just be a few lines to slap the component in.
hyperdx
github_2023
typescript
538
hyperdxio
MikeShi42
@@ -0,0 +1,19 @@ +export interface ExplainResult { + database: string; + table: string; + parts: string; + rows: string; + marks: string; +} + +interface QueryExplanationProps { + explainResults?: Array<ExplainResult>; +} + +export function QueryExplanation({ explainResults }: QueryExplanationProps) { + if (!explainResults?.length) return null; + + const rows = explainResults[0].rows; + + return rows ? <div className="fs-8">Read Rows: {rows}</div> : null;
If possible, we're trying to move towards the mantine library instead and away from bootstrap (not an explicit goal to retire BS rn but hopefully we can deprecate its usage over time). The equivalent is something like `<Text size="xs">`
hyperdx
github_2023
typescript
538
hyperdxio
MikeShi42
@@ -0,0 +1,36 @@ +import { useQuery } from '@tanstack/react-query'; + +import { sendQuery } from '@/clickhouse'; +import { + ChartConfigWithDateRange, + renderChartConfig, +} from '@/renderChartConfig'; + +export function useExplainQuery( + config: ChartConfigWithDateRange, + options?: { enabled?: boolean }, +) { + const { + data: explainData, + isLoading, + error, + } = useQuery({
I think for the lint you'll want something like `useQuery<ExplainResult[]>` here or something like that
hyperdx
github_2023
typescript
538
hyperdxio
MikeShi42
@@ -23,6 +23,7 @@ import { extractColumnReference, JSDataType, } from '@/clickhouse'; +import { useExplainQuery } from '@/hooks/useExplainQuery';
unused import?
hyperdx
github_2023
typescript
538
hyperdxio
MikeShi42
@@ -458,226 +458,235 @@ export const RawLogTable = memo( }); return ( - <div - className="overflow-auto h-100 fs-8 bg-inherit" - onScroll={e => { - fetchMoreOnBottomReached(e.target as HTMLDivElement); - - if (e.target != null) { - const { scrollTop } = e.target as HTMLDivElement; - onScroll?.(scrollTop); - } - }} - ref={tableContainerRef} - // Fixes flickering scroll bar: https://github.com/TanStack/virtual/issues/426#issuecomment-1403438040 - // style={{ overflowAnchor: 'none' }} - > - <table - className="w-100 bg-inherit" - id={tableId} - style={{ tableLayout: 'fixed' }} + <> + {!isLoading && explainResults && (
looking at the UI a bit more, I wonder if it makes sense being next to `SearchTotalCount` in the DBSearch page as opposed to being part of the table component? thinking something like <img width="853" alt="image" src="https://github.com/user-attachments/assets/611e05cb-b3e2-4264-987d-42815712b842" />
hyperdx
github_2023
others
530
hyperdxio
wrn14897
@@ -134,6 +134,9 @@ services: PORT: ${HYPERDX_API_PORT} REDIS_URL: redis://redis:6379 USAGE_STATS_ENABLED: ${USAGE_STATS_ENABLED:-false} + # Event deltas create large SQL queries so we need to increase + # the max header size for proxied SQL requests + NODE_OPTIONS: '--max-http-header-size=131072'
should we also set this up for prod build? or this is only for dev for now
hyperdx
github_2023
typescript
530
hyperdxio
wrn14897
@@ -258,50 +258,84 @@ export default function DBDeltaChart({ config: ChartConfigWithOptDateRange; outlierSqlCondition: string; }) { - const { data: outlierData } = useQueriedChartConfig({ + const { data: outlierPartIds } = useQueriedChartConfig({ ...config, - select: '*', + select: '_part, _part_offset', filters: [ ...(config.filters ?? []), { type: 'sql', condition: `${outlierSqlCondition}`, }, ], - // TODO: Introduce sampling granules for large results - // filters: [ - // ...(config.filters ?? []), - // { - // type: 'sql', - // condition: 'indexHint()', - // }, - // ], orderBy: [{ ordering: 'DESC', valueExpression: 'rand()' }], limit: { limit: 1000 }, }); - const { data: inlierData } = useQueriedChartConfig({ + const { data: outlierData } = useQueriedChartConfig( + { + ...config, + select: '*', + filters: [ + ...(config.filters ?? []), + { + type: 'sql', + condition: `${outlierSqlCondition}`, + }, + { + type: 'sql', + condition: `indexHint((_part, _part_offset) IN (${outlierPartIds?.data + ?.map((r: any) => `('${r._part}', ${r._part_offset})`) + ?.join(',')}))`, + }, + ], + orderBy: [{ ordering: 'DESC', valueExpression: 'rand()' }], + limit: { limit: 1000 },
nit: I'd create a const for this sampling size number
hyperdx
github_2023
typescript
532
hyperdxio
MikeShi42
@@ -35,6 +35,9 @@ mongoose.connection.on('reconnectFailed', () => { }); export const connectDB = async () => { + if (config.MONGO_URI == null) {
nit: i suspect a truthy check would be mildly better, not by much though
hyperdx
github_2023
others
532
hyperdxio
MikeShi42
@@ -1,8 +1,13 @@ #!/bin/bash +export FRONTEND_URL="${FRONTEND_URL:-${HYPERDX_APP_URL:-http://localhost}:${HYPERDX_APP_PORT:-8080}}" + +echo "Visit the HyperDX UI at $FRONTEND_URL" +echo "" + # Use concurrently to run both the API and App servers npx concurrently \ "--kill-others" \ "--names=API,APP" \ - "APP_TYPE=api PORT=${HYPERDX_API_PORT:-8000} node -r /app/api/node_modules/@hyperdx/node-opentelemetry/build/src/tracing /app/api/build/index.js" \ - "/app/app/node_modules/.bin/next start -p ${HYPERDX_APP_PORT:-8080}" + "PORT=${HYPERDX_API_PORT:-8000} HYPERDX_APP_PORT=${HYPERDX_APP_PORT:-8080} node -r /app/api/node_modules/@hyperdx/node-opentelemetry/build/src/tracing /app/api/build/index.js" \
can follow up in another pr, but can we add concurrently to dependencies so we don't get `npm warn exec The following package was not found and will be installed: concurrently@9.1.0` on boot? it also makes new boots really slow
hyperdx
github_2023
others
532
hyperdxio
MikeShi42
@@ -1,8 +1,13 @@ #!/bin/bash +export FRONTEND_URL="${FRONTEND_URL:-${HYPERDX_APP_URL:-http://localhost}:${HYPERDX_APP_PORT:-8080}}" + +echo "Visit the HyperDX UI at $FRONTEND_URL" +echo "" + # Use concurrently to run both the API and App servers npx concurrently \ "--kill-others" \
just ux feedback for later, ctrl+c doesn't seem to kill this script, but it works fine in old local mode. I'm wondering if some of the `wait -n` stuff can help? https://github.com/hyperdxio/hyperdx/blob/main/docker/local/entry.sh#L85 (I forgot how it was fixed there)
hyperdx
github_2023
others
532
hyperdxio
MikeShi42
@@ -101,32 +98,20 @@ services: # - db # - redis app: - image: ${IMAGE_NAME_HDX}:${IMAGE_VERSION}-app + image: ${IMAGE_NAME_HDX}:${IMAGE_VERSION} ports: - ${HYPERDX_API_PORT}:${HYPERDX_API_PORT} - ${HYPERDX_APP_PORT}:${HYPERDX_APP_PORT} environment: - APP_TYPE: 'api' - CLICKHOUSE_HOST: http://ch-server:8123 - CLICKHOUSE_LOG_LEVEL: ${HYPERDX_LOG_LEVEL} - CLICKHOUSE_PASSWORD: api - CLICKHOUSE_USER: api - EXPRESS_SESSION_SECRET: 'hyperdx is cool 👋' FRONTEND_URL: ${HYPERDX_APP_URL}:${HYPERDX_APP_PORT} - HDX_NODE_ADVANCED_NETWORK_CAPTURE: 1 - HDX_NODE_BETA_MODE: 1 - HDX_NODE_CONSOLE_CAPTURE: 1 HYPERDX_API_KEY: ${HYPERDX_API_KEY} HYPERDX_API_PORT: ${HYPERDX_API_PORT} HYPERDX_APP_PORT: ${HYPERDX_APP_PORT} HYPERDX_APP_URL: ${HYPERDX_APP_URL} HYPERDX_LOG_LEVEL: ${HYPERDX_LOG_LEVEL} - INGESTOR_API_URL: 'http://ingestor:8002' MINER_API_URL: 'http://miner:5123'
is this still used?
hyperdx
github_2023
others
531
hyperdxio
MikeShi42
@@ -22,7 +22,7 @@ services: depends_on: - ch-server ch-server: - image: clickhouse/clickhouse-server:23.8.8-alpine + image: clickhouse/clickhouse-server:head-alpine
?
hyperdx
github_2023
typescript
531
hyperdxio
MikeShi42
@@ -279,12 +279,12 @@ export const translateExternalAlertToInternalAlert = ( name: alertInput.name, message: alertInput.message, ...(alertInput.source === 'search' && alertInput.savedSearchId - ? { source: 'LOG', logViewId: alertInput.savedSearchId } + ? { source: 'LOG', savedSearchId: alertInput.savedSearchId }
Ideally since we're migrating models we can just completely get rid of these functions or greatly simplify them right and just bake them into the model?
hyperdx
github_2023
typescript
531
hyperdxio
MikeShi42
@@ -186,89 +161,33 @@ export const updateAlert = async ( }; export const getAlerts = async (teamId: ObjectId) => { - const [logViewIds, dashboardIds] = await dashboardLogViewIds(teamId); - - return Alert.find({ - $or: [ - { - logView: { - $in: logViewIds, - }, - }, - { - dashboardId: { - $in: dashboardIds, - }, - }, - ], - }); + return Alert.find({ team: teamId }); }; export const getAlertById = async ( alertId: ObjectId | string, teamId: ObjectId | string, ) => { - const [logViewIds, dashboardIds] = await dashboardLogViewIds(teamId); - return Alert.findOne({ _id: alertId, - $or: [ - { - logView: { - $in: logViewIds, - }, - }, - { - dashboardId: { - $in: dashboardIds, - }, - }, - ], + team: teamId, }); }; -export const getAlertsWithLogViewAndDashboard = async (teamId: ObjectId) => { - const [logViewIds, dashboardIds] = await dashboardLogViewIds(teamId); - - return Alert.find({ - $or: [ - { - logView: { - $in: logViewIds, - }, - }, - { - dashboardId: { - $in: dashboardIds, - }, - }, - ], - }).populate<{ - logView: ILogView; +export const getAlertsEnhanced = async (teamId: ObjectId) => {
enhanced 🤔
hyperdx
github_2023
typescript
525
hyperdxio
wrn14897
@@ -216,6 +216,23 @@ export class ClickHouseQueryError extends Error { } } +export function extractColumnReference( + sql: string, + maxIterations = 10, +): string | null { + let iterations = 0; + + // Loop until we remove all function calls and get just the column, with a maximum limit + while (/\w+\([^()]*\)/.test(sql) && iterations < maxIterations) { + // Replace the outermost function with its content + sql = sql.replace(/\w+\(([^()]*)\)/, '$1'); + iterations++; + } + + // If we reached the max iterations without resolving, return null to indicate an issue + return iterations < maxIterations ? sql.trim() : null;
what if it resolves at the last iteration? do we get null? usually I'd add a few simple unit tests for function like this. on the other hand, I wonder if we want to use sql parser here
hyperdx
github_2023
typescript
525
hyperdxio
wrn14897
@@ -681,24 +682,30 @@ export const RawLogTable = memo( }, ); -function mergeSelectWithPrimaryKey( +function mergeSelectWithPrimaryAndPartitionKey( select: SelectList, primaryKeys: string, + partitionKey: string, ): { select: SelectList; additionalKeysLength: number } { - const keys = primaryKeys.split(',').map(k => k.trim()); + const partitionKeyArr = partitionKey + .split(',') + .map(k => extractColumnReference(k.trim())) + .filter((k): k is string => k != null && k.length > 0);
curious why do we need to extract column reference here? is is because we try to reduce the redundant select?
hyperdx
github_2023
others
519
hyperdxio
MikeShi42
@@ -7,7 +7,7 @@ "node": ">=18.12.0" }, "scripts": { - "dev": "NEXT_PUBLIC_SERVER_URL=http://localhost:8000 next dev -p 8080", + "dev": "next dev",
don't we want to keep port 8080?
hyperdx
github_2023
others
516
hyperdxio
kruegernet
@@ -154,6 +154,32 @@ features in the future. In the meantime, we're highly aligned with Gitlab's - [Discord](https://discord.gg/FErRRKU78j) - [Email](mailto:support@hyperdx.io) +## HyperDX V2 Roadmap + +HyperDX v2 is currently in early beta, with the goals of accomplishing +deployment simplicity, native SQL support, and improved performance for PB+ +deployments. Currently we've released a subset of features with the goal of +getting early feedback from the community. + +Here's a list of high-level list of support we're working on delivering as part
```suggestion Here's a high-level list of support we're working on delivering as part ```
hyperdx
github_2023
typescript
515
hyperdxio
wrn14897
@@ -11,10 +9,12 @@ export const CLICKHOUSE_HOST = // ONLY USED IN LOCAL MODE // ex: HDX_LOCAL_DEFAULT_CONNECTIONS='[{"id":"local","name":"Demo","host":"https://demo-ch.hyperdx.io","username":"demo","password":"demo"}]' HDX_LOCAL_DEFAULT_SOURCES='[{"id":"l701179602","kind":"trace","name":"Demo Traces","connection":"local","from":{"databaseName":"default","tableName":"otel_traces"},"timestampValueExpression":"Timestamp","defaultTableSelectExpression":"Timestamp, ServiceName, StatusCode, round(Duration / 1e6), SpanName","serviceNameExpression":"ServiceName","eventAttributesExpression":"SpanAttributes","resourceAttributesExpression":"ResourceAttributes","traceIdExpression":"TraceId","spanIdExpression":"SpanId","implicitColumnExpression":"SpanName","durationExpression":"Duration","durationPrecision":9,"parentSpanIdExpression":"ParentSpanId","spanKindExpression":"SpanKind","spanNameExpression":"SpanName","logSourceId":"l-758211293","statusCodeExpression":"StatusCode","statusMessageExpression":"StatusMessage"},{"id":"l-758211293","kind":"log","name":"Demo Logs","connection":"local","from":{"databaseName":"default","tableName":"otel_logs"},"timestampValueExpression":"TimestampTime","defaultTableSelectExpression":"Timestamp, ServiceName, SeverityText, Body","serviceNameExpression":"ServiceName","severityTextExpression":"SeverityText","eventAttributesExpression":"LogAttributes","resourceAttributesExpression":"ResourceAttributes","traceIdExpression":"TraceId","spanIdExpression":"SpanId","implicitColumnExpression":"Body","traceSourceId":"l701179602"}]' yarn dev:local
nit: would be great to update this comment as well
hyperdx
github_2023
typescript
515
hyperdxio
wrn14897
@@ -11,10 +9,12 @@ export const CLICKHOUSE_HOST = // ONLY USED IN LOCAL MODE // ex: HDX_LOCAL_DEFAULT_CONNECTIONS='[{"id":"local","name":"Demo","host":"https://demo-ch.hyperdx.io","username":"demo","password":"demo"}]' HDX_LOCAL_DEFAULT_SOURCES='[{"id":"l701179602","kind":"trace","name":"Demo Traces","connection":"local","from":{"databaseName":"default","tableName":"otel_traces"},"timestampValueExpression":"Timestamp","defaultTableSelectExpression":"Timestamp, ServiceName, StatusCode, round(Duration / 1e6), SpanName","serviceNameExpression":"ServiceName","eventAttributesExpression":"SpanAttributes","resourceAttributesExpression":"ResourceAttributes","traceIdExpression":"TraceId","spanIdExpression":"SpanId","implicitColumnExpression":"SpanName","durationExpression":"Duration","durationPrecision":9,"parentSpanIdExpression":"ParentSpanId","spanKindExpression":"SpanKind","spanNameExpression":"SpanName","logSourceId":"l-758211293","statusCodeExpression":"StatusCode","statusMessageExpression":"StatusMessage"},{"id":"l-758211293","kind":"log","name":"Demo Logs","connection":"local","from":{"databaseName":"default","tableName":"otel_logs"},"timestampValueExpression":"TimestampTime","defaultTableSelectExpression":"Timestamp, ServiceName, SeverityText, Body","serviceNameExpression":"ServiceName","severityTextExpression":"SeverityText","eventAttributesExpression":"LogAttributes","resourceAttributesExpression":"ResourceAttributes","traceIdExpression":"TraceId","spanIdExpression":"SpanId","implicitColumnExpression":"Body","traceSourceId":"l701179602"}]' yarn dev:local -export const HDX_LOCAL_DEFAULT_CONNECTIONS = - publicRuntimeConfig.hdxLocalDefaultConnections; -export const HDX_LOCAL_DEFAULT_SOURCES = - publicRuntimeConfig.hdxLocalDefaultSources; +export const HDX_LOCAL_DEFAULT_CONNECTIONS = env( + 'NEXT_PUBLIC_HDX_LOCAL_DEFAULT_CONNECTIONS', +); +export const HDX_LOCAL_DEFAULT_SOURCES = env(
I feel it would be handy if the `NEXT_PUBLIC_IS_LOCAL_MODE` is also runtime
hyperdx
github_2023
typescript
513
hyperdxio
MikeShi42
@@ -10,14 +11,15 @@ export function SourceSelectControlled({ ...props }: { size?: string; onCreate?: () => void } & UseControllerProps<any>) { const { data } = useSources(); + const hasLocalSources = !!HDX_LOCAL_DEFAULT_SOURCES;
```suggestion const hasDefaultSources = !!HDX_LOCAL_DEFAULT_SOURCES; ```
hyperdx
github_2023
typescript
512
hyperdxio
MikeShi42
@@ -567,3 +567,20 @@ export const mergePath = (path: string[]) => { } return `${key}['${rest.join("']['")}']`; }; + +export const _useTry = <T>(fn: () => T): [null | Error | unknown, null | T] => { + let output = null; + let error = null; + try { + output = fn(); + return [error, output]; + } catch (e) { + error = e; + return [error, output]; + } +}; + +export const parseJSON = <T = any>(json: string) => {
not blocking, but I'd prefer `tryParseJSON` in the future
hyperdx
github_2023
others
508
hyperdxio
MikeShi42
@@ -13,6 +13,13 @@ $padding-x: 24px; border-left: 1px solid $slate-900; } +.panelDragBar {
nit on 2 space indentation :) minor UI improvement, I think it'd be nice if the bar lit up a bit when hovered to make it more clear it's interactive as well: ```scss .panelDragBar { position: absolute; width: 3px; height: 100%; cursor: col-resize; background-color: transparent; &:hover { background-color: $slate-900; transition: background-color 0.2s ease-in-out; } } ```
hyperdx
github_2023
typescript
507
hyperdxio
wrn14897
@@ -420,7 +421,7 @@ function timeBucketExpr({ alias?: string; }) { const unsafeTimestampValueExpression = { - UNSAFE_RAW_SQL: timestampValueExpression, + UNSAFE_RAW_SQL: getFirstTimestampValueExpression(timestampValueExpression),
style: it would be slightly cleaner if the method (called `extractValueExpressions` or something) extracts multi fields and trim. Then we can reuse it here and later
hyperdx
github_2023
typescript
476
hyperdxio
MikeShi42
@@ -0,0 +1,346 @@ +import React from 'react'; +import { add, Duration, format, sub } from 'date-fns'; +import { useAtom } from 'jotai'; +import { atomWithStorage } from 'jotai/utils'; +import { useHotkeys } from 'react-hotkeys-hook'; +import { + Button, + Card, + CloseButton, + Divider, + Group, + Popover, + ScrollArea, + SegmentedControl, + Select, + Space, + Stack, + Text, + TextInput, +} from '@mantine/core'; +import { DateInput, DateInputProps } from '@mantine/dates'; +import { useDisclosure } from '@mantine/hooks'; + +import { useUserPreferences } from '@/useUserPreferences'; + +import { Icon } from '../Icon'; + +import { useTimePickerForm } from './useTimePickerForm'; +import { + dateParser, + DURATION_OPTIONS, + DURATIONS, + parseTimeRangeInput, + RELATIVE_TIME_OPTIONS, +} from './utils'; + +const modeAtom = atomWithStorage('hdx-time-picker-mode', 'Time range'); + +const DATE_INPUT_PLACEHOLDER = 'YYY-MM-DD HH:mm:ss'; +const DATE_INPUT_FORMAT = 'YYYY-MM-DD HH:mm:ss'; +const LIVE_TAIL_TIME_QUERY = 'Live Tail'; + +const DateInputCmp = (props: DateInputProps) => ( + <DateInput + size="xs" + highlightToday + placeholder={DATE_INPUT_PLACEHOLDER} + valueFormat={DATE_INPUT_FORMAT} + variant="filled" + dateParser={dateParser} + onKeyDown={e => { + if (e.key === 'Enter' && e.target instanceof HTMLInputElement) { + e.target.blur(); + } + }} + {...props} + /> +); + +const H = ({ children }: { children: React.ReactNode }) => ( + <Text size="xxs" c="dimmed" lh={1.1}> + {children} + </Text> +); + +export const TimePicker = ({ + inputValue: value, + setInputValue: onChange, + onSearch, + onSubmit, + showLive = false, +}: { + inputValue: string; + setInputValue: (str: string) => any; + onSearch: (rangeStr: string) => void; + onSubmit?: (rangeStr: string) => void; + showLive?: boolean; +}) => { + const { + userPreferences: { timeFormat }, + } = useUserPreferences(); + + const [opened, { close, toggle }] = useDisclosure(false); + + useHotkeys('d', () => toggle(), { preventDefault: true }, [toggle]);
nit: it'd be nice to have it focus the input box so the user can start typing in their date immediately without needing to use the mouse at all
hyperdx
github_2023
typescript
460
hyperdxio
MikeShi42
@@ -1086,7 +1137,8 @@ export default function DashboardPage({ /> <div style={{ width: 200 }} className="ms-2"> <GranularityPicker
It'd be really helpful to have a tooltip here so that users know that granularity is locked to auto when live mode is enabled, otherwise it's a bit confusing why the dropdown isn't working.
hyperdx
github_2023
typescript
438
hyperdxio
colehpage
@@ -2392,8 +2402,12 @@ SELECT * FROM sessions WHERE sessions.sessionId IN ( SELECT sessionIdsWithRecordings.sessionId FROM sessionIdsWithRecordings + ) OR sessions.sessionId IN ( + SELECT sessionIdsWithUserActivity.sessionId FROM sessionIdsWithUserActivity )`,
I assume with sessionId being indexed this is plenty performant, but still trying to figure out what's best in clickhouse - what is the benefit of doing IN's vs JOIN's? Is it just preference?
hyperdx
github_2023
typescript
438
hyperdxio
colehpage
@@ -2382,6 +2386,12 @@ export const getSessions = async ({ const sessionsWithRecordingsQuery = SqlString.format( `WITH sessions AS (${sessionsWithSearchQuery}),
is `sessionsWithSearchQuery` using string interpolation because it's a complex query and can't be used with the placeholders? If so should SqlString.raw(...) be used or is it not necessary and/or possible here?
hyperdx
github_2023
typescript
412
hyperdxio
MikeShi42
@@ -2692,6 +2696,22 @@ export default function LogSidePanel({ } }, ['mouseup', 'touchend']); + const shareUrl = useMemo(() => { + if (shareUrlProp) { + return shareUrlProp; + } + if (logData == null) { + return window.location.href; + } + return `${window.location.origin}/search?${new URLSearchParams({
I'm worried this will lead to excess scrolling of the log table on the search page (if the original time range is large, and without a query it can take a long time to actually scroll the table to bring the event into focus)
hyperdx
github_2023
typescript
413
hyperdxio
MikeShi42
@@ -217,7 +219,9 @@ const MemoChart = memo(function MemoChart({ }, [groupKeys, displayType, lineNames, graphResults]); const sizeRef = useRef<[number, number]>([0, 0]); - const timeFormat: TimeFormat = useUserPreferences().timeFormat; + const { + userPreferences: { timeFormat }, + } = useUserPreferences();
I suspect it's out of scope for this PR, but we'll want to update all our charts to support the UTC preference as well, otherwise it'll be confusing that you toggle on UTC mode but the charts will stay in local time. (HDX-681) I think for now we should just add some copy that it only applies to the search page in the preference modal?
hyperdx
github_2023
typescript
396
hyperdxio
colehpage
@@ -177,6 +195,25 @@ const Line = React.memo( [keyName, parentKeyPath], ); + // Hide LineMenu when selecting text in the value + const valueRef = React.useRef<HTMLSpanElement>(null); + const [isSelectingValue, setIsSelectingValue] = React.useState(false); + const handleValueSelectStart = React.useCallback(() => { + setIsSelectingValue(true); + }, []); + const handleValueMouseUp = React.useCallback(() => { + setIsSelectingValue(false); + }, []); + React.useEffect(() => { + const _valueRef = valueRef.current;
Should this be optionally chained since valueRef can be null? or is that case impossible
hyperdx
github_2023
others
386
hyperdxio
colehpage
@@ -579,8 +576,14 @@ reroute_dropped = true source = ''' # extract shared fields if is_object(.b) { - .s_id = string(del(.b.span_id)) ?? string(del(.b.spanID)) ?? null
Ahhh great no duplicates of spanID if .b.span_id is there 👍 great
hyperdx
github_2023
others
387
hyperdxio
MikeShi42
@@ -83,8 +83,13 @@ source = ''' # TODO: support metrics } + # attach a fake token for local mode + if is_nullish(.hdx_token) && "${IS_LOCAL_APP_MODE:-false}" == "true" { + .hdx_token = "00000000-0000-4000-a000-000000000000" + } + # check if token is in uuid format - if "${ENABLE_TOKEN_MATCHING_CHECK:-true}" == "true" && !match(to_string(.hdx_token) ?? "", r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') { + if !match(to_string(.hdx_token) ?? "", r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') {
imo we should disable all checks in local mode, including the UUID one
hyperdx
github_2023
others
79
hyperdxio
wrn14897
@@ -42,15 +42,15 @@ exporters: loglevel: ${env:HYPERDX_LOG_LEVEL} logzio/traces: account_token: 'X' # required but we don't use it - endpoint: 'http://ingestor:8002?hdx_platform=otel-traces' + endpoint: 'http://localhost:8002?hdx_platform=otel-traces'
I believe this change would break the current services. I'd suggest to document these networking updates in README in `aws` dir
hyperdx
github_2023
others
79
hyperdxio
wrn14897
@@ -0,0 +1,208 @@ +version: '3'
Can we move this to `aws` dir ?
hyperdx
github_2023
others
79
hyperdxio
wrn14897
@@ -39,6 +39,19 @@ dev-int: ci-int: docker compose -p int -f ./docker-compose.ci.yml run --rm api ci:int +.PHONY: aws-ecs +aws-ecs: + ecs-cli configure profile --profile-name ${ECS_PROFILE_NAME} --access-key ${AWS_ACCESS_KEY_ID} --secret-key ${AWS_SECRET_ACCESS_KEY} + ecs-cli configure --cluster ${ECS_CLUSTER_NAME} --default-launch-type ${ECS_LAUNCH_TYPE} --region ${AWS_REGION} --config-name ${ECS_PROFILE_NAME} + +.PHONY: aws-compose +aws-compose: + HYPERDX_APP_URL=${HYPERDX_APP_ALB_URL} HYPERDX_APP_PORT=${HYPERDX_APP_ALB_PORT} ecs-cli compose --project-name ${ECS_CLUSTER_NAME} --file ./docker-compose.aws.yml --region ${AWS_REGION} --ecs-params ./aws/ecs-params.yml create --launch-type ${ECS_LAUNCH_TYPE} --create-log-groups + +.PHONY: aws-create-service +aws-create-service: + aws ecs create-service --service-name ${ECS_SERVICE_NAME} --cluster ${ECS_CLUSTER_NAME} --cli-input-json file://aws/service-definition.json +
Can we move this to `aws/Makefile` instead ?
hyperdx
github_2023
others
79
hyperdxio
wrn14897
@@ -10,3 +10,11 @@ HYPERDX_APP_URL=http://localhost HYPERDX_LOG_LEVEL=debug OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 # port is fixed +# AWS configuration +ECS_PROFILE_NAME=hyperdx +ECS_SERVICE_NAME=hyperdx +ECS_CLUSTER_NAME=hyperdx +AWS_REGION=us-east-1 +ECS_LAUNCH_TYPE=FARGATE +HYPERDX_APP_ALB_PORT=443 +HYPERDX_APP_ALB_URL=https://localhost
since this is in README already, I think we can either remove them or add them to `/aws/.env.aws`
hyperdx
github_2023
others
384
hyperdxio
wrn14897
@@ -70,9 +73,14 @@ EXPOSE 1888 4317 4318 55679 13133 RUN apk update RUN apk add wget shadow -RUN wget https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.90.1/otelcol-contrib_0.90.1_linux_arm64.apk && \ - apk add --allow-untrusted otelcol-contrib_0.90.1_linux_arm64.apk && \ - rm -rf otelcol-contrib_0.90.1_linux_arm64.apk +# Check the target platform and choose the appropriate package +RUN if [ "${TARGETPLATFORM}" = "linux/arm64" ]; then \ + wget https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.90.1/otelcol-contrib_0.90.1_linux_arm64.apk; \ + else \ + wget https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.90.1/otelcol-contrib_0.90.1_linux_amd64.apk; \
It would be better to throw if the platform is not supported
hyperdx
github_2023
typescript
349
hyperdxio
MikeShi42
@@ -320,7 +320,7 @@ const Tile = forwardRef( </div> ) : ( <div - className="fs-7 text-muted flex-grow-1 overflow-hidden" + className="fs-7 text-muted flex-grow-1"
The only thing I can think of that we added this for is possibly for Y axis overflow (like a million legend items overflowing the tile). Though at this point I think we have legend overflow handling as well so should be safe to remove, unless we still need a overflow y hidden for some reason.
hyperdx
github_2023
typescript
367
hyperdxio
colehpage
@@ -23,3 +23,10 @@ export async function findUserByEmailInTeam( export function findUsersByTeam(team: string | ObjectId) { return User.find({ team }).sort({ createdAt: 1 }); } + +export function deleteTeamMember(teamId: string | ObjectId, userId: string) { + return User.findOneAndDelete({ + team: teamId, + _id: userId,
`_id: ObjectId` will still match in the find if a string id is passed correct?
hyperdx
github_2023
typescript
367
hyperdxio
colehpage
@@ -154,27 +160,77 @@ router.get('/invitations', async (req, res, next) => { } }); +router.delete( + '/invitation/:id', + validateRequest({ + params: z.object({ + id: objectIdSchema, + }), + }), + async (req, res, next) => { + try { + const id = req.params.id; + + await TeamInvite.findByIdAndDelete(id); + + return res.json({ message: 'TeamInvite deleted' }); + } catch (e) { + next(e); + } + }, +); + router.get('/members', async (req, res, next) => { try { const teamId = req.user?.team; + const userId = req.user?._id; if (teamId == null) { throw new Error(`User ${req.user?._id} not associated with a team`); } + if (userId == null) {
is this in any way possible ever since the model schema requires it for the document to exist in the first place? Not saying it's bad protection but what is the edge case?
hyperdx
github_2023
typescript
367
hyperdxio
colehpage
@@ -682,6 +771,56 @@ export default function TeamPage() { )} </> )} + <Modal + aria-labelledby="contained-modal-title-vcenter" + centered + onHide={() => + setDeleteTeamMemberConfirmationModalData({ + mode: null, + id: null, + email: null, + }) + } + show={deleteTeamMemberConfirmationModalData.id != null} + size="lg" + > + <Modal.Body className="bg-grey rounded"> + <h3 className="text-muted">Delete Team Member</h3> + <h5 className="text-muted">
I would personally make this either a `<p>` or a `<div>` or whatever our version is instead of `<h5>` so it looks like <img width="659" alt="image" src="https://github.com/hyperdxio/hyperdx/assets/4743932/a6e4c415-0528-4805-922c-db716c724f07"> and not <img width="600" alt="image" src="https://github.com/hyperdxio/hyperdx/assets/4743932/880bc183-4a6a-4bf5-b457-0f0f1ca8b745">
hyperdx
github_2023
typescript
359
hyperdxio
MikeShi42
@@ -158,4 +158,48 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete('/users/:userEmail', async (req, res, next) => { + try { + const teamId = req.user?.team; + const userEmail = req.params.userEmail; + if (teamId == null) { + throw new Error(`User ${req.user?._id} not associated with a team`); + } + if (userEmail == null) {
we're trying to move all parameter validation via `zod` to keep our validation logic cleaner and get some nice TS typing on top ([example](https://github.com/hyperdxio/hyperdx/blob/a2c257f5eb0288af2b97be27269d5642763e9a12/packages/api/src/routers/api/logViews.ts#L12))
hyperdx
github_2023
typescript
359
hyperdxio
MikeShi42
@@ -158,4 +158,48 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete('/users/:userEmail', async (req, res, next) => { + try { + const teamId = req.user?.team; + const userEmail = req.params.userEmail;
my preference here is that we're able to remove users by `id` instead of email (invites as well, but that isn't as big of a priority).
hyperdx
github_2023
typescript
359
hyperdxio
MikeShi42
@@ -31,6 +31,13 @@ export default function TeamPage() { rotateApiKeyConfirmationModalShow, setRotateApiKeyConfirmationModalShow, ] = useState(false); + const [ + deleteTeamMemberConfirmationModalData, + setDeleteTeamMemberConfirmationModalData, + ] = useState({
mega nit: i feel like this could be simplified by using a nullable string instead of needing to encode both show and email separately.
hyperdx
github_2023
typescript
359
hyperdxio
MikeShi42
@@ -693,6 +801,18 @@ export default function TeamPage() { 📋 Copy URL </Button> </CopyToClipboard> + <Button
nit: we're trying to move all our buttons to be based on mantine instead of bootstrap ([exmaple](https://github.com/hyperdxio/hyperdx/blob/a2c257f5eb0288af2b97be27269d5642763e9a12/packages/app/src/SaveSearchModal.tsx#L86))
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -158,4 +158,48 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete('/users/:userEmail', async (req, res, next) => { + try { + const teamId = req.user?.team; + const userEmail = req.params.userEmail; + if (teamId == null) { + throw new Error(`User ${req.user?._id} not associated with a team`); + } + if (userEmail == null) { + throw new Error(`User email not provided`); + } + + const team = await getTeam(teamId); + if (team == null) { + throw new Error(`Team ${teamId} not found`); + }
any reason we need to look up team here ?
hyperdx
github_2023
typescript
359
hyperdxio
MikeShi42
@@ -158,4 +166,38 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete( + '/users/:id', + validateRequest({ + params: z.object({ + id: z.string(), + }), + }), + async (req, res, next) => { + try { + const id = req.params.id; + const user = await findUserById(id); + const teamInvite = await TeamInvite.findOne({
imo feels weird to overload the endpoint to delete two different resources that have no overlap. Let's just keep this endpoint to deleting users for now, we can create a separate one for deleting invites.
hyperdx
github_2023
typescript
359
hyperdxio
MikeShi42
@@ -93,11 +101,50 @@ export default function TeamPage() { }); }; + const deleteTeamMemberAction = (id: string) => { + if (id) { + deleteTeamMember.mutate( + { userEmail: encodeURIComponent(id) },
userId?
hyperdx
github_2023
typescript
359
hyperdxio
MikeShi42
@@ -693,6 +803,19 @@ export default function TeamPage() { 📋 Copy URL </Button> </CopyToClipboard> + <MButton
just noting if we remove team invites from the API, to remove this part too
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -158,4 +166,58 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete( + '/users/:id', + validateRequest({ + params: z.object({ + id: z.string(), + }), + }), + async (req, res, next) => { + try { + const id = req.params.id; + const user = await findUserById(id); + + if (user == null) { + throw new Error(`User ${id} not found`); + } +
we need to make sure the user is in the same team
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -158,4 +166,58 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete( + '/users/:id', + validateRequest({ + params: z.object({ + id: z.string(),
can use `objectIdSchema` from zod.ts file
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -158,4 +166,58 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete( + '/users/:id', + validateRequest({ + params: z.object({ + id: z.string(), + }), + }), + async (req, res, next) => { + try { + const id = req.params.id; + const user = await findUserById(id); + + if (user == null) { + throw new Error(`User ${id} not found`); + } + + if (user) { + await user.deleteOne(); + } + + res.json({ message: 'User deleted' }); + } catch (e) { + next(e); + } + }, +); + +router.delete( + '/teamInvites/:id', + validateRequest({ + params: z.object({ + id: z.string(),
can use objectIdSchema from zod.ts file
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -158,4 +167,59 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete( + '/users/:id', + validateRequest({ + params: z.object({ + id: objectIdSchema, + }), + }), + async (req, res, next) => { + try { + const teamId = req.user?.team || ''; + const id = req.params.id; + const user = await findUserByEmailInTeam(id, teamId);
This is incorrect. The 1st arg in `findUserByEmailInTeam` is email not the id.
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -158,4 +167,59 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete( + '/users/:id', + validateRequest({ + params: z.object({ + id: objectIdSchema, + }), + }), + async (req, res, next) => { + try { + const teamId = req.user?.team || ''; + const id = req.params.id; + const user = await findUserByEmailInTeam(id, teamId); + + if (user == null) { + throw new Error(`User ${id} not found`); + } + + if (user) { + await user.deleteOne(); + } + + res.json({ message: 'User deleted' }); + } catch (e) { + next(e); + } + }, +); + +router.delete( + '/teamInvites/:id', + validateRequest({ + params: z.object({ + id: objectIdSchema, + }), + }), + async (req, res, next) => { + try { + const id = req.params.id; + const teamInvite = await TeamInvite.findOne({
can use 'findByIdAndDelete' to simplify the whole thing ([findByIdAndDelete()](https://mongoosejs.com/docs/api/model.html#Model.findByIdAndDelete()))
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -188,4 +197,51 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete( + '/users/:id',
can we follow the other route naming convention and call this `/member/:id` ?
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -188,4 +197,51 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete( + '/users/:id', + validateRequest({ + params: z.object({ + id: objectIdSchema, + }), + }), + async (req, res, next) => { + try { + const teamId = req.user?.team || ''; + const id = req.params.id; + const user = await deleteUserByIdAndTeam(id, teamId); + + if (user == null) { + throw new Error(`User ${id} not found`); + } + + res.json({ message: 'User deleted' }); + } catch (e) { + next(e); + } + }, +); + +router.delete( + '/invitations/:id',
`invitation/:id`
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -157,17 +163,20 @@ router.get('/invitations', async (req, res, next) => { router.get('/members', async (req, res, next) => { try { const teamId = req.user?.team; + const userId = req.user?._id; if (teamId == null) { throw new Error(`User ${req.user?._id} not associated with a team`); } const teamUsers = await findUsersByTeam(teamId); res.json({ data: teamUsers.map(user => ({ ...pick(user.toJSON({ virtuals: true }), [ + '_id', 'email', 'name', 'hasPasswordAuth', ]), + isCurrentUser: userId ? user._id.equals(userId) : false,
should throw if `userId` doesnt exist
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -188,4 +200,51 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete( + '/member/:id', + validateRequest({ + params: z.object({ + id: objectIdSchema, + }), + }), + async (req, res, next) => { + try { + const teamId = req.user?.team || ''; + const id = req.params.id; + const user = await deleteUserByIdAndTeam(id, teamId); + + if (user == null) { + throw new Error(`User ${id} not found`); + }
I don't think we need to throw 500 back if the user doesn't exist
hyperdx
github_2023
typescript
359
hyperdxio
wrn14897
@@ -188,4 +200,51 @@ router.get('/tags', async (req, res, next) => { } }); +router.delete( + '/member/:id', + validateRequest({ + params: z.object({ + id: objectIdSchema, + }), + }), + async (req, res, next) => { + try { + const teamId = req.user?.team || ''; + const id = req.params.id; + const user = await deleteUserByIdAndTeam(id, teamId); + + if (user == null) { + throw new Error(`User ${id} not found`); + } + + res.json({ message: 'User deleted' }); + } catch (e) { + next(e); + } + }, +); + +router.delete( + '/invitation/:id', + validateRequest({ + params: z.object({ + id: objectIdSchema, + }), + }), + async (req, res, next) => { + try { + const id = req.params.id; + const deletedTeamInvite = await TeamInvite.findByIdAndDelete(id); + + if (deletedTeamInvite == null) { + throw new Error(`TeamInvite ${id} not found`); + }
same here. no need to throw
hyperdx
github_2023
go
187
hyperdxio
wrn14897
@@ -0,0 +1,39 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strings" + + "github.com/DataDog/go-sqllexer" +) + +func main() { + reader := bufio.NewReader(os.Stdin) + for { + query, err := reader.ReadString('\n') + if err != nil { + // write to stderr + fmt.Fprintf(os.Stderr, "error: %s\n", err) + os.Exit(1) + } + stripped_string := strings.Trim(query, " \t\r\n") + if stripped_string == "" { + // skip empty entries + continue + } + + normalizer := sqllexer.NewNormalizer( + sqllexer.WithCollectComments(false), + sqllexer.WithCollectCommands(false), + sqllexer.WithCollectTables(false), + sqllexer.WithKeepSQLAlias(false), + ) + + normalized, _, _ := normalizer.Normalize(query)
Don't we want to handle exceptions here ?
hyperdx
github_2023
go
187
hyperdxio
wrn14897
@@ -0,0 +1,39 @@ +package main
Would be nice if we write a simple test for this script
hyperdx
github_2023
typescript
187
hyperdxio
wrn14897
@@ -0,0 +1,24 @@ +import * as childProcess from 'child_process'; + +import { sqlObfuscator } from '../sqlObfuscator'; + +describe('logParser', () => { + it('obfuscates a basic query', async () => { + const n = 1; + const start = Date.now(); + for (let i = 0; i < n; i++) {
nit: probably don't need this loop ?
hyperdx
github_2023
typescript
187
hyperdxio
wrn14897
@@ -0,0 +1,47 @@ +import { spawn } from 'child_process'; + +let subprocess: any; + +const getChild = () => { + if (subprocess) { + return subprocess; + } + + const arch = process.arch; +
maybe we want to validate arch here ?
hyperdx
github_2023
typescript
187
hyperdxio
wrn14897
@@ -0,0 +1,47 @@ +import { spawn } from 'child_process'; + +let subprocess: any; + +const getChild = () => { + if (subprocess) { + return subprocess; + } + + const arch = process.arch; + + subprocess = spawn(`src/gobin/sql_obfuscator_${arch}`, [], { + stdio: ['pipe', 'pipe', 'pipe', 'ipc'], + }); + + process.on('SIGINT', () => { + subprocess.kill('SIGINT'); + }); + + return subprocess; +}; + +export const sqlObfuscator = async (sql: string): Promise<string> => { + subprocess = getChild(); + const strippedSql = sql.replace(/(\r\n|\n|\r)/gm, ' '); + subprocess.stdin.write(`${strippedSql}\n`); + + return new Promise((resolve, reject) => { + const removeListeners = (subprocess: any) => { + subprocess.stdout.removeAllListeners(); + subprocess.stderr.removeAllListeners(); + subprocess.removeAllListeners(); + };
we can move this guy out of promise scope, right ?
hyperdx
github_2023
typescript
187
hyperdxio
wrn14897
@@ -0,0 +1,47 @@ +import { spawn } from 'child_process'; + +let subprocess: any; + +const getChild = () => { + if (subprocess) { + return subprocess; + } + + const arch = process.arch; + + subprocess = spawn(`src/gobin/sql_obfuscator_${arch}`, [], { + stdio: ['pipe', 'pipe', 'pipe', 'ipc'], + }); + + process.on('SIGINT', () => { + subprocess.kill('SIGINT'); + }); + + return subprocess; +}; + +export const sqlObfuscator = async (sql: string): Promise<string> => { + subprocess = getChild(); + const strippedSql = sql.replace(/(\r\n|\n|\r)/gm, ' '); + subprocess.stdin.write(`${strippedSql}\n`); + + return new Promise((resolve, reject) => { + const removeListeners = (subprocess: any) => { + subprocess.stdout.removeAllListeners(); + subprocess.stderr.removeAllListeners(); + subprocess.removeAllListeners(); + }; + const errorOutput = (data: any) => { + removeListeners(subprocess); + reject(data.toString()); + }; + const dataRecieved = (data: any) => { + removeListeners(subprocess); + resolve(data.toString()); + }; + subprocess.stdout.on('data', dataRecieved); + subprocess.stderr.on('data', errorOutput); + subprocess.on('error', errorOutput); + subprocess.on('exit', errorOutput);
'exit' event has different kind of callback ?
hyperdx
github_2023
typescript
187
hyperdxio
wrn14897
@@ -0,0 +1,47 @@ +import { spawn } from 'child_process'; + +let subprocess: any; + +const getChild = () => { + if (subprocess) { + return subprocess; + } + + const arch = process.arch; + + subprocess = spawn(`src/gobin/sql_obfuscator_${arch}`, [], { + stdio: ['pipe', 'pipe', 'pipe', 'ipc'], + }); + + process.on('SIGINT', () => { + subprocess.kill('SIGINT'); + }); + + return subprocess; +}; + +export const sqlObfuscator = async (sql: string): Promise<string> => { + subprocess = getChild(); + const strippedSql = sql.replace(/(\r\n|\n|\r)/gm, ' '); + subprocess.stdin.write(`${strippedSql}\n`); + + return new Promise((resolve, reject) => { + const removeListeners = (subprocess: any) => { + subprocess.stdout.removeAllListeners(); + subprocess.stderr.removeAllListeners(); + subprocess.removeAllListeners(); + }; + const errorOutput = (data: any) => { + removeListeners(subprocess); + reject(data.toString()); + }; + const dataRecieved = (data: any) => { + removeListeners(subprocess); + resolve(data.toString()); + }; + subprocess.stdout.on('data', dataRecieved);
Trying to understand this. how do we know if all stdout are streamed back already ? what if its more than a buffer ? I wonder if we want to aggregate the data at 'close' event and resolve the promise from there
hyperdx
github_2023
typescript
209
hyperdxio
wrn14897
@@ -955,7 +955,14 @@ export const buildMetricSeriesQuery = async ({ })(${isRate ? 'rate' : 'value'}) as data`, ); } else { - logger.error(`Unsupported data type: ${dataType}`); + if (dataType === MetricsDataType.Histogram) { + if (!['p50', 'p90', 'p95', 'p99'].includes(aggFn)) { + throw new Error(`Unsupported aggFn for Histogram: ${aggFn}`); + } + selectClause.push(`max(value) as data`); + } else { + logger.error(`Unsupported data type (994): ${dataType} `); + }
can clean this up: ``` else if (dataType === MetricsDataType.Histogram) { if (!['p50', 'p90', 'p95', 'p99'].includes(aggFn)) { throw new Error(`Unsupported aggFn for Histogram: ${aggFn}`); } selectClause.push(`max(value) as data`); } else { // I think we should probably throw instead of bypassing it in this case throw new Error(`Unsupported data type: ${dataType}`); } ```
hyperdx
github_2023
typescript
209
hyperdxio
wrn14897
@@ -1017,6 +1024,41 @@ export const buildMetricSeriesQuery = async ({ ], ); + const quantile = + aggFn === AggFn.P50 + ? '0.5' + : aggFn === AggFn.P90 + ? '0.90' + : aggFn === AggFn.P95 + ? '0.95' + : '0.99'; + + const histogramMetricSource = SqlString.format( + `SELECT + toStartOfInterval(timestamp, INTERVAL ?) as timestamp, + name, + quantileTimingWeighted(${quantile}) + ( + /* this comes in as a string either with the max value for the bucket or '+Inf' */ + toUInt64OrDefault(??._string_attributes['le'], 18446744073709551614), /* 2^64 - 2 */ + toUInt64(value) /* would normally be a Float64 */ + ) as value, + mapFilter((k, v) -> (k != 'le'), _string_attributes) as _string_attributes + FROM ?? + where name = ? + AND data_type = 'Histogram' + AND (?) + GROUP BY name, _string_attributes, timestamp + ORDER BY timestamp ASC`.trim(),
should we order by _string_attributes ?
hyperdx
github_2023
typescript
209
hyperdxio
wrn14897
@@ -1017,6 +1024,41 @@ export const buildMetricSeriesQuery = async ({ ], ); + const quantile = + aggFn === AggFn.P50 + ? '0.5' + : aggFn === AggFn.P90 + ? '0.90' + : aggFn === AggFn.P95 + ? '0.95' + : '0.99';
can we create a function for this guy ?