Repository navigation
feat(api): SLO definitions behind ENABLE_SLOS #3794
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
alex-fedotyev
wants to merge
1
commit into
alex/HDX-3001-slo-06-history
from
alex/HDX-3001-slo-07-api-definitions
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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: {}, | ||
| createdAt: slo.createdAt.toISOString(), | ||
| updatedAt: slo.updatedAt.toISOString(), | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 beforeSlo.create, to shrink the window. If the limit has to hold strictly, enforce it atomically, for example with a per-team counter updated byfindOneAndUpdatewith$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