Compare commits

..

5 Commits

Author SHA1 Message Date
nityanandagohain
5c24c882d9 fix: address comment 2026-10-29 16:33:49 +05:30
nityanandagohain
dbd318feaf Merge remote-tracking branch 'origin/main' into issue_nerve_463 2026-10-29 16:18:19 +05:30
Naman Verma
5097d1578f chore: preemptively update rules v2 schema's api spec properties (#13306)
Some checks are pending
build-staging / js-build (push) Blocked by required conditions
build-staging / prepare (push) Waiting to run
build-staging / go-build (push) Blocked by required conditions
build-staging / staging (push) Blocked by required conditions
cacheci / tests (push) Waiting to run
Release Drafter / update_release_draft (push) Waiting to run
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

Rules v1 to v2 migration is gonna happen soon, so its better to have at
least our api spec updated so that agents stop creating v1 rules
2026-10-29 09:29:02 +00:00
nityanandagohain
3c263501b4 fix: update integration test 2026-10-26 16:52:56 +05:30
nityanandagohain
d04c0a2366 feat(authz): enable FGA for llm pricing rule routes 2026-10-26 15:57:28 +05:30
39 changed files with 1190 additions and 591 deletions

View File

@@ -3932,6 +3932,7 @@ components:
- logs-field
- traces-field
- metrics-field
- llm-pricing-rule
type: string
CoretypesObject:
properties:
@@ -11389,8 +11390,7 @@ components:
evaluation:
allOf:
- $ref: '#/components/schemas/RuletypesEvaluationEnvelope'
description: The evaluation window, as a kind and spec. Required when schemaVersion
is v2alpha1; derived from evalWindow and frequency for v1.
description: The evaluation window, as a kind and spec.
frequency:
description: How often the rule is evaluated, as a Go duration such as 1m.
Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set
@@ -11406,8 +11406,7 @@ components:
notificationSettings:
allOf:
- $ref: '#/components/schemas/RuletypesNotificationSettings'
description: Grouping, re-notification and routing behaviour. Required when
schemaVersion is v2alpha1; derived from the v1 fields otherwise.
description: Grouping, re-notification and routing behaviour.
preferredChannels:
description: The displayName of each notification channel to notify, for
schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries
@@ -11420,26 +11419,30 @@ components:
- $ref: '#/components/schemas/RuletypesRuleType'
description: 'The evaluation strategy: threshold_rule compares against thresholds,
promql_rule evaluates a PromQL expression, anomaly_rule scores deviation
from seasonal history. Defaults to threshold_rule for builder queries
and is forced to promql_rule for promql queries.'
from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql
queries and is forced to promql_rule for promql queries.'
schemaVersion:
description: 'The rule payload schema: v1 (the default when omitted) uses
the flat condition fields, v2alpha1 uses condition.thresholds, evaluation
and notificationSettings.'
description: The rule payload schema.
enum:
- v2alpha1
type: string
source:
deprecated: true
description: The URL of the page the rule was created from. Informational;
it is not used for evaluation.
type: string
version:
description: The query payload version. Only v5 is accepted and it is filled
in when omitted.
deprecated: true
description: The query payload version. Nothing reads it.
type: string
required:
- alert
- alertType
- ruleType
- condition
- evaluation
- schemaVersion
- notificationSettings
type: object
RuletypesPostableRuleView:
properties:
@@ -11528,8 +11531,7 @@ components:
evaluation:
allOf:
- $ref: '#/components/schemas/RuletypesEvaluationEnvelope'
description: The evaluation window, as a kind and spec. Required when schemaVersion
is v2alpha1; derived from evalWindow and frequency for v1.
description: The evaluation window, as a kind and spec.
frequency:
description: How often the rule is evaluated, as a Go duration such as 1m.
Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set
@@ -11548,8 +11550,7 @@ components:
notificationSettings:
allOf:
- $ref: '#/components/schemas/RuletypesNotificationSettings'
description: Grouping, re-notification and routing behaviour. Required when
schemaVersion is v2alpha1; derived from the v1 fields otherwise.
description: Grouping, re-notification and routing behaviour.
preferredChannels:
description: The displayName of each notification channel to notify, for
schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries
@@ -11562,14 +11563,15 @@ components:
- $ref: '#/components/schemas/RuletypesRuleType'
description: 'The evaluation strategy: threshold_rule compares against thresholds,
promql_rule evaluates a PromQL expression, anomaly_rule scores deviation
from seasonal history. Defaults to threshold_rule for builder queries
and is forced to promql_rule for promql queries.'
from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql
queries and is forced to promql_rule for promql queries.'
schemaVersion:
description: 'The rule payload schema: v1 (the default when omitted) uses
the flat condition fields, v2alpha1 uses condition.thresholds, evaluation
and notificationSettings.'
description: The rule payload schema.
enum:
- v2alpha1
type: string
source:
deprecated: true
description: The URL of the page the rule was created from. Informational;
it is not used for evaluation.
type: string
@@ -11584,8 +11586,8 @@ components:
updatedBy:
type: string
version:
description: The query payload version. Only v5 is accepted and it is filled
in when omitted.
deprecated: true
description: The query payload version. Nothing reads it.
type: string
required:
- id
@@ -11594,6 +11596,9 @@ components:
- alertType
- ruleType
- condition
- evaluation
- schemaVersion
- notificationSettings
type: object
RuletypesRuleCondition:
properties:
@@ -11643,8 +11648,7 @@ components:
against, hourly, daily or weekly.'
selectedQueryName:
description: The name of the query whose result is evaluated, such as A
or F1. Must match a query in compositeQuery. When omitted, F1 is used
if present, otherwise the enabled query with the highest name.
or F1. Must match a query in compositeQuery.
type: string
target:
description: 'schemaVersion v1 only: the value compared against, in targetUnit.
@@ -11660,10 +11664,11 @@ components:
thresholds:
allOf:
- $ref: '#/components/schemas/RuletypesRuleThresholdData'
description: The thresholds to evaluate, as a kind and spec. Required when
schemaVersion is v2alpha1; derived from op, target and matchType for v1.
description: The thresholds to evaluate, as a kind and spec.
required:
- compositeQuery
- selectedQueryName
- thresholds
type: object
RuletypesRuleThresholdData:
discriminator:
@@ -15755,9 +15760,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- VIEWER
- llm-pricing-rule:list
- tokenizer:
- VIEWER
- llm-pricing-rule:list
summary: List pricing rules
tags:
- llmpricingrules
@@ -15802,9 +15807,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- llm-pricing-rule:update
- tokenizer:
- ADMIN
- llm-pricing-rule:update
summary: Create or update pricing rules
tags:
- llmpricingrules
@@ -15850,9 +15855,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- llm-pricing-rule:delete
- tokenizer:
- ADMIN
- llm-pricing-rule:delete
summary: Delete a pricing rule
tags:
- llmpricingrules
@@ -15908,9 +15913,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- VIEWER
- llm-pricing-rule:read
- tokenizer:
- VIEWER
- llm-pricing-rule:read
summary: Get a pricing rule
tags:
- llmpricingrules
@@ -15963,9 +15968,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- VIEWER
- llm-pricing-rule:list
- tokenizer:
- VIEWER
- llm-pricing-rule:list
summary: List unmapped models
tags:
- llmpricingrules
@@ -25312,13 +25317,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -25353,22 +25358,36 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
target: 2
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evalWindow: 24h
frequency: 3h
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
labels:
severity: warning
preferredChannels:
- slack-ingestion
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL
@@ -26264,13 +26283,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -26305,22 +26324,36 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
target: 2
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evalWindow: 24h
frequency: 3h
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
labels:
severity: warning
preferredChannels:
- slack-ingestion
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL
@@ -27117,13 +27150,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -27158,22 +27191,36 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
target: 2
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evalWindow: 24h
frequency: 3h
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
labels:
severity: warning
preferredChannels:
- slack-ingestion
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL
@@ -28676,13 +28723,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -28717,22 +28764,36 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
target: 2
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evalWindow: 24h
frequency: 3h
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
labels:
severity: warning
preferredChannels:
- slack-ingestion
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL

View File

