Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/api/.env.development
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ INGESTION_API_KEY="super-secure-ingestion-api-key"
HYPERDX_API_KEY=$INGESTION_API_KEY
ANTHROPIC_API_KEY="your-anthropic-api-key-here"
ENABLE_PROMQL=true
ENABLE_SLOS=true
1 change: 1 addition & 0 deletions packages/api/.env.test
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ OPAMP_PORT=${HDX_CI_OPAMP_PORT:-14320}
# operational noise (validation errors, MCP tool errors, etc.) during tests.
HYPERDX_LOG_LEVEL=error
ENABLE_PROMQL=true
ENABLE_SLOS=true
4 changes: 4 additions & 0 deletions packages/api/src/api-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import favoritesRouter from './routers/api/favorites';
import iacRouter from './routers/api/iac';
import pinnedFiltersRouter from './routers/api/pinnedFilters';
import savedSearchRouter from './routers/api/savedSearch';
import slosRouter from './routers/api/slos';
import sourcesRouter from './routers/api/sources';
import externalRoutersV2 from './routers/external-api/v2';
import usageStats from './tasks/usageStats';
Expand Down Expand Up @@ -123,6 +124,9 @@ app.use('/iac', isUserAuthenticated, iacRouter);
if (config.IS_PROMQL_ENABLED) {
app.use('/v1/prometheus', isUserAuthenticated, routers.prometheusRouter);
}
if (config.IS_SLOS_ENABLED) {
app.use('/slos', isUserAuthenticated, slosRouter);
}
// ---------------------------------------------------------------------

// TODO: Separate external API routers from internal routers
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export const DEFAULT_CONNECTIONS = env.DEFAULT_CONNECTIONS;
export const DEFAULT_SOURCES = env.DEFAULT_SOURCES;

export const IS_PROMQL_ENABLED = env.ENABLE_PROMQL === 'true';
export const IS_SLOS_ENABLED = env.ENABLE_SLOS === 'true';

