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 | 209 | hyperdxio | wrn14897 | @@ -751,6 +751,181 @@ Array [
"ts_bucket": 1641341100,
},
]
+`);
+
+ const buildMetricSeriesHistogram = ({
+ tags,
+ name,
+ points,
+ data_type,
+ is_delta,
+ is_monotonic,
+ unit,
+ }: {
+ tags: Record<string, string>;
+ name: string;
+ points: { value: number; timestamp: string | number; le: string }[];
+ data_type: clickhouse.MetricsDataType;
+ is_monotonic: boolean;
+ is_delta: boolean;
+ unit: string;
+ }): MetricModel[] => {
+ return points.map(({ value, timestamp, le }) => ({
+ _string_attributes: { ...tags, le: le.toString() },
+ name,
+ value,
+ timestamp: parseInt(timestamp.toString(), 10) * 1000000,
+ data_type,
+ is_monotonic,
+ is_delta,
+ unit,
+ }));
+ };
+
+ await clickhouse.bulkInsertTeamMetricStream(
+ buildMetricSeriesHistogram({
+ name: 'test.response_time',
+ tags: { host: 'test2', runId },
+ data_type: clickhouse.MetricsDataType.Histogram,
+ is_monotonic: false,
+ is_delta: false,
+ unit: '',
+
+ // OK this is a fun one. We want a histogram with a bunch of buckets
+ // but we need to make sure that the quantile value is some reasonable value
+ // So here's a distribution where the p50 is 50ms, p90 is 100ms, p99 is 200ms
+ points: [
+ { value: 10, timestamp: now, le: '10' },
+ { value: 20, timestamp: now, le: '30' },
+ { value: 25, timestamp: now, le: '50' },
+ { value: 15, timestamp: now, le: '100' },
+ { value: 5, timestamp: now, le: '200' },
+ { value: 0, timestamp: now, le: '300' },
+ { value: 0, timestamp: now, le: '500' },
+ { value: 0, timestamp: now, le: '1000' },
+ { value: 0, timestamp: now, le: '+Inf' },
+ ], | this is awesome. I wonder if we can also add points in the next window so we know it works with multiple timestamp buckets |
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 | maybe we can add `??._string_attributes` here so we know its realiased |
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 */ | style suggestion: can we move the comments out from the query itself ? |
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( | we can also add a comment here to let people know the implementation doesnt linear interpolate the bucket values |
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(),
+ [granularity, tableName, tableName, name, SqlString.raw(whereClause)],
+ );
+
+ const source =
+ dataType === 'Histogram' | can use `MetricsDataType.Histogram` enum |
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' | nit: I wonder if we want to pass var instead of hard coding the data type here |
hyperdx | github_2023 | typescript | 358 | hyperdxio | MikeShi42 | @@ -0,0 +1,99 @@
+import { FormEvent, useEffect, useState } from 'react'; | Are we not able to re-use the SaveSearchModal instead of creating a new component? |
hyperdx | github_2023 | typescript | 358 | hyperdxio | MikeShi42 | @@ -704,6 +712,37 @@ function SearchPage() {
setShowSaveSearchModal(false);
}}
/>
+ <RenameSearchModal
+ show={renameSearchModalData.show}
+ searchName={selectedSavedSearch?.name ?? ''}
+ onHide={() =>
+ setRenameSearchModalData({
+ show: false,
+ searchID: null,
+ })
+ }
+ searchID={renameSearchModalData.searchID || ''}
+ searchQuery={displayedSearchQuery}
+ onRenameSuccess={responseData => {
+ toast.success('Saved search renamed');
+ router.push( | Do we need to push this route? I'm not sure renaming requires this right? |
hyperdx | github_2023 | typescript | 358 | hyperdxio | MikeShi42 | @@ -685,8 +692,11 @@ function SearchPage() {
</Head>
<SaveSearchModal
show={showSaveSearchModal}
+ mode={saveSearchModalData.mode}
onHide={() => setShowSaveSearchModal(false)}
searchQuery={displayedSearchQuery}
+ searchName={selectedSavedSearch?.name ?? ''}
+ searchID={saveSearchModalData.searchID ?? ''} | Can't this always be derived from `selectedSavedSearch?._id`? |
hyperdx | github_2023 | typescript | 358 | hyperdxio | MikeShi42 | @@ -461,6 +461,13 @@ function SearchPage() {
);
const [showSaveSearchModal, setShowSaveSearchModal] = useState(false);
+ const [saveSearchModalData, setSaveSearchModalData] = useState<{ | I think this can be combined with `showSaveSearchModal`, maybe can be renamed into something like `saveSearchModalMode` and then just have `'update' | 'save' | 'hidden'` or something like that. |
hyperdx | github_2023 | typescript | 358 | hyperdxio | MikeShi42 | @@ -460,7 +460,9 @@ function SearchPage() {
[searchInput],
);
- const [showSaveSearchModal, setShowSaveSearchModal] = useState(false);
+ const [saveSearchModalMode, setSaveSearchModalMode] = useState<
+ 'update' | 'save' | 'hidden'
+ >('save'); | This need to be initialized as hidden or else it will show up every time the user opens the page |
hyperdx | github_2023 | others | 361 | hyperdxio | wrn14897 | @@ -37,6 +42,7 @@ ENABLE_GO_PARSER="false" \
GO_PARSER_API_URL="http://go-parser:7777" \
ENABLE_TOKEN_MATCHING_CHECK="false" \
vector \
+ -qq \ | nit: imo it would be more readable to use `VECTOR_LOG` |
hyperdx | github_2023 | typescript | 361 | hyperdxio | wrn14897 | @@ -125,13 +126,23 @@ export default function MyApp({ Component, pageProps }: AppPropsWithLayout) {
fetch('/api/config')
.then(res => res.json())
.then(_jsonData => {
+ // Set API url dynamically for users who aren't rebuilding
+ try {
+ const url = new URL(_jsonData.apiServerUrl);
+ if (url != null) {
+ apiConfigs.prefixUrl = url.toString().replace(/\/$/, ''); | oh I see. So the hack is we reset this `apiConfigs` global var |
hyperdx | github_2023 | typescript | 361 | hyperdxio | wrn14897 | @@ -699,20 +719,20 @@ const api = {
},
useInstallation() {
return useQuery<any, HTTPError>(`installation`, () =>
- server(`installation`).json(),
+ hdxServer(`installation`).json(), | I assume the default method is GET |
hyperdx | github_2023 | typescript | 361 | hyperdxio | wrn14897 | @@ -20,7 +20,7 @@ export default function PasswordResetPage({
<div>
<Form
className="text-start"
- action={`${API_SERVER_URL}/password-reset`}
+ action={`${SERVER_URL}/password-reset`} | double check that this url won't be updated dynamically, right ? |
hyperdx | github_2023 | others | 148 | hyperdxio | wrn14897 | @@ -0,0 +1,90 @@
+# Starts several services in a single container for local use
+# - Clickhouse
+# - Mongo
+# - Otel Collector (otelcol)
+# - Ingestor (Vector)
+# - API (Node)
+# - Aggregator (Node)
+# - App (Frontend)
+# - Redis Cache
+
+# TODO:
+# - Customize ports, need to set up env vars or relax CORS and other port requirements
+# - Have otel collector listen to a directory users can mount logs into
+# - Allow persisting settings on disk
+# - Limiting persisted data with some auto rotation
+
+FROM clickhouse/clickhouse-server:23.11.1-alpine AS base
+
+# ===
+# === Install Deps
+# ===
+
+# == Install Otel Collector Deps ==
+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
+RUN apk add --allow-untrusted otelcol-contrib_0.90.1_linux_arm64.apk
+
+# == Install Node Deps ==
+RUN apk add nodejs npm yarn | better to use `nvm use` to lock node version |
hyperdx | github_2023 | others | 148 | hyperdxio | wrn14897 | @@ -0,0 +1,90 @@
+# Starts several services in a single container for local use
+# - Clickhouse
+# - Mongo
+# - Otel Collector (otelcol)
+# - Ingestor (Vector)
+# - API (Node)
+# - Aggregator (Node)
+# - App (Frontend)
+# - Redis Cache
+
+# TODO:
+# - Customize ports, need to set up env vars or relax CORS and other port requirements
+# - Have otel collector listen to a directory users can mount logs into
+# - Allow persisting settings on disk
+# - Limiting persisted data with some auto rotation
+
+FROM clickhouse/clickhouse-server:23.11.1-alpine AS base
+
+# ===
+# === Install Deps
+# ===
+
+# == Install Otel Collector Deps ==
+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
+RUN apk add --allow-untrusted otelcol-contrib_0.90.1_linux_arm64.apk
+
+# == Install Node Deps ==
+RUN apk add nodejs npm yarn
+
+# == Install Vector Deps ==
+RUN apk add curl
+RUN curl --proto '=https' --tlsv1.2 -sSfL https://sh.vector.dev | bash -s -- -y | we also want to specify vector version (https://github.com/hyperdxio/hyperdx/blob/843cfa3ba8c7ae0f1104f880c77f3c5677591206/.github/workflows/main.yml#L28) |
hyperdx | github_2023 | others | 148 | hyperdxio | wrn14897 | @@ -0,0 +1,90 @@
+# Starts several services in a single container for local use
+# - Clickhouse
+# - Mongo
+# - Otel Collector (otelcol)
+# - Ingestor (Vector)
+# - API (Node)
+# - Aggregator (Node)
+# - App (Frontend)
+# - Redis Cache
+
+# TODO:
+# - Customize ports, need to set up env vars or relax CORS and other port requirements
+# - Have otel collector listen to a directory users can mount logs into
+# - Allow persisting settings on disk
+# - Limiting persisted data with some auto rotation
+
+FROM clickhouse/clickhouse-server:23.11.1-alpine AS base
+
+# ===
+# === Install Deps
+# ===
+
+# == Install Otel Collector Deps ==
+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
+RUN apk add --allow-untrusted otelcol-contrib_0.90.1_linux_arm64.apk
+
+# == Install Node Deps ==
+RUN apk add nodejs npm yarn
+
+# == Install Vector Deps ==
+RUN apk add curl
+RUN curl --proto '=https' --tlsv1.2 -sSfL https://sh.vector.dev | bash -s -- -y
+
+# == Install MongoDB v4 Deps ==
+RUN echo 'http://dl-cdn.alpinelinux.org/alpine/v3.9/main' >> /etc/apk/repositories
+RUN echo 'http://dl-cdn.alpinelinux.org/alpine/v3.9/community' >> /etc/apk/repositories
+RUN apk update
+RUN apk add mongodb yaml-cpp=0.6.2-r2
+
+# == Install Redis ==
+RUN apk add redis | version ? |
hyperdx | github_2023 | others | 148 | hyperdxio | wrn14897 | @@ -0,0 +1,11 @@
+#!/bin/bash
+# Meant to be run from the root of the repo
+
+docker build -f ./docker/local/Dockerfile \
+ --build-context clickhouse=./docker/clickhouse \
+ --build-context otel-collector=./docker/otel-collector \
+ --build-context ingestor=./docker/ingestor \
+ --build-context local=./docker/local \
+ --build-context api=./packages/api \
+ --build-context app=docker-image://ghcr.io/hyperdxio/hyperdx:1.3.0-app \ | Is this intentional ? (app context) |
hyperdx | github_2023 | others | 148 | hyperdxio | wrn14897 | @@ -27,6 +27,7 @@
"jsonwebtoken": "^9.0.0",
"lodash": "^4.17.21",
"minimist": "^1.2.7",
+ "mongodb": "^6.3.0", | I think this is supposed to be dev dep ? (for migration script) |
hyperdx | github_2023 | others | 148 | hyperdxio | wrn14897 | @@ -14,7 +14,51 @@
# - Allow persisting settings on disk
# - Limiting persisted data with some auto rotation
-FROM clickhouse/clickhouse-server:23.11.1-alpine AS base
+# Get Node base image to copy over Node binaries
+ARG NODE_VERSION=18.15.0
+FROM node:${NODE_VERSION}-alpine AS node
+
+# == API Builder Image ==
+FROM node:${NODE_VERSION}-alpine AS api_builder
+
+WORKDIR /app/api
+COPY ./yarn.lock .
+COPY --from=api ./package.json .
+RUN yarn install --frozen-lockfile && yarn cache clean
+
+COPY --from=api ./tsconfig.json .
+COPY --from=api ./src ./src
+RUN yarn run build
+
+# == App Builder Image ==
+FROM node:${NODE_VERSION}-alpine AS app_builder
+
+WORKDIR /app/app
+
+COPY ./yarn.lock ./.yarnrc .
+COPY ./.yarn ./.yarn
+COPY --from=app ./package.json .
+
+RUN yarn install --frozen-lockfile && yarn cache clean
+
+COPY --from=app ./.eslintrc.js ./next.config.js ./tsconfig.json ./next.config.js ./mdx.d.ts ./.eslintrc.js ./
+COPY --from=app ./src ./src
+COPY --from=app ./pages ./pages
+COPY --from=app ./public ./public
+COPY --from=app ./styles ./styles
+
+ENV NEXT_TELEMETRY_DISABLED 1
+ENV NEXT_OUTPUT_STANDALONE true
+RUN yarn build
+
+# == Clickhouse/Base Image ==
+
+FROM clickhouse/clickhouse-server:23.11.1-alpine AS clickhouse_base | I would suggest to align the ch version with the prebuilt and dev envs (v23.8.8) |
hyperdx | github_2023 | others | 148 | hyperdxio | wrn14897 | @@ -25,15 +69,25 @@ 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
-RUN apk add --allow-untrusted otelcol-contrib_0.90.1_linux_arm64.apk
+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
# == Install Node Deps ==
-RUN apk add nodejs npm yarn
+
+COPY --from=node /usr/lib /usr/lib
+COPY --from=node /usr/local/lib /usr/local/lib
+COPY --from=node /usr/local/include /usr/local/include
+COPY --from=node /usr/local/bin /usr/local/bin
+
+RUN npm install -g yarn --force
# == Install Vector Deps ==
RUN apk add curl
-RUN curl --proto '=https' --tlsv1.2 -sSfL https://sh.vector.dev | bash -s -- -y
+RUN mkdir -p vector
+RUN curl -sSfL --proto '=https' --tlsv1.2 https://packages.timber.io/vector/0.34.0/vector-0.34.0-x86_64-unknown-linux-musl.tar.gz | tar xzf - -C vector --strip-components=2 && \ | v0.35.0 |
hyperdx | github_2023 | typescript | 321 | hyperdxio | wrn14897 | @@ -243,3 +245,67 @@ export const deleteAlert = async (id: string, teamId: ObjectId) => {
],
});
};
+
+export const generateSignedAlertSilenceToken = async (
+ id: string,
+ teamId: ObjectId,
+) => {
+ const secret = process.env.EXPRESS_SESSION_SECRET;
+
+ if (!secret) {
+ logger.error(
+ 'EXPRESS_SESSION_SECRET is not set for signing token, skipping alert silence JWT generation',
+ );
+ return '';
+ }
+
+ const alert = await getAlertById(id, teamId);
+ if (alert == null) {
+ throw new Error('Alert not found');
+ }
+
+ const token = sign(
+ { silenceAlertId: alert._id.toString() },
+ process.env.EXPRESS_SESSION_SECRET,
+ {
+ expiresIn: '1h',
+ },
+ );
+
+ // Slack does not accept ids longer than 255 characters
+ if (token.length > 255) {
+ logger.error(
+ 'Alert silence JWT length is greater than 255 characters, this may cause issues with some clients.',
+ );
+ }
+
+ return token;
+};
+
+export const silenceAlertFromTokenAndTeam = async ( | nit: would be nice to make silence window size adjustable |
hyperdx | github_2023 | typescript | 321 | hyperdxio | wrn14897 | @@ -606,24 +606,32 @@ export const processAlert = async (now: Date, alert: AlertDocument) => {
checkData,
});
- try {
- await fireChannelEvent({
+ if ((alert.silencedUntil?.getTime() ?? 0) <= now.getTime()) { | nit: maybe its a bit more readable if we do this within fireChannelEvent |
hyperdx | github_2023 | typescript | 338 | hyperdxio | MikeShi42 | @@ -1818,21 +1818,39 @@ export const getMultiSeriesChartLegacyFormat = async ({
const flatData = result.data.flatMap(row => {
if (seriesReturnType === 'column') {
- return series.map((_, i) => {
+ return series.map((s, i) => {
+ const groupBy =
+ s.type === 'number' ? [] : 'groupBy' in s ? s.groupBy : [];
+ const attributes = groupBy.reduce((acc, g) => {
+ acc[g] = row.group[groupBy.indexOf(g)]; | nit: I think we can replace indexOf with the 3rd arg in the callback to grab the index faster that way |
hyperdx | github_2023 | typescript | 338 | hyperdxio | MikeShi42 | @@ -2550,8 +2568,9 @@ export const checkAlert = async ({
`
SELECT
?
- count(*) as data,
- toUnixTimestamp(toStartOfInterval(timestamp, INTERVAL ?)) as ts_bucket
+ count(*) AS data,
+ any(_string_attributes) AS attributes, | I think we might also need to extract the default properties like service, level, etc. that are in columns as attributes as well. |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -0,0 +1,27 @@
+import { Db, MongoClient } from 'mongodb'; | we don't need the migration if all these fields are optional and the new changes won't break the old records |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -13,6 +14,10 @@ export interface IWebhook {
team: ObjectId;
updatedAt: Date;
url: string;
+ description: string;
+ queryParams: string;
+ headers: string;
+ body: string; | we should add `?` if these are optional |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -28,6 +33,22 @@ const WebhookSchema = new Schema<IWebhook>(
required: true,
},
url: {
+ type: String,
+ required: false, // TODO: should this not be required?
+ },
+ description: {
+ type: String,
+ required: false,
+ },
+ queryParams: {
+ type: String,
+ required: false,
+ },
+ headers: {
+ type: String,
+ required: false,
+ }, | I wonder if it makes more sense to use `Map` type for headers (https://mongoosejs.com/docs/schematypes.html#maps) |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -444,6 +502,127 @@ describe('checkAlerts', () => {
);
});
+ it('LOG alert - generic webhook', async () => { | ๐ |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -160,27 +161,134 @@ export const notifyChannel = async ({
}),
});
- // ONLY SUPPORTS SLACK WEBHOOKS FOR NOW
if (webhook?.service === 'slack') {
- await slack.postMessageToWebhook(webhook.url, {
- text: message.title,
- blocks: [
- {
- type: 'section',
- text: {
- type: 'mrkdwn',
- text: `*<${message.hdxLink} | ${message.title}>*\n${message.body}`,
- },
- },
- ],
- });
+ await handleSendSlackWebhook(webhook, message);
+ } else if (webhook?.service === 'generic') {
+ await handleSendGenericWebhook(webhook, message);
}
break;
}
default:
throw new Error(`Unsupported channel type: ${channel}`);
}
};
+
+const handleSendSlackWebhook = async (
+ webhook: IWebhook,
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ },
+) => {
+ await slack.postMessageToWebhook(webhook.url, {
+ text: message.title,
+ blocks: [
+ {
+ type: 'section',
+ text: {
+ type: 'mrkdwn',
+ text: `*<${message.hdxLink} | ${message.title}>*\n${message.body}`,
+ },
+ },
+ ],
+ });
+};
+
+export const handleSendGenericWebhook = async (
+ webhook: IWebhook,
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ },
+) => {
+ // QUERY PARAMS
+ let url: string;
+ // user input of queryParams is disabled on the frontend for now
+ if (webhook.queryParams) {
+ const queryParams = JSON.parse(webhook.queryParams);
+ const queryParamsString = new URLSearchParams(queryParams).toString();
+
+ // user may have included params in both the url and the query params
+ // so they should be merged
+ const tmpURL = new URL(webhook.url);
+ if (queryParamsString) {
+ tmpURL.search = tmpURL.search
+ ? `${tmpURL.search}&${queryParamsString}`
+ : queryParamsString;
+ }
+ url = tmpURL.toString();
+ } else {
+ // if there are no query params given, just use the url
+ url = webhook.url;
+ }
+
+ const parsedHeaders = webhook.headers ? JSON.parse(webhook.headers) : {};
+
+ // HEADERS
+ // TODO: handle real webhook security and signage after v0
+ // X-HyperDX-Signature FROM PRIVATE SHA-256 HMAC, time based nonces, caching functionality etc
+ const headers = {
+ 'Content-Type': 'application/json', // default, will be overwritten if user has set otherwise
+ ...parsedHeaders,
+ };
+
+ // BODY
+ let parsedBody: Record<string, string | number | symbol> = {};
+ if (webhook.body) {
+ const injectedBody = injectIntoPlaceholders(webhook.body, {
+ $HDX_ALERT_URL: message.hdxLink,
+ $HDX_ALERT_TITLE: message.title,
+ $HDX_ALERT_BODY: message.body,
+ });
+ parsedBody = JSON.parse(injectedBody);
+ }
+
+ try {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: headers,
+ body: JSON.stringify(parsedBody),
+ }); | nit: I think we'd need a request-error-tolerant api client here (handling retry for example). Don't need to do it in this PR and we can add it later |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -223,8 +223,8 @@ export const alertSchema = z
// External API Alerts
// ==============================
-export const externalSlackWebhookAlertChannel = z.object({
- type: z.literal('slack_webhook'),
+export const externalWebhookAlertChannel = z.object({
+ type: z.literal('webhook'), | we should still support `slack_webhook` type for backward compatibility reason |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -93,7 +93,7 @@ describe('/api/v1/alerts', () => {
Array [
Object {
"channel": Object {
- "type": "slack_webhook",
+ "type": "webhook", | we still want to test `slack_webhook` here to make sure the translator is working fine |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -223,8 +223,8 @@ export const alertSchema = z
// External API Alerts | I think we need to update zod's `alertSchema` so the validator works properly with the new schema. Also one idea is to use zod to do the parsing to make sure the input string is in JSON stringified format (ref: https://github.com/colinhacks/zod/discussions/2215) |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -28,6 +33,22 @@ const WebhookSchema = new Schema<IWebhook>(
required: true,
},
url: {
+ type: String,
+ required: false, // TODO: should this not be required? | Its not required in EE. In OSS, the url should be required. But I think we can just update the `IWebhook` for now |
hyperdx | github_2023 | others | 337 | hyperdxio | wrn14897 | @@ -99,7 +103,7 @@
"@types/jest": "^28.1.6",
"@types/lodash": "^4.14.186",
"@types/pluralize": "^0.0.29",
- "@types/react": "18.2.23",
+ "@types/react": "^18.2.0", | this seems to cause issue on unit test. any reason for this change ? |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -160,27 +160,144 @@ export const notifyChannel = async ({
}),
});
- // ONLY SUPPORTS SLACK WEBHOOKS FOR NOW
if (webhook?.service === 'slack') {
- await slack.postMessageToWebhook(webhook.url, {
- text: message.title,
- blocks: [
- {
- type: 'section',
- text: {
- type: 'mrkdwn',
- text: `*<${message.hdxLink} | ${message.title}>*\n${message.body}`,
- },
- },
- ],
- });
+ await handleSendSlackWebhook(webhook, message);
+ } else if (webhook?.service === 'generic') {
+ await handleSendGenericWebhook(webhook, message);
}
break;
}
default:
throw new Error(`Unsupported channel type: ${channel}`);
}
};
+
+const handleSendSlackWebhook = async (
+ webhook: IWebhook,
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ },
+) => {
+ if (!webhook.url) {
+ throw new Error('Webhook URL is not set');
+ }
+
+ await slack.postMessageToWebhook(webhook.url, {
+ text: message.title,
+ blocks: [
+ {
+ type: 'section',
+ text: {
+ type: 'mrkdwn',
+ text: `*<${message.hdxLink} | ${message.title}>*\n${message.body}`,
+ },
+ },
+ ],
+ });
+};
+
+export const handleSendGenericWebhook = async (
+ webhook: IWebhook,
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ },
+) => {
+ // QUERY PARAMS
+
+ if (!webhook.url) {
+ throw new Error('Webhook URL is not set');
+ }
+
+ let url: string;
+ // user input of queryParams is disabled on the frontend for now
+ if (webhook.queryParams) {
+ const queryParamsString = new URLSearchParams(
+ webhook.queryParams,
+ ).toString();
+
+ // user may have included params in both the url and the query params
+ // so they should be merged
+ const tmpURL = new URL(webhook.url);
+ if (queryParamsString) {
+ tmpURL.search = tmpURL.search
+ ? `${tmpURL.search}&${queryParamsString}`
+ : queryParamsString; | nit: I wonder if we can use `tmpURL.searchParams.append(xxx, yyy)` (since queryParams is an object) |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -160,27 +160,144 @@ export const notifyChannel = async ({
}),
});
- // ONLY SUPPORTS SLACK WEBHOOKS FOR NOW
if (webhook?.service === 'slack') {
- await slack.postMessageToWebhook(webhook.url, {
- text: message.title,
- blocks: [
- {
- type: 'section',
- text: {
- type: 'mrkdwn',
- text: `*<${message.hdxLink} | ${message.title}>*\n${message.body}`,
- },
- },
- ],
- });
+ await handleSendSlackWebhook(webhook, message);
+ } else if (webhook?.service === 'generic') {
+ await handleSendGenericWebhook(webhook, message);
}
break;
}
default:
throw new Error(`Unsupported channel type: ${channel}`);
}
};
+
+const handleSendSlackWebhook = async (
+ webhook: IWebhook,
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ },
+) => {
+ if (!webhook.url) {
+ throw new Error('Webhook URL is not set');
+ }
+
+ await slack.postMessageToWebhook(webhook.url, {
+ text: message.title,
+ blocks: [
+ {
+ type: 'section',
+ text: {
+ type: 'mrkdwn',
+ text: `*<${message.hdxLink} | ${message.title}>*\n${message.body}`,
+ },
+ },
+ ],
+ });
+};
+
+export const handleSendGenericWebhook = async (
+ webhook: IWebhook,
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ },
+) => {
+ // QUERY PARAMS
+
+ if (!webhook.url) {
+ throw new Error('Webhook URL is not set');
+ }
+
+ let url: string;
+ // user input of queryParams is disabled on the frontend for now
+ if (webhook.queryParams) {
+ const queryParamsString = new URLSearchParams(
+ webhook.queryParams,
+ ).toString();
+
+ // user may have included params in both the url and the query params
+ // so they should be merged
+ const tmpURL = new URL(webhook.url);
+ if (queryParamsString) {
+ tmpURL.search = tmpURL.search
+ ? `${tmpURL.search}&${queryParamsString}`
+ : queryParamsString;
+ }
+ url = tmpURL.toString();
+ } else {
+ // if there are no query params given, just use the url
+ url = webhook.url;
+ }
+
+ // HEADERS
+ // TODO: handle real webhook security and signage after v0
+ // X-HyperDX-Signature FROM PRIVATE SHA-256 HMAC, time based nonces, caching functionality etc
+
+ const headers = {
+ 'Content-Type': 'application/json', // default, will be overwritten if user has set otherwise
+ ...(webhook.headers?.toObject() || {}), | nit: `??` is probably what we want here ? |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -160,27 +160,144 @@ export const notifyChannel = async ({
}),
});
- // ONLY SUPPORTS SLACK WEBHOOKS FOR NOW
if (webhook?.service === 'slack') {
- await slack.postMessageToWebhook(webhook.url, {
- text: message.title,
- blocks: [
- {
- type: 'section',
- text: {
- type: 'mrkdwn',
- text: `*<${message.hdxLink} | ${message.title}>*\n${message.body}`,
- },
- },
- ],
- });
+ await handleSendSlackWebhook(webhook, message);
+ } else if (webhook?.service === 'generic') {
+ await handleSendGenericWebhook(webhook, message);
}
break;
}
default:
throw new Error(`Unsupported channel type: ${channel}`);
}
};
+
+const handleSendSlackWebhook = async (
+ webhook: IWebhook,
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ },
+) => {
+ if (!webhook.url) {
+ throw new Error('Webhook URL is not set');
+ }
+
+ await slack.postMessageToWebhook(webhook.url, {
+ text: message.title,
+ blocks: [
+ {
+ type: 'section',
+ text: {
+ type: 'mrkdwn',
+ text: `*<${message.hdxLink} | ${message.title}>*\n${message.body}`,
+ },
+ },
+ ],
+ });
+};
+
+export const handleSendGenericWebhook = async (
+ webhook: IWebhook,
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ },
+) => {
+ // QUERY PARAMS
+
+ if (!webhook.url) {
+ throw new Error('Webhook URL is not set');
+ }
+
+ let url: string;
+ // user input of queryParams is disabled on the frontend for now
+ if (webhook.queryParams) {
+ const queryParamsString = new URLSearchParams(
+ webhook.queryParams,
+ ).toString();
+
+ // user may have included params in both the url and the query params
+ // so they should be merged
+ const tmpURL = new URL(webhook.url);
+ if (queryParamsString) {
+ tmpURL.search = tmpURL.search
+ ? `${tmpURL.search}&${queryParamsString}`
+ : queryParamsString;
+ }
+ url = tmpURL.toString();
+ } else {
+ // if there are no query params given, just use the url
+ url = webhook.url;
+ }
+
+ // HEADERS
+ // TODO: handle real webhook security and signage after v0
+ // X-HyperDX-Signature FROM PRIVATE SHA-256 HMAC, time based nonces, caching functionality etc
+
+ const headers = {
+ 'Content-Type': 'application/json', // default, will be overwritten if user has set otherwise
+ ...(webhook.headers?.toObject() || {}),
+ };
+
+ // BODY
+ let parsedBody: Record<string, string | number | symbol> = {};
+ if (webhook.body) {
+ const injectedBody = injectIntoPlaceholders(JSON.stringify(webhook.body), {
+ $HDX_ALERT_URL: message.hdxLink,
+ $HDX_ALERT_TITLE: message.title,
+ $HDX_ALERT_BODY: message.body,
+ });
+ parsedBody = JSON.parse(injectedBody); | nit: trying to understand why we stringify and parse the body field instead of just iterating through values |
hyperdx | github_2023 | typescript | 337 | hyperdxio | wrn14897 | @@ -3,6 +3,17 @@ import mongoose, { Schema } from 'mongoose';
export enum WebhookService {
Slack = 'slack',
+ Generic = 'generic',
+}
+
+interface MongooseMap extends Map<string, string> {
+ // https://mongoosejs.com/docs/api/map.html#MongooseMap.prototype.toJSON()
+ // Converts this map to a native JavaScript Map for JSON.stringify(). Set the flattenMaps option to convert this map to a POJO instead.
+ // doc.myMap.toJSON() instanceof Map; // true
+ // doc.myMap.toJSON({ flattenMaps: true }) instanceof Map; // false
+ toJSON: (options?: { | so we need to set `flattenMaps` to true to convert the document to JSON ? not very intuitive |
hyperdx | github_2023 | typescript | 334 | hyperdxio | ellipsis-dev[bot] | @@ -599,6 +601,55 @@ export default function ServiceDashboardPage() {
</Grid.Col>
</Grid>
</Tabs.Panel>
+ <Tabs.Panel value="errors">
+ <Grid>
+ <Grid.Col span={12}>
+ <Card p="md">
+ <Card.Section p="md" py="xs" withBorder>
+ Error Events per Service
+ </Card.Section>
+ <Card.Section p="md" py="sm" h={CHART_HEIGHT}>
+ <HDXMultiSeriesTimeChart
+ defaultDisplayType="stacked_bar"
+ config={{
+ dateRange,
+ granularity: convertDateRangeToGranularityString(
+ dateRange,
+ 60,
+ ),
+ seriesReturnType: 'column',
+ series: [
+ {
+ type: 'time',
+ groupBy: ['service'],
+ where: scopeWhereQuery('level:"error"'),
+ table: 'logs',
+ aggFn: 'count',
+ },
+ ],
+ }}
+ />
+ </Card.Section>
+ </Card>
+ </Grid.Col>
+ <Grid.Col span={12}>
+ <Card p="md">
+ <Card.Section p="md" py="xs" withBorder>
+ Error Patterns
+ </Card.Section>
+ <Card.Section p="md" py="sm">
+ <MemoPatternTableWithSidePanel
+ isUTC={false}
+ config={{
+ where: scopeWhereQuery('level:error'), | The level filter in the scopeWhereQuery function should be 'level:"error"' instead of 'level:error' to correctly filter the logs.
```suggestion
where: scopeWhereQuery('level:"error"'),
``` |
hyperdx | github_2023 | typescript | 331 | hyperdxio | ellipsis-dev[bot] | @@ -465,16 +472,31 @@ export function MetricNameSelect({
}, [metricNamesData]);
return (
- <AsyncSelect
- isLoading={isLoading}
- isDisabled={isError}
+ <MSelect
+ disabled={isLoading || isError}
+ variant="filled"
placeholder={
isLoading
? 'Loading...'
: isError
? 'Unable to load metrics'
: 'Select a metric...'
}
+ data={options}
+ limit={100}
+ comboboxProps={{
+ position: 'bottom-start',
+ width: 'auto',
+ }}
+ value={value ?? undefined}
+ searchable
+ clearable
+ onChange={value => setValue(value ?? undefined)}
+ />
+ );
+
+ return ( | The AsyncSelect component is still being returned at the end of the MetricNameSelect function. This seems redundant as the MSelect component is already being returned earlier in the function. Consider removing this redundant return statement. |
hyperdx | github_2023 | typescript | 331 | hyperdxio | ellipsis-dev[bot] | @@ -2,7 +2,13 @@ import { useMemo, useRef, useState } from 'react';
import { add } from 'date-fns';
import Select from 'react-select';
import AsyncSelect from 'react-select/async'; | This import of AsyncSelect is no longer used and should be removed to keep the code clean. |
hyperdx | github_2023 | typescript | 331 | hyperdxio | ellipsis-dev[bot] | @@ -441,6 +447,7 @@
</>
);
}
+import { Autocomplete } from '@mantine/core'; | This import of Autocomplete is not used and should be removed to keep the code clean. |
hyperdx | github_2023 | typescript | 331 | hyperdxio | ellipsis-dev[bot] | @@ -465,34 +472,26 @@
}, [metricNamesData]);
return (
- <AsyncSelect
- isLoading={isLoading}
- isDisabled={isError}
+ <MSelect | The MSelect component should include a similar filtering functionality to the loadOptions prop of the AsyncSelect component it replaced. This will prevent potential performance issues if the options list is very large. |
hyperdx | github_2023 | typescript | 314 | hyperdxio | MikeShi42 | @@ -1,56 +1,75 @@
import { memo } from 'react';
import api from './api';
-import type { AggFn, NumberFormat } from './types';
+import { Granularity } from './ChartUtils';
+import type { AggFn, ChartSeries, NumberFormat } from './types';
import { formatNumber } from './utils';
const HDXNumberChart = memo(
({
- config: { table, aggFn, field, where, dateRange, numberFormat },
+ config: {
+ series,
+ table,
+ aggFn,
+ field,
+ where,
+ dateRange,
+ numberFormat,
+ granularity,
+ },
onSettled,
}: {
config: {
+ series: ChartSeries[];
table: string;
aggFn: AggFn;
field: string;
where: string;
dateRange: [Date, Date];
numberFormat?: NumberFormat;
+ granularity?: Granularity;
};
onSettled?: () => void;
}) => {
- const { data, isError, isLoading } =
- table === 'logs'
- ? api.useLogsChart(
- {
- aggFn,
- endDate: dateRange[1] ?? new Date(),
- field,
- granularity: undefined,
- groupBy: '',
- q: where,
- startDate: dateRange[0] ?? new Date(),
- },
- {
- onSettled,
- },
- )
- : api.useMetricsChart(
- {
- aggFn,
- endDate: dateRange[1] ?? new Date(),
- granularity: undefined,
- name: field,
- q: where,
- startDate: dateRange[0] ?? new Date(),
- groupBy: '',
- },
- {
- onSettled,
- },
- );
+ const isLogsChartApi = table === 'logs' && series.length === 1;
+
+ const { data, isError, isLoading } = isLogsChartApi | Do you think we can just use the multi-series for everything here? |
hyperdx | github_2023 | typescript | 316 | hyperdxio | MikeShi42 | @@ -697,6 +727,10 @@ export default function DashboardPage() {
chart={chart}
dateRange={searchedTimeRange}
onEditClick={() => setEditedChart(chart)}
+ onAddAlertClick={() => {
+ setIsAddingAlert(true); | I'm curious if it would've been possible instead of having a boolean here to set the `alert` property to either the actual chart alert or `DEFAULT_ALERT` at this level instead of needing to depend on a useEffect? That feels a bit cleaner, but maybe there's some details that make it more annoying/harder to implement. |
hyperdx | github_2023 | typescript | 326 | hyperdxio | ellipsis-dev[bot] | @@ -206,11 +253,36 @@ export const buildAlertMessageTemplateTitle = ({
throw new Error(`Unsupported alert source: ${(alert as any).source}`);
};
+
+export const getDefaultExternalAction = (
+ alert: AlertMessageTemplateDefaultView['alert'],
+) => {
+ if (
+ alert.channel.type === 'slack_webhook' &&
+ alert.channel.webhookId != null
+ ) {
+ return `@${alert.channel.type}-${alert.channel.webhookId}`;
+ }
+ return null;
+};
+
+export const translateExternalActionsToInternal = (template: string) => {
+ // ex: @slack_webhook-1234_5678 -> "{{NOTIFY_FN_NAME channel="slack_webhook" id="1234_5678}}"
+ return template.replace(/@([a-zA-Z0-9_-]+)/g, (match, input) => {
+ const [channel, id] = input.split('-');
+ // TODO: sanity check ??
+ return `{{${NOTIFY_FN_NAME} channel="${channel}" id="${id}"}}`;
+ });
+};
+
+// this method will build the body of the alert message and will be used to send the alert to the channel
export const buildAlertMessageTemplateBody = async ({ | The function `buildAlertMessageTemplateBody` is quite large and complex. Consider breaking it down into smaller, more manageable functions to improve readability and maintainability. |
hyperdx | github_2023 | typescript | 326 | hyperdxio | ellipsis-dev[bot] | @@ -133,6 +131,48 @@ type AlertMessageTemplateDefaultView = {
};
value: number;
};
+export const notifyChannel = async ({
+ channel,
+ id,
+ message,
+ teamId,
+}: {
+ channel: AlertMessageTemplateDefaultView['alert']['channel']['type'];
+ id: string;
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ };
+ teamId: string;
+}) => {
+ switch (channel) {
+ case 'slack_webhook': {
+ const webhook = await Webhook.findOne({
+ _id: id, | This function should handle the case where the webhook is not found in the database. Consider adding a check for whether the webhook is null and handle it appropriately. |
hyperdx | github_2023 | typescript | 326 | hyperdxio | ellipsis-dev[bot] | @@ -256,85 +369,43 @@
.join('\n'),
2500,
);
- return `${group ? `Group: "${group}"` : ''}
+ rawTemplateBody = `${group ? `Group: "${group}"` : ''}
${value} lines found, expected ${
alert.threshold_type === 'above' ? 'less than' : 'greater than'
} ${alert.threshold} lines
-${renderTemplate(template, view)}
+${targetTemplate}
\`\`\`
${truncatedResults}
-\`\`\`
-`;
+\`\`\``;
} else if (alert.source === 'chart') {
if (dashboard == null) {
throw new Error('Source is CHART but dashboard is null');
}
- return `${group ? `Group: "${group}"` : ''}
+ rawTemplateBody = `${group ? `Group: "${group}"` : ''}
${value} ${
doesExceedThreshold(
alert.threshold_type === 'above',
alert.threshold, | Consider simplifying this complex ternary operation. You could create a separate function to handle this logic or use a more straightforward control flow structure like if-else statements. |
hyperdx | github_2023 | typescript | 326 | hyperdxio | ellipsis-dev[bot] | @@ -133,6 +131,55 @@ type AlertMessageTemplateDefaultView = {
};
value: number;
};
+export const notifyChannel = async ({
+ channel,
+ id,
+ message,
+ teamId,
+}: {
+ channel: AlertMessageTemplateDefaultView['alert']['channel']['type'];
+ id: string;
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ };
+ teamId: string;
+}) => {
+ switch (channel) {
+ case 'slack_webhook': {
+ const webhook = await Webhook.findOne({ | Consider adding error handling to manage scenarios where the `id` provided does not exist in the database. This will improve the robustness of the `notifyChannel` function. |
hyperdx | github_2023 | typescript | 326 | hyperdxio | ellipsis-dev[bot] | @@ -133,6 +132,55 @@ type AlertMessageTemplateDefaultView = {
};
value: number;
};
+export const notifyChannel = async ({
+ channel,
+ id,
+ message,
+ teamId,
+}: {
+ channel: AlertMessageTemplateDefaultView['alert']['channel']['type'];
+ id: string;
+ message: {
+ hdxLink: string;
+ title: string;
+ body: string;
+ };
+ teamId: string;
+}) => {
+ switch (channel) {
+ case 'slack_webhook': {
+ const webhook = await Webhook.findOne({
+ team: teamId,
+ ...(mongoose.isValidObjectId(id)
+ ? { _id: id }
+ : {
+ name: {
+ $regex: new RegExp(`^${id}`), // FIXME: a hacky way to match the prefix | The regular expression used to match the prefix of the webhook name is not safe. It does not escape special characters, which could lead to unexpected behavior or security vulnerabilities. Consider using a library or function to escape special characters in the `id` before constructing the regular expression.
```suggestion
name: {
$regex: new RegExp(`^${escapeRegExp(id)}`),
},
``` |
hyperdx | github_2023 | typescript | 326 | hyperdxio | ellipsis-dev[bot] | @@ -177,40 +225,71 @@ export const buildAlertMessageTemplateTitle = ({
view: AlertMessageTemplateDefaultView;
}) => {
const { alert, dashboard, savedSearch, value } = view;
+ const handlebars = Handlebars.create(); | Consider refactoring this complex ternary operation to improve code readability. |
hyperdx | github_2023 | typescript | 318 | hyperdxio | MikeShi42 | @@ -404,14 +373,14 @@ describe('checkAlerts', () => {
1,
'https://hooks.slack.com/services/123',
{
- text: 'Alert for "Max Duration" in "My Dashboard" - 102 exceeds 10',
blocks: [
{
text: {
text: [
`*<http://localhost:9090/dashboards/${dashboard._id}?from=1700170200000&granularity=5+minute&to=1700174700000 | Alert for "Max Duration" in "My Dashboard">*`,
'Group: "HyperDX"',
'102 exceeds 10',
+ '', | nit: should we just `trim()` the rendered string so we don't send extra new lines? |
hyperdx | github_2023 | typescript | 263 | hyperdxio | wrn14897 | @@ -0,0 +1,205 @@
+import express, { NextFunction, Request, Response } from 'express';
+import _ from 'lodash';
+import { z } from 'zod';
+import { validateRequest } from 'zod-express-middleware';
+
+import {
+ createAlert,
+ deleteAlert,
+ getAlerts,
+ updateAlert,
+ validateGroupByProperty,
+} from '@/controllers/alerts';
+import { getTeam } from '@/controllers/team';
+import { AlertDocument } from '@/models/alert';
+import {
+ alertSchema,
+ externalAlertSchema,
+ externalAlertSchemaWithId,
+ objectIdSchema,
+} from '@/utils/zod';
+
+const router = express.Router();
+
+// TODO: Dedup with private API router
+// Validate groupBy property
+const validateGroupBy = async (
+ req: Request,
+ res: Response,
+ next: NextFunction,
+) => {
+ const { groupBy, source } = req.body || {};
+ if (source === 'LOG' && groupBy) {
+ const teamId = req.user?.team;
+ if (teamId == null) {
+ return res.sendStatus(403);
+ }
+ const team = await getTeam(teamId);
+ if (team == null) {
+ return res.sendStatus(403);
+ }
+ // Validate groupBy property
+ const groupByValid = await validateGroupByProperty({
+ groupBy,
+ logStreamTableVersion: team.logStreamTableVersion,
+ teamId: teamId.toString(),
+ });
+ if (!groupByValid) {
+ return res.status(400).json({
+ error: 'Invalid groupBy property',
+ });
+ }
+ }
+ next();
+};
+
+const translateExternalAlertToInternalAlert = (
+ alertInput: z.infer<typeof externalAlertSchema>,
+): z.infer<typeof alertSchema> => {
+ return {
+ interval: alertInput.interval,
+ threshold: alertInput.threshold,
+ type: alertInput.threshold_type === 'above' ? 'presence' : 'absence',
+ channel: {
+ ...alertInput.channel,
+ type: 'webhook',
+ },
+ ...(alertInput.source === 'search' && alertInput.savedSearchId
+ ? { source: 'LOG', logViewId: alertInput.savedSearchId }
+ : alertInput.source === 'chart' && alertInput.dashboardId
+ ? {
+ source: 'CHART',
+ dashboardId: alertInput.dashboardId,
+ chartId: alertInput.chartId,
+ }
+ : ({} as never)),
+ };
+};
+
+const translateAlertDocumentToExternalAlert = (
+ alertDoc: AlertDocument,
+): z.infer<typeof externalAlertSchemaWithId> => {
+ return {
+ id: alertDoc._id.toString(),
+ interval: alertDoc.interval,
+ threshold: alertDoc.threshold,
+ threshold_type: alertDoc.type === 'absence' ? 'below' : 'above',
+ channel: {
+ ...alertDoc.channel,
+ type: 'slack_webhook',
+ },
+ ...(alertDoc.source === 'LOG' && alertDoc.logView
+ ? { source: 'search', savedSearchId: alertDoc.logView.toString() }
+ : alertDoc.source === 'CHART' && alertDoc.dashboardId
+ ? {
+ source: 'chart',
+ dashboardId: alertDoc.dashboardId.toString(),
+ chartId: alertDoc.chartId as string,
+ }
+ : ({} as never)), | shouldn't we throw here ? |
hyperdx | github_2023 | typescript | 263 | hyperdxio | wrn14897 | @@ -93,22 +97,129 @@ const makeAlert = (alert: AlertInput) => {
};
};
-export const createAlert = async (teamId: ObjectId, alertInput: AlertInput) => {
+export const createAlert = async (
+ teamId: ObjectId,
+ alertInput: z.infer<typeof alertSchema>,
+) => {
+ if (alertInput.source === 'CHART') { | nit: I feel it would be cleaner if `AlertSource` is an enum |
hyperdx | github_2023 | typescript | 301 | hyperdxio | wrn14897 | @@ -27,7 +27,7 @@ const registrationSchema = z
'Password must include at least one number',
)
.refine(
- pass => /[!@#$%^&*(),.?":{}|<>]/.test(pass),
+ pass => /[!@#$%^&*(),.?":{}|<>-]/.test(pass), | can we also add `;` to the list ? |
hyperdx | github_2023 | typescript | 301 | hyperdxio | wrn14897 | @@ -27,7 +27,7 @@ const registrationSchema = z
'Password must include at least one number',
)
.refine(
- pass => /[!@#$%^&*(),.?":{}|<>]/.test(pass),
+ pass => /[!@#$%^&*(),.?":{}|<>;-]/.test(pass), | I realized = + are also missing |
hyperdx | github_2023 | typescript | 288 | hyperdxio | wrn14897 | @@ -172,7 +176,7 @@ export function seriesToSearchQuery({
aggFn !== 'count' && field ? ` ${field}:*` : ''
}${
'groupBy' in s && s.groupBy != null && s.groupBy.length > 0
- ? ` ${s.groupBy}:${groupByValue}`
+ ? ` ${s.groupBy}:${groupByValue ?? '*'}` | groupBy * ? |
hyperdx | github_2023 | typescript | 276 | hyperdxio | wrn14897 | @@ -19,6 +19,38 @@ export async function deleteDashboardAndAlerts(
}
}
+export async function updateDashboard(
+ dashboardId: string,
+ teamId: ObjectId,
+ {
+ name,
+ charts,
+ query,
+ tags,
+ }: {
+ name: string;
+ charts: z.infer<typeof chartSchema>[];
+ query: string;
+ tags: z.infer<typeof tagsSchema>;
+ },
+) {
+ const updatedDashboard = await Dashboard.findOneAndUpdate(
+ {
+ _id: dashboardId,
+ team: teamId,
+ },
+ {
+ name,
+ charts,
+ query,
+ tags: tags && uniq(tags),
+ },
+ { new: true },
+ );
+
+ return updatedDashboard;
+}
+
export async function updateDashboardAndAlerts( | nit: I assume we can reuse `updateDashboard` in here |
hyperdx | github_2023 | others | 283 | hyperdxio | MikeShi42 | @@ -205,6 +205,7 @@ services:
CLICKHOUSE_LOG_LEVEL: ${HYPERDX_LOG_LEVEL}
CLICKHOUSE_PASSWORD: api
CLICKHOUSE_USER: api
+ DEBUG: 'http-graceful-shutdown' | do we want to keep this? |
hyperdx | github_2023 | typescript | 279 | hyperdxio | wrn14897 | @@ -0,0 +1,87 @@
+import opentelemetry, { SpanStatusCode } from '@opentelemetry/api';
+import express from 'express';
+import _ from 'lodash';
+import { z } from 'zod';
+import { validateRequest } from 'zod-express-middleware';
+
+import * as clickhouse from '@/clickhouse';
+import { getTeam } from '@/controllers/team';
+import { translateExternalSeriesToInternalSeries } from '@/utils/externalApi';
+import { externalQueryChartSeriesSchema } from '@/utils/zod';
+
+const router = express.Router();
+
+router.post(
+ '/series',
+ validateRequest({
+ body: z.object({
+ series: z.array(externalQueryChartSeriesSchema).refine(
+ series => {
+ const groupByFields = series[0].groupBy;
+ return series.every(s => _.isEqual(s.groupBy, groupByFields));
+ },
+ {
+ message: 'All series must have the same groupBy fields',
+ },
+ ), | oh this is cool |
hyperdx | github_2023 | typescript | 279 | hyperdxio | wrn14897 | @@ -0,0 +1,87 @@
+import opentelemetry, { SpanStatusCode } from '@opentelemetry/api';
+import express from 'express';
+import _ from 'lodash';
+import { z } from 'zod';
+import { validateRequest } from 'zod-express-middleware';
+
+import * as clickhouse from '@/clickhouse';
+import { getTeam } from '@/controllers/team';
+import { translateExternalSeriesToInternalSeries } from '@/utils/externalApi';
+import { externalQueryChartSeriesSchema } from '@/utils/zod';
+
+const router = express.Router();
+
+router.post(
+ '/series',
+ validateRequest({
+ body: z.object({
+ series: z.array(externalQueryChartSeriesSchema).refine(
+ series => {
+ const groupByFields = series[0].groupBy;
+ return series.every(s => _.isEqual(s.groupBy, groupByFields));
+ },
+ {
+ message: 'All series must have the same groupBy fields',
+ },
+ ),
+ endTime: z.number(),
+ granularity: z.nativeEnum(clickhouse.Granularity).optional(),
+ startTime: z.number(),
+ seriesReturnType: z.optional(z.nativeEnum(clickhouse.SeriesReturnType)),
+ }),
+ }),
+ async (req, res, next) => {
+ try {
+ const teamId = req.user?.team;
+ const { endTime, granularity, startTime, seriesReturnType, series } =
+ req.body;
+
+ const internalSeries = series.map(s =>
+ translateExternalSeriesToInternalSeries({
+ type: 'time', // just to reuse the same fn
+ ...s,
+ }),
+ ); | nit: can do this after team validation |
hyperdx | github_2023 | typescript | 279 | hyperdxio | wrn14897 | @@ -0,0 +1,190 @@
+import { z } from 'zod';
+
+import type { IDashboard } from '@/models/dashboard';
+import {
+ chartSchema,
+ externalChartSchema,
+ externalChartSchemaWithId,
+ histogramChartSeriesSchema,
+ markdownChartSeriesSchema,
+ numberChartSeriesSchema,
+ searchChartSeriesSchema,
+ tableChartSeriesSchema,
+ timeChartSeriesSchema,
+} from '@/utils/zod';
+
+export const translateExternalSeriesToInternalSeries = (
+ s: z.infer<typeof externalChartSchema>['series'][number],
+) => {
+ const {
+ type,
+ data_source,
+ aggFn,
+ field,
+ fields,
+ where,
+ groupBy,
+ sortOrder,
+ content,
+ numberFormat,
+ metricDataType,
+ } = s;
+
+ const table = data_source === 'metrics' ? 'metrics' : 'logs';
+
+ if (type === 'time') {
+ if (aggFn == null) {
+ throw new Error('aggFn must be set for time chart');
+ }
+
+ const series: z.infer<typeof timeChartSeriesSchema> = {
+ type: 'time',
+ table,
+ aggFn,
+ where: where ?? '',
+ groupBy: groupBy ?? [],
+ ...(field ? { field } : {}),
+ ...(numberFormat ? { numberFormat } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'table') {
+ if (aggFn == null) {
+ throw new Error('aggFn must be set for table chart');
+ }
+
+ const series: z.infer<typeof tableChartSeriesSchema> = {
+ type: 'table',
+ table,
+ aggFn,
+ where: where ?? '',
+ groupBy: groupBy ?? [],
+ sortOrder: sortOrder ?? 'desc',
+ ...(field ? { field } : {}),
+ ...(numberFormat ? { numberFormat } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'number') {
+ if (aggFn == null) {
+ throw new Error('aggFn must be set for number chart');
+ }
+
+ const series: z.infer<typeof numberChartSeriesSchema> = {
+ type: 'number',
+ table,
+ aggFn,
+ where: where ?? '',
+ ...(field ? { field } : {}),
+ ...(numberFormat ? { numberFormat } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'histogram') {
+ const series: z.infer<typeof histogramChartSeriesSchema> = {
+ type: 'histogram',
+ table,
+ where: where ?? '',
+ ...(field ? { field } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'search') {
+ const series: z.infer<typeof searchChartSeriesSchema> = {
+ type: 'search',
+ fields: fields ?? [],
+ where: where ?? '',
+ };
+
+ return series;
+ } else if (type === 'markdown') {
+ const series: z.infer<typeof markdownChartSeriesSchema> = {
+ type: 'markdown',
+ content: content ?? '',
+ };
+
+ return series;
+ }
+
+ throw new Error(`Invalid chart type ${type}`);
+};
+
+export const translateExternalChartToInternalChart = (
+ chartInput: z.infer<typeof externalChartSchemaWithId>,
+): z.infer<typeof chartSchema> => {
+ const { id, x, name, y, w, h, series, asRatio } = chartInput;
+ return {
+ id,
+ name,
+ x,
+ y,
+ w,
+ h,
+ seriesReturnType: asRatio ? 'ratio' : 'column',
+ series: series.map(s => translateExternalSeriesToInternalSeries(s)),
+ };
+};
+
+const translateChartDocumentToExternalChart = (
+ chart: z.infer<typeof chartSchema>,
+): z.infer<typeof externalChartSchemaWithId> => {
+ const { id, x, name, y, w, h, series, seriesReturnType } = chart;
+ return {
+ id,
+ name,
+ x,
+ y,
+ w,
+ h,
+ asRatio: seriesReturnType === 'ratio',
+ series: series.map(s => {
+ const {
+ type,
+ table,
+ aggFn,
+ field,
+ where,
+ groupBy,
+ sortOrder,
+ content,
+ numberFormat,
+ } = s;
+
+ return {
+ type,
+ data_source: table === 'metrics' ? 'metrics' : 'events', | do we want to make this guy camelcase ? |
hyperdx | github_2023 | typescript | 142 | hyperdxio | MikeShi42 | @@ -120,6 +120,7 @@ const api = {
const endTime = endDate.getTime();
// FIXME: pass metric name and type separately
+ if (!name.includes(' - ')) return; | I think this should be throwing a react error as this will cause a different number of hooks to run from render to render.
I'm not sure what the intent is, but I suspect we want to be actually toggling the `enabled` property of the react-query query. I also suspect we want to add this logic in the component rather than here. |
hyperdx | github_2023 | typescript | 244 | hyperdxio | MikeShi42 | @@ -75,7 +70,7 @@ const AlertSchema = new Schema<IAlert>(
type: String,
required: true,
},
- channel: Schema.Types.Mixed, // slack, email, etc
+ channel: mongoose.Schema.Types.Mixed, | Reading more, I think this is intending to be a objectid pointing to a doc in the channel collection right? |
hyperdx | github_2023 | typescript | 253 | hyperdxio | MikeShi42 | @@ -1019,6 +1024,71 @@ 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(
+ `
+ WITH points AS (
+ SELECT
+ timestamp,
+ name,
+ arraySort((x) -> x[2],
+ groupArray([
+ toFloat64(value),
+ toFloat64OrDefault(_string_attributes['le'], inf)
+ ])
+ ) AS _point,
+ neighbor(_point, -1) AS _prev_point,
+ length(_point) AS n,
+ if (
+ n = length(_prev_point),
+ arrayMap((x, y) -> [x[1] - y[1], x[2]], _point, _prev_point),
+ _point | We should use a NaN here/filter out this point somehow since we can't rely on the point value itself. |
hyperdx | github_2023 | typescript | 253 | hyperdxio | MikeShi42 | @@ -1019,6 +1024,71 @@ 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(
+ `
+ WITH points AS (
+ SELECT
+ timestamp,
+ name,
+ arraySort((x) -> x[2],
+ groupArray([
+ toFloat64(value),
+ toFloat64OrDefault(_string_attributes['le'], inf)
+ ])
+ ) AS _point,
+ neighbor(_point, -1) AS _prev_point,
+ length(_point) AS n,
+ if (
+ n = length(_prev_point),
+ arrayMap((x, y) -> [x[1] - y[1], x[2]], _point, _prev_point),
+ _point
+ ) AS point,
+ mapFilter((k, v) -> (k != 'le'), _string_attributes) AS filtered_string_attributes
+ FROM (?)
+ WHERE mapContains(_string_attributes, 'le')
+ GROUP BY timestamp, name, filtered_string_attributes
+ )
+ SELECT
+ timestamp,
+ name,
+ filtered_string_attributes AS _string_attributes,
+ point[n][1] AS total,
+ toFloat64(?) * total AS rank,
+ arrayFirstIndex(x -> x[1] > rank, point) AS upper_idx,
+ if (
+ upper_idx = n, | we should also check that the last bucket is actually infinite before substituting the 2nd to last bucket |
hyperdx | github_2023 | typescript | 253 | hyperdxio | MikeShi42 | @@ -1019,6 +1024,71 @@ 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(
+ `
+ WITH points AS (
+ SELECT
+ timestamp,
+ name,
+ arraySort((x) -> x[2],
+ groupArray([
+ toFloat64(value),
+ toFloat64OrDefault(_string_attributes['le'], inf)
+ ])
+ ) AS _point,
+ neighbor(_point, -1) AS _prev_point,
+ length(_point) AS n,
+ if (
+ n = length(_prev_point),
+ arrayMap((x, y) -> [x[1] - y[1], x[2]], _point, _prev_point),
+ _point
+ ) AS point,
+ mapFilter((k, v) -> (k != 'le'), _string_attributes) AS filtered_string_attributes
+ FROM (?)
+ WHERE mapContains(_string_attributes, 'le')
+ GROUP BY timestamp, name, filtered_string_attributes
+ )
+ SELECT
+ timestamp,
+ name,
+ filtered_string_attributes AS _string_attributes,
+ point[n][1] AS total,
+ toFloat64(?) * total AS rank,
+ arrayFirstIndex(x -> x[1] > rank, point) AS upper_idx,
+ if (
+ upper_idx = n,
+ point[upper_idx - 1][2],
+ if (
+ upper_idx = 1, | If the bucket boundary is greater than 0, we should interpolate from 0 to bucket boundary. If it's less than 0, we should do this logic of returning the lowest bucket. |
hyperdx | github_2023 | typescript | 253 | hyperdxio | MikeShi42 | @@ -1019,6 +1024,71 @@ 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(
+ `
+ WITH points AS ( | I think we need one more CTE at the top here to properly calculate the group by request from the user, that aggregates bucket counts of all timeseries in a given group. (Ex. add up the counts for all 50 servers in one AWS region, if I wanted to group by AWS region) |
hyperdx | github_2023 | typescript | 268 | hyperdxio | MikeShi42 | @@ -747,6 +780,22 @@ export default function SearchPage() {
setShowSaveSearchModal(true);
}}
/>
+ <Tags | We probably need to add a check to ensure the user is actually looking at a saved search, and hide otherwise. |
hyperdx | github_2023 | typescript | 267 | hyperdxio | wrn14897 | @@ -0,0 +1,373 @@
+import express from 'express';
+import { uniq } from 'lodash';
+import { ObjectId } from 'mongodb';
+import { z } from 'zod';
+import { validateRequest } from 'zod-express-middleware';
+
+import {
+ deleteDashboardAndAlerts,
+ updateDashboardAndAlerts,
+} from '@/controllers/dashboard';
+import Dashboard, { IDashboard } from '@/models/dashboard';
+import {
+ chartSchema,
+ externalChartSchema,
+ externalChartSchemaWithId,
+ histogramChartSeriesSchema,
+ markdownChartSeriesSchema,
+ numberChartSeriesSchema,
+ objectIdSchema,
+ searchChartSeriesSchema,
+ tableChartSeriesSchema,
+ tagsSchema,
+ timeChartSeriesSchema,
+} from '@/utils/zod';
+
+const router = express.Router();
+
+function translateExternalChartToInternalChart(
+ chartInput: z.infer<typeof externalChartSchemaWithId>,
+): z.infer<typeof chartSchema> {
+ const { id, x, name, y, w, h, series, asRatio } = chartInput;
+ return {
+ id,
+ name,
+ x,
+ y,
+ w,
+ h,
+ seriesReturnType: asRatio ? 'ratio' : 'column',
+ series: series.map(s => {
+ const {
+ type,
+ data_source,
+ aggFn,
+ field,
+ fields,
+ where,
+ groupBy,
+ sortOrder,
+ content,
+ numberFormat,
+ metricDataType,
+ } = s;
+
+ const table = data_source === 'metrics' ? 'metrics' : 'logs';
+
+ if (type === 'time') {
+ if (aggFn == null) {
+ throw new Error('aggFn must be set for time chart');
+ }
+
+ const series: z.infer<typeof timeChartSeriesSchema> = {
+ type: 'time',
+ table,
+ aggFn,
+ where: where ?? '',
+ groupBy: groupBy ?? [],
+ ...(field ? { field } : {}),
+ ...(numberFormat ? { numberFormat } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'table') {
+ if (aggFn == null) {
+ throw new Error('aggFn must be set for table chart');
+ }
+
+ const series: z.infer<typeof tableChartSeriesSchema> = {
+ type: 'table',
+ table,
+ aggFn,
+ where: where ?? '',
+ groupBy: groupBy ?? [],
+ sortOrder: sortOrder ?? 'desc',
+ ...(field ? { field } : {}),
+ ...(numberFormat ? { numberFormat } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'number') {
+ if (aggFn == null) {
+ throw new Error('aggFn must be set for number chart');
+ }
+
+ const series: z.infer<typeof numberChartSeriesSchema> = {
+ type: 'number',
+ table,
+ aggFn,
+ where: where ?? '',
+ ...(field ? { field } : {}),
+ ...(numberFormat ? { numberFormat } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'histogram') {
+ const series: z.infer<typeof histogramChartSeriesSchema> = {
+ type: 'histogram',
+ table,
+ where: where ?? '',
+ ...(field ? { field } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'search') {
+ const series: z.infer<typeof searchChartSeriesSchema> = {
+ type: 'search',
+ fields: fields ?? [],
+ where: where ?? '',
+ };
+
+ return series;
+ } else if (type === 'markdown') {
+ const series: z.infer<typeof markdownChartSeriesSchema> = {
+ type: 'markdown',
+ content: content ?? '',
+ };
+
+ return series;
+ }
+
+ throw new Error(`Invalid chart type ${type}`);
+ }),
+ };
+}
+
+const translateChartDocumentToExternalChart = (
+ chart: z.infer<typeof chartSchema>,
+): z.infer<typeof externalChartSchemaWithId> => {
+ const { id, x, name, y, w, h, series, seriesReturnType } = chart;
+ return {
+ id,
+ name,
+ x,
+ y,
+ w,
+ h,
+ asRatio: seriesReturnType === 'ratio',
+ series: series.map(s => {
+ const {
+ type,
+ table,
+ aggFn,
+ field,
+ where,
+ groupBy,
+ sortOrder,
+ content,
+ numberFormat,
+ } = s;
+
+ return {
+ type,
+ data_source: table === 'metrics' ? 'metrics' : 'events',
+ aggFn,
+ field,
+ where,
+ groupBy,
+ sortOrder,
+ content,
+ numberFormat,
+ };
+ }),
+ };
+};
+
+const translateDashboardDocumentToExternalDashboard = (
+ dashboard: IDashboard,
+): {
+ id: string;
+ name: string;
+ charts: z.infer<typeof externalChartSchemaWithId>[];
+ query: string;
+ tags: string[];
+} => {
+ const { _id, name, charts, query, tags } = dashboard;
+
+ return {
+ id: _id.toString(),
+ name,
+ charts: charts.map(translateChartDocumentToExternalChart),
+ query,
+ tags,
+ };
+};
+
+router.get(
+ '/:id',
+ validateRequest({
+ params: z.object({
+ id: objectIdSchema,
+ }),
+ }),
+ async (req, res, next) => {
+ try {
+ const teamId = req.user?.team;
+ if (teamId == null) {
+ return res.sendStatus(403);
+ }
+
+ const dashboard = await Dashboard.findOne(
+ { team: teamId, _id: req.params.id },
+ { _id: 1, name: 1, charts: 1, query: 1 },
+ );
+
+ if (dashboard == null) {
+ return res.sendStatus(404);
+ }
+
+ res.json({
+ data: translateDashboardDocumentToExternalDashboard(dashboard),
+ });
+ } catch (e) {
+ next(e);
+ }
+ },
+);
+
+router.get('/', async (req, res, next) => { | do we need limit and offset for this guy ? |
hyperdx | github_2023 | typescript | 267 | hyperdxio | wrn14897 | @@ -0,0 +1,373 @@
+import express from 'express';
+import { uniq } from 'lodash';
+import { ObjectId } from 'mongodb';
+import { z } from 'zod';
+import { validateRequest } from 'zod-express-middleware';
+
+import {
+ deleteDashboardAndAlerts,
+ updateDashboardAndAlerts,
+} from '@/controllers/dashboard';
+import Dashboard, { IDashboard } from '@/models/dashboard';
+import {
+ chartSchema,
+ externalChartSchema,
+ externalChartSchemaWithId,
+ histogramChartSeriesSchema,
+ markdownChartSeriesSchema,
+ numberChartSeriesSchema,
+ objectIdSchema,
+ searchChartSeriesSchema,
+ tableChartSeriesSchema,
+ tagsSchema,
+ timeChartSeriesSchema,
+} from '@/utils/zod';
+
+const router = express.Router();
+
+function translateExternalChartToInternalChart(
+ chartInput: z.infer<typeof externalChartSchemaWithId>,
+): z.infer<typeof chartSchema> {
+ const { id, x, name, y, w, h, series, asRatio } = chartInput;
+ return {
+ id,
+ name,
+ x,
+ y,
+ w,
+ h,
+ seriesReturnType: asRatio ? 'ratio' : 'column',
+ series: series.map(s => {
+ const {
+ type,
+ data_source,
+ aggFn,
+ field,
+ fields,
+ where,
+ groupBy,
+ sortOrder,
+ content,
+ numberFormat,
+ metricDataType,
+ } = s;
+
+ const table = data_source === 'metrics' ? 'metrics' : 'logs';
+
+ if (type === 'time') {
+ if (aggFn == null) {
+ throw new Error('aggFn must be set for time chart');
+ }
+
+ const series: z.infer<typeof timeChartSeriesSchema> = {
+ type: 'time',
+ table,
+ aggFn,
+ where: where ?? '',
+ groupBy: groupBy ?? [],
+ ...(field ? { field } : {}),
+ ...(numberFormat ? { numberFormat } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'table') {
+ if (aggFn == null) {
+ throw new Error('aggFn must be set for table chart');
+ }
+
+ const series: z.infer<typeof tableChartSeriesSchema> = {
+ type: 'table',
+ table,
+ aggFn,
+ where: where ?? '',
+ groupBy: groupBy ?? [],
+ sortOrder: sortOrder ?? 'desc',
+ ...(field ? { field } : {}),
+ ...(numberFormat ? { numberFormat } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'number') {
+ if (aggFn == null) {
+ throw new Error('aggFn must be set for number chart');
+ }
+
+ const series: z.infer<typeof numberChartSeriesSchema> = {
+ type: 'number',
+ table,
+ aggFn,
+ where: where ?? '',
+ ...(field ? { field } : {}),
+ ...(numberFormat ? { numberFormat } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'histogram') {
+ const series: z.infer<typeof histogramChartSeriesSchema> = {
+ type: 'histogram',
+ table,
+ where: where ?? '',
+ ...(field ? { field } : {}),
+ ...(metricDataType ? { metricDataType } : {}),
+ };
+
+ return series;
+ } else if (type === 'search') {
+ const series: z.infer<typeof searchChartSeriesSchema> = {
+ type: 'search',
+ fields: fields ?? [],
+ where: where ?? '',
+ };
+
+ return series;
+ } else if (type === 'markdown') {
+ const series: z.infer<typeof markdownChartSeriesSchema> = {
+ type: 'markdown',
+ content: content ?? '',
+ };
+
+ return series;
+ }
+
+ throw new Error(`Invalid chart type ${type}`);
+ }),
+ };
+}
+
+const translateChartDocumentToExternalChart = (
+ chart: z.infer<typeof chartSchema>,
+): z.infer<typeof externalChartSchemaWithId> => {
+ const { id, x, name, y, w, h, series, seriesReturnType } = chart;
+ return {
+ id,
+ name,
+ x,
+ y,
+ w,
+ h,
+ asRatio: seriesReturnType === 'ratio',
+ series: series.map(s => {
+ const {
+ type,
+ table,
+ aggFn,
+ field,
+ where,
+ groupBy,
+ sortOrder,
+ content,
+ numberFormat,
+ } = s;
+
+ return {
+ type,
+ data_source: table === 'metrics' ? 'metrics' : 'events',
+ aggFn,
+ field,
+ where,
+ groupBy,
+ sortOrder,
+ content,
+ numberFormat,
+ };
+ }),
+ };
+};
+
+const translateDashboardDocumentToExternalDashboard = (
+ dashboard: IDashboard,
+): {
+ id: string;
+ name: string;
+ charts: z.infer<typeof externalChartSchemaWithId>[];
+ query: string;
+ tags: string[];
+} => {
+ const { _id, name, charts, query, tags } = dashboard;
+
+ return {
+ id: _id.toString(),
+ name,
+ charts: charts.map(translateChartDocumentToExternalChart),
+ query,
+ tags,
+ };
+};
+
+router.get(
+ '/:id',
+ validateRequest({
+ params: z.object({
+ id: objectIdSchema,
+ }),
+ }),
+ async (req, res, next) => {
+ try {
+ const teamId = req.user?.team;
+ if (teamId == null) {
+ return res.sendStatus(403);
+ }
+
+ const dashboard = await Dashboard.findOne(
+ { team: teamId, _id: req.params.id },
+ { _id: 1, name: 1, charts: 1, query: 1 },
+ );
+
+ if (dashboard == null) {
+ return res.sendStatus(404);
+ }
+
+ res.json({
+ data: translateDashboardDocumentToExternalDashboard(dashboard),
+ });
+ } catch (e) {
+ next(e);
+ }
+ },
+);
+
+router.get('/', async (req, res, next) => {
+ try {
+ const teamId = req.user?.team;
+ if (teamId == null) {
+ return res.sendStatus(403);
+ }
+
+ const dashboards = await Dashboard.find(
+ { team: teamId },
+ { _id: 1, name: 1, charts: 1, query: 1 },
+ ).sort({ name: -1 }); | we might want to expose sort query to the user (like name or createdAt) |
hyperdx | github_2023 | typescript | 261 | hyperdxio | MikeShi42 | @@ -507,6 +507,140 @@ const NodesTable = ({
);
};
+const NamespacesTable = ({
+ where,
+ dateRange,
+}: {
+ where: string;
+ dateRange: [Date, Date];
+}) => {
+ const groupBy = ['k8s.namespace.name'];
+
+ const { data, isError, isLoading } = api.useMultiSeriesChart({
+ series: [
+ {
+ table: 'metrics',
+ field: 'k8s.pod.cpu.utilization - Gauge',
+ type: 'table',
+ aggFn: 'avg', | I think it makes more sense to show the aggregate CPU and memory usage via a `sum` here |
hyperdx | github_2023 | typescript | 261 | hyperdxio | MikeShi42 | @@ -507,6 +507,140 @@ const NodesTable = ({
);
};
+const NamespacesTable = ({
+ where,
+ dateRange,
+}: {
+ where: string;
+ dateRange: [Date, Date];
+}) => {
+ const groupBy = ['k8s.namespace.name'];
+
+ const { data, isError, isLoading } = api.useMultiSeriesChart({
+ series: [
+ {
+ table: 'metrics',
+ field: 'k8s.pod.cpu.utilization - Gauge',
+ type: 'table',
+ aggFn: 'avg',
+ where,
+ groupBy,
+ },
+ {
+ table: 'metrics',
+ field: 'k8s.pod.memory.usage - Gauge',
+ type: 'table',
+ aggFn: 'avg',
+ where,
+ groupBy,
+ },
+ {
+ table: 'metrics',
+ field: 'k8s.namespace.phase - Gauge',
+ type: 'table',
+ aggFn: 'avg', | I think we'd want to use `last_value` here |
hyperdx | github_2023 | typescript | 261 | hyperdxio | MikeShi42 | @@ -848,7 +982,61 @@ export default function KubernetesDashboardPage() {
</Grid.Col>
</Grid>
</Tabs.Panel>
- <Tabs.Panel value="namespaces">Namespaces</Tabs.Panel>
+ <Tabs.Panel value="namespaces">
+ <Grid>
+ <Grid.Col span={6}>
+ <Card p="md">
+ <Card.Section p="md" py="xs" withBorder>
+ CPU Usage
+ </Card.Section>
+ <Card.Section p="md" py="sm" h={CHART_HEIGHT}>
+ <HDXLineChart
+ config={{
+ dateRange,
+ granularity: convertDateRangeToGranularityString(
+ dateRange,
+ 60,
+ ),
+ groupBy: 'k8s.namespace.name',
+ where: whereClause,
+ table: 'metrics',
+ aggFn: 'avg', | same here I think we'd want `sum` for cpu/mem |
hyperdx | github_2023 | typescript | 260 | hyperdxio | MikeShi42 | @@ -472,30 +479,37 @@ const NodesTable = ({
) : (
<tbody>
{nodesList.map(node => (
- <tr key={node.name}>
- <td>{node.name || 'N/A'}</td>
- <td>
- {node.ready === 1 ? (
- <Badge color="green" fw="normal" tt="none" size="md">
- Ready
- </Badge>
- ) : (
- <Badge color="red" fw="normal" tt="none" size="md">
- Not Ready
- </Badge>
- )}
- </td>
- <td>
- {formatNumber(
- node.cpuAvg,
- K8S_CPU_PERCENTAGE_NUMBER_FORMAT,
- )}
- </td>
- <td>
- {formatNumber(node.memAvg, K8S_MEM_NUMBER_FORMAT)}
- </td>
- <td>{node.uptime ? formatUptime(node.uptime) : 'โ'}</td>
- </tr>
+ <Link key={node.name} href={getLink(node.name)}> | any chance we can add anchor tags to these so they're more clicky? |
hyperdx | github_2023 | typescript | 260 | hyperdxio | MikeShi42 | @@ -0,0 +1,286 @@
+import * as React from 'react';
+import Link from 'next/link';
+import Drawer from 'react-modern-drawer';
+import { StringParam, useQueryParam, withDefault } from 'use-query-params';
+import {
+ Anchor,
+ Badge,
+ Card,
+ Flex,
+ Grid,
+ SegmentedControl,
+ Text,
+} from '@mantine/core';
+
+import { DrawerBody, DrawerHeader } from './components/DrawerUtils';
+import api from './api';
+import {
+ convertDateRangeToGranularityString,
+ K8S_CPU_PERCENTAGE_NUMBER_FORMAT,
+ K8S_MEM_NUMBER_FORMAT,
+} from './ChartUtils';
+import HDXLineChart from './HDXLineChart';
+import { InfraPodsStatusTable } from './KubernetesDashboardPage';
+import { LogTableWithSidePanel } from './LogTableWithSidePanel';
+import { parseTimeQuery, useTimeQuery } from './timeQuery';
+import { formatUptime } from './utils';
+import { useZIndex, ZIndexContext } from './zIndex';
+
+import styles from '../styles/LogSidePanel.module.scss';
+
+const CHART_HEIGHT = 300;
+const defaultTimeRange = parseTimeQuery('Past 1h', false);
+
+const PodDetailsProperty = React.memo(
+ ({ label, value }: { label: string; value?: React.ReactNode }) => {
+ if (!value) return null;
+ return (
+ <div className="pe-4">
+ <Text size="xs" color="gray.6">
+ {label}
+ </Text>
+ <Text size="sm" color="gray.3">
+ {value}
+ </Text>
+ </div>
+ );
+ },
+);
+
+const NodeDetails = ({
+ name,
+ dateRange,
+}: {
+ name: string;
+ dateRange: [Date, Date];
+}) => {
+ const where = `k8s.node.name:"${name}"`;
+ const groupBy = ['k8s.node.name'];
+
+ const { data } = api.useMultiSeriesChart({
+ series: [
+ {
+ table: 'metrics',
+ field: 'k8s.node.condition_ready - Gauge',
+ type: 'table',
+ aggFn: 'avg',
+ where,
+ groupBy,
+ },
+ {
+ table: 'metrics',
+ field: 'k8s.node.uptime - Sum',
+ type: 'table',
+ aggFn: 'avg',
+ where,
+ groupBy,
+ },
+ ],
+ endDate: dateRange[1] ?? new Date(),
+ startDate: dateRange[0] ?? new Date(),
+ seriesReturnType: 'column',
+ });
+
+ const properties = React.useMemo(() => {
+ const series: Record<string, any> = data?.data?.[0] || {};
+ return {
+ ready: series['series_0.data'],
+ uptime: series['series_1.data'],
+ };
+ }, [data?.data]);
+
+ return (
+ <Grid.Col span={12}>
+ <div className="p-2 gap-2 d-flex flex-wrap">
+ <PodDetailsProperty label="Node" value={name} />
+ <PodDetailsProperty
+ label="Status"
+ value={
+ properties.ready === 1 ? (
+ <Badge color="green" fw="normal" tt="none" size="md">
+ Ready
+ </Badge>
+ ) : (
+ <Badge color="red" fw="normal" tt="none" size="md">
+ Not Ready
+ </Badge>
+ )
+ }
+ />
+ <PodDetailsProperty
+ label="Uptime"
+ value={formatUptime(properties.uptime)}
+ />
+ </div>
+ </Grid.Col>
+ );
+};
+
+function NodeLogs({
+ where,
+ dateRange,
+}: {
+ where: string;
+ dateRange: [Date, Date];
+}) {
+ const [resultType, setResultType] = React.useState<'all' | 'error'>('all');
+
+ const _where = where + (resultType === 'error' ? ' level:err' : '');
+
+ return (
+ <Card p="md">
+ <Card.Section p="md" py="xs" withBorder>
+ <Flex justify="space-between" align="center">
+ Latest Node Logs & Spans
+ <Flex gap="xs" align="center">
+ <SegmentedControl
+ size="xs"
+ value={resultType}
+ onChange={(value: string) => {
+ if (value === 'all' || value === 'error') {
+ setResultType(value);
+ }
+ }}
+ data={[
+ { label: 'All', value: 'all' },
+ { label: 'Errors', value: 'error' },
+ ]}
+ />
+ <Link href={`/search?q=${encodeURIComponent(_where)}`} passHref>
+ <Anchor size="xs" color="dimmed">
+ Search <i className="bi bi-box-arrow-up-right"></i>
+ </Anchor>
+ </Link>
+ </Flex>
+ </Flex>
+ </Card.Section>
+ <Card.Section p="md" py="sm" h={CHART_HEIGHT}>
+ <LogTableWithSidePanel
+ config={{
+ dateRange,
+ where: _where,
+ }}
+ isLive={false}
+ isUTC={false}
+ setIsUTC={() => {}}
+ onPropertySearchClick={() => {}}
+ />
+ </Card.Section>
+ </Card>
+ );
+}
+
+export default function NodeDetailsSidePanel() {
+ const [nodeName, setNodeName] = useQueryParam(
+ 'nodeName',
+ withDefault(StringParam, ''),
+ {
+ updateType: 'replaceIn',
+ },
+ );
+
+ const contextZIndex = useZIndex();
+ const drawerZIndex = contextZIndex + 10;
+
+ const where = React.useMemo(() => {
+ return `k8s.node.name:"${nodeName}"`;
+ }, [nodeName]);
+
+ const { searchedTimeRange: dateRange } = useTimeQuery({
+ isUTC: false,
+ defaultValue: 'Past 1h',
+ defaultTimeRange: [
+ defaultTimeRange?.[0]?.getTime() ?? -1,
+ defaultTimeRange?.[1]?.getTime() ?? -1,
+ ],
+ });
+
+ const handleClose = React.useCallback(() => {
+ setNodeName(undefined);
+ }, [setNodeName]);
+
+ if (!nodeName) {
+ return null;
+ }
+
+ return (
+ <Drawer
+ enableOverlay
+ overlayOpacity={0.1}
+ duration={0}
+ open={!!nodeName}
+ onClose={handleClose}
+ direction="right"
+ size={'80vw'}
+ zIndex={drawerZIndex}
+ >
+ <ZIndexContext.Provider value={drawerZIndex}>
+ <div className={styles.panel}>
+ <DrawerHeader
+ header={`Details for ${nodeName}`}
+ onClose={handleClose}
+ />
+ <DrawerBody>
+ <Grid>
+ <NodeDetails name={nodeName} dateRange={dateRange} />
+ <Grid.Col span={6}>
+ <Card p="md">
+ <Card.Section p="md" py="xs" withBorder>
+ CPU Usage by Pod
+ </Card.Section>
+ <Card.Section p="md" py="sm" h={CHART_HEIGHT}>
+ <HDXLineChart
+ config={{
+ dateRange,
+ granularity: convertDateRangeToGranularityString(
+ dateRange,
+ 60,
+ ),
+ groupBy: 'k8s.pod.name',
+ where,
+ table: 'metrics',
+ aggFn: 'avg',
+ field: 'k8s.pod.cpu.utilization - Gauge',
+ numberFormat: K8S_CPU_PERCENTAGE_NUMBER_FORMAT,
+ }}
+ />
+ </Card.Section>
+ </Card>
+ </Grid.Col>
+ <Grid.Col span={6}>
+ <Card p="md">
+ <Card.Section p="md" py="xs" withBorder>
+ Memory Usage by Pod
+ </Card.Section>
+ <Card.Section p="md" py="sm" h={CHART_HEIGHT}>
+ <HDXLineChart
+ config={{
+ dateRange,
+ granularity: convertDateRangeToGranularityString(
+ dateRange,
+ 60,
+ ),
+ groupBy: 'k8s.pod.name',
+ where,
+ table: 'metrics',
+ aggFn: 'avg',
+ field: 'k8s.pod.memory.usage - Gauge',
+ numberFormat: K8S_MEM_NUMBER_FORMAT,
+ }}
+ />
+ </Card.Section>
+ </Card>
+ </Grid.Col>
+ <Grid.Col span={12}>
+ <InfraPodsStatusTable dateRange={dateRange} where={where} /> | When clicking on the pod table here, the side panel gets obscured behind since it's triggering it in the "wrong" z index context. I wonder if we still need to import side panels like we do with the log side panel (along with the table, instead of just globally on a page). |
hyperdx | github_2023 | typescript | 260 | hyperdxio | MikeShi42 | @@ -0,0 +1,286 @@
+import * as React from 'react';
+import Link from 'next/link';
+import Drawer from 'react-modern-drawer';
+import { StringParam, useQueryParam, withDefault } from 'use-query-params';
+import {
+ Anchor,
+ Badge,
+ Card,
+ Flex,
+ Grid,
+ SegmentedControl,
+ Text,
+} from '@mantine/core';
+
+import { DrawerBody, DrawerHeader } from './components/DrawerUtils';
+import api from './api';
+import {
+ convertDateRangeToGranularityString,
+ K8S_CPU_PERCENTAGE_NUMBER_FORMAT,
+ K8S_MEM_NUMBER_FORMAT,
+} from './ChartUtils';
+import HDXLineChart from './HDXLineChart';
+import { InfraPodsStatusTable } from './KubernetesDashboardPage';
+import { LogTableWithSidePanel } from './LogTableWithSidePanel';
+import { parseTimeQuery, useTimeQuery } from './timeQuery';
+import { formatUptime } from './utils';
+import { useZIndex, ZIndexContext } from './zIndex';
+
+import styles from '../styles/LogSidePanel.module.scss';
+
+const CHART_HEIGHT = 300;
+const defaultTimeRange = parseTimeQuery('Past 1h', false);
+
+const PodDetailsProperty = React.memo(
+ ({ label, value }: { label: string; value?: React.ReactNode }) => {
+ if (!value) return null;
+ return (
+ <div className="pe-4">
+ <Text size="xs" color="gray.6">
+ {label}
+ </Text>
+ <Text size="sm" color="gray.3">
+ {value}
+ </Text>
+ </div>
+ );
+ },
+);
+
+const NodeDetails = ({
+ name,
+ dateRange,
+}: {
+ name: string;
+ dateRange: [Date, Date];
+}) => {
+ const where = `k8s.node.name:"${name}"`;
+ const groupBy = ['k8s.node.name'];
+
+ const { data } = api.useMultiSeriesChart({
+ series: [
+ {
+ table: 'metrics',
+ field: 'k8s.node.condition_ready - Gauge',
+ type: 'table',
+ aggFn: 'avg', | probably want `last_value` for both of these |
hyperdx | github_2023 | typescript | 256 | hyperdxio | svc-shorpo | @@ -528,6 +507,43 @@ const NodesTable = ({
);
};
+const K8sMetricTagValueSelect = ({
+ metricAttribute,
+ searchQuery,
+ setSearchQuery,
+ placeholder,
+ dropdownClosedWidth,
+ icon,
+}: {
+ metricAttribute: string;
+ searchQuery: string;
+ setSearchQuery: (query: string) => void;
+ placeholder: string;
+ dropdownClosedWidth: number;
+ icon: React.ReactNode;
+}) => {
+ return (
+ <MetricTagValueSelect
+ metricName="k8s.pod.cpu.utilization - Gauge"
+ metricAttribute={metricAttribute}
+ value={''} | hmm |
hyperdx | github_2023 | typescript | 252 | hyperdxio | MikeShi42 | @@ -431,3 +431,16 @@ export const formatNumber = (
(options.unit ? ` ${options.unit}` : '')
);
};
+
+// format uptime as days, hours, minutes or seconds
+export const formatUptime = (seconds: number) => {
+ if (seconds < 60) {
+ return `${seconds}s`;
+ } else if (seconds < 60 * 60) {
+ return `${Math.floor(seconds / 60)}m`;
+ } else if (seconds < 60 * 60 * 24) {
+ return `${Math.floor(seconds / 60 / 60)}h`;
+ } else {
+ return `${Math.floor(seconds / 60 / 60 / 24)}d`; | Would https://date-fns.org/v3.2.0/docs/formatDistance or `formatDistanceToNowStrictShort` (in the utils) not work here? |
hyperdx | github_2023 | typescript | 237 | hyperdxio | MikeShi42 | @@ -18,11 +19,16 @@ router.post('/', async (req, res, next) => {
}
const logView = await new LogView({
name,
+ tags,
query: `${query}`,
team: teamId,
creator: userId,
}).save();
-
+ if (tags?.length) {
+ redisClient.del(`tags:${teamId}`).catch(e => { | my 2c is that we should avoid caching complexity until it's warranted. I think for now avoiding caching and just reading directly from mongo would be perfect. Usually just long CH-operations warrant caching (and even then I try to push for cache-less approaches)
Though @wrn14897 maintains the backend so I'll defer to his final judgement :) |
hyperdx | github_2023 | typescript | 237 | hyperdxio | MikeShi42 | @@ -144,4 +148,43 @@ router.patch('/apiKey', async (req, res, next) => {
}
});
+router.get('/tags', async (req, res, next) => {
+ try {
+ const teamId = req.user?.team;
+ if (teamId == null) {
+ throw new Error(`User ${req.user?._id} not associated with a team`);
+ }
+ const simpleCache = new SimpleCache(
+ `tags:${teamId}`,
+ ms('10m'),
+ async () => {
+ const _tags: string[] = [];
+ const dashboards = await Dashboard.find( | We've gotten a bit loose with our standards recently, but our preference is actually that mongoose code lives under a controller, maybe under the `controllers/team.ts` in this case - so that we can encapsulate data fetching separate from router logic. I know that several of our routes don't do this but we've recently talked about trying to get back on track again :) |
hyperdx | github_2023 | typescript | 237 | hyperdxio | wrn14897 | @@ -31,3 +33,24 @@ export function getTeamByApiKey(apiKey: string) {
export function rotateTeamApiKey(teamId: ObjectId) {
return Team.findByIdAndUpdate(teamId, { apiKey: uuidv4() }, { new: true });
}
+
+export async function getTags(teamId: ObjectId) {
+ const dashboardTags = await Dashboard.aggregate([
+ { $match: { team: teamId } },
+ { $unwind: '$tags' },
+ { $group: { _id: '$tags' } },
+ ]);
+
+ const logViewTags = await LogView.aggregate([
+ { $match: { team: teamId } },
+ { $unwind: '$tags' },
+ { $group: { _id: '$tags' } },
+ ]); | we can fetch these concurrently |
hyperdx | github_2023 | typescript | 237 | hyperdxio | wrn14897 | @@ -106,15 +107,15 @@ router.post(
return res.sendStatus(403);
}
- const { name, charts, query } = req.body ?? {};
+ const { name, charts, query, tags } = req.body ?? {}; | we might want to assert the uniqueness of tagging values and also enforce the size limit |
hyperdx | github_2023 | typescript | 237 | hyperdxio | wrn14897 | @@ -108,12 +108,13 @@ router.post(
}
const { name, charts, query, tags } = req.body ?? {};
+
// Create new dashboard from name and charts
const newDashboard = await new Dashboard({
name,
charts,
query,
- tags,
+ tags: tags && uniq(tags), | double check that we want to assign this undefined instead empty array ? |
hyperdx | github_2023 | typescript | 249 | hyperdxio | wrn14897 | @@ -652,3 +652,21 @@ export const buildSearchQueryWhereCondition = async ({
builder.teamId = teamId;
return await builder.timestampInBetween(startTime, endTime).build();
};
+
+export const buildPostGroupWhereCondition = ({ query }: { query: string }) => { | nit: I wonder why we don't pass query string directly |
hyperdx | github_2023 | typescript | 251 | hyperdxio | wrn14897 | @@ -37,7 +37,7 @@ export const timeChartSeriesSchema = z.object({
aggFn: aggFnSchema,
field: z.union([z.string(), z.undefined()]),
where: z.string(),
- groupBy: z.array(z.string()),
+ groupBy: z.array(z.string()).max(10), | ๐ |
hyperdx | github_2023 | typescript | 250 | hyperdxio | wrn14897 | @@ -189,6 +190,27 @@ export class SQLSerializer implements Serializer {
};
}
+ operator(op: lucene.Operator) {
+ switch (op) {
+ case 'NOT':
+ case 'AND NOT':
+ return 'AND NOT';
+ case 'OR NOT':
+ return 'OR NOT';
+ // @ts-ignore TODO: Types need to be fixed upstream
+ case '&&':
+ case '<implicit>': | nit: use `IMPLICIT_FIELD` ? |
hyperdx | github_2023 | typescript | 242 | hyperdxio | MikeShi42 | @@ -14,3 +14,4 @@ export const IS_OSS = process.env.NEXT_PUBLIC_IS_OSS ?? 'true' === 'true';
export const METRIC_ALERTS_ENABLED = process.env.NODE_ENV === 'development';
export const K8S_METRICS_ENABLED = process.env.NODE_ENV === 'development';
export const SERVICE_DASHBOARD_ENABLED = process.env.NODE_ENV === 'development';
+export const K8S_DASHBOARD_ENABLED = process.env.NODE_ENV === 'development'; | just a note for next time - we're starting to think of using specific env flags for specific features ex. `NEXT_PUBLIC_DEV_K8S_DASHBOARD_ENABLED`, this makes it easier to opt-in/out of UI on various environments like being able to do more dogfooding in staging without mucking NODE_ENV there.
Let's ship this as-is and this is an easy fix once we're closer to getting this in staging. |
hyperdx | github_2023 | typescript | 235 | hyperdxio | MikeShi42 | @@ -0,0 +1,168 @@
+import * as React from 'react';
+import { useRouter } from 'next/router';
+import { SpotlightAction, SpotlightProvider } from '@mantine/spotlight';
+
+import api from './api';
+import { SERVICE_DASHBOARD_ENABLED } from './config';
+import Logo from './Icon';
+
+const useSpotlightActions = () => {
+ const router = useRouter();
+
+ const { data: logViewsData } = api.useLogViews();
+ const { data: dashboardsData } = api.useDashboards();
+
+ const actions = React.useMemo<SpotlightAction[]>(() => {
+ const logViews = logViewsData?.data ?? [];
+ const dashboards = dashboardsData?.data ?? [];
+
+ const logViewActions: SpotlightAction[] = [];
+
+ // Saved searches
+ logViews.forEach(logView => {
+ logViewActions.push({
+ group: 'Saved searches',
+ icon: <i className="bi bi-layout-text-sidebar-reverse" />,
+ description: logView.query,
+ title: logView.name,
+ keywords: ['search', 'log', 'saved'],
+ onTrigger: () => {
+ router.push(`/search/${logView._id}`);
+ },
+ });
+ });
+
+ // Dashboards
+ dashboards.forEach(dashboard => {
+ logViewActions.push({
+ group: 'Dashboards',
+ icon: <i className="bi bi-grid-1x2" />,
+ title: dashboard.name,
+ keywords: ['dashboard'],
+ onTrigger: () => {
+ router.push(`/dashboards/${dashboard._id}`);
+ },
+ });
+ });
+
+ logViewActions.push(
+ {
+ group: 'Menu',
+ icon: <i className="bi bi-layout-text-sidebar-reverse" />,
+ title: 'Search',
+ description: 'Start a new search',
+ keywords: ['log', 'events', 'logs'],
+ onTrigger: () => {
+ router.push('/search');
+ },
+ },
+ {
+ group: 'Menu',
+ icon: <i className="bi bi-graph-up" />,
+ title: 'Chart Explorer',
+ description: 'Explore your data',
+ keywords: ['graph', 'metrics'],
+ onTrigger: () => {
+ router.push('/chart');
+ },
+ },
+ {
+ group: 'Menu',
+ icon: <i className="bi bi-grid-1x2" />,
+ title: 'New Dashboard',
+ description: 'Create a new dashboard',
+ keywords: ['graph'],
+ onTrigger: () => {
+ router.push('/dashboards');
+ },
+ },
+ {
+ group: 'Menu',
+ icon: <i className="bi bi-laptop" />,
+ title: 'Client Sessions',
+ description: 'View client sessions',
+ keywords: ['browser', 'web'],
+ onTrigger: () => {
+ router.push('/sessions');
+ },
+ },
+ {
+ group: 'Menu',
+ icon: <i className="bi bi-bell" />,
+ title: 'Alerts',
+ description: 'View and manage alerts',
+ onTrigger: () => {
+ router.push('/alerts');
+ },
+ },
+ ...(SERVICE_DASHBOARD_ENABLED
+ ? [
+ {
+ group: 'Menu',
+ title: 'Service Health',
+ icon: <i className="bi bi-heart-pulse" />,
+ description: 'HTTP, Database and Infrastructure metrics',
+ onTrigger: () => {
+ router.push('/services');
+ },
+ },
+ ]
+ : []),
+ {
+ group: 'Menu',
+ icon: <i className="bi bi-gear" />,
+ title: 'Team Settings',
+
+ onTrigger: () => {
+ router.push('/team');
+ },
+ },
+ {
+ group: 'Menu',
+ icon: <i className="bi bi-question-circle" />,
+ title: 'Documentation',
+ keywords: ['help', 'docs'],
+ onTrigger: () => {
+ router.push('/help'); | this should go to https://www.hyperdx.io/docs |
hyperdx | github_2023 | typescript | 234 | hyperdxio | MikeShi42 | @@ -645,7 +645,7 @@ export default function SearchPage() {
}, [setResultsMode]);
return (
- <div className="LogViewerPage d-flex" style={{ height: '100vh' }}> | Testing out locally I suspect this is breaking the search table scroll behavior (we're scrolling the page instead of the search results) |
hyperdx | github_2023 | typescript | 231 | hyperdxio | jaggederest | @@ -514,6 +517,27 @@ export default function AppNav({ fixed = false }: { fixed?: boolean }) {
: 'ok' // All alerts are green
: 'none'; // No alerts are set up
+ const [searchesListQ, setSearchesListQ] = useState(''); | Could consider using local storage here and for `dashboardsListQ`, too. |
hyperdx | github_2023 | typescript | 231 | hyperdxio | jaggederest | @@ -514,6 +517,27 @@ export default function AppNav({ fixed = false }: { fixed?: boolean }) {
: 'ok' // All alerts are green
: 'none'; // No alerts are set up
+ const [searchesListQ, setSearchesListQ] = useState('');
+ const [dashboardsListQ, setDashboardsListQ] = useState('');
+
+ const filteredSearchesList = useMemo(() => {
+ if (searchesListQ === '') {
+ return logViews;
+ }
+ return logViews.filter(lv =>
+ lv.name.toLocaleLowerCase().includes(searchesListQ.toLocaleLowerCase()), | Nit: These are probably a candidate for future refactoring into a function since they look identical except the `logViews` and `searchesListQ` parameter differences ๐ |
hyperdx | github_2023 | typescript | 231 | hyperdxio | jaggederest | @@ -808,41 +851,54 @@ export default function AppNav({ fixed = false }: { fixed?: boolean }) {
query.config !=
JSON.stringify(REDIS_DASHBOARD_CONFIG) &&
query.config != JSON.stringify(MONGO_DASHBOARD_CONFIG)
- ? 'text-success fw-bold'
- : 'text-muted-hover',
+ ? [styles.listLinkActive]
+ : null,
)}
>
- <i className="bi bi-plus me-2" />
- New Dashboard
+ <div className="my-1">
+ <i className="bi bi-plus me-2" />
+ New Dashboard
+ </div>
</a>
</Link>
- <div className="fw-bold text-light fs-8 ms-3 mt-3">
- SAVED DASHBOARDS
- </div>
- {(dashboards ?? []).length === 0 ? (
- <div className="text-muted ms-3 mt-2">0 saved dashboards</div>
+ <Input
+ placeholder="Saved Dashboards"
+ variant="unstyled"
+ size="xs"
+ ml={4}
+ icon={<i className="bi bi-search fs-8 ps-1" />}
+ rightSection={
+ dashboardsListQ && (
+ <CloseButton
+ size="xs"
+ onClick={() => setDashboardsListQ('')}
+ />
+ )
+ }
+ value={dashboardsListQ}
+ onChange={e => setDashboardsListQ(e.currentTarget.value)}
+ />
+ {dashboards.length === 0 ? (
+ <div className="text-slate-300 fs-8 p-2 px-3">
+ No saved dashboards | Nit: Should probably match the `No results matching <i>{searchesListQ}</i>` style above |
hyperdx | github_2023 | typescript | 231 | hyperdxio | MikeShi42 | @@ -426,6 +423,64 @@ function PresetSearchLink({ query, name }: { query: string; name: string }) {
);
}
+function SearchInput({
+ placeholder,
+ value,
+ onChange,
+}: {
+ placeholder: string;
+ value: string;
+ onChange: (arg0: string) => void;
+}) {
+ return (
+ <Input
+ placeholder={placeholder}
+ value={value}
+ onChange={e => onChange(e.currentTarget.value)}
+ icon={<i className="bi bi-search fs-8 ps-1" />}
+ rightSection={
+ value && (
+ <CloseButton size="xs" radius="xl" onClick={() => onChange('')} />
+ )
+ }
+ mt={8}
+ size="xs"
+ variant="filled"
+ radius="xl"
+ sx={{
+ input: {
+ minHeight: 28,
+ height: 28,
+ lineHeight: 28,
+ },
+ }}
+ />
+ );
+}
+
+function useSearchableList<T extends { name: string }>({
+ items,
+}: {
+ items: T[];
+}) {
+ const [q, setQ] = useState('');
+
+ const filteredList = useMemo(() => {
+ if (q === '') {
+ return items;
+ }
+ return items.filter(item => | just an fyi, we do have fuse.js already included and can use it in the future as well for fancy search :) |
hyperdx | github_2023 | typescript | 231 | hyperdxio | MikeShi42 | @@ -592,58 +665,90 @@ export default function AppNav({ fixed = false }: { fixed?: boolean }) {
/>
)}
</div>
- {isSearchExpanded && !isCollapsed && (
- <>
- <div className="fw-bold text-light fs-8 ms-3 mt-3">
- SAVED SEARCHES
- </div>
- {(logViews ?? []).length === 0 ? (
- <div className="text-muted ms-3 mt-2">No saved searches</div>
- ) : null}
- {(logViews ?? []).map(lv => (
- <Link
- href={`/search/${lv._id}?${new URLSearchParams(
- timeRangeQuery.from != -1 && timeRangeQuery.to != -1
- ? {
- from: timeRangeQuery.from.toString(),
- to: timeRangeQuery.to.toString(),
- tq: inputTimeQuery,
- }
- : {},
- ).toString()}`}
- key={lv._id}
- >
+ {!isCollapsed && isSearchExpanded && (
+ <div className={styles.list}>
+ {isLogViewsLoading ? (
+ <Loader
+ color="gray.7"
+ variant="dots"
+ mx="md"
+ my="xs"
+ size="sm"
+ />
+ ) : logViews.length === 0 ? (
+ <Link href="/search">
<a
className={cx(
- 'd-flex justify-content-between ms-3 mt-2 cursor-pointer text-decoration-none',
- {
- 'text-success fw-bold':
- lv._id === query.savedSearchId,
- 'text-muted-hover': lv._id !== query.savedSearchId,
- },
+ styles.listLink,
+ pathname.includes('search') &&
+ Object.keys(query).length === 0 &&
+ styles.listLinkActive,
)}
- title={lv.name}
>
- <div className="d-inline-block text-truncate">
- {lv.name}
+ <div className="mt-1 "> | Just dup'ing the same message in chat, not totally sold on using `Live Tail` for empty state, I think ideally we still try to hint to the user as much as we can that they can create saved searches. |
hyperdx | github_2023 | typescript | 200 | hyperdxio | wrn14897 | @@ -1,6 +1,16 @@
+export type JSONBlob = Record<string, Json>;
+
+export type Json =
+ | string
+ | number
+ | boolean
+ | null
+ | Json[]
+ | { [key: string]: Json }; | This can be `JSONBlob` |
hyperdx | github_2023 | typescript | 200 | hyperdxio | wrn14897 | @@ -123,7 +121,7 @@ export const mapObjectToKeyValuePairs = async (
const pushArray = (
type: 'bool' | 'number' | 'string',
keyPath: string,
- value: any,
+ value: number | string, // Note that booleans are converted to 0 or 1 | ๐ |
hyperdx | github_2023 | typescript | 200 | hyperdxio | wrn14897 | @@ -247,17 +245,26 @@ export type VectorMetric = {
v: number; // value
};
-abstract class ParsingInterface<T> {
- abstract _parse(
- log: T,
- ...args: any[]
- ): Promise<LogStreamModel | MetricModel | RrwebEventModel>;
+const convertToStringMap = (blob: JSONBlob) => { | Can we leave non-type changes to another PR ? What is this change about ? Any chance we can reuse `mapObjectToKeyValuePairs` ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.