diff --git a/packages/api/.env.development b/packages/api/.env.development index 54c44226d..9461f17a2 100644 --- a/packages/api/.env.development +++ b/packages/api/.env.development @@ -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 diff --git a/packages/api/.env.test b/packages/api/.env.test index bf91334d1..9638ea325 100644 --- a/packages/api/.env.test +++ b/packages/api/.env.test @@ -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 diff --git a/packages/api/src/api-app.ts b/packages/api/src/api-app.ts index cf1928230..da454b284 100644 --- a/packages/api/src/api-app.ts +++ b/packages/api/src/api-app.ts @@ -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'; @@ -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 diff --git a/packages/api/src/config.ts b/packages/api/src/config.ts index 2fb4e311c..1dbf13a3c 100644 --- a/packages/api/src/config.ts +++ b/packages/api/src/config.ts @@ -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); diff --git a/packages/api/src/controllers/slo.ts b/packages/api/src/controllers/slo.ts new file mode 100644 index 000000000..7cc8eaca0 --- /dev/null +++ b/packages/api/src/controllers/slo.ts @@ -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 { + 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: {}, + createdAt: slo.createdAt.toISOString(), + updatedAt: slo.updatedAt.toISOString(), + }; +} diff --git a/packages/api/src/models/slo.ts b/packages/api/src/models/slo.ts new file mode 100644 index 000000000..a2bd61993 --- /dev/null +++ b/packages/api/src/models/slo.ts @@ -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 { + _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( + { + 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('Slo', SloSchema); diff --git a/packages/api/src/routers/api/__tests__/slos.int.test.ts b/packages/api/src/routers/api/__tests__/slos.int.test.ts new file mode 100644 index 000000000..f30e9c9a8 --- /dev/null +++ b/packages/api/src/routers/api/__tests__/slos.int.test.ts @@ -0,0 +1,154 @@ +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import mongoose from 'mongoose'; + +import * as config from '@/config'; +import { + DEFAULT_DATABASE, + DEFAULT_TRACES_TABLE, + getLoggedInAgent, + getServer, +} from '@/fixtures'; +import Connection from '@/models/connection'; +import Slo from '@/models/slo'; +import { Source } from '@/models/source'; + +// ClickHouse is shared across tests and files, so scope every SLO to this +// run's service. +const SERVICE = `slo-${Date.now()}`; + +describe('SLO router', () => { + const server = getServer(); + let agent: Awaited>['agent']; + let sourceId: string; + + const definition = (overrides: Record = {}) => ({ + name: 'Checkout availability', + source: sourceId, + indicator: { + template: 'availability', + eligible: { where: `ServiceName = '${SERVICE}'`, whereLanguage: 'sql' }, + good: "StatusCode != 'Error'", + }, + target: 99, + window: '7d', + ...overrides, + }); + + beforeAll(async () => { + await server.start(); + }); + + beforeEach(async () => { + const result = await getLoggedInAgent(server); + agent = result.agent; + const connection = await Connection.create({ + team: result.team._id, + name: 'Default', + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + const source = await Source.create({ + kind: SourceKind.Trace, + team: result.team._id, + from: { databaseName: DEFAULT_DATABASE, tableName: DEFAULT_TRACES_TABLE }, + timestampValueExpression: 'Timestamp', + connection: connection._id, + name: 'Traces', + traceIdExpression: 'TraceId', + spanIdExpression: 'SpanId', + parentSpanIdExpression: 'ParentSpanId', + spanNameExpression: 'SpanName', + spanKindExpression: 'SpanKind', + durationExpression: 'Duration', + durationPrecision: 9, + statusCodeExpression: 'StatusCode', + }); + sourceId = source._id.toString(); + }); + + afterEach(async () => { + await server.clearDBs(); + }); + + afterAll(async () => { + await server.stop(); + }); + + it('creates, lists, updates and deletes an SLO', async () => { + const created = await agent.post('/slos').send(definition()).expect(200); + expect(created.body).toEqual( + expect.objectContaining({ + name: 'Checkout availability', + source: sourceId, + target: 99, + window: '7d', + alerts: {}, + // Computed in the background, never in the request. + status: null, + }), + ); + const id = created.body.id; + + const list = await agent.get('/slos').expect(200); + expect(list.body.map((slo: { id: string }) => slo.id)).toEqual([id]); + + await agent + .put(`/slos/${id}`) + .send(definition({ name: 'Checkout success' })) + .expect(200); + const fetched = await agent.get(`/slos/${id}`).expect(200); + expect(fetched.body.name).toBe('Checkout success'); + + await agent.delete(`/slos/${id}`).expect(204); + await agent.get(`/slos/${id}`).expect(404); + }); + + it('rejects a definition it cannot save, saying why', async () => { + await agent + .post('/slos') + .send(definition({ name: ' ' })) + .expect(400); + await agent + .post('/slos') + .send( + definition({ + indicator: { + template: 'availability', + eligible: { where: '', whereLanguage: 'sql' }, + }, + }), + ) + .expect(400); + // ClickHouse cannot run the condition: the save fails with its message. + const rejected = await agent + .post('/slos') + .send( + definition({ + indicator: { + template: 'availability', + eligible: { where: '', whereLanguage: 'sql' }, + good: "StatusCod != 'Error'", + }, + }), + ) + .expect(400); + expect(rejected.body.message).toContain('StatusCod'); + expect(await Slo.countDocuments()).toBe(0); + }); + + it("does not expose another team's SLO", async () => { + const other = await Slo.create({ + ...definition(), + source: new mongoose.Types.ObjectId(), + team: new mongoose.Types.ObjectId(), + }); + const id = other._id.toString(); + + await agent.get(`/slos/${id}`).expect(404); + await agent.put(`/slos/${id}`).send(definition()).expect(404); + await agent.delete(`/slos/${id}`).expect(404); + expect((await agent.get('/slos').expect(200)).body).toEqual([]); + expect(await Slo.exists({ _id: id })).toBeTruthy(); + }); +}); diff --git a/packages/api/src/routers/api/slos.ts b/packages/api/src/routers/api/slos.ts new file mode 100644 index 000000000..3350f63b7 --- /dev/null +++ b/packages/api/src/routers/api/slos.ts @@ -0,0 +1,113 @@ +import { withQueryAttribution } from '@hyperdx/common-utils/dist/clickhouse/node'; +import { SloInputSchema } from '@hyperdx/common-utils/dist/slo'; +import express from 'express'; +import { z } from 'zod/v3'; +import { processRequest, validateRequest } from 'zod-express-middleware'; + +import { + createSlo, + deleteSlo, + formatSlo, + getSlo, + listSlos, + updateSlo, +} from '@/controllers/slo'; +import { getNonNullUserWithTeam } from '@/middleware/auth'; +import { setBusinessContext } from '@/utils/instrumentation'; +import { objectIdSchema } from '@/utils/zod'; + +const router = express.Router(); + +// Saves run a short check query against ClickHouse; tag it as an SLO read on +// top of the `api` scope the auth middleware opened. +router.use((_req, _res, next) => { + withQueryAttribution({ surface: 'slo' }, () => next()); +}); + +// As effects, so processRequest types the parsed request as the schemas' +// output (with defaults applied) rather than their input. +const sloIdParams = z + .object({ id: objectIdSchema }) + .transform(params => params); +const sloBody = SloInputSchema.transform(definition => definition); + +router.get('/', async (req, res, next) => { + try { + const { teamId } = getNonNullUserWithTeam(req); + setBusinessContext({ teamId: teamId.toString() }); + const slos = await listSlos(teamId.toString()); + res.json(slos.map(slo => formatSlo(slo))); + } catch (e) { + next(e); + } +}); + +router.get( + '/:id', + validateRequest({ params: sloIdParams }), + async (req, res, next) => { + try { + const { teamId } = getNonNullUserWithTeam(req); + setBusinessContext({ teamId: teamId.toString() }); + const slo = await getSlo(teamId.toString(), req.params.id); + if (!slo) return res.sendStatus(404); + res.json(formatSlo(slo)); + } catch (e) { + next(e); + } + }, +); + +router.post('/', processRequest({ body: sloBody }), async (req, res, next) => { + try { + const { teamId, userId } = getNonNullUserWithTeam(req); + setBusinessContext({ teamId: teamId.toString() }); + const slo = await createSlo( + teamId.toString(), + userId?.toString(), + req.body, + ); + res.json(formatSlo(slo)); + } catch (e) { + next(e); + } +}); + +router.put( + '/:id', + processRequest({ params: sloIdParams, body: sloBody }), + async (req, res, next) => { + try { + const { teamId, userId } = getNonNullUserWithTeam(req); + setBusinessContext({ teamId: teamId.toString() }); + const slo = await updateSlo( + teamId.toString(), + req.params.id, + userId?.toString(), + req.body, + ); + if (!slo) return res.sendStatus(404); + res.json(formatSlo(slo)); + } catch (e) { + next(e); + } + }, +); + +router.delete( + '/:id', + validateRequest({ params: sloIdParams }), + async (req, res, next) => { + try { + const { teamId } = getNonNullUserWithTeam(req); + setBusinessContext({ teamId: teamId.toString() }); + const deleted = await deleteSlo(teamId.toString(), req.params.id); + if (!deleted) return res.sendStatus(404); + res.sendStatus(204); + } catch (e) { + next(e); + } + }, +); + +export default router;