export const EXTERNAL_API_RATE_LIMIT_MAX = (() => {
const parsed = Number(env.EXTERNAL_API_RATE_LIMIT_MAX);
Expand Down
223 changes: 223 additions & 0 deletions packages/api/src/controllers/slo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
import type { ClickhouseClient as BaseClickhouseClient } from '@hyperdx/common-utils/dist/clickhouse/node';
import { tryOptimizeConfigWithMaterializedView } from '@hyperdx/common-utils/dist/core/materializedViews';
import {
getMetadata,
Metadata,
} from '@hyperdx/common-utils/dist/core/metadata';
import { buildSloCountsChartConfig } from '@hyperdx/common-utils/dist/core/slo';
import {
SLO_MAX_PER_TEAM,
SloApiResponse,
SloDefinition,
} from '@hyperdx/common-utils/dist/slo';
import {
BuilderChartConfigWithDateRange,
isLogSource,
isTraceSource,
SourceKind,
TSource,
} from '@hyperdx/common-utils/dist/types';
import mongoose from 'mongoose';
import { performance } from 'perf_hooks';

import { ClickhouseClient } from '@/clickhouse';
import { getConnectionById } from '@/controllers/connection';
import { getSource } from '@/controllers/sources';
import Slo, { ISlo } from '@/models/slo';
import { getClickHouseErrorType } from '@/utils/clickhouseErrors';
import { Api400Error } from '@/utils/errors';

type SloQueryContext = {
source: TSource;
clickhouseClient: BaseClickhouseClient;
metadata: Metadata;
};

/** SLOs are defined on log or trace sources the team owns. */
async function getSloSource(teamId: string, sourceId: string) {
const source = await getSource(teamId, sourceId);
if (!source) {
throw new Api400Error(`Source not found: ${sourceId}`);
}
if (source.kind !== SourceKind.Log && source.kind !== SourceKind.Trace) {
throw new Api400Error(
`SLOs are defined on log or trace sources; "${source.name}" is a ${source.kind} source.`,
);
}
return source;
}

async function getSloQueryContext(
teamId: string,
sourceId: string,
timeoutMs: number,
): Promise<SloQueryContext> {
const source = await getSloSource(teamId, sourceId);
const connection = await getConnectionById(
teamId,
source.connection.toString(),
true,
);
if (!connection) {
throw new Api400Error(`Connection not found for source: ${sourceId}`);
}
const clickhouseClient = new ClickhouseClient({
host: connection.host,
username: connection.username,
password: connection.password,
requestTimeout: timeoutMs,
});
return { source, clickhouseClient, metadata: getMetadata(clickhouseClient) };
}

/**
* Runs an SLO query, from a materialized view of the source when one covers
* it, as charts and alerts do; otherwise from the source's table. A timeout
* ends the query sooner than the client's own.
*/
async function runSloQuery(
ctx: SloQueryContext,
config: BuilderChartConfigWithDateRange,
timeoutMs?: number,
) {
const startedAt = performance.now();
const signal = timeoutMs != null ? AbortSignal.timeout(timeoutMs) : undefined;
const { source } = ctx;
const optimized =
(isLogSource(source) || isTraceSource(source)) &&
source.materializedViews?.length
? await tryOptimizeConfigWithMaterializedView(
config,
ctx.metadata,
ctx.clickhouseClient,
signal,
source,
)
: config;
const result = await ctx.clickhouseClient.queryChartConfig({
config: optimized,
metadata: ctx.metadata,
querySettings: source.querySettings,
opts: { abort_signal: signal },
});
return {
rows: result.data,
rowsRead: Number(result.statistics?.rows_read ?? 0),
durationMs: Math.round(performance.now() - startedAt),
};
}

/** The save-time check reads one minute, enough to compile and run the query. */
const SLO_CHECK_RANGE_MS = 60_000;
const SLO_CHECK_TIMEOUT_MS = 15_000;

/**
* Runs the SLO's counts query over the last minute, so a condition ClickHouse
* rejects (an unknown column, a syntax error) fails the save with ClickHouse's
* message instead of turning up later as an error state.
*/
async function checkSloQuery(teamId: string, definition: SloDefinition) {
const ctx = await getSloQueryContext(
teamId,
definition.source,
SLO_CHECK_TIMEOUT_MS,
);
const now = new Date();
try {
await runSloQuery(
ctx,
buildSloCountsChartConfig({
slo: definition,
source: ctx.source,
dateRange: [new Date(now.getTime() - SLO_CHECK_RANGE_MS), now],
// By group when there is one, so a bad group-by fails the save too.
scope: { byGroup: true },
}),
);
} catch (e) {
// Only errors ClickHouse returned describe the definition; a network
// failure is the server's problem, not the user's.
if (getClickHouseErrorType(e) != null && e instanceof Error) {
throw new Api400Error(`The SLO's query failed: ${e.message}`);
}
throw e;
}
}

export function listSlos(teamId: string) {
return Slo.find({ team: teamId }).sort({ name: 1 }).lean();
}

export function getSlo(teamId: string, sloId: string) {
if (!mongoose.Types.ObjectId.isValid(sloId)) return null;
return Slo.findOne({ _id: sloId, team: teamId }).lean();
}

export async function createSlo(
teamId: string,
userId: string | undefined,
definition: SloDefinition,
) {
if ((await Slo.countDocuments({ team: teamId })) >= SLO_MAX_PER_TEAM) {
throw new Api400Error(`A team can have at most ${SLO_MAX_PER_TEAM} SLOs`);
}
await checkSloQuery(teamId, definition);
return (
await Slo.create({
...definition,
groupBy: definition.groupBy || null,
team: teamId,
createdBy: userId,
updatedBy: userId,
})
).toObject();
}

export async function updateSlo(
teamId: string,
sloId: string,
userId: string | undefined,
definition: SloDefinition,
) {
const existing = await getSlo(teamId, sloId);
if (!existing) return null;
await checkSloQuery(teamId, definition);
return Slo.findOneAndUpdate(
{ _id: sloId, team: teamId },
{
$set: {
...definition,
description: definition.description ?? '',
groupBy: definition.groupBy || null,
updatedBy: userId,
},
},
{ new: true },
).lean();
}

export async function deleteSlo(teamId: string, sloId: string) {
if (!mongoose.Types.ObjectId.isValid(sloId)) return false;
const result = await Slo.deleteOne({ _id: sloId, team: teamId });
return result.deletedCount > 0;
}

export function formatSlo(slo: ISlo): SloApiResponse {
return {
id: slo._id.toString(),
version: slo.version,
name: slo.name,
description: slo.description,
tags: slo.tags ?? [],
source: slo.source.toString(),
indicator: slo.indicator,
target: slo.target,
window: slo.window,
groupBy: slo.groupBy ?? null,
alerts: slo.alerts ?? {},
status: slo.status ?? null,
alertStates: {},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 P2 — The per-team SLO limit is a check-then-insert with a 15s ClickHouse query in between, so concurrent creates can exceed SLO_MAX_PER_TEAM

Run the count check after checkSloQuery, right before Slo.create, to shrink the window. If the limit has to hold strictly, enforce it atomically, for example with a per-team counter updated by findOneAndUpdate with $lt.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

createdAt: slo.createdAt.toISOString(),
updatedAt: slo.updatedAt.toISOString(),
};
}
66 changes: 66 additions & 0 deletions packages/api/src/models/slo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import type { SloDefinition, SloStatus } from '@hyperdx/common-utils/dist/slo';
import mongoose, { Schema } from 'mongoose';

import type { ObjectId } from '.';

export interface ISlo extends Omit<SloDefinition, 'source'> {
_id: ObjectId;
team: ObjectId;
source: ObjectId;
/**
* Latest snapshot, refreshed in the background and stored with the
* definition so lists and the detail page read it without querying.
*/
status?: SloStatus | null;
createdBy?: ObjectId;
updatedBy?: ObjectId;
createdAt: Date;
updatedAt: Date;
}

const SloSchema = new Schema<ISlo>(
{
version: { type: Number, required: true, default: 1 },
name: { type: String, required: true },
description: { type: String, required: false },
tags: { type: [String], default: [] },
// Immutable: `team` pins an SLO to its owning tenant.
team: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Team',
required: true,
immutable: true,
},
source: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Source',
required: true,
},
// Validated by SloInputSchema at the API boundary.
indicator: { type: Schema.Types.Mixed, required: true },
target: { type: Number, required: true },
window: { type: String, required: true },
// Expression whose values each get their own numbers and alert.
groupBy: { type: String, required: false },
status: { type: Schema.Types.Mixed, required: false },
// Immutable: ownership attribution is set once at creation.
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: false,
immutable: true,
},
updatedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: false,
},
},
{ timestamps: true },
);

SloSchema.index({ team: 1, name: 1 });
// The status refresh picks the stalest snapshots first.
SloSchema.index({ 'status.evaluatedAt': 1 });

export default mongoose.model<ISlo>('Slo', SloSchema);
Loading
Loading