@@ -3579,6 +3579,7 @@ export enum CoretypesKindDTO {
'logs-field' = 'logs-field',
'traces-field' = 'traces-field',
'metrics-field' = 'metrics-field',
'llm-pricing-rule' = 'llm-pricing-rule',
}
export enum CoretypesTypeDTO {
user = 'user',
@@ -12584,6 +12585,12 @@ export type RuletypesPostableRuleDTOAnnotations = { [key: string]: string };
*/
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
/**
* The rule payload schema.
*/
export enum RuletypesPostableRuleDTOSchemaVersion {
v2alpha1 = 'v2alpha1',
}
export enum RuletypesSeasonalityDTO {
hourly = 'hourly',
daily = 'daily',
@@ -12660,9 +12667,9 @@ export interface RuletypesRuleConditionDTO {
seasonality?: RuletypesSeasonalityDTO;
/**
* @type string
* @description The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery. When omitted, F1 is used if present, otherwise the enabled query with the highest name.
* @description The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery.
*/
selectedQueryName?: string;
selectedQueryName: string;
/**
* @type number,null
* @format double
@@ -12675,9 +12682,9 @@ export interface RuletypesRuleConditionDTO {
*/
targetUnit?: string;
/**
* @description The thresholds to evaluate, as a kind and spec. Required when schemaVersion is v2alpha1; derived from op, target and matchType for v1.
* @description The thresholds to evaluate, as a kind and spec.
*/
thresholds?: RuletypesRuleThresholdDataDTO;
thresholds: RuletypesRuleThresholdDataDTO;
}
export interface RuletypesPostableRuleDTO {
@@ -12715,9 +12722,9 @@ export interface RuletypesPostableRuleDTO {
*/
evalWindow?: string;
/**
* @description The evaluation window, as a kind and spec. Required when schemaVersion is v2alpha1; derived from evalWindow and frequency for v1.
* @description The evaluation window, as a kind and spec.
*/
evaluation?: RuletypesEvaluationEnvelopeDTO;
evaluation: RuletypesEvaluationEnvelopeDTO;
/**
* @type string
* @description How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead.
@@ -12729,23 +12736,24 @@ export interface RuletypesPostableRuleDTO {
*/
labels?: RuletypesPostableRuleDTOLabels;
/**
* @description Grouping, re-notification and routing behaviour. Required when schemaVersion is v2alpha1; derived from the v1 fields otherwise.
* @description Grouping, re-notification and routing behaviour.
*/
notificationSettings?: RuletypesNotificationSettingsDTO;
notificationSettings: RuletypesNotificationSettingsDTO;
/**
* @type array
* @description The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels.
*/
preferredChannels?: string[];
/**
* @description The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder queries and is forced to promql_rule for promql queries.
* @description The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries.
*/
ruleType: RuletypesRuleTypeDTO;
/**
* @enum v2alpha1
* @type string
* @description The rule payload schema: v1 (the default when omitted) uses the flat condition fields, v2alpha1 uses condition.thresholds, evaluation and notificationSettings.
* @description The rule payload schema.
*/
schemaVersion?: string;
schemaVersion: RuletypesPostableRuleDTOSchemaVersion;
/**
* @type string
* @description The URL of the page the rule was created from. Informational; it is not used for evaluation.
@@ -12753,7 +12761,7 @@ export interface RuletypesPostableRuleDTO {
source?: string;
/**
* @type string
* @description The query payload version. Only v5 is accepted and it is filled in when omitted.
* @description The query payload version. Nothing reads it.
*/
version?: string;
}
@@ -12776,6 +12784,12 @@ export type RuletypesRuleDTOAnnotations = { [key: string]: string };
*/
export type RuletypesRuleDTOLabels = { [key: string]: string };
/**
* The rule payload schema.
*/
export enum RuletypesRuleDTOSchemaVersion {
v2alpha1 = 'v2alpha1',
}
export interface RuletypesRuleDTO {
/**
* @type string
@@ -12820,9 +12834,9 @@ export interface RuletypesRuleDTO {
*/
evalWindow?: string;
/**
* @description The evaluation window, as a kind and spec. Required when schemaVersion is v2alpha1; derived from evalWindow and frequency for v1.
* @description The evaluation window, as a kind and spec.
*/
evaluation?: RuletypesEvaluationEnvelopeDTO;
evaluation: RuletypesEvaluationEnvelopeDTO;
/**
* @type string
* @description How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead.
@@ -12839,23 +12853,24 @@ export interface RuletypesRuleDTO {
*/
labels?: RuletypesRuleDTOLabels;
/**
* @description Grouping, re-notification and routing behaviour. Required when schemaVersion is v2alpha1; derived from the v1 fields otherwise.
* @description Grouping, re-notification and routing behaviour.
*/
notificationSettings?: RuletypesNotificationSettingsDTO;
notificationSettings: RuletypesNotificationSettingsDTO;
/**
* @type array
* @description The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels.
*/
preferredChannels?: string[];
/**
* @description The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder queries and is forced to promql_rule for promql queries.
* @description The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries.
*/
ruleType: RuletypesRuleTypeDTO;
/**
* @enum v2alpha1
* @type string
* @description The rule payload schema: v1 (the default when omitted) uses the flat condition fields, v2alpha1 uses condition.thresholds, evaluation and notificationSettings.
* @description The rule payload schema.
*/
schemaVersion?: string;
schemaVersion: RuletypesRuleDTOSchemaVersion;
/**
* @type string
* @description The URL of the page the rule was created from. Informational; it is not used for evaluation.
@@ -12876,7 +12891,7 @@ export interface RuletypesRuleDTO {
updatedBy?: string;
/**
* @type string
* @description The query payload version. Only v5 is accepted and it is filled in when omitted.
* @description The query payload version. Nothing reads it.
*/
version?: string;
}

View File

@@ -1,6 +1,6 @@
import { useMemo } from 'react';
import { EditorProps } from '@monaco-editor/react';
import MonacoEditor from 'lib/monaco/MonacoEditor';
import MEditor, { EditorProps } from '@monaco-editor/react';
import { useIsDarkMode } from 'hooks/useDarkMode';
function Editor({
value,
@@ -10,6 +10,8 @@ function Editor({
height,
options,
}: MEditorProps): JSX.Element {
const isDarkMode = useIsDarkMode();
const onChangeHandler = (newValue?: string): void => {
if (readOnly) {
return;
@@ -26,7 +28,8 @@ function Editor({
);
return (
<MonacoEditor
<MEditor
theme={isDarkMode ? 'vs-dark' : 'vs-light'}
language={language}
value={value}
options={editorOptions}

View File

@@ -1,11 +1,17 @@
import MEditor from '@monaco-editor/react';
import { Play, RotateCcw } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Callout } from '@signozhq/ui/callout';
import MonacoEditor from 'lib/monaco/MonacoEditor';
import { useIsDarkMode } from 'hooks/useDarkMode';
import styles from './TestTab.module.scss';
import JsonEditorSkeleton from './JsonEditorSkeleton';
import TestResult from './TestResult';
import {
defineSignozJsonTheme,
SIGNOZ_JSON_THEME_DARK,
SIGNOZ_JSON_THEME_LIGHT,
} from './jsonEditorTheme';
import { UseTestSpanMapper } from './useTestSpanMapper';
interface TestTabProps {
@@ -26,6 +32,7 @@ function TestTab({ spanTest }: TestTabProps): JSX.Element {
error,
validationError,
} = spanTest;
const isDarkMode = useIsDarkMode();
function renderResults(): JSX.Element {
if (error) {
@@ -115,12 +122,14 @@ function TestTab({ spanTest }: TestTabProps): JSX.Element {
data-testid="test-span-input"
aria-label="Sample span JSON"
>
<MonacoEditor
<MEditor
language="json"
value={input}
onChange={(value): void => setInput(value ?? '')}
height="100%"
loading={<JsonEditorSkeleton />}
theme={isDarkMode ? SIGNOZ_JSON_THEME_DARK : SIGNOZ_JSON_THEME_LIGHT}
beforeMount={defineSignozJsonTheme}
options={{
minimap: { enabled: false },
fontSize: 12,

View File

@@ -0,0 +1,38 @@
//TODO: This is a local theme for now, but ideally for the editor as well. Just like prettyViewer, we have a theme. We should have a theme for the editor as well.
import { Monaco } from '@monaco-editor/react';
import { Color } from '@signozhq/design-tokens';
export const SIGNOZ_JSON_THEME_DARK = 'signoz-attr-mapping-json-dark';
export const SIGNOZ_JSON_THEME_LIGHT = 'signoz-attr-mapping-json-light';
const SHARED_THEME = {
inherit: true,
colors: {
'editor.background': '#00000000', // transparent — inherit the panel bg
},
fontFamily: 'SF Mono, Geist Mono, Fira Code, monospace',
fontSize: 12,
fontWeight: 'normal',
lineHeight: 18,
letterSpacing: -0.06,
};
export function defineSignozJsonTheme(monaco: Monaco): void {
monaco.editor.defineTheme(SIGNOZ_JSON_THEME_DARK, {
...SHARED_THEME,
base: 'vs-dark',
rules: [
{ token: 'string.key.json', foreground: Color.BG_ROBIN_400 },
{ token: 'string.value.json', foreground: Color.BG_VANILLA_400 },
],
});
monaco.editor.defineTheme(SIGNOZ_JSON_THEME_LIGHT, {
...SHARED_THEME,
base: 'vs',
rules: [
{ token: 'string.key.json', foreground: Color.BG_ROBIN_500 },
{ token: 'string.value.json', foreground: Color.BG_INK_400 },
],
});
}

View File

@@ -1,8 +1,10 @@
import { ChangeEvent, useCallback } from 'react';
import MEditor, { Monaco } from '@monaco-editor/react';
import { Color } from '@signozhq/design-tokens';
import { Input } from 'antd';
import { LEGEND } from 'constants/global';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import MonacoEditor from 'lib/monaco/MonacoEditor';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { IClickHouseQuery } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { getFormatedLegend } from 'utils/getFormatedLegend';
@@ -69,6 +71,22 @@ function ClickHouseQueryBuilder({
[handleUpdateQuery],
);
const isDarkMode = useIsDarkMode();
function setEditorTheme(monaco: Monaco): void {
monaco.editor.defineTheme('my-theme', {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'string.key.json', foreground: Color.BG_VANILLA_400 },
{ token: 'string.value.json', foreground: Color.BG_ROBIN_400 },
],
colors: {
'editor.background': Color.BG_INK_300,
},
});
}
return (
<QueryHeader
name={queryData?.name}
@@ -77,13 +95,15 @@ function ClickHouseQueryBuilder({
onDelete={handleRemoveQuery}
deletable={deletable}
>
<MonacoEditor
<MEditor
language="sql"
height="200px"
onChange={handleUpdateEditor}
value={queryData?.query}
onMount={(_, monaco): void => {
void document.fonts.ready.then(() => monaco.editor.remeasureFonts());
document.fonts.ready.then(() => {
monaco.editor.remeasureFonts();
});
}}
options={{
scrollbar: {
@@ -95,6 +115,8 @@ function ClickHouseQueryBuilder({
fontSize: 14,
fontFamily: 'Space Mono',
}}
theme={isDarkMode ? 'my-theme' : 'light'}
beforeMount={setEditorTheme}
/>
<Input
onChange={handleUpdateInput}

View File

@@ -7,7 +7,7 @@ import {
useRef,
} from 'react';
import { useCopyToClipboard } from 'react-use';
import { Monaco, OnMount } from '@monaco-editor/react';
import MEditor, { Monaco, OnMount } from '@monaco-editor/react';
import { Color } from '@signozhq/design-tokens';
import { Check, Copy } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
@@ -15,9 +15,12 @@ import { Tooltip } from '@signozhq/ui/tooltip';
import { Typography } from '@signozhq/ui/typography';
import type { AuthtypesTransactionGroupDTO } from 'api/generated/services/sigNoz.schemas';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { EDITABLE_EDITOR_OPTIONS } from 'lib/monaco/editorOptions';
import MonacoEditor from 'lib/monaco/MonacoEditor';
import {
defineJsonTheme,
EDITABLE_EDITOR_OPTIONS,
JSON_THEME_DARK,
} from '../../monaco.config';
import {
transformResourcePermissionsToTransactionGroups,
transformTransactionGroupsToResourcePermissions,
@@ -31,7 +34,7 @@ import {
import styles from './JsonEditor.module.scss';
import { JsonEditorProps, JsonEditorRef } from './JsonEditor.types';
type MonacoEditorInstance = Parameters<OnMount>[0];
type MonacoEditor = Parameters<OnMount>[0];
const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
function JsonEditor({ resources, mode, onChange, onValidityChange }, ref) {
@@ -47,7 +50,7 @@ const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
});
const prevModeRef = useRef(mode);
const completionDisposableRef = useRef<{ dispose(): void } | null>(null);
const editorRef = useRef<MonacoEditorInstance | null>(null);
const editorRef = useRef<MonacoEditor | null>(null);
const markersListenerRef = useRef<{ dispose(): void } | null>(null);
const hasError = parseError !== null || schemaErrors.length > 0;
@@ -97,6 +100,7 @@ const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
);
const configureMonaco = useCallback((monaco: Monaco): void => {
defineJsonTheme(monaco);
registerJsonSchema(monaco);
completionDisposableRef.current = registerCompletionProvider(monaco);
}, []);
@@ -180,7 +184,7 @@ const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
</Button>
</Tooltip>
</div>
<MonacoEditor
<MEditor
value={jsonBuffer}
language="json"
path={ROLE_PERMISSIONS_MODEL_PATH}
@@ -188,6 +192,7 @@ const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
onChange={handleEditorChange}
onMount={handleEditorMount}
height="100%"
theme={isDarkMode ? JSON_THEME_DARK : 'light'}
beforeMount={configureMonaco}
/>
</div>
@@ -220,11 +225,7 @@ const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
className={styles.jsonEditorErrorMessage}
>
{schemaErrors[0]}
{schemaErrors.length > 1 && (
<span className="translate-safe">
{` (+${schemaErrors.length - 1} more)`}
</span>
)}
{schemaErrors.length > 1 && ` (+${schemaErrors.length - 1} more)`}
</Typography>
</div>
)}

View File

@@ -1,13 +1,17 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCopyToClipboard } from 'react-use';
import MEditor from '@monaco-editor/react';
import { Color } from '@signozhq/design-tokens';
import { Check, Copy } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { READONLY_EDITOR_OPTIONS } from 'lib/monaco/editorOptions';
import MonacoEditor from 'lib/monaco/MonacoEditor';
import {
defineJsonTheme,
JSON_THEME_DARK,
READONLY_EDITOR_OPTIONS,
} from '../monaco.config';
import { RolePermissionsData } from '../types';
import { transformResourcePermissionsToTransactionGroups } from '../hooks/useRolePermissions';
@@ -75,11 +79,13 @@ function ReadOnlyJsonViewer({
</Button>
</Tooltip>
</div>
<MonacoEditor
<MEditor
value={jsonContent}
language="json"
options={READONLY_EDITOR_OPTIONS}
height="100%"
theme={isDarkMode ? JSON_THEME_DARK : 'light'}
beforeMount={defineJsonTheme}
/>
</div>
</div>

View File

@@ -1,7 +1,24 @@
import { Monaco } from '@monaco-editor/react';
import { Color } from '@signozhq/design-tokens';
type EditorOptions = Parameters<Monaco['editor']['create']>[1];
export const JSON_THEME_DARK = 'json-theme-dark';
export function defineJsonTheme(monaco: Monaco): void {
monaco.editor.defineTheme(JSON_THEME_DARK, {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'string.key.json', foreground: Color.BG_VANILLA_400 },
{ token: 'string.value.json', foreground: Color.BG_ROBIN_400 },
],
colors: {
'editor.background': Color.BG_INK_400,
},
});
}
const BASE_EDITOR_OPTIONS: EditorOptions = {
automaticLayout: true,
wordWrap: 'on',

View File

@@ -1,25 +0,0 @@
import { useCallback } from 'react';
import MEditor, { EditorProps, Monaco } from '@monaco-editor/react';
import { EDITOR_THEME, registerEditorTheme } from './editorTheme';
export type MonacoEditorProps = Omit<EditorProps, 'theme'>;
function MonacoEditor({
beforeMount,
...props
}: MonacoEditorProps): JSX.Element {
const handleBeforeMount = useCallback(
(monaco: Monaco): void => {
registerEditorTheme(monaco);
beforeMount?.(monaco);
},
[beforeMount],
);
return (
<MEditor {...props} theme={EDITOR_THEME} beforeMount={handleBeforeMount} />
);
}
export default MonacoEditor;

View File

@@ -1,58 +0,0 @@
import type { EditorProps, Monaco } from '@monaco-editor/react';
import { render } from '@testing-library/react';
import { EDITOR_THEME, registerEditorTheme } from '../editorTheme';
import MonacoEditor from '../MonacoEditor';
const editorProps = jest.fn();
jest.mock('@monaco-editor/react', () => ({
__esModule: true,
default: (props: EditorProps): JSX.Element => {
editorProps(props);
return <div data-testid="monaco" />;
},
}));
jest.mock('../editorTheme', () => ({
EDITOR_THEME: 'signoz',
registerEditorTheme: jest.fn(),
}));
function lastProps(): EditorProps {
return editorProps.mock.calls[editorProps.mock.calls.length - 1][0];
}
describe('MonacoEditor', () => {
beforeEach(() => {
editorProps.mockClear();
jest.mocked(registerEditorTheme).mockClear();
});
it('renders with the shared theme and forwards the other props', () => {
render(<MonacoEditor language="json" value="{}" height="100%" />);
expect(lastProps()).toMatchObject({
theme: EDITOR_THEME,
language: 'json',
value: '{}',
height: '100%',
});
});
it('registers the theme before the caller sets up monaco', () => {
const calls: string[] = [];
jest
.mocked(registerEditorTheme)
.mockImplementation(() => calls.push('theme'));
const beforeMount = jest.fn(() => calls.push('caller'));
const monaco = {} as Monaco;
render(<MonacoEditor beforeMount={beforeMount} />);
lastProps().beforeMount?.(monaco);
expect(registerEditorTheme).toHaveBeenCalledWith(monaco);
expect(beforeMount).toHaveBeenCalledWith(monaco);
expect(calls).toStrictEqual(['theme', 'caller']);
});
});

View File

@@ -1,138 +0,0 @@
import type { Monaco } from '@monaco-editor/react';
type EditorThemeModule = typeof import('../editorTheme');
const DARK_TOKENS = {
'--l1-background': '#0b0c0e',
'--l1-foreground': '#eceef2',
'--bg-vanilla-400': '#c0c1c3',
'--bg-robin-400': '#7190f9',
};
const LIGHT_TOKENS = {
'--l1-background': '#ffffff',
'--l1-foreground': '#121317',
'--bg-vanilla-400': '#c0c1c3',
'--bg-robin-400': '#7190f9',
};
function setTokens(tokens: Record<string, string>): void {
Object.entries(tokens).forEach(([name, value]) => {
document.body.style.setProperty(name, value);
});
}
function createMonaco(): { monaco: Monaco; defineTheme: jest.Mock } {
const defineTheme = jest.fn();
return {
monaco: { editor: { defineTheme } } as unknown as Monaco,
defineTheme,
};
}
function loadModule(): EditorThemeModule {
let mod: EditorThemeModule | undefined;
jest.isolateModules(() => {
mod = jest.requireActual<EditorThemeModule>('../editorTheme');
});
return mod as EditorThemeModule;
}
async function flushMutations(): Promise<void> {
await Promise.resolve();
}
describe('registerEditorTheme', () => {
afterEach(() => {
document.body.removeAttribute('style');
document.body.className = '';
});
it('defines a dark theme with the JSON token colours on a dark surface', () => {
setTokens(DARK_TOKENS);
const { registerEditorTheme, EDITOR_THEME } = loadModule();
const { monaco, defineTheme } = createMonaco();
registerEditorTheme(monaco);
expect(defineTheme).toHaveBeenCalledTimes(1);
expect(defineTheme).toHaveBeenCalledWith(EDITOR_THEME, {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'string.key.json', foreground: 'c0c1c3' },
{ token: 'string.value.json', foreground: '7190f9' },
],
colors: {
'editor.background': '#0b0c0e',
'editor.foreground': '#eceef2',
},
});
});
it('keeps the vs palette on a light surface', () => {
setTokens(LIGHT_TOKENS);
const { registerEditorTheme } = loadModule();
const { monaco, defineTheme } = createMonaco();
registerEditorTheme(monaco);
expect(defineTheme).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
base: 'vs',
rules: [],
colors: {
'editor.background': '#ffffff',
'editor.foreground': '#121317',
},
}),
);
});
it('redefines the theme when the body class switches the tokens', async () => {
setTokens(DARK_TOKENS);
const { registerEditorTheme } = loadModule();
const { monaco, defineTheme } = createMonaco();
registerEditorTheme(monaco);
setTokens(LIGHT_TOKENS);
document.body.classList.add('lightMode');
await flushMutations();
expect(defineTheme).toHaveBeenCalledTimes(2);
expect(defineTheme).toHaveBeenLastCalledWith(
expect.any(String),
expect.objectContaining({ base: 'vs' }),
);
});
it('ignores body class changes that leave the tokens alone', async () => {
setTokens(DARK_TOKENS);
const { registerEditorTheme } = loadModule();
const { monaco, defineTheme } = createMonaco();
registerEditorTheme(monaco);
document.body.classList.add('ant-scrolling-effect');
await flushMutations();
expect(defineTheme).toHaveBeenCalledTimes(1);
});
it('watches the body once however many editors mount', async () => {
const observe = jest.spyOn(MutationObserver.prototype, 'observe');
setTokens(DARK_TOKENS);
const { registerEditorTheme } = loadModule();
const { monaco, defineTheme } = createMonaco();
registerEditorTheme(monaco);
registerEditorTheme(monaco);
setTokens(LIGHT_TOKENS);
document.body.classList.add('lightMode');
await flushMutations();
expect(observe).toHaveBeenCalledTimes(1);
expect(defineTheme).toHaveBeenCalledTimes(2);
observe.mockRestore();
});
});

View File

@@ -1,78 +0,0 @@
import type { Monaco } from '@monaco-editor/react';
export const EDITOR_THEME = 'signoz';
let definedBackground: string | undefined;
let bodyClassObserver: MutationObserver | undefined;
function token(name: string): string {
return getComputedStyle(document.body)
.getPropertyValue(name)
.trim()
.replace('#', '');
}
function isDark(hex: string): boolean {
if (hex.length < 6) {
return true;
}
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
return 0.299 * r + 0.587 * g + 0.114 * b < 128;
}
function defineEditorTheme(monaco: Monaco): void {
const background = token('--l1-background');
if (background === definedBackground) {
return;
}
definedBackground = background;
const foreground = token('--l1-foreground');
const keyColor = token('--bg-vanilla-400');
const valueColor = token('--bg-robin-400');
// Both token colours are picked to read on a dark surface, so on a light one
// they wash out, the keys worst of all. Monaco's own `vs` palette is built
// for that surface, so let it keep its colours there, as the role viewer does.
const rules: { token: string; foreground: string }[] = [];
if (isDark(background)) {
if (keyColor) {
rules.push({ token: 'string.key.json', foreground: keyColor });
}
if (valueColor) {
rules.push({ token: 'string.value.json', foreground: valueColor });
}
}
const colors: Record<string, string> = {};
if (background) {
colors['editor.background'] = `#${background}`;
}
if (foreground) {
colors['editor.foreground'] = `#${foreground}`;
}
monaco.editor.defineTheme(EDITOR_THEME, {
base: isDark(background) ? 'vs-dark' : 'vs',
inherit: true,
rules,
colors,
});
}
// Monaco has a single theme for every editor on the page, and the design tokens
// switch with the body's `dark` class, so the theme follows that class instead
// of being defined per editor.
export function registerEditorTheme(monaco: Monaco): void {
defineEditorTheme(monaco);
if (bodyClassObserver) {
return;
}
bodyClassObserver = new MutationObserver(() => defineEditorTheme(monaco));
bodyClassObserver.observe(document.body, {
attributes: true,
attributeFilter: ['class'],
});
}

View File

@@ -0,0 +1,52 @@
import type { Monaco } from '@monaco-editor/react';
export const JSON_EDITOR_THEME = 'signoz-json';
function token(el: HTMLElement, name: string): string {
return getComputedStyle(el).getPropertyValue(name).trim().replace('#', '');
}
function isDark(hex: string): boolean {
if (hex.length < 6) {
return true;
}
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
return 0.299 * r + 0.587 * g + 0.114 * b < 128;
}
export function defineJsonEditorTheme(monaco: Monaco, el: HTMLElement): void {
const background = token(el, '--l1-background');
const foreground = token(el, '--l1-foreground');
const keyColor = token(el, '--bg-vanilla-400');
const valueColor = token(el, '--bg-robin-400');
// Both token colours are picked to read on a dark surface, so on a light one
// they wash out, the keys worst of all. Monaco's own `vs` palette is built
// for that surface, so let it keep its colours there, as the role viewer does.
const rules: { token: string; foreground: string }[] = [];
if (isDark(background)) {
if (keyColor) {
rules.push({ token: 'string.key.json', foreground: keyColor });
}
if (valueColor) {
rules.push({ token: 'string.value.json', foreground: valueColor });
}
}
const colors: Record<string, string> = {};
if (background) {
colors['editor.background'] = `#${background}`;
}
if (foreground) {
colors['editor.foreground'] = `#${foreground}`;
}
monaco.editor.defineTheme(JSON_EDITOR_THEME, {
base: isDark(background) ? 'vs-dark' : 'vs',
inherit: true,
rules,
colors,
});
}

View File

@@ -1,8 +1,10 @@
import {
RuletypesAlertStateDTO,
RuletypesAlertTypeDTO,
RuletypesEvaluationRollingDTOKind,
RuletypesPanelTypeDTO,
RuletypesQueryTypeDTO,
RuletypesRuleDTOSchemaVersion,
RuletypesRuleTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import type {
@@ -38,6 +40,12 @@ const make = (
evalWindow: '5m0s',
frequency: '1m0s',
ruleType: RuletypesRuleTypeDTO.threshold_rule,
schemaVersion: RuletypesRuleDTOSchemaVersion.v2alpha1,
evaluation: {
kind: RuletypesEvaluationRollingDTOKind.rolling,
spec: { evalWindow: '5m0s', frequency: '1m0s' },
},
notificationSettings: { usePolicy: false, renotify: { enabled: false } },
...overrides,
});

View File

@@ -1,11 +1,15 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCopyToClipboard } from 'react-use';
import MEditor from '@monaco-editor/react';
import { DrawerWrapper } from '@signozhq/ui/drawer';
import { useGetNotificationChannel } from 'api/generated/services/channels';
import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
import Spinner from 'components/Spinner';
import { READONLY_EDITOR_OPTIONS } from 'lib/monaco/editorOptions';
import MonacoEditor from 'lib/monaco/MonacoEditor';
import { READONLY_EDITOR_OPTIONS } from 'container/RolesSettings/monaco.config';
import {
defineJsonEditorTheme,
JSON_EDITOR_THEME,
} from 'lib/monaco/jsonEditorTheme';
import { channelToJson, hasSecrets } from '../../utils/channelJson';
import styles from './ChannelJsonDialog.module.scss';
@@ -88,11 +92,18 @@ function ChannelJsonDialog({
/>
<div className={styles.editor}>
<MonacoEditor
<MEditor
value={json}
language="json"
options={READONLY_EDITOR_OPTIONS}
height="100%"
theme="vs-dark"
// the same theme the dashboard JSON drawer uses: it reads the
// page's own tokens, so it follows light and dark
onMount={(editor, monaco): void => {
defineJsonEditorTheme(monaco, editor.getContainerDomNode());
monaco.editor.setTheme(JSON_EDITOR_THEME);
}}
/>
</div>
</div>

View File

@@ -18,6 +18,7 @@ import {
RuletypesMatchTypeDTO,
RuletypesPanelTypeDTO,
RuletypesQueryTypeDTO,
RuletypesRuleDTOSchemaVersion,
RuletypesRuleTypeDTO,
RuletypesSeasonalityDTO,
RuletypesThresholdBasicDTOKind,
@@ -34,7 +35,6 @@ import {
type AlertmanagertypesGettableNotificationChannelDTO,
type AlertmanagertypesListedNotificationChannelDTO,
} from 'api/generated/services/sigNoz.schemas';
import { NEW_ALERT_SCHEMA_VERSION } from 'types/api/alerts/alertTypesV2';
const MINUTE = 60 * 1000;
const HOUR = 60 * MINUTE;
@@ -388,18 +388,18 @@ const buildRule = (index: number, shape: RuleShape): RuletypesRuleDTO => {
},
evalWindow: isAnomaly ? '1h0m0s' : '5m0s',
frequency: '1m0s',
...(isAnomaly && {
evaluation: {
kind: RuletypesEvaluationRollingDTOKind.rolling,
spec: { evalWindow: '1h0m0s', frequency: '1m0s' },
},
}),
evaluation: {
kind: RuletypesEvaluationRollingDTOKind.rolling,
spec: { evalWindow: isAnomaly ? '1h0m0s' : '5m0s', frequency: '1m0s' },
},
createdAt: ago((index + 3) * DAY),
updatedAt: ago((index + 1) * HOUR),
createdBy: 'ada@signoz.io',
updatedBy: 'grace@signoz.io',
schemaVersion:
shape.schema === 'classic' ? undefined : NEW_ALERT_SCHEMA_VERSION,
// classic rows predate schemaVersion, which the spec now requires
schemaVersion: (shape.schema === 'classic'
? undefined
: RuletypesRuleDTOSchemaVersion.v2alpha1) as RuletypesRuleDTOSchemaVersion,
version: 'v5',
source: 'http://localhost/alerts',
preferredChannels: ['ops-slack'],

View File

@@ -1,4 +1,5 @@
import { KeyboardEvent, useCallback } from 'react';
import MEditor from '@monaco-editor/react';
import { TriangleAlert } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
@@ -11,7 +12,10 @@ import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
import { useCopyToClipboard } from 'react-use';
import { toast } from '@signozhq/ui/sonner';
import MonacoEditor from 'lib/monaco/MonacoEditor';
import {
defineJsonEditorTheme,
JSON_EDITOR_THEME,
} from 'lib/monaco/jsonEditorTheme';
import styles from './JsonEditorDrawer.module.scss';
import JsonEditorToolbar from './JsonEditorToolbar';
import { useJsonEditor } from './useJsonEditor';
@@ -209,7 +213,7 @@ function JsonEditorDrawer({
onReset={reset}
/>
<div className={styles.editor}>
<MonacoEditor
<MEditor
language="json"
height="100%"
value={draft}
@@ -221,7 +225,10 @@ function JsonEditorDrawer({
fontSize: 13,
fontFamily: 'Space Mono',
}}
onMount={(_editor, monaco): void => {
theme="vs-dark"
onMount={(editor, monaco): void => {
defineJsonEditorTheme(monaco, editor.getContainerDomNode());
monaco.editor.setTheme(JSON_EDITOR_THEME);
void document.fonts.ready.then(() => monaco.editor.remeasureFonts());
}}
/>

View File

@@ -1,13 +1,11 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { Route } from 'react-router-dom';
import * as monaco from 'monaco-editor';
import ROUTES from 'constants/routes';
import { screen, userEvent, waitFor, within } from 'storybook/test';
import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { waitForMonacoText } from '@/storybook/visual/waitForMonacoText';
import { panelEditorMocks, savePanel } from './PanelEditorPage.stories.mocks';
@@ -251,43 +249,3 @@ export const TextPanelSavedToast: Story = {
args: { panel: 'new', newPanelKind: 'text' },
play: PanelSavedToast.play,
};
const CLICKHOUSE_QUERY =
'SELECT toStartOfInterval(timestamp, INTERVAL 1 MINUTE) AS ts, serviceName, count() AS calls FROM signoz_traces.distributed_signoz_index_v3 WHERE timestamp > now() - INTERVAL 1 HOUR GROUP BY ts, serviceName ORDER BY ts';
/**
* The ClickHouse Query tab with a query written in its SQL editor, over the
* panel the editor opened on.
*/
export const ClickHouseQuery: Story = {
play: async ({ canvasElement }): Promise<void> => {
const tab = await within(canvasElement).findByRole(
'tab',
{ name: /ClickHouse Query/ },
{ timeout: 10000 },
);
await userEvent.click(tab);
// Typing into Monaco's hidden textarea never reaches its model in this runner.
const model = await waitFor(
() => {
const found = monaco.editor
.getModels()
.find((candidate) => candidate.getLanguageId() === 'sql');
if (!found) {
throw new Error('The SQL editor has not mounted');
}
return found;
},
{ timeout: 15000 },
);
model.setValue(CLICKHOUSE_QUERY);
await waitForMonacoText(canvasElement);
await userEvent.unhover(tab);
(document.activeElement as HTMLElement | null)?.blur();
},
};

View File

@@ -1,8 +1,10 @@
import { useState } from 'react';
import MEditor, { Monaco } from '@monaco-editor/react';
import { Color } from '@signozhq/design-tokens';
import { Button } from '@signozhq/ui/button';
import { DialogWrapper } from '@signozhq/ui/dialog';
import { Maximize2 } from '@signozhq/icons';
import MonacoEditor from 'lib/monaco/MonacoEditor';
import { useIsDarkMode } from 'hooks/useDarkMode';
import styles from './NewDashboardModal.module.scss';
@@ -13,6 +15,18 @@ interface Props {
height?: string;
}
const defineTheme = (monaco: Monaco): void => {
monaco.editor.defineTheme('my-theme', {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'string.key.json', foreground: Color.BG_VANILLA_400 },
{ token: 'string.value.json', foreground: Color.BG_ROBIN_400 },
],
colors: { 'editor.background': Color.BG_INK_300 },
});
};
// JSON editor with a one-click "expand" into an extra-wide modal for easier
// editing/review. The expanded editor shares the same value, so edits persist.
function JsonEditor({
@@ -21,10 +35,11 @@ function JsonEditor({
readOnly = false,
height = '38vh',
}: Props): JSX.Element {
const isDarkMode = useIsDarkMode();
const [expanded, setExpanded] = useState(false);
const renderEditor = (editorHeight: string): JSX.Element => (
<MonacoEditor
<MEditor
language="json"
height={editorHeight}
value={value}
@@ -36,6 +51,8 @@ function JsonEditor({
fontSize: 14,
fontFamily: 'Space Mono',
}}
theme={isDarkMode ? 'my-theme' : 'light'}
beforeMount={defineTheme}
/>
);

View File

@@ -3,7 +3,6 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { waitForMonacoText } from '@/storybook/visual/waitForMonacoText';
import LLMObservabilityPage from '../../index';
import {
@@ -102,21 +101,3 @@ export const ChangesSavedToast: Story = {
}
},
};
/**
* The Test tab: the JSON editor pre-filled with the sample span, before any run.
*/
export const TestTab: Story = {
play: async ({ canvasElement }): Promise<void> => {
const tab = await within(canvasElement).findByRole(
'tab',
{ name: 'Test' },
{ timeout: 10000 },
);
await userEvent.click(tab);
await waitForMonacoText(canvasElement);
await userEvent.unhover(tab);
(document.activeElement as HTMLElement | null)?.blur();
},
};

View File

@@ -12,7 +12,6 @@ import {
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { waitForMonacoText } from '@/storybook/visual/waitForMonacoText';
import {
focusSpanIndex,
@@ -326,19 +325,3 @@ export const TraceExportCancelledToast: Story = {
await userEvent.click(await screen.findByTestId('trace-download-cancel'));
},
};
/** The span panel switched from the pretty view to the span's raw JSON. */
export const SpanJsonView: Story = {
play: async ({ canvasElement }): Promise<void> => {
const option = await within(canvasElement).findByTestId(
'data-viewer-view-mode-button-json',
undefined,
untilLoaded,
);
await userEvent.click(option);
await waitForMonacoText(canvasElement);
await userEvent.unhover(option);
(document.activeElement as HTMLElement | null)?.blur();
},
};

View File

@@ -1,8 +1,9 @@
import { useState } from 'react';
import { EditorProps } from '@monaco-editor/react';
import MEditor, { EditorProps, Monaco } from '@monaco-editor/react';
import { Color } from '@signozhq/design-tokens';
import { Switch } from '@signozhq/ui/switch';
import { Typography } from '@signozhq/ui/typography';
import MonacoEditor from 'lib/monaco/MonacoEditor';
import { useIsDarkMode } from 'hooks/useDarkMode';
import './JsonView.styles.scss';
@@ -37,16 +38,36 @@ const editorOptions: EditorProps['options'] = {
folding: false,
};
function setEditorTheme(monaco: Monaco): void {
monaco.editor.defineTheme('signoz-dark', {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'string.key.json', foreground: Color.BG_VANILLA_400 },
{ token: 'string.value.json', foreground: Color.BG_ROBIN_400 },
],
colors: {
'editor.background': '#00000000', // transparent
},
fontFamily: 'SF Mono, Geist Mono, Fira Code, monospace',
fontSize: 12,
fontWeight: 'normal',
lineHeight: 18,
letterSpacing: -0.06,
});
}
function JsonView({
data,
height = '575px',
fontSize = 12,
}: JsonViewProps): JSX.Element {
const [isWrapWord, setIsWrapWord] = useState(true);
const isDarkMode = useIsDarkMode();
return (
<div className="json-view">
<MonacoEditor
<MEditor
value={data}
language="json"
options={{
@@ -56,6 +77,8 @@ function JsonView({
}}
onChange={(): void => {}}
height={height}
theme={isDarkMode ? 'signoz-dark' : 'light'}
beforeMount={setEditorTheme}
/>
<div className="json-view__footer">
<div className="json-view__wrap-toggle">

View File

@@ -74,7 +74,8 @@
"meter-metrics",
"logs-field",
"traces-field",
"metrics-field"
"metrics-field",
"llm-pricing-rule"
],
"type": "string"
},

View File

@@ -1,26 +0,0 @@
import { waitFor } from 'storybook/test';
/**
* Monaco mounts its container before its language loads, so the editor is on
* screen while still blank or uncoloured. Waits for text with at least two
* token colours, which only exists once the tokenizer has run.
*/
export const waitForMonacoText = async (
canvasElement: HTMLElement,
): Promise<void> => {
await waitFor(
() => {
const lines = canvasElement.querySelector('.monaco-editor .view-lines');
const tokens = new Set(
Array.from(lines?.querySelectorAll('span[class^="mtk"]') ?? []).map(
(token) => token.className,
),
);
if (!lines?.textContent?.trim() || tokens.size < 2) {
throw new Error('Monaco has not rendered its text');
}
},
{ timeout: 15_000 },
);
};

View File

@@ -4,14 +4,15 @@ import (
"net/http"
"github.com/SigNoz/signoz/pkg/http/handler"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/SigNoz/signoz/pkg/types/llmpricingruletypes"
"github.com/gorilla/mux"
)
func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
if err := router.Handle("/api/v1/llm_pricing_rules", handler.New(
provider.authzMiddleware.ViewAccess(provider.llmPricingRuleHandler.List),
provider.authzMiddleware.CheckResources(provider.llmPricingRuleHandler.List, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
handler.OpenAPIDef{
ID: "ListLLMPricingRules",
Tags: []string{"llmpricingrules"},
@@ -25,14 +26,20 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceLLMPricingRule.Scope(coretypes.VerbList)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceLLMPricingRule,
Verb: coretypes.VerbList,
Category: coretypes.ActionCategoryDataAccess,
Selector: coretypes.WildcardSelector,
}),
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/llm_pricing_rules", handler.New(
provider.authzMiddleware.AdminAccess(provider.llmPricingRuleHandler.CreateOrUpdate),
provider.authzMiddleware.CheckResources(provider.llmPricingRuleHandler.CreateOrUpdate, authtypes.SigNozAdminRoleName),
handler.OpenAPIDef{
ID: "CreateOrUpdateLLMPricingRules",
Tags: []string{"llmpricingrules"},
@@ -43,14 +50,20 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusNoContent,
ErrorStatusCodes: []int{http.StatusBadRequest},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceLLMPricingRule.Scope(coretypes.VerbUpdate)}),
},
handler.WithResourceDefs(handler.TelemetryResourceDef{
Verb: coretypes.VerbUpdate,
Category: coretypes.ActionCategoryConfigurationChange,
Selector: llmpricingruletypes.RuleSelector,
Resources: llmpricingruletypes.UpdatableRulesResources,
}),
)).Methods(http.MethodPut).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/llm_pricing_rules/unmapped_models", handler.New(
provider.authzMiddleware.ViewAccess(provider.llmPricingRuleHandler.ListUnmappedModels),
provider.authzMiddleware.CheckResources(provider.llmPricingRuleHandler.ListUnmappedModels, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
handler.OpenAPIDef{
ID: "ListUnmappedLLMModels",
Tags: []string{"llmpricingrules"},
@@ -63,14 +76,20 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusBadRequest},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceLLMPricingRule.Scope(coretypes.VerbList)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceLLMPricingRule,
Verb: coretypes.VerbList,
Category: coretypes.ActionCategoryDataAccess,
Selector: coretypes.WildcardSelector,
}),
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/llm_pricing_rules/{id}", handler.New(
provider.authzMiddleware.ViewAccess(provider.llmPricingRuleHandler.Get),
provider.authzMiddleware.CheckResources(provider.llmPricingRuleHandler.Get, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
handler.OpenAPIDef{
ID: "GetLLMPricingRule",
Tags: []string{"llmpricingrules"},
@@ -83,14 +102,21 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceLLMPricingRule.Scope(coretypes.VerbRead)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceLLMPricingRule,
Verb: coretypes.VerbRead,
Category: coretypes.ActionCategoryDataAccess,
ID: coretypes.PathParam("id"),
Selector: coretypes.IDSelector,
}),
)).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v1/llm_pricing_rules/{id}", handler.New(
provider.authzMiddleware.AdminAccess(provider.llmPricingRuleHandler.Delete),
provider.authzMiddleware.CheckResources(provider.llmPricingRuleHandler.Delete, authtypes.SigNozAdminRoleName),
handler.OpenAPIDef{
ID: "DeleteLLMPricingRule",
Tags: []string{"llmpricingrules"},
@@ -103,8 +129,15 @@ func (provider *provider) addLLMPricingRuleRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusNoContent,
ErrorStatusCodes: []int{http.StatusNotFound},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceLLMPricingRule.Scope(coretypes.VerbDelete)}),
},
handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceMetaResourceLLMPricingRule,
Verb: coretypes.VerbDelete,
Category: coretypes.ActionCategoryConfigurationChange,
ID: coretypes.PathParam("id"),
Selector: coretypes.IDSelector,
}),
)).Methods(http.MethodDelete).GetError(); err != nil {
return err
}

View File

@@ -221,16 +221,15 @@ func postableRuleExamples() []handler.OpenAPIExample {
},
{
Name: "metric_anomaly",
Summary: "Metric anomaly rule (v1 only)",
Description: "Anomaly rules are not yet supported under schemaVersion v2alpha1, so this example uses the v1 shape. Wraps a builder query in the `anomaly` function with daily seasonality SigNoz compares each point against the forecast for that time of day. Fires when the anomaly score stays below the threshold for the entire window; `requireMinPoints` guards against noisy intervals.",
Summary: "Metric anomaly rule",
Description: "Wraps a builder query in the `anomaly` function with daily seasonality, so SigNoz compares each point against the forecast for that time of day. The threshold is compared against the signed anomaly score, so `below` with a target of -2 fires when an abrupt drop holds for the entire window; `requireMinPoints` guards against noisy intervals.",
Value: map[string]any{
"alert": "Anomalous drop in ingested spans",
"alertType": "METRIC_BASED_ALERT",
"description": "Detect an abrupt drop in span ingestion using a z-score anomaly function",
"ruleType": "anomaly_rule",
"version": "v5",
"evalWindow": "24h",
"frequency": "3h",
"alert": "Anomalous drop in ingested spans",
"alertType": "METRIC_BASED_ALERT",
"description": "Detect an abrupt drop in span ingestion using a z-score anomaly function",
"ruleType": "anomaly_rule",
"version": "v5",
"schemaVersion": "v2alpha1",
"condition": map[string]any{
"compositeQuery": map[string]any{
"queryType": "builder",
@@ -256,17 +255,29 @@ func postableRuleExamples() []handler.OpenAPIExample {
},
},
},
"op": "below",
"matchType": "all_the_times",
"target": 2,
"algorithm": "standard",
"seasonality": "daily",
"selectedQueryName": "A",
"requireMinPoints": true,
"requiredNumPoints": 3,
"thresholds": map[string]any{
"kind": "basic",
"spec": []any{
map[string]any{
"name": "warning",
"op": "below",
"matchType": "all_the_times",
"target": -2,
"channels": []any{"slack-ingestion"},
},
},
},
},
"labels": map[string]any{"severity": "warning"},
"preferredChannels": []any{"slack-ingestion"},
"evaluation": rolling("24h", "3h"),
"notificationSettings": map[string]any{
"renotify": renotify("4h", "firing"),
},
"labels": map[string]any{"severity": "warning"},
"annotations": map[string]any{
"description": "Ingestion rate for tenant {{$tenant_id}} is anomalously low (z-score {{$value}}).",
"summary": "Span ingestion anomaly",

View File

@@ -266,6 +266,7 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewAddMetricsFieldTuplesFactory(sqlstore),
sqlmigration.NewAddGCPConnectionMethodFactory(),
sqlmigration.NewDeleteOrphanSARolesFactory(),
sqlmigration.NewAddLLMPricingRuleTuplesFactory(sqlstore),
)
}

View File

@@ -0,0 +1,162 @@
package sqlmigration
import (
"context"
"database/sql"
"encoding/json"
"time"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/oklog/ulid/v2"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect"
"github.com/uptrace/bun/migrate"
)
type addLLMPricingRuleTuples struct {
sqlstore sqlstore.SQLStore
}
func NewAddLLMPricingRuleTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
return factory.NewProviderFactory(factory.MustNewName("add_llm_pricing_rule_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
return &addLLMPricingRuleTuples{sqlstore: sqlstore}, nil
})
}
func (migration *addLLMPricingRuleTuples) Register(migrations *migrate.Migrations) error {
return migrations.Register(migration.Up, migration.Down)
}
func (migration *addLLMPricingRuleTuples) Up(ctx context.Context, db *bun.DB) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
var storeID string
err = tx.QueryRowContext(ctx, `SELECT id FROM store WHERE name = ? LIMIT 1`, "signoz").Scan(&storeID)
if err != nil {
return err
}
var orgIDs []string
err = tx.NewSelect().
Table("organizations").
Column("id").
Scan(ctx, &orgIDs)
if err != nil && err != sql.ErrNoRows {
return err
}
isPG := migration.sqlstore.BunDB().Dialect().Name() == dialect.PG
tuples := []migrationTuple{
{authtypes.SigNozAdminRoleName, "metaresource", "llm-pricing-rule", "read"},
{authtypes.SigNozAdminRoleName, "metaresource", "llm-pricing-rule", "update"},
{authtypes.SigNozAdminRoleName, "metaresource", "llm-pricing-rule", "delete"},
{authtypes.SigNozAdminRoleName, "metaresource", "llm-pricing-rule", "list"},
{authtypes.SigNozEditorRoleName, "metaresource", "llm-pricing-rule", "read"},
{authtypes.SigNozEditorRoleName, "metaresource", "llm-pricing-rule", "list"},
{authtypes.SigNozViewerRoleName, "metaresource", "llm-pricing-rule", "read"},
{authtypes.SigNozViewerRoleName, "metaresource", "llm-pricing-rule", "list"},
}
for _, orgID := range orgIDs {
for _, tuple := range tuples {
entropy := ulid.DefaultEntropy()
now := time.Now().UTC()
tupleID := ulid.MustNew(ulid.Timestamp(now), entropy).String()
objectID := "organization/" + orgID + "/" + tuple.objectName + "/*"
roleSubject := "organization/" + orgID + "/role/" + tuple.roleName
if isPG {
user := "role:" + roleSubject + "#assignee"
result, err := tx.ExecContext(ctx, `
INSERT INTO tuple (store, object_type, object_id, relation, _user, user_type, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, object_type, object_id, relation, _user) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, user, "userset", tupleID, now,
)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
continue
}
_, err = tx.ExecContext(ctx, `
INSERT INTO changelog (store, object_type, object_id, relation, _user, operation, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, ulid, object_type) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, user, 0, tupleID, now,
)
if err != nil {
return err
}
} else {
result, err := tx.ExecContext(ctx, `
INSERT INTO tuple (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, user_type, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", "userset", tupleID, now,
)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
continue
}
_, err = tx.ExecContext(ctx, `
INSERT INTO changelog (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, operation, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, ulid, object_type) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", 0, tupleID, now,
)
if err != nil {
return err
}
}
}
}
managedRoleGroups := make(map[string]string, len(coretypes.ManagedRoleToTransactions))
for roleName, transactions := range coretypes.ManagedRoleToTransactions {
data, err := json.Marshal(authtypes.NewTransactionGroupsFromTransactions(transactions))
if err != nil {
return err
}
managedRoleGroups[roleName] = string(data)
}
for _, orgID := range orgIDs {
for roleName, data := range managedRoleGroups {
if _, err := tx.NewUpdate().
Model(new(roles)).
Set("transaction_groups = ?", data).
Where("org_id = ?", orgID).
Where("type = ?", authtypes.RoleTypeManaged.StringValue()).
Where("name = ?", roleName).
Exec(ctx); err != nil {
return err
}
}
}
return tx.Commit()
}
func (migration *addLLMPricingRuleTuples) Down(context.Context, *bun.DB) error {
return nil
}

View File

@@ -80,6 +80,7 @@ func (name Kind) Enum() []any {
KindLogsField,
KindTracesField,
KindMetricsField,
KindLLMPricingRule,
}
}

View File

@@ -40,6 +40,7 @@ var Kinds = []Kind{
KindLogsField,
KindTracesField,
KindMetricsField,
KindLLMPricingRule,
}
var (
@@ -82,4 +83,5 @@ var (
KindLogsField = MustNewKind("logs-field")
KindTracesField = MustNewKind("traces-field")
KindMetricsField = MustNewKind("metrics-field")
KindLLMPricingRule = MustNewKind("llm-pricing-rule")
)

View File

@@ -218,6 +218,11 @@ var ManagedRoleToTransactions = map[string][]Transaction{
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
// llm-pricing-rule — admin writes, viewer reads
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
},
SigNozEditorRoleName: {
// cloud-integration — editor can read accounts
@@ -317,6 +322,9 @@ var ManagedRoleToTransactions = map[string][]Transaction{
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
// llm-pricing-rule — read only (admin writes)
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
},
SigNozViewerRoleName: {
// cloud-integration — viewer can read accounts
@@ -381,6 +389,9 @@ var ManagedRoleToTransactions = map[string][]Transaction{
// metrics-field — viewer reads
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindMetricsField}, WildCardSelectorString)},
// llm-pricing-rule — read only
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLLMPricingRule}, WildCardSelectorString)},
},
SigNozAnonymousRoleName: {
// public-dashboard — anonymous read

View File

@@ -40,6 +40,7 @@ var Resources = []Resource{
ResourceMetaResourceLogsField,
ResourceMetaResourceTracesField,
ResourceMetaResourceMetricsField,
ResourceMetaResourceLLMPricingRule,
}
var (
@@ -82,4 +83,5 @@ var (
ResourceMetaResourceLogsField = NewResourceMetaResource(KindLogsField)
ResourceMetaResourceTracesField = NewResourceMetaResource(KindTracesField)
ResourceMetaResourceMetricsField = NewResourceMetaResource(KindMetricsField, VerbList, VerbRead, VerbUpdate)
ResourceMetaResourceLLMPricingRule = NewResourceMetaResource(KindLLMPricingRule, VerbList, VerbRead, VerbUpdate, VerbDelete)
)

View File

@@ -0,0 +1,65 @@
package llmpricingruletypes
import (
"context"
"encoding/json"
"slices"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
// UpdatableRulesResources resolves the pricing rules an upsert body writes to.
//
// A rule with isOverride and an id is an edit, checked by that id. Everything
// else resolves to the wildcard: isOverride without an id is a create, sourceId
// without isOverride is a sync row, and an empty list has nothing to check.
func UpdatableRulesResources(ec coretypes.ExtractorContext) ([]coretypes.ResourceWithID, error) {
// encoding/json with the handler's tags, so duplicate or case-variant id
// keys resolve to the id that is actually written.
var body struct {
Rules []*struct {
// Normalised through valuer so an uppercase id still matches the
// lowercase selector regex of the metaresource type.
ID *valuer.UUID `json:"id"`
IsOverride *bool `json:"isOverride"`
} `json:"rules"`
}
if err := json.Unmarshal(ec.RequestBody, &body); err != nil {
return nil, errors.Wrapf(err, errors.TypeInvalidInput, ErrCodePricingRuleInvalidInput, "invalid pricing rules body")
}
ids := make([]string, 0, len(body.Rules))
wildcard := len(body.Rules) == 0
for _, rule := range body.Rules {
if rule == nil || rule.ID == nil || rule.IsOverride == nil {
wildcard = true
continue
}
if !slices.Contains(ids, rule.ID.StringValue()) {
ids = append(ids, rule.ID.StringValue())
}
}
if wildcard {
ids = append(ids, coretypes.WildCardSelectorString)
}
resources := make([]coretypes.ResourceWithID, 0, len(ids))
for _, id := range ids {
resources = append(resources, coretypes.ResourceWithID{Resource: coretypes.ResourceMetaResourceLLMPricingRule, ID: id})
}
return resources, nil
}
// RuleSelector exists because IDSelector would turn the wildcard entry into
// the wildcard twice; an id still resolves to the id plus the wildcard.
func RuleSelector(ctx context.Context, resource coretypes.Resource, id string, orgID valuer.UUID) ([]coretypes.Selector, error) {
if id == coretypes.WildCardSelectorString {
return coretypes.WildcardSelector(ctx, resource, id, orgID)
}
return coretypes.IDSelector(ctx, resource, id, orgID)
}

View File

@@ -0,0 +1,116 @@
package llmpricingruletypes
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
func TestUpdatableRulesResources(t *testing.T) {
testCases := []struct {
name string
body string
want []string
wantErr bool
}{
{
name: "EmptyRules_Wildcard",
body: `{"rules":[]}`,
want: []string{"*"},
},
{
name: "Edit_ID",
body: `{"rules":[{"id":"0b6d1a4e-5c1f-4d2a-9e3b-1f2a3b4c5d6e","isOverride":true}]}`,
want: []string{"0b6d1a4e-5c1f-4d2a-9e3b-1f2a3b4c5d6e"},
},
{
name: "Create_Wildcard",
body: `{"rules":[{"modelName":"gpt","isOverride":true}]}`,
want: []string{"*"},
},
{
name: "SyncRow_Wildcard",
body: `{"rules":[{"sourceId":"4e9a0b12-3c4d-4e5f-8a6b-7c8d9e0f1a2b"}]}`,
want: []string{"*"},
},
{
name: "Mixed_DedupedIDsThenWildcardOnce",
body: `{"rules":[{"id":"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d","isOverride":true},{"modelName":"new","isOverride":true},{"id":"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d","isOverride":false},{"sourceId":"7bcd3e45-6f7a-4b8c-9d9e-0f1a2b3c4d5e"}]}`,
want: []string{"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d", "*"},
},
{
name: "UppercaseID_Lowercased",
body: `{"rules":[{"id":"8CDE4F56-7A8B-4C9D-8E0F-1A2B3C4D5E6F","isOverride":true}]}`,
want: []string{"8cde4f56-7a8b-4c9d-8e0f-1a2b3c4d5e6f"},
},
{
name: "DuplicateIDKey_LastWins",
body: `{"rules":[{"id":"0b6d1a4e-5c1f-4d2a-9e3b-1f2a3b4c5d6e","id":"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d","isOverride":true}]}`,
want: []string{"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d"},
},
{
name: "CaseVariantIDKey_LastWins",
body: `{"rules":[{"id":"0b6d1a4e-5c1f-4d2a-9e3b-1f2a3b4c5d6e","ID":"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d","isOverride":true}]}`,
want: []string{"6abc2d34-5e6f-4a7b-8c8d-9e0f1a2b3c4d"},
},
{
name: "InvalidID_Rejected",
body: `{"rules":[{"id":"not-a-uuid","isOverride":true}]}`,
wantErr: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
resources, err := UpdatableRulesResources(coretypes.ExtractorContext{RequestBody: []byte(testCase.body)})
if testCase.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
got := make([]string, 0, len(resources))
for _, resource := range resources {
got = append(got, resource.ID)
}
assert.Equal(t, testCase.want, got)
})
}
}
func TestRuleSelector(t *testing.T) {
testCases := []struct {
name string
id string
want []string
}{
{
name: "Wildcard_WildcardOnly",
id: "*",
want: []string{"*"},
},
{
name: "ID_IDThenWildcard",
id: "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
want: []string{"a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "*"},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
selectors, err := RuleSelector(context.Background(), coretypes.ResourceMetaResourceLLMPricingRule, testCase.id, valuer.GenerateUUID())
require.NoError(t, err)
got := make([]string, 0, len(selectors))
for _, selector := range selectors {
got = append(got, selector.String())
}
assert.Equal(t, testCase.want, got)
})
}
}

View File

@@ -117,10 +117,10 @@ type RuleCondition struct {
TargetUnit string `json:"targetUnit,omitempty" description:"schemaVersion v1 only: the unit of target, such as percent or ms. Converted to compositeQuery.unit before comparison when the two differ."`
Algorithm string `json:"algorithm,omitempty" description:"anomaly_rule only: the anomaly detection algorithm. The supported value is standard."`
Seasonality Seasonality `json:"seasonality,omitzero" description:"anomaly_rule only: the seasonal period the history is compared against, hourly, daily or weekly."`
SelectedQuery string `json:"selectedQueryName,omitempty" description:"The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery. When omitted, F1 is used if present, otherwise the enabled query with the highest name."`
SelectedQuery string `json:"selectedQueryName,omitempty" required:"true" description:"The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery."`
RequireMinPoints bool `json:"requireMinPoints,omitempty" description:"Whether a series is skipped until it has at least requiredNumPoints points in the window. Defaults to false."`
RequiredNumPoints int `json:"requiredNumPoints,omitempty" description:"The minimum number of points a series needs before it is evaluated. Must be greater than 0 when requireMinPoints is true."`
Thresholds *RuleThresholdData `json:"thresholds,omitempty" description:"The thresholds to evaluate, as a kind and spec. Required when schemaVersion is v2alpha1; derived from op, target and matchType for v1."`
Thresholds *RuleThresholdData `json:"thresholds,omitempty" required:"true" description:"The thresholds to evaluate, as a kind and spec."`
}
func (rc *RuleCondition) SelectedQueryName() string {

View File

@@ -9,6 +9,7 @@ import (
"unicode/utf8"
"github.com/prometheus/alertmanager/config"
"github.com/swaggest/jsonschema-go"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types"
@@ -63,7 +64,7 @@ type PostableRule struct {
AlertName valuer.DisplayName `json:"alert" required:"true" description:"The display name of the alert rule."`
AlertType AlertType `json:"alertType" required:"true" description:"The signal the rule evaluates: METRIC_BASED_ALERT, TRACES_BASED_ALERT, LOGS_BASED_ALERT, EXCEPTIONS_BASED_ALERT or AI_TRACES_BASED_ALERT."`
Description string `json:"description,omitempty" description:"A human readable description of what the rule monitors."`
RuleType RuleType `json:"ruleType" required:"true" description:"The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder queries and is forced to promql_rule for promql queries."`
RuleType RuleType `json:"ruleType" required:"true" description:"The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries."`
EvalWindow valuer.TextDuration `json:"evalWindow,omitzero" description:"The lookback window as a Go duration such as 5m. Only read when schemaVersion is v1, defaulting to 5m; v2alpha1 rules set it in evaluation.spec instead."`
Frequency valuer.TextDuration `json:"frequency,omitzero" description:"How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead."`
@@ -77,12 +78,12 @@ type PostableRule struct {
PreferredChannels []string `json:"preferredChannels,omitempty" description:"The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels."`
Version string `json:"version" description:"The query payload version. Only v5 is accepted and it is filled in when omitted."`
Version string `json:"version" description:"The query payload version. Nothing reads it."`
Evaluation *EvaluationEnvelope `json:"evaluation,omitempty" description:"The evaluation window, as a kind and spec. Required when schemaVersion is v2alpha1; derived from evalWindow and frequency for v1."`
SchemaVersion string `json:"schemaVersion,omitempty" description:"The rule payload schema: v1 (the default when omitted) uses the flat condition fields, v2alpha1 uses condition.thresholds, evaluation and notificationSettings."`
Evaluation *EvaluationEnvelope `json:"evaluation,omitempty" required:"true" description:"The evaluation window, as a kind and spec."`
SchemaVersion string `json:"schemaVersion,omitempty" required:"true" enum:"v2alpha1" description:"The rule payload schema."`
NotificationSettings *NotificationSettings `json:"notificationSettings,omitempty" description:"Grouping, re-notification and routing behaviour. Required when schemaVersion is v2alpha1; derived from the v1 fields otherwise."`
NotificationSettings *NotificationSettings `json:"notificationSettings,omitempty" required:"true" description:"Grouping, re-notification and routing behaviour."`
}
type NotificationSettings struct {
@@ -335,6 +336,19 @@ func (r *PostableRule) UnmarshalJSON(bytes []byte) error {
return r.validate()
}
var _ jsonschema.Preparer = PostableRule{}
// PrepareJSONSchema marks version and source deprecated: nothing reads them,
// they stay only so existing clients keep a stable schema.
func (PostableRule) PrepareJSONSchema(schema *jsonschema.Schema) error {
for _, name := range []string{"version", "source"} {
if property, ok := schema.Properties[name]; ok && property.TypeObject != nil {
property.TypeObject.WithDeprecated(true)
}
}
return nil
}
func isValidLabelName(ln string) bool {
if len(ln) == 0 {
return false

View File

@@ -297,6 +297,16 @@
"list"
]
},
{
"type": "metaresource",
"kind": "llm-pricing-rule",
"verbs": [
"read",
"update",
"delete",
"list"
]
},
{
"type": "metaresource",
"kind": "ttl-setting",
@@ -528,6 +538,14 @@
"list"
]
},
{
"type": "metaresource",
"kind": "llm-pricing-rule",
"verbs": [
"read",
"list"
]
},
{
"type": "metaresource",
"kind": "ttl-setting",
@@ -707,6 +725,14 @@
"list"
]
},
{
"type": "metaresource",
"kind": "llm-pricing-rule",
"verbs": [
"read",
"list"
]
},
{
"type": "metaresource",
"kind": "ttl-setting",

View File

@@ -0,0 +1,267 @@
from collections.abc import Callable
from http import HTTPStatus
import pytest
import requests
from wiremock.resources.mappings import Mapping
from fixtures import types
from fixtures.auth import (
USER_ADMIN_EMAIL,
USER_ADMIN_PASSWORD,
add_license,
change_user_role,
create_active_user,
)
from fixtures.llmpricingrules import (
LLM_PRICING_RULES_URL,
delete_all_llm_pricing_rules,
list_llm_pricing_rules,
upsert_llm_pricing_rules,
)
from fixtures.role import find_role_by_name, transaction_group
user_password = "password123Z$"
editor_email = "llm-pricing-editor@integration.test"
viewer_email = "llm-pricing-viewer@integration.test"
updater_role = "llm-pricing-updater"
updater_email = "llm-pricing-updater@integration.test"
scoped_role = "llm-pricing-scoped"
scoped_email = "llm-pricing-scoped@integration.test"
PROBE_RULE = {
"modelName": "authz-probe",
"provider": "OpenAI",
"modelPattern": ["authz-probe*"],
"unit": "per_million_tokens",
"pricing": {"input": 1, "output": 2},
"isOverride": True,
"enabled": True,
}
OTHER_RULE = {
"modelName": "authz-probe-other",
"provider": "Anthropic",
"modelPattern": ["authz-probe-other*"],
"unit": "per_million_tokens",
"pricing": {"input": 3, "output": 4},
"isOverride": True,
"enabled": True,
}
def test_setup(
signoz: types.SigNoz,
create_user_admin: types.Operation, # pylint: disable=unused-argument
make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
get_token: Callable[[str, str], str],
create_role: Callable[..., str],
) -> None:
add_license(signoz, make_http_mocks, get_token)
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
delete_all_llm_pricing_rules(signoz, admin_token)
assert upsert_llm_pricing_rules(signoz, admin_token, [PROBE_RULE, OTHER_RULE]).status_code == HTTPStatus.NO_CONTENT
probe_id = next(r["id"] for r in list_llm_pricing_rules(signoz, admin_token) if r["modelName"] == PROBE_RULE["modelName"])
create_active_user(signoz, admin_token, email=editor_email, role="signoz-editor", password=user_password)
create_active_user(signoz, admin_token, email=viewer_email, role="signoz-viewer", password=user_password)
create_role(admin_token, updater_role, [transaction_group("update", "metaresource", "llm-pricing-rule", ["*"])])
updater = create_active_user(signoz, admin_token, email=updater_email, role="signoz-viewer", password=user_password)
change_user_role(signoz, admin_token, updater, "signoz-viewer", updater_role)
create_role(
admin_token,
scoped_role,
[
transaction_group("read", "metaresource", "llm-pricing-rule", [probe_id]),
transaction_group("update", "metaresource", "llm-pricing-rule", [probe_id]),
transaction_group("delete", "metaresource", "llm-pricing-rule", [probe_id]),
],
)
scoped = create_active_user(signoz, admin_token, email=scoped_email, role="signoz-viewer", password=user_password)
change_user_role(signoz, admin_token, scoped, "signoz-viewer", scoped_role)
@pytest.mark.parametrize(
"path",
[LLM_PRICING_RULES_URL, f"{LLM_PRICING_RULES_URL}/unmapped_models"],
ids=["list", "unmapped_models"],
)
@pytest.mark.parametrize(
("email", "expected"),
[
(USER_ADMIN_EMAIL, HTTPStatus.OK),
(editor_email, HTTPStatus.OK),
(viewer_email, HTTPStatus.OK),
(updater_email, HTTPStatus.FORBIDDEN),
(scoped_email, HTTPStatus.FORBIDDEN),
],
ids=["admin", "editor", "viewer", "updater", "scoped"],
)
def test_reads_need_list_grant(
signoz: types.SigNoz,
get_token: Callable[[str, str], str],
path: str,
email: str,
expected: HTTPStatus,
) -> None:
token = get_token(email, USER_ADMIN_PASSWORD if email == USER_ADMIN_EMAIL else user_password)
response = requests.get(
signoz.self.host_configs["8080"].get(path),
headers={"Authorization": f"Bearer {token}"},
timeout=10,
)
assert response.status_code == expected, response.text
if expected == HTTPStatus.FORBIDDEN:
assert "llm-pricing-rule:list" in response.text
@pytest.mark.parametrize(
("email", "model_name", "expected"),
[
(USER_ADMIN_EMAIL, PROBE_RULE["modelName"], HTTPStatus.OK),
(editor_email, PROBE_RULE["modelName"], HTTPStatus.OK),
(viewer_email, PROBE_RULE["modelName"], HTTPStatus.OK),
(updater_email, PROBE_RULE["modelName"], HTTPStatus.FORBIDDEN),
(scoped_email, PROBE_RULE["modelName"], HTTPStatus.OK),
(scoped_email, OTHER_RULE["modelName"], HTTPStatus.FORBIDDEN),
],
ids=["admin", "editor", "viewer", "updater", "scoped_granted", "scoped_other"],
)
def test_get_needs_read_grant(
signoz: types.SigNoz,
get_token: Callable[[str, str], str],
email: str,
model_name: str,
expected: HTTPStatus,
) -> None:
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
rule_id = next(r["id"] for r in list_llm_pricing_rules(signoz, admin_token) if r["modelName"] == model_name)
token = get_token(email, USER_ADMIN_PASSWORD if email == USER_ADMIN_EMAIL else user_password)
response = requests.get(
signoz.self.host_configs["8080"].get(f"{LLM_PRICING_RULES_URL}/{rule_id}"),
headers={"Authorization": f"Bearer {token}"},
timeout=10,
)
assert response.status_code == expected, response.text
if expected == HTTPStatus.FORBIDDEN:
assert "llm-pricing-rule:read" in response.text
@pytest.mark.parametrize(
("email", "expected"),
[
(editor_email, HTTPStatus.FORBIDDEN),
(viewer_email, HTTPStatus.FORBIDDEN),
(scoped_email, HTTPStatus.NO_CONTENT),
(updater_email, HTTPStatus.NO_CONTENT),
(USER_ADMIN_EMAIL, HTTPStatus.NO_CONTENT),
],
ids=["editor", "viewer", "scoped", "updater", "admin"],
)
def test_upsert_needs_update_grant(
signoz: types.SigNoz,
get_token: Callable[[str, str], str],
email: str,
expected: HTTPStatus,
) -> None:
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
rule_id = next(r["id"] for r in list_llm_pricing_rules(signoz, admin_token) if r["modelName"] == PROBE_RULE["modelName"])
token = get_token(email, USER_ADMIN_PASSWORD if email == USER_ADMIN_EMAIL else user_password)
response = upsert_llm_pricing_rules(signoz, token, [{**PROBE_RULE, "id": rule_id}])
assert response.status_code == expected, response.text
if expected == HTTPStatus.FORBIDDEN:
assert "llm-pricing-rule:update" in response.text
@pytest.mark.parametrize(
"shape",
["other_rule", "create", "sync_row", "own_and_other"],
ids=["other_rule", "create", "sync_row", "own_and_other"],
)
def test_upsert_scoped_to_granted_rule(
signoz: types.SigNoz,
get_token: Callable[[str, str], str],
shape: str,
) -> None:
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
rules = {r["modelName"]: r for r in list_llm_pricing_rules(signoz, admin_token)}
own = {**PROBE_RULE, "id": rules[PROBE_RULE["modelName"]]["id"]}
other = {**OTHER_RULE, "id": rules[OTHER_RULE["modelName"]]["id"]}
sync_row = {**{k: v for k, v in PROBE_RULE.items() if k != "isOverride"}, "sourceId": "11111111-1111-4111-8111-111111111199"}
bodies = {"other_rule": [other], "create": [PROBE_RULE], "sync_row": [sync_row], "own_and_other": [own, other]}
response = upsert_llm_pricing_rules(signoz, get_token(scoped_email, user_password), bodies[shape])
assert response.status_code == HTTPStatus.FORBIDDEN, response.text
assert "llm-pricing-rule:update" in response.text
def test_revoke_update_grant(
signoz: types.SigNoz,
get_token: Callable[[str, str], str],
) -> None:
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
rule_id = next(r["id"] for r in list_llm_pricing_rules(signoz, admin_token) if r["modelName"] == PROBE_RULE["modelName"])
response = requests.put(
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{find_role_by_name(signoz, admin_token, scoped_role)}"),
json={
"description": "",
"transactionGroups": [
transaction_group("read", "metaresource", "llm-pricing-rule", [rule_id]),
transaction_group("delete", "metaresource", "llm-pricing-rule", [rule_id]),
],
},
headers={"Authorization": f"Bearer {admin_token}"},
timeout=10,
)
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
response = upsert_llm_pricing_rules(signoz, get_token(scoped_email, user_password), [{**PROBE_RULE, "id": rule_id}])
assert response.status_code == HTTPStatus.FORBIDDEN, response.text
assert "llm-pricing-rule:update" in response.text
@pytest.mark.parametrize(
("email", "model_name", "expected"),
[
(editor_email, PROBE_RULE["modelName"], HTTPStatus.FORBIDDEN),
(viewer_email, PROBE_RULE["modelName"], HTTPStatus.FORBIDDEN),
(updater_email, PROBE_RULE["modelName"], HTTPStatus.FORBIDDEN),
(scoped_email, OTHER_RULE["modelName"], HTTPStatus.FORBIDDEN),
(scoped_email, PROBE_RULE["modelName"], HTTPStatus.NO_CONTENT),
(USER_ADMIN_EMAIL, OTHER_RULE["modelName"], HTTPStatus.NO_CONTENT),
],
ids=["editor", "viewer", "updater", "scoped_other", "scoped_granted", "admin"],
)
def test_delete_needs_delete_grant(
signoz: types.SigNoz,
get_token: Callable[[str, str], str],
email: str,
model_name: str,
expected: HTTPStatus,
) -> None:
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
rule_id = next(r["id"] for r in list_llm_pricing_rules(signoz, admin_token) if r["modelName"] == model_name)
token = get_token(email, USER_ADMIN_PASSWORD if email == USER_ADMIN_EMAIL else user_password)
response = requests.delete(
signoz.self.host_configs["8080"].get(f"{LLM_PRICING_RULES_URL}/{rule_id}"),
headers={"Authorization": f"Bearer {token}"},
timeout=10,
)
assert response.status_code == expected, response.text
if expected == HTTPStatus.FORBIDDEN:
assert "llm-pricing-rule:delete" in response.text
def test_cleanup(
signoz: types.SigNoz,
get_token: Callable[[str, str], str],
) -> None:
delete_all_llm_pricing_rules(signoz, get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD))