mirror of
https://github.com/SigNoz/signoz.git
synced 2026-10-31 21:40:42 +00:00
Compare commits
4 Commits
refactor/s
...
issue_nerv
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20080ec988 | ||
|
|
5097d1578f | ||
|
|
fb33e31c4c | ||
|
|
0a0cd96e93 |
@@ -3932,6 +3932,8 @@ components:
|
||||
- logs-field
|
||||
- traces-field
|
||||
- metrics-field
|
||||
- span-mapper-group
|
||||
- span-mapper
|
||||
type: string
|
||||
CoretypesObject:
|
||||
properties:
|
||||
@@ -11389,8 +11391,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 +11407,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 +11420,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 +11532,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 +11551,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 +11564,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 +11587,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 +11597,9 @@ components:
|
||||
- alertType
|
||||
- ruleType
|
||||
- condition
|
||||
- evaluation
|
||||
- schemaVersion
|
||||
- notificationSettings
|
||||
type: object
|
||||
RuletypesRuleCondition:
|
||||
properties:
|
||||
@@ -11643,8 +11649,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 +11665,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:
|
||||
@@ -17810,9 +17816,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- span-mapper-group:list
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- span-mapper-group:list
|
||||
summary: List span attribute mapping groups
|
||||
tags:
|
||||
- spanmapper
|
||||
@@ -17873,9 +17879,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- span-mapper-group:create
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- span-mapper-group:create
|
||||
summary: Create a span attribute mapping group
|
||||
tags:
|
||||
- spanmapper
|
||||
@@ -17920,9 +17926,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- span-mapper-group:delete
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- span-mapper-group:delete
|
||||
summary: Delete a span attribute mapping group
|
||||
tags:
|
||||
- spanmapper
|
||||
@@ -17978,9 +17984,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- span-mapper-group:update
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- span-mapper-group:update
|
||||
summary: Update a span attribute mapping group
|
||||
tags:
|
||||
- spanmapper
|
||||
@@ -18043,9 +18049,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- span-mapper-group:read
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- span-mapper-group:read
|
||||
summary: List span mappers for a group
|
||||
tags:
|
||||
- spanmapper
|
||||
@@ -18118,9 +18124,11 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- span-mapper:create
|
||||
- span-mapper-group:attach
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- span-mapper:create
|
||||
- span-mapper-group:attach
|
||||
summary: Create a span mapper
|
||||
tags:
|
||||
- spanmapper
|
||||
@@ -18170,9 +18178,11 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- span-mapper:delete
|
||||
- span-mapper-group:detach
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- span-mapper:delete
|
||||
- span-mapper-group:detach
|
||||
summary: Delete a span mapper
|
||||
tags:
|
||||
- spanmapper
|
||||
@@ -18233,9 +18243,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- span-mapper:update
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- span-mapper:update
|
||||
summary: Update a span mapper
|
||||
tags:
|
||||
- spanmapper
|
||||
@@ -18243,7 +18253,8 @@ paths:
|
||||
/api/v1/span_mapper_groups/test:
|
||||
post:
|
||||
deprecated: false
|
||||
description: Tests how span mappers would transform sample spans
|
||||
description: Tests how span mappers would transform sample spans. Groups sent
|
||||
without mappers are read from the store by name.
|
||||
operationId: TestSpanMappers
|
||||
requestBody:
|
||||
content:
|
||||
@@ -18297,9 +18308,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- span-mapper-group:read
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
- span-mapper-group:read
|
||||
summary: Test span mappers against sample spans
|
||||
tags:
|
||||
- spanmapper
|
||||
@@ -25312,13 +25323,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 +25364,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 +26289,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 +26330,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 +27156,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 +27197,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 +28729,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 +28770,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
|
||||
|
||||
@@ -3579,6 +3579,8 @@ export enum CoretypesKindDTO {
|
||||
'logs-field' = 'logs-field',
|
||||
'traces-field' = 'traces-field',
|
||||
'metrics-field' = 'metrics-field',
|
||||
'span-mapper-group' = 'span-mapper-group',
|
||||
'span-mapper' = 'span-mapper',
|
||||
}
|
||||
export enum CoretypesTypeDTO {
|
||||
user = 'user',
|
||||
@@ -12584,6 +12586,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 +12668,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 +12683,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 +12723,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 +12737,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 +12762,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 +12785,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 +12835,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 +12854,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 +12892,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;
|
||||
}
|
||||
|
||||
@@ -803,7 +803,7 @@ export const useUpdateSpanMapper = <
|
||||
return useMutation(getUpdateSpanMapperMutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* Tests how span mappers would transform sample spans
|
||||
* Tests how span mappers would transform sample spans. Groups sent without mappers are read from the store by name.
|
||||
* @summary Test span mappers against sample spans
|
||||
*/
|
||||
export const testSpanMappers = (
|
||||
|
||||
@@ -4,7 +4,6 @@ import { Button } from '@signozhq/ui/button';
|
||||
import { Drawer, Tooltip } from 'antd';
|
||||
import { ToggleGroup } from '@signozhq/ui/toggle-group';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import LogStateIndicator from 'components/Logs/LogStateIndicator/LogStateIndicator';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import QuerySearch from 'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch';
|
||||
@@ -148,7 +147,7 @@ function LogDetailInner({
|
||||
|
||||
const { options } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
|
||||
});
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import FieldsSelector from 'components/FieldsSelector';
|
||||
import LogsFormatOptionsMenu from 'components/LogsFormatOptionsMenu/LogsFormatOptionsMenu';
|
||||
import { MAX_LOGS_LIST_SIZE } from 'constants/liveTail';
|
||||
@@ -55,7 +54,7 @@ function LiveLogsContainer({
|
||||
|
||||
const { options, config } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { Card } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import LogDetail from 'components/LogDetail';
|
||||
import { VIEW_TYPES } from 'components/LogDetail/constants';
|
||||
import ListLogView from 'components/Logs/ListLogView';
|
||||
@@ -31,7 +30,7 @@ import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useEventSource } from 'providers/EventSource';
|
||||
// interfaces
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { StringOperators } from 'types/common/queryBuilder';
|
||||
import { DataSource, StringOperators } from 'types/common/queryBuilder';
|
||||
|
||||
import loadingPlaneUrl from '@/assets/Icons/loading-plane.gif';
|
||||
import { getAbsoluteUrl } from 'utils/basePath';
|
||||
@@ -69,7 +68,7 @@ function LiveLogsList({
|
||||
|
||||
const { options, config } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: StringOperators.NOOP,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Virtuoso } from 'react-virtuoso';
|
||||
import { Button, Skeleton } from 'antd';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import RawLogView from 'components/Logs/RawLogView';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
@@ -17,7 +16,7 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { StringOperators } from 'types/common/queryBuilder';
|
||||
import { DataSource, StringOperators } from 'types/common/queryBuilder';
|
||||
import { withBasePath } from 'utils/basePath';
|
||||
|
||||
import { useContextLogData } from './useContextLogData';
|
||||
@@ -46,7 +45,7 @@ function ContextLogRenderer({
|
||||
|
||||
const { options } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { Card } from 'antd';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
|
||||
import LogDetail from 'components/LogDetail';
|
||||
import { VIEW_TYPES } from 'components/LogDetail/constants';
|
||||
@@ -78,7 +77,7 @@ function LogsExplorerList({
|
||||
|
||||
const { options, config } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator:
|
||||
currentStagedQueryData?.aggregateOperator || StringOperators.NOOP,
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ReactNode, useState } from 'react';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import DownloadOptionsMenu from 'components/DownloadOptionsMenu/DownloadOptionsMenu';
|
||||
import FieldsSelector from 'components/FieldsSelector';
|
||||
import LogsFormatOptionsMenu from 'components/LogsFormatOptionsMenu/LogsFormatOptionsMenu';
|
||||
@@ -29,7 +28,7 @@ function LogsActionsContainer({
|
||||
}): JSX.Element {
|
||||
const { options, config } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,20 +1,11 @@
|
||||
import { createElement, ReactNode } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import type { NotificationInstance } from 'antd/es/notification/interface';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { useQueries } from 'react-query';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useGetQueryKeySuggestions } from 'hooks/querySuggestions/useGetQueryKeySuggestions';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
|
||||
import {
|
||||
FormattingOptions,
|
||||
PreferenceContextValue,
|
||||
PreferenceSlice,
|
||||
} from 'providers/preferences/types';
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { FontSize } from '../types';
|
||||
import useOptionsMenu from '../useOptionsMenu';
|
||||
|
||||
// Mock all dependencies
|
||||
@@ -22,118 +13,104 @@ jest.mock('hooks/useNotifications');
|
||||
jest.mock('providers/preferences/context/PreferenceContextProvider');
|
||||
jest.mock('hooks/useUrlQueryData');
|
||||
jest.mock('hooks/querySuggestions/useGetQueryKeySuggestions');
|
||||
|
||||
const mockUseNotifications = jest.mocked(useNotifications);
|
||||
const mockUsePreferenceContext = jest.mocked(usePreferenceContext);
|
||||
const mockUseUrlQueryData = jest.mocked(useUrlQueryData);
|
||||
const mockUseGetQueryKeySuggestions = jest.mocked(useGetQueryKeySuggestions);
|
||||
|
||||
type KeySuggestionsResult = ReturnType<typeof useGetQueryKeySuggestions>;
|
||||
|
||||
// The hook reads only `data.data.data.keys` and `isFetching`.
|
||||
const keySuggestions = (
|
||||
attributeKeys: Record<string, string>[],
|
||||
): KeySuggestionsResult =>
|
||||
({
|
||||
data: { data: { data: { complete: true, keys: { attributeKeys } } } },
|
||||
isFetching: false,
|
||||
}) as unknown as KeySuggestionsResult;
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }): JSX.Element =>
|
||||
createElement(QueryClientProvider, { client: new QueryClient() }, children);
|
||||
|
||||
const toIds = (columns: TelemetryFieldKey[]): string[] =>
|
||||
columns.map((column) => `${column.fieldContext}:${column.name}`);
|
||||
jest.mock('react-query', () => ({
|
||||
...jest.requireActual('react-query'),
|
||||
useQueries: jest.fn(),
|
||||
}));
|
||||
|
||||
describe('useOptionsMenu', () => {
|
||||
const mockNotifications = {
|
||||
error: jest.fn() as jest.MockedFunction<NotificationInstance['error']>,
|
||||
success: jest.fn() as jest.MockedFunction<NotificationInstance['success']>,
|
||||
} as Partial<NotificationInstance> as NotificationInstance;
|
||||
const mockUpdateColumns = jest.fn() as jest.MockedFunction<
|
||||
PreferenceSlice['updateColumns']
|
||||
>;
|
||||
const mockUpdateFormatting = jest.fn() as jest.MockedFunction<
|
||||
PreferenceSlice['updateFormatting']
|
||||
>;
|
||||
const mockRedirectWithQuery = jest.fn() as jest.MockedFunction<
|
||||
(newQueryData: unknown) => void
|
||||
>;
|
||||
|
||||
const slice = (
|
||||
columns: TelemetryFieldKey[],
|
||||
formatting: FormattingOptions,
|
||||
): PreferenceSlice => ({
|
||||
preferences: { columns, formatting },
|
||||
loading: false,
|
||||
error: null,
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
});
|
||||
|
||||
const rawFormatting: FormattingOptions = {
|
||||
format: 'raw',
|
||||
maxLines: 1,
|
||||
fontSize: FontSize.SMALL,
|
||||
};
|
||||
const mockNotifications = { error: jest.fn(), success: jest.fn() };
|
||||
const mockUpdateColumns = jest.fn();
|
||||
const mockUpdateFormatting = jest.fn();
|
||||
const mockRedirectWithQuery = jest.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
mockUseNotifications.mockReturnValue({
|
||||
(useNotifications as jest.Mock).mockReturnValue({
|
||||
notifications: mockNotifications,
|
||||
});
|
||||
|
||||
mockUsePreferenceContext.mockReturnValue({
|
||||
[SavedviewtypesSourceDTO.traces]: slice([], rawFormatting),
|
||||
[SavedviewtypesSourceDTO.logs]: slice([], rawFormatting),
|
||||
} satisfies PreferenceContextValue);
|
||||
(usePreferenceContext as jest.Mock).mockReturnValue({
|
||||
traces: {
|
||||
preferences: {
|
||||
columns: [],
|
||||
formatting: {
|
||||
format: 'raw',
|
||||
maxLines: 1,
|
||||
fontSize: 'small',
|
||||
},
|
||||
},
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
logs: {
|
||||
preferences: {
|
||||
columns: [],
|
||||
formatting: {
|
||||
format: 'raw',
|
||||
maxLines: 1,
|
||||
fontSize: 'small',
|
||||
},
|
||||
},
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
});
|
||||
|
||||
mockUseUrlQueryData.mockReturnValue({
|
||||
(useUrlQueryData as jest.Mock).mockReturnValue({
|
||||
query: null,
|
||||
queryData: undefined,
|
||||
redirectWithQuery: mockRedirectWithQuery,
|
||||
});
|
||||
|
||||
(useQueries as jest.Mock).mockReturnValue([]);
|
||||
});
|
||||
|
||||
it('does not show isRoot or isEntryPoint in column options when sourcePage is traces', () => {
|
||||
it('does not show isRoot or isEntryPoint in column options when dataSource is TRACES', () => {
|
||||
// Mock the query key suggestions to return data including isRoot and isEntryPoint
|
||||
mockUseGetQueryKeySuggestions.mockReturnValue(
|
||||
keySuggestions([
|
||||
{
|
||||
name: 'isRoot',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'bool',
|
||||
fieldContext: '',
|
||||
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
|
||||
data: {
|
||||
data: {
|
||||
data: {
|
||||
keys: {
|
||||
attributeKeys: [
|
||||
{
|
||||
name: 'isRoot',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'bool',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'isEntryPoint',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'bool',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'duration',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'float64',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'serviceName',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'isEntryPoint',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'bool',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'duration',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'float64',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'serviceName',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
]),
|
||||
);
|
||||
},
|
||||
isFetching: false,
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.TRACES,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
// Get the column options from the config
|
||||
@@ -150,38 +127,98 @@ describe('useOptionsMenu', () => {
|
||||
expect(optionNames).toContain('serviceName');
|
||||
});
|
||||
|
||||
it('shows body in column options when sourcePage is logs', () => {
|
||||
it('does not show body in column options when dataSource is METRICS', () => {
|
||||
// Mock the query key suggestions to return data including body
|
||||
mockUseGetQueryKeySuggestions.mockReturnValue(
|
||||
keySuggestions([
|
||||
{
|
||||
name: 'body',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
|
||||
data: {
|
||||
data: {
|
||||
data: {
|
||||
keys: {
|
||||
attributeKeys: [
|
||||
{
|
||||
name: 'body',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'status',
|
||||
signal: 'metrics',
|
||||
fieldDataType: 'int64',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'value',
|
||||
signal: 'metrics',
|
||||
fieldDataType: 'float64',
|
||||
fieldContext: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'level',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'timestamp',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'int64',
|
||||
fieldContext: '',
|
||||
},
|
||||
]),
|
||||
},
|
||||
isFetching: false,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.METRICS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
// Get the column options from the config
|
||||
const columnOptions = result.current.config.addColumn?.options ?? [];
|
||||
const optionNames = columnOptions.map((option) => option.label);
|
||||
|
||||
// body should NOT be in the options
|
||||
expect(optionNames).not.toContain('body');
|
||||
|
||||
// Other attributes should be present
|
||||
expect(optionNames).toContain('status');
|
||||
expect(optionNames).toContain('value');
|
||||
});
|
||||
|
||||
it('does not show body in column options when dataSource is LOGS', () => {
|
||||
// Mock the query key suggestions to return data including body
|
||||
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
|
||||
data: {
|
||||
data: {
|
||||
data: {
|
||||
keys: {
|
||||
attributeKeys: [
|
||||
{
|
||||
name: 'body',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'level',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'timestamp',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'int64',
|
||||
fieldContext: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
isFetching: false,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
// Get the column options from the config
|
||||
@@ -197,15 +234,15 @@ describe('useOptionsMenu', () => {
|
||||
});
|
||||
|
||||
describe('reorderSelectColumns / handleRemoveSelectedColumn — composite ID lookup', () => {
|
||||
const baseFormatting: FormattingOptions = {
|
||||
const baseFormatting = {
|
||||
format: 'table',
|
||||
maxLines: 1,
|
||||
fontSize: FontSize.SMALL,
|
||||
fontSize: 'small',
|
||||
};
|
||||
|
||||
// Two entries share the same `name` but differ in `fieldContext` — the
|
||||
// exact case composite IDs are meant to disambiguate.
|
||||
const seedColumns: TelemetryFieldKey[] = [
|
||||
const seedColumns = [
|
||||
{
|
||||
name: 'body',
|
||||
fieldContext: 'log',
|
||||
@@ -227,26 +264,36 @@ describe('useOptionsMenu', () => {
|
||||
{
|
||||
name: 'timestamp',
|
||||
fieldContext: 'log',
|
||||
fieldDataType: '',
|
||||
signal: 'logs',
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mockUseGetQueryKeySuggestions.mockReturnValue(keySuggestions([]));
|
||||
mockUsePreferenceContext.mockReturnValue({
|
||||
[SavedviewtypesSourceDTO.traces]: slice([], baseFormatting),
|
||||
[SavedviewtypesSourceDTO.logs]: slice(seedColumns, baseFormatting),
|
||||
} satisfies PreferenceContextValue);
|
||||
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
|
||||
data: { data: { data: { keys: {} } } },
|
||||
isFetching: false,
|
||||
});
|
||||
(usePreferenceContext as jest.Mock).mockReturnValue({
|
||||
traces: {
|
||||
preferences: { columns: [], formatting: baseFormatting },
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
logs: {
|
||||
preferences: { columns: seedColumns, formatting: baseFormatting },
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('reorders by composite IDs — preserves both same-name variants distinctly', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
// New order: [attribute:service.name, log:body, resource:service.name, log:timestamp]
|
||||
@@ -259,7 +306,12 @@ describe('useOptionsMenu', () => {
|
||||
|
||||
expect(mockUpdateColumns).toHaveBeenCalledTimes(1);
|
||||
const reordered = mockUpdateColumns.mock.calls[0][0];
|
||||
expect(toIds(reordered)).toStrictEqual([
|
||||
expect(
|
||||
reordered.map(
|
||||
(c: { name: string; fieldContext: string }) =>
|
||||
`${c.fieldContext}:${c.name}`,
|
||||
),
|
||||
).toStrictEqual([
|
||||
'attribute:service.name',
|
||||
'log:body',
|
||||
'resource:service.name',
|
||||
@@ -268,13 +320,11 @@ describe('useOptionsMenu', () => {
|
||||
});
|
||||
|
||||
it('reorder ignores ids that are not columns (e.g. state-indicator) and skips unknown ids', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
result.current.config.addColumn?.onReorder([
|
||||
@@ -288,7 +338,12 @@ describe('useOptionsMenu', () => {
|
||||
|
||||
const reordered = mockUpdateColumns.mock.calls[0][0];
|
||||
// state-indicator + unknown.composite filtered; rest preserved in given order.
|
||||
expect(toIds(reordered)).toStrictEqual([
|
||||
expect(
|
||||
reordered.map(
|
||||
(c: { name: string; fieldContext: string }) =>
|
||||
`${c.fieldContext}:${c.name}`,
|
||||
),
|
||||
).toStrictEqual([
|
||||
'log:timestamp',
|
||||
'log:body',
|
||||
'resource:service.name',
|
||||
@@ -297,13 +352,11 @@ describe('useOptionsMenu', () => {
|
||||
});
|
||||
|
||||
it('removes only the variant whose composite ID matches', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
// Removing 'resource:service.name' should drop ONLY the resource variant.
|
||||
@@ -311,21 +364,20 @@ describe('useOptionsMenu', () => {
|
||||
|
||||
expect(mockUpdateColumns).toHaveBeenCalledTimes(1);
|
||||
const remaining = mockUpdateColumns.mock.calls[0][0];
|
||||
expect(toIds(remaining)).toStrictEqual([
|
||||
'log:body',
|
||||
'attribute:service.name',
|
||||
'log:timestamp',
|
||||
]);
|
||||
expect(
|
||||
remaining.map(
|
||||
(c: { name: string; fieldContext: string }) =>
|
||||
`${c.fieldContext}:${c.name}`,
|
||||
),
|
||||
).toStrictEqual(['log:body', 'attribute:service.name', 'log:timestamp']);
|
||||
});
|
||||
|
||||
it('removing by a non-matching composite ID is a no-op (filter returns the full list)', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
result.current.config.addColumn?.onRemove('unknown.composite');
|
||||
@@ -338,34 +390,35 @@ describe('useOptionsMenu', () => {
|
||||
|
||||
describe('fieldsSelector.value drops legacy columns without a name', () => {
|
||||
it('excludes entries missing name while keeping valid columns', () => {
|
||||
mockUseGetQueryKeySuggestions.mockReturnValue(keySuggestions([]));
|
||||
mockUsePreferenceContext.mockReturnValue({
|
||||
[SavedviewtypesSourceDTO.traces]: slice(
|
||||
[
|
||||
{ name: 'body', fieldContext: 'log' },
|
||||
// A legacy stored column: `key` only, no `name`.
|
||||
{
|
||||
key: 'legacy-key-no-name',
|
||||
fieldContext: 'log',
|
||||
} as unknown as TelemetryFieldKey,
|
||||
{ name: 'timestamp', fieldContext: 'log' },
|
||||
],
|
||||
{
|
||||
format: 'table',
|
||||
maxLines: 1,
|
||||
fontSize: FontSize.SMALL,
|
||||
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
|
||||
data: { data: { data: { keys: {} } } },
|
||||
isFetching: false,
|
||||
});
|
||||
(usePreferenceContext as jest.Mock).mockReturnValue({
|
||||
traces: {
|
||||
preferences: {
|
||||
columns: [
|
||||
{ name: 'body', fieldContext: 'log' },
|
||||
{ key: 'legacy-key-no-name', fieldContext: 'log' },
|
||||
{ name: 'timestamp', fieldContext: 'log' },
|
||||
],
|
||||
formatting: { format: 'table', maxLines: 1, fontSize: 'small' },
|
||||
},
|
||||
),
|
||||
[SavedviewtypesSourceDTO.logs]: slice([], {}),
|
||||
} satisfies PreferenceContextValue);
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
logs: {
|
||||
preferences: { columns: [], formatting: {} },
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.TRACES,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
const fields = result.current.config.fieldsSelector?.value ?? [];
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { PREFERENCE_SOURCE_PAGES } from 'providers/preferences/constants';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { FontSize, OptionsQuery } from './types';
|
||||
@@ -15,14 +13,6 @@ export const defaultOptionsQuery: OptionsQuery = {
|
||||
fontSize: FontSize.SMALL,
|
||||
};
|
||||
|
||||
export const SOURCE_PAGE_SIGNAL: Record<
|
||||
(typeof PREFERENCE_SOURCE_PAGES)[number],
|
||||
DataSource
|
||||
> = {
|
||||
[SavedviewtypesSourceDTO.logs]: DataSource.LOGS,
|
||||
[SavedviewtypesSourceDTO.traces]: DataSource.TRACES,
|
||||
};
|
||||
|
||||
export const EXCLUDED_COLUMNS: Record<DataSource, string[]> = {
|
||||
[DataSource.TRACES]: ['body', 'isRoot', 'isEntryPoint'],
|
||||
[DataSource.METRICS]: ['body'],
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useQueries } from 'react-query';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { getKeySuggestions } from 'api/querySuggestions/getKeySuggestions';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { AxiosResponse } from 'axios';
|
||||
@@ -12,7 +11,6 @@ import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import { has } from 'lodash-es';
|
||||
import { AllTraceFilterKeyValue } from 'constants/traceFilterKeys';
|
||||
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
|
||||
import { PreferenceSourcePage } from 'providers/preferences/types';
|
||||
import {
|
||||
QueryKeyRequestProps,
|
||||
QueryKeySuggestionsResponseProps,
|
||||
@@ -22,13 +20,13 @@ import {
|
||||
FieldDataType,
|
||||
SignalType,
|
||||
} from 'types/api/v5/queryRange';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
defaultLogsSelectedColumns,
|
||||
defaultOptionsQuery,
|
||||
defaultTraceSelectedColumns,
|
||||
EXCLUDED_COLUMNS,
|
||||
SOURCE_PAGE_SIGNAL,
|
||||
URL_OPTIONS,
|
||||
} from './constants';
|
||||
import {
|
||||
@@ -42,7 +40,7 @@ import { buildCompositeKey, getOptionsFromKeys } from './utils';
|
||||
|
||||
interface UseOptionsMenuProps {
|
||||
storageKey?: string;
|
||||
sourcePage: PreferenceSourcePage;
|
||||
dataSource: DataSource;
|
||||
aggregateOperator?: string;
|
||||
initialOptions?: InitialOptions;
|
||||
}
|
||||
@@ -54,14 +52,15 @@ interface UseOptionsMenu {
|
||||
}
|
||||
|
||||
const useOptionsMenu = ({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
// aggregateOperator,
|
||||
initialOptions = {},
|
||||
}: UseOptionsMenuProps): UseOptionsMenu => {
|
||||
const signal = SOURCE_PAGE_SIGNAL[sourcePage];
|
||||
const { notifications } = useNotifications();
|
||||
const prefCtx = usePreferenceContext();
|
||||
// TODO: send null to updateColumns and updateFormatting if dataSource is not logs or traces
|
||||
const { preferences, updateColumns, updateFormatting } =
|
||||
usePreferenceContext()[sourcePage];
|
||||
const slice = dataSource === DataSource.TRACES ? prefCtx.traces : prefCtx.logs;
|
||||
const { preferences, updateColumns, updateFormatting } = slice;
|
||||
|
||||
const [searchText, setSearchText] = useState<string>('');
|
||||
const [isFocused, setIsFocused] = useState<boolean>(false);
|
||||
@@ -69,10 +68,10 @@ const useOptionsMenu = ({
|
||||
|
||||
const initialQueryParamsV5: QueryKeyRequestProps = useMemo(
|
||||
() => ({
|
||||
signal,
|
||||
signal: dataSource,
|
||||
searchText: '',
|
||||
}),
|
||||
[signal],
|
||||
[dataSource],
|
||||
);
|
||||
|
||||
const { query: optionsQuery, redirectWithQuery: redirectWithOptionsData } =
|
||||
@@ -128,7 +127,7 @@ const useOptionsMenu = ({
|
||||
?.map((column) => attributesData.find(({ name }) => name === column))
|
||||
.filter((e) => !!e) || []) as TelemetryFieldKey[];
|
||||
|
||||
if (sourcePage === SavedviewtypesSourceDTO.traces) {
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
initialSelected = initialSelected
|
||||
?.map((col) => {
|
||||
if (col && Object.keys(AllTraceFilterKeyValue).includes(col?.name)) {
|
||||
@@ -158,7 +157,7 @@ const useOptionsMenu = ({
|
||||
isFetchedInitialAttributes,
|
||||
initialOptions?.selectColumns,
|
||||
initialAttributesResult,
|
||||
sourcePage,
|
||||
dataSource,
|
||||
]);
|
||||
|
||||
const {
|
||||
@@ -196,7 +195,7 @@ const useOptionsMenu = ({
|
||||
fieldDataType: e.fieldDataType,
|
||||
}));
|
||||
}
|
||||
if (sourcePage === SavedviewtypesSourceDTO.traces) {
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
return defaultTraceSelectedColumns.map((e) => ({
|
||||
...e,
|
||||
name: e.name,
|
||||
@@ -204,16 +203,16 @@ const useOptionsMenu = ({
|
||||
}
|
||||
|
||||
return [];
|
||||
}, [sourcePage, searchedAttributesDataV5?.data.data.keys]);
|
||||
}, [dataSource, searchedAttributesDataV5?.data.data.keys]);
|
||||
|
||||
const initialOptionsQuery: OptionsQuery = useMemo(() => {
|
||||
let defaultColumns: TelemetryFieldKey[] = defaultOptionsQuery.selectColumns;
|
||||
if (sourcePage === SavedviewtypesSourceDTO.traces) {
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
defaultColumns = defaultTraceSelectedColumns.map((e) => ({
|
||||
...e,
|
||||
name: e.name,
|
||||
}));
|
||||
} else if (sourcePage === SavedviewtypesSourceDTO.logs) {
|
||||
} else if (dataSource === DataSource.LOGS) {
|
||||
// eslint-disable-next-line sonarjs/no-identical-functions
|
||||
defaultColumns = defaultLogsSelectedColumns.map((e) => ({
|
||||
...e,
|
||||
@@ -233,7 +232,7 @@ const useOptionsMenu = ({
|
||||
...initialOptions,
|
||||
selectColumns: finalSelectColumns,
|
||||
};
|
||||
}, [sourcePage, initialOptions, initialSelectedColumns]);
|
||||
}, [dataSource, initialOptions, initialSelectedColumns]);
|
||||
|
||||
const selectedColumnKeys = useMemo(
|
||||
() => preferences?.columns?.map(({ name }) => name) || [],
|
||||
@@ -242,7 +241,7 @@ const useOptionsMenu = ({
|
||||
|
||||
const optionsFromAttributeKeys = useMemo(() => {
|
||||
const filteredAttributeKeys = searchedAttributeKeys.filter((item) => {
|
||||
const exclusions = EXCLUDED_COLUMNS[signal];
|
||||
const exclusions = EXCLUDED_COLUMNS[dataSource];
|
||||
if (exclusions) {
|
||||
return !exclusions.includes(item.name);
|
||||
}
|
||||
@@ -250,7 +249,7 @@ const useOptionsMenu = ({
|
||||
});
|
||||
|
||||
return getOptionsFromKeys(filteredAttributeKeys, selectedColumnKeys);
|
||||
}, [signal, searchedAttributeKeys, selectedColumnKeys]);
|
||||
}, [dataSource, searchedAttributeKeys, selectedColumnKeys]);
|
||||
|
||||
const handleRedirectWithOptionsData = useCallback(
|
||||
(newQueryData: OptionsQuery) => {
|
||||
@@ -286,10 +285,7 @@ const useOptionsMenu = ({
|
||||
buildCompositeKey(f.name, f.fieldContext, f.fieldDataType) !== columnKey,
|
||||
);
|
||||
|
||||
if (
|
||||
!newSelectedColumns?.length &&
|
||||
sourcePage !== SavedviewtypesSourceDTO.logs
|
||||
) {
|
||||
if (!newSelectedColumns?.length && dataSource !== DataSource.LOGS) {
|
||||
notifications.error({
|
||||
message: 'There must be at least one selected column',
|
||||
});
|
||||
@@ -298,7 +294,7 @@ const useOptionsMenu = ({
|
||||
|
||||
updateColumns(newSelectedColumns || []);
|
||||
},
|
||||
[sourcePage, notifications, preferences, updateColumns],
|
||||
[dataSource, notifications, preferences, updateColumns],
|
||||
);
|
||||
|
||||
const handleFormatChange = useCallback(
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useState } from 'react';
|
||||
import { act, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
|
||||
import { act, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import SavedViewsHeader from '../SavedViewsHeader';
|
||||
import { mockSavedViewsApi } from './savedViewsApiMock';
|
||||
@@ -27,7 +28,7 @@ const errors = {
|
||||
};
|
||||
|
||||
function Harness(): JSX.Element {
|
||||
const traces = usePreferenceContext()[SavedviewtypesSourceDTO.traces];
|
||||
const { traces } = usePreferenceContext();
|
||||
const [headerKey, setHeaderKey] = useState(0);
|
||||
const columns = traces.preferences?.columns ?? [];
|
||||
|
||||
@@ -36,7 +37,7 @@ function Harness(): JSX.Element {
|
||||
<SavedViewsHeader
|
||||
key={headerKey}
|
||||
source={SavedviewtypesSourceDTO.traces}
|
||||
onOpenViews={jest.fn() as jest.MockedFunction<() => void>}
|
||||
onOpenViews={jest.fn()}
|
||||
/>
|
||||
<span data-testid="columns">
|
||||
{columns.map((column) => column.name).join(',')}
|
||||
@@ -83,14 +84,13 @@ describe('SavedViewsHeader columns', () => {
|
||||
});
|
||||
|
||||
it('keeps edited columns when the view is fetched again', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockSavedViewsApi([errors]);
|
||||
await openView();
|
||||
|
||||
await user.click(screen.getByTestId('add-column'));
|
||||
await userEvent.click(screen.getByTestId('add-column'));
|
||||
await waitFor(() => expect(isDirty()).toBe(true));
|
||||
|
||||
await user.click(screen.getByTestId('remount-header'));
|
||||
await userEvent.click(screen.getByTestId('remount-header'));
|
||||
await act(() => new Promise((resolve) => setTimeout(resolve, 200)));
|
||||
|
||||
expect(columnsText()).toBe('service.name,name,extra-2');
|
||||
@@ -98,37 +98,35 @@ describe('SavedViewsHeader columns', () => {
|
||||
});
|
||||
|
||||
it('discard puts the saved columns back', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockSavedViewsApi([errors]);
|
||||
await openView();
|
||||
|
||||
await user.click(screen.getByTestId('add-column'));
|
||||
await userEvent.click(screen.getByTestId('add-column'));
|
||||
await waitFor(() => expect(isDirty()).toBe(true));
|
||||
|
||||
await user.click(screen.getByTestId('saved-views-discard'));
|
||||
await userEvent.click(screen.getByTestId('saved-views-discard'));
|
||||
|
||||
await waitFor(() => expect(columnsText()).toBe('service.name,name'));
|
||||
expect(isDirty()).toBe(false);
|
||||
});
|
||||
|
||||
it('discard after an update goes back to the updated columns', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockSavedViewsApi([errors]);
|
||||
await openView();
|
||||
|
||||
await user.click(screen.getByTestId('add-column'));
|
||||
await userEvent.click(screen.getByTestId('add-column'));
|
||||
await waitFor(() => expect(isDirty()).toBe(true));
|
||||
await user.click(screen.getByTestId('saved-views-save-changes'));
|
||||
await userEvent.click(screen.getByTestId('saved-views-save-changes'));
|
||||
const update = await screen.findByTestId(
|
||||
'saved-views-save-changes-item-update',
|
||||
);
|
||||
await waitFor(() => expectRowUsable(update), MENU_CHECK_TIMEOUT);
|
||||
await user.click(update);
|
||||
await userEvent.click(update);
|
||||
await waitFor(() => expect(isDirty()).toBe(false));
|
||||
|
||||
await user.click(screen.getByTestId('add-column'));
|
||||
await userEvent.click(screen.getByTestId('add-column'));
|
||||
await waitFor(() => expect(isDirty()).toBe(true));
|
||||
await user.click(screen.getByTestId('saved-views-discard'));
|
||||
await userEvent.click(screen.getByTestId('saved-views-discard'));
|
||||
|
||||
await waitFor(() => expect(columnsText()).toBe('service.name,name,extra-2'));
|
||||
expect(isDirty()).toBe(false);
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import { Copy, Link, PenLine, Trash2 } from '@signozhq/icons';
|
||||
import { SavedviewtypesSchemaVersionDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
SavedviewtypesSchemaVersionDTO,
|
||||
SavedviewtypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
buildSavedViewDeletePermission,
|
||||
buildSavedViewUpdatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { SavedViewRowActionConfig, SaveViewModalMode } from './types';
|
||||
|
||||
export const SAVED_VIEW_SCHEMA_VERSION = SavedviewtypesSchemaVersionDTO.v2;
|
||||
|
||||
// Only the logs and traces explorers have columns and formatting to save.
|
||||
export const SAVED_VIEW_OPTIONS_DATA_SOURCE: Partial<
|
||||
Record<SavedviewtypesSourceDTO, DataSource>
|
||||
> = {
|
||||
[SavedviewtypesSourceDTO.logs]: DataSource.LOGS,
|
||||
[SavedviewtypesSourceDTO.traces]: DataSource.TRACES,
|
||||
};
|
||||
|
||||
// What selecting a view writes to the url, so clearing it removes exactly these.
|
||||
export const SAVED_VIEW_URL_PARAMS = [
|
||||
QueryParams.viewKey,
|
||||
|
||||
@@ -8,9 +8,10 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useGetSavedViewParams } from 'hooks/saveViews/useGetSavedViewParams';
|
||||
import { buildSavedViewReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { isPreferenceSourcePage } from 'providers/preferences/utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { toAPIError } from 'utils/errorUtils';
|
||||
|
||||
import { SAVED_VIEW_OPTIONS_DATA_SOURCE } from '../constants';
|
||||
import { UseActiveSavedViewResult } from '../types';
|
||||
import { hasUnsavedViewChanges } from '../utils/hasUnsavedViewChanges';
|
||||
|
||||
@@ -20,9 +21,9 @@ export function useActiveSavedView(
|
||||
const { viewKey } = useGetSavedViewParams();
|
||||
const { stagedQuery, panelType } = useQueryBuilder();
|
||||
|
||||
const hasOptions = isPreferenceSourcePage(source);
|
||||
const optionsDataSource = SAVED_VIEW_OPTIONS_DATA_SOURCE[source];
|
||||
const { options } = useOptionsMenu({
|
||||
sourcePage: hasOptions ? source : SavedviewtypesSourceDTO.logs,
|
||||
dataSource: optionsDataSource ?? DataSource.LOGS,
|
||||
});
|
||||
|
||||
const { isLoading: isCheckingRead, deniedPermissions } = useAuthZ(
|
||||
@@ -62,7 +63,7 @@ export function useActiveSavedView(
|
||||
view,
|
||||
stagedQuery,
|
||||
panelType: panelType ?? PANEL_TYPES.LIST,
|
||||
options: hasOptions ? options : undefined,
|
||||
options: optionsDataSource ? options : undefined,
|
||||
});
|
||||
}, [
|
||||
view,
|
||||
@@ -70,7 +71,7 @@ export function useActiveSavedView(
|
||||
isStagedQueryCurrent,
|
||||
stagedQuery,
|
||||
panelType,
|
||||
hasOptions,
|
||||
optionsDataSource,
|
||||
options,
|
||||
]);
|
||||
|
||||
|
||||
@@ -20,12 +20,13 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useGetSavedViewParams } from 'hooks/saveViews/useGetSavedViewParams';
|
||||
import { useHandleExplorerTabChange } from 'hooks/useHandleExplorerTabChange';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import { usePreferenceSlice } from 'providers/preferences/context/usePreferenceSlice';
|
||||
import { isPreferenceSourcePage } from 'providers/preferences/utils';
|
||||
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { toAPIError } from 'utils/errorUtils';
|
||||
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
|
||||
|
||||
import {
|
||||
SAVED_VIEW_OPTIONS_DATA_SOURCE,
|
||||
SAVED_VIEW_SCHEMA_VERSION,
|
||||
SAVED_VIEW_TOAST_POSITION,
|
||||
SAVED_VIEW_URL_PARAMS,
|
||||
@@ -59,11 +60,15 @@ export function useSavedViewActions(
|
||||
const { viewKey } = useGetSavedViewParams();
|
||||
const logSavedViewEvent = useSavedViewLogEvent(source);
|
||||
|
||||
const hasOptions = isPreferenceSourcePage(source);
|
||||
const optionsDataSource = SAVED_VIEW_OPTIONS_DATA_SOURCE[source];
|
||||
const { options } = useOptionsMenu({
|
||||
sourcePage: hasOptions ? source : SavedviewtypesSourceDTO.logs,
|
||||
dataSource: optionsDataSource ?? DataSource.LOGS,
|
||||
});
|
||||
const preferenceSlice = usePreferenceSlice(source);
|
||||
const preferences = usePreferenceContext();
|
||||
const preferencesSlice =
|
||||
optionsDataSource === DataSource.TRACES
|
||||
? preferences.traces
|
||||
: preferences.logs;
|
||||
|
||||
const { mutateAsync: createSavedView, isLoading: isCreating } =
|
||||
useCreateSavedView();
|
||||
@@ -81,10 +86,10 @@ export function useSavedViewActions(
|
||||
query: stagedQuery ?? currentQuery,
|
||||
panelType: panelType ?? PANEL_TYPES.LIST,
|
||||
displayName,
|
||||
options: hasOptions ? options : undefined,
|
||||
options: optionsDataSource ? options : undefined,
|
||||
color,
|
||||
}),
|
||||
[stagedQuery, currentQuery, panelType, hasOptions, options],
|
||||
[stagedQuery, currentQuery, panelType, optionsDataSource, options],
|
||||
);
|
||||
|
||||
const selectView = useCallback(
|
||||
@@ -100,14 +105,14 @@ export function useSavedViewActions(
|
||||
|
||||
const revertView = useCallback(
|
||||
(view: SavedviewtypesSavedViewDTO): void => {
|
||||
if (preferenceSlice) {
|
||||
if (optionsDataSource) {
|
||||
const { columns, formatting } = getViewColumnsAndFormatting(
|
||||
view.spec,
|
||||
source,
|
||||
optionsDataSource,
|
||||
);
|
||||
preferenceSlice.updateColumns(columns);
|
||||
preferencesSlice.updateColumns(columns);
|
||||
if (formatting) {
|
||||
preferenceSlice.updateFormatting(formatting);
|
||||
preferencesSlice.updateFormatting(formatting);
|
||||
}
|
||||
}
|
||||
selectView(view);
|
||||
@@ -115,7 +120,7 @@ export function useSavedViewActions(
|
||||
[SavedViewEventKeys.ViewId]: view.id,
|
||||
});
|
||||
},
|
||||
[source, preferenceSlice, selectView, logSavedViewEvent],
|
||||
[optionsDataSource, preferencesSlice, selectView, logSavedViewEvent],
|
||||
);
|
||||
|
||||
// The query builder redirects only ever add params, so the url is rebuilt
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
SavedviewtypesSavedViewSpecDTO,
|
||||
SavedviewtypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { SavedviewtypesSavedViewSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import {
|
||||
defaultLogsSelectedColumns,
|
||||
@@ -10,6 +7,7 @@ import {
|
||||
} from 'container/OptionsMenu/constants';
|
||||
import { FontSize, LogViewMode } from 'container/OptionsMenu/types';
|
||||
import { Preferences } from 'providers/preferences/types';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
function withColumnNames(
|
||||
columns: TelemetryFieldKey[] | undefined,
|
||||
@@ -27,11 +25,11 @@ function withColumnNames(
|
||||
// defaults filled in where the view has none.
|
||||
export function getViewColumnsAndFormatting(
|
||||
spec: SavedviewtypesSavedViewSpecDTO | undefined,
|
||||
sourcePage: SavedviewtypesSourceDTO,
|
||||
dataSource: DataSource,
|
||||
): Preferences {
|
||||
const selectedFields = spec?.selectedFields as TelemetryFieldKey[] | undefined;
|
||||
|
||||
if (sourcePage === SavedviewtypesSourceDTO.logs) {
|
||||
if (dataSource === DataSource.LOGS) {
|
||||
return {
|
||||
columns: ensureLogsRequiredColumns(
|
||||
withColumnNames(selectedFields) || defaultLogsSelectedColumns,
|
||||
@@ -44,7 +42,7 @@ export function getViewColumnsAndFormatting(
|
||||
},
|
||||
};
|
||||
}
|
||||
if (sourcePage === SavedviewtypesSourceDTO.traces) {
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
return { columns: selectedFields || defaultTraceSelectedColumns };
|
||||
}
|
||||
return { columns: [] };
|
||||
|
||||
@@ -7,7 +7,6 @@ import { HasUnsavedViewChangesArgs } from '../types';
|
||||
import { getSavedViewQuery } from './getSavedViewQuery';
|
||||
import { toSavedViewPanelType } from './toSavedViewSpec';
|
||||
import { getViewColumnsAndFormatting } from './getViewColumnsAndFormatting';
|
||||
import { toSavedViewSource } from './toSavedViewSource';
|
||||
|
||||
// Legacy context names the server stores under their v5 name.
|
||||
const FIELD_CONTEXT_ALIASES: Record<string, TelemetrytypesFieldContextDTO> = {
|
||||
@@ -80,7 +79,7 @@ export function hasUnsavedViewChanges({
|
||||
const dataSource = stagedQuery.builder.queryData[0]?.dataSource;
|
||||
const { columns, formatting } = getViewColumnsAndFormatting(
|
||||
view.spec,
|
||||
toSavedViewSource(dataSource),
|
||||
dataSource,
|
||||
);
|
||||
const toNames = (fields: { name?: string; key?: string }[]): unknown[] =>
|
||||
fields.map((field) => field.name ?? field.key);
|
||||
|
||||
@@ -3,8 +3,11 @@ import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { SavedViewSourcePage } from '../types';
|
||||
|
||||
// Queries and the AI assistant name a source by DataSource (the signal), the
|
||||
// api keys views by source page.
|
||||
// Explorers and the preferences module are keyed by DataSource (the signal),
|
||||
// the api keys views by source page. Same values today, so this is the one
|
||||
// place they meet. AI observability views will come with their own source and
|
||||
// DataSource cannot tell them apart from traces, so preferences should move to
|
||||
// source page at that point and this map goes with it.
|
||||
const SAVED_VIEW_SOURCE: Record<SavedViewSourcePage, SavedviewtypesSourceDTO> =
|
||||
{
|
||||
[DataSource.LOGS]: SavedviewtypesSourceDTO.logs,
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import DownloadOptionsMenu from 'components/DownloadOptionsMenu/DownloadOptionsMenu';
|
||||
import ListViewOrderBy from 'components/OrderBy/ListViewOrderBy';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView/types';
|
||||
@@ -87,7 +86,7 @@ function ListView({
|
||||
|
||||
const { options, config } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.TRACES_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
aggregateOperator: 'count',
|
||||
initialOptions: {
|
||||
selectColumns: defaultSelectedColumns,
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
|
||||
@@ -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'],
|
||||
|
||||
@@ -73,7 +73,7 @@ function TracesExplorer(): JSX.Element {
|
||||
|
||||
const { options } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.TRACES_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
aggregateOperator: 'noop',
|
||||
initialOptions: {
|
||||
selectColumns: defaultSelectedColumns,
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { LogViewMode, FontSize } from 'container/OptionsMenu/types';
|
||||
import { LogViewMode } from 'container/OptionsMenu/types';
|
||||
import {
|
||||
defaultLogsSelectedColumns,
|
||||
defaultTraceSelectedColumns,
|
||||
} from 'container/OptionsMenu/constants';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { usePreferenceContext } from '../context/PreferenceContextProvider';
|
||||
import { PreferenceSourcePage } from '../types';
|
||||
|
||||
const ROUTE_LOGS = '/logs';
|
||||
const ROUTE_TRACES = '/traces';
|
||||
@@ -38,13 +38,14 @@ function getLocalStorageJSON<T>(key: string): T | null {
|
||||
}
|
||||
|
||||
function Consumer({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
testIdPrefix,
|
||||
}: {
|
||||
sourcePage: PreferenceSourcePage;
|
||||
dataSource: DataSource;
|
||||
testIdPrefix: string;
|
||||
}): JSX.Element {
|
||||
const slice = usePreferenceContext()[sourcePage];
|
||||
const ctx = usePreferenceContext();
|
||||
const slice = dataSource === DataSource.TRACES ? ctx.traces : ctx.logs;
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -57,7 +58,7 @@ function Consumer({
|
||||
type="button"
|
||||
onClick={(): void => {
|
||||
const newCols: TelemetryFieldKey[] =
|
||||
sourcePage === SavedviewtypesSourceDTO.traces
|
||||
dataSource === DataSource.TRACES
|
||||
? (defaultTraceSelectedColumns.slice(0, 1) as TelemetryFieldKey[])
|
||||
: (defaultLogsSelectedColumns.slice(0, 1) as TelemetryFieldKey[]);
|
||||
slice.updateColumns(newCols);
|
||||
@@ -77,10 +78,7 @@ describe('PreferencesProvider integration', () => {
|
||||
describe('Logs', () => {
|
||||
it('loads defaults when no localStorage or url provided', () => {
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.logs}
|
||||
testIdPrefix={TESTID_LOGS}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_LOGS,
|
||||
@@ -103,10 +101,7 @@ describe('PreferencesProvider integration', () => {
|
||||
});
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.logs}
|
||||
testIdPrefix={TESTID_LOGS}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_LOGS,
|
||||
@@ -121,10 +116,7 @@ describe('PreferencesProvider integration', () => {
|
||||
it('direct mode updateColumns persists to localStorage', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.logs}
|
||||
testIdPrefix={TESTID_LOGS}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_LOGS,
|
||||
@@ -150,7 +142,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
render(
|
||||
<Consumer sourcePage={SavedviewtypesSourceDTO.logs} testIdPrefix="logs" />,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix="logs" />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: initialEntry,
|
||||
@@ -183,10 +175,7 @@ describe('PreferencesProvider integration', () => {
|
||||
});
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.logs}
|
||||
testIdPrefix={TESTID_LOGS}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_LOGS,
|
||||
@@ -208,7 +197,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
function FormattingConsumer(): JSX.Element {
|
||||
const logs = usePreferenceContext()[SavedviewtypesSourceDTO.logs];
|
||||
const { logs } = usePreferenceContext();
|
||||
return (
|
||||
<button
|
||||
data-testid="logs-update-formatting"
|
||||
@@ -246,10 +235,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const initialEntry = `/logs?viewKey=${encodeURIComponent(viewKey)}`;
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.logs}
|
||||
testIdPrefix={TESTID_LOGS}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
|
||||
undefined,
|
||||
{ initialRoute: initialEntry },
|
||||
);
|
||||
@@ -268,10 +254,7 @@ describe('PreferencesProvider integration', () => {
|
||||
describe('Traces', () => {
|
||||
it('loads defaults when no localStorage or url provided', () => {
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix={TESTID_TRACES}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_TRACES,
|
||||
@@ -290,10 +273,7 @@ describe('PreferencesProvider integration', () => {
|
||||
});
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix={TESTID_TRACES}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_TRACES,
|
||||
@@ -306,10 +286,7 @@ describe('PreferencesProvider integration', () => {
|
||||
it('direct mode updateColumns persists to localStorage', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix={TESTID_TRACES}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_TRACES,
|
||||
@@ -332,10 +309,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix="traces"
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix="traces" />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: initialEntry,
|
||||
@@ -364,10 +338,7 @@ describe('PreferencesProvider integration', () => {
|
||||
});
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix={TESTID_TRACES}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
|
||||
undefined,
|
||||
{ initialRoute: ROUTE_TRACES },
|
||||
);
|
||||
@@ -384,7 +355,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
function TracesFormattingConsumer(): JSX.Element {
|
||||
const traces = usePreferenceContext()[SavedviewtypesSourceDTO.traces];
|
||||
const { traces } = usePreferenceContext();
|
||||
return (
|
||||
<button
|
||||
data-testid="traces-update-formatting"
|
||||
@@ -419,10 +390,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const initialEntry = `/traces?viewKey=${encodeURIComponent(viewKey)}`;
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix={TESTID_TRACES}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
|
||||
undefined,
|
||||
{ initialRoute: initialEntry },
|
||||
);
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { defaultLogsSelectedColumns } from 'container/OptionsMenu/constants';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { renderHook, waitFor } from 'tests/test-utils';
|
||||
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import logsLoaderConfig from '../configs/logsLoaderConfig';
|
||||
import { usePreferenceLoader } from '../loader/usePreferenceLoader';
|
||||
@@ -45,18 +42,15 @@ jest.mock('../configs/tracesLoaderConfig', () => ({
|
||||
}));
|
||||
|
||||
describe('usePreferenceLoader', () => {
|
||||
const setReSync = jest.fn() as jest.MockedFunction<
|
||||
Dispatch<SetStateAction<boolean>>
|
||||
>;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should load logs preferences based on priority order', async () => {
|
||||
const setReSync = jest.fn();
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceLoader({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
reSync: false,
|
||||
setReSync,
|
||||
}),
|
||||
@@ -77,9 +71,10 @@ describe('usePreferenceLoader', () => {
|
||||
});
|
||||
|
||||
it('should load traces preferences', async () => {
|
||||
const setReSync = jest.fn();
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceLoader({
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
reSync: false,
|
||||
setReSync,
|
||||
}),
|
||||
@@ -98,11 +93,13 @@ describe('usePreferenceLoader', () => {
|
||||
});
|
||||
|
||||
it('should call setReSync when reSync is true', async () => {
|
||||
const setReSync = jest.fn();
|
||||
|
||||
// Test that the hook calls setReSync(false) when reSync is true
|
||||
// We'll unmount quickly to avoid the infinite loop
|
||||
const { unmount } = renderHook(() =>
|
||||
usePreferenceLoader({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
reSync: true,
|
||||
setReSync,
|
||||
}),
|
||||
@@ -121,25 +118,19 @@ describe('usePreferenceLoader', () => {
|
||||
|
||||
it('should handle errors during loading', async () => {
|
||||
// Make first call succeed (initial state), second call throw in reSync effect
|
||||
const localSpy = jest.spyOn(logsLoaderConfig, 'local');
|
||||
// The loader reads stored columns by name, though `local()` types them as
|
||||
// the older key-based shape.
|
||||
const localSpy: jest.SpyInstance = jest.spyOn(logsLoaderConfig, 'local');
|
||||
localSpy.mockImplementationOnce(() => ({
|
||||
columns: [{ name: 'local-column' }] as unknown as BaseAutocompleteData[],
|
||||
formatting: {
|
||||
maxLines: 5,
|
||||
format: 'table',
|
||||
fontSize: FontSize.MEDIUM,
|
||||
version: 1,
|
||||
},
|
||||
columns: [{ name: 'local-column' }],
|
||||
formatting: { maxLines: 5, format: 'table', fontSize: 'medium', version: 1 },
|
||||
}));
|
||||
localSpy.mockImplementationOnce(() => {
|
||||
throw new Error('Loading failed');
|
||||
});
|
||||
|
||||
const setReSync = jest.fn();
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceLoader({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
reSync: true,
|
||||
setReSync,
|
||||
}),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useGetSavedView } from 'api/generated/services/saved-view';
|
||||
import {
|
||||
SavedviewtypesSavedViewDTO,
|
||||
@@ -8,21 +9,32 @@ import {
|
||||
defaultTraceSelectedColumns,
|
||||
ensureLogsRequiredColumns,
|
||||
} from 'container/OptionsMenu/constants';
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { usePreferenceLoader } from '../loader/usePreferenceLoader';
|
||||
import { usePreferenceSync } from '../sync/usePreferenceSync';
|
||||
import { PreferenceMode, Preferences } from '../types';
|
||||
import { usePreferenceUpdater } from '../updater/usePreferenceUpdater';
|
||||
import { PreferenceMode } from '../types';
|
||||
|
||||
jest.mock('api/generated/services/saved-view');
|
||||
|
||||
jest.mock('../loader/usePreferenceLoader');
|
||||
jest.mock('../updater/usePreferenceUpdater');
|
||||
const loaderPreferences = { columns: [{ name: 'from-loader' }] };
|
||||
jest.mock('../loader/usePreferenceLoader', () => ({
|
||||
usePreferenceLoader: jest.fn(() => ({
|
||||
preferences: loaderPreferences,
|
||||
loading: false,
|
||||
error: null,
|
||||
})),
|
||||
}));
|
||||
|
||||
const loaderPreferences: Preferences = { columns: [{ name: 'from-loader' }] };
|
||||
jest.mock('../updater/usePreferenceUpdater', () => ({
|
||||
usePreferenceUpdater: jest.fn(() => ({
|
||||
updateColumns: jest.fn(),
|
||||
updateFormatting: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockedUseGetSavedView = jest.mocked(useGetSavedView);
|
||||
const mockedUseGetSavedView = useGetSavedView as jest.MockedFunction<
|
||||
typeof useGetSavedView
|
||||
>;
|
||||
|
||||
function makeView(
|
||||
id: string,
|
||||
@@ -64,19 +76,6 @@ function mockViews(views: SavedviewtypesSavedViewDTO[]): void {
|
||||
describe('usePreferenceSync in saved view mode', () => {
|
||||
beforeEach(() => {
|
||||
mockedUseGetSavedView.mockReset();
|
||||
jest.mocked(usePreferenceLoader).mockReturnValue({
|
||||
preferences: loaderPreferences,
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
jest.mocked(usePreferenceUpdater).mockReturnValue({
|
||||
updateColumns: jest.fn() as jest.MockedFunction<
|
||||
ReturnType<typeof usePreferenceUpdater>['updateColumns']
|
||||
>,
|
||||
updateFormatting: jest.fn() as jest.MockedFunction<
|
||||
ReturnType<typeof usePreferenceUpdater>['updateFormatting']
|
||||
>,
|
||||
});
|
||||
});
|
||||
|
||||
it('fetches the view only in saved view mode with a view id', () => {
|
||||
@@ -85,7 +84,7 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.DIRECT,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
savedViewId: undefined,
|
||||
}),
|
||||
);
|
||||
@@ -102,7 +101,7 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.DIRECT,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
savedViewId: undefined,
|
||||
}),
|
||||
);
|
||||
@@ -121,7 +120,7 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.SAVED_VIEW,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
savedViewId: 'view-1',
|
||||
}),
|
||||
);
|
||||
@@ -148,7 +147,7 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.SAVED_VIEW,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
savedViewId: 'view-1',
|
||||
}),
|
||||
);
|
||||
@@ -175,14 +174,14 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
const withFields = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.SAVED_VIEW,
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
savedViewId: 'with-fields',
|
||||
}),
|
||||
);
|
||||
const withoutFields = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.SAVED_VIEW,
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
savedViewId: 'without-fields',
|
||||
}),
|
||||
);
|
||||
@@ -203,7 +202,7 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.SAVED_VIEW,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
savedViewId: 'missing',
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,39 +1,45 @@
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { LogViewMode, FontSize } from 'container/OptionsMenu/types';
|
||||
import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import { LogViewMode } from 'container/OptionsMenu/types';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import {
|
||||
FormattingOptions,
|
||||
PreferenceMode,
|
||||
Preferences,
|
||||
} from 'providers/preferences/types';
|
||||
import { act, renderHook } from 'tests/test-utils';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import getLogsUpdaterConfig from '../configs/logsUpdaterConfig';
|
||||
import getTracesUpdaterConfig from '../configs/tracesUpdaterConfig';
|
||||
import { usePreferenceUpdater } from '../updater/usePreferenceUpdater';
|
||||
|
||||
jest.mock('../configs/logsUpdaterConfig');
|
||||
jest.mock('../configs/tracesUpdaterConfig');
|
||||
jest.mock('hooks/useUrlQueryData');
|
||||
// Mock the config updaters
|
||||
const mockUpdateColumns = jest.fn();
|
||||
const mockUpdateFormatting = jest.fn();
|
||||
|
||||
type LogsUpdater = ReturnType<typeof getLogsUpdaterConfig>;
|
||||
type TracesUpdater = ReturnType<typeof getTracesUpdaterConfig>;
|
||||
jest.mock('../configs/logsUpdaterConfig', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn().mockImplementation(() => ({
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockLogsUpdateColumns = jest.fn() as jest.MockedFunction<
|
||||
LogsUpdater['updateColumns']
|
||||
>;
|
||||
const mockLogsUpdateFormatting = jest.fn() as jest.MockedFunction<
|
||||
LogsUpdater['updateFormatting']
|
||||
>;
|
||||
const mockTracesUpdateColumns = jest.fn() as jest.MockedFunction<
|
||||
TracesUpdater['updateColumns']
|
||||
>;
|
||||
const mockTracesUpdateFormatting = jest.fn() as jest.MockedFunction<
|
||||
TracesUpdater['updateFormatting']
|
||||
>;
|
||||
jest.mock('../configs/tracesUpdaterConfig', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn().mockImplementation(() => ({
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
})),
|
||||
}));
|
||||
|
||||
// Mock the URL query hook
|
||||
jest.mock('hooks/useUrlQueryData', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn().mockReturnValue({
|
||||
redirectWithQuery: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('usePreferenceUpdater', () => {
|
||||
const mockPreferences: Preferences = {
|
||||
@@ -45,36 +51,18 @@ describe('usePreferenceUpdater', () => {
|
||||
version: 1,
|
||||
},
|
||||
};
|
||||
const setReSync = jest.fn() as jest.MockedFunction<
|
||||
Dispatch<SetStateAction<boolean>>
|
||||
>;
|
||||
const setSavedViewPreferences = jest.fn() as jest.MockedFunction<
|
||||
Dispatch<SetStateAction<Preferences | null>>
|
||||
>;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(getLogsUpdaterConfig).mockReturnValue({
|
||||
updateColumns: mockLogsUpdateColumns,
|
||||
updateFormatting: mockLogsUpdateFormatting,
|
||||
});
|
||||
jest.mocked(getTracesUpdaterConfig).mockReturnValue({
|
||||
updateColumns: mockTracesUpdateColumns,
|
||||
updateFormatting: mockTracesUpdateFormatting,
|
||||
});
|
||||
jest.mocked(useUrlQueryData).mockReturnValue({
|
||||
query: null,
|
||||
queryData: undefined,
|
||||
redirectWithQuery: jest.fn() as jest.MockedFunction<
|
||||
(newQueryData: unknown) => void
|
||||
>,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return updateColumns and updateFormatting functions', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
@@ -87,7 +75,9 @@ describe('usePreferenceUpdater', () => {
|
||||
expect(typeof result.current.updateFormatting).toBe('function');
|
||||
});
|
||||
|
||||
it('should call the logs updater for updateColumns with the logs list key', () => {
|
||||
it('should call the logs updater for updateColumns with logs dataSource', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
const newColumns: TelemetryFieldKey[] = [
|
||||
{
|
||||
name: 'new-column',
|
||||
@@ -98,7 +88,7 @@ describe('usePreferenceUpdater', () => {
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
@@ -111,15 +101,16 @@ describe('usePreferenceUpdater', () => {
|
||||
});
|
||||
|
||||
// Should call the logs updater
|
||||
expect(mockLogsUpdateColumns).toHaveBeenCalledWith(
|
||||
expect(mockUpdateColumns).toHaveBeenCalledWith(
|
||||
newColumns,
|
||||
PreferenceMode.DIRECT,
|
||||
);
|
||||
expect(mockTracesUpdateColumns).not.toHaveBeenCalled();
|
||||
expect(setReSync).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('should call the logs updater for updateFormatting with the logs list key', () => {
|
||||
it('should call the logs updater for updateFormatting with logs dataSource', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
const newFormatting: FormattingOptions = {
|
||||
maxLines: 10,
|
||||
format: 'table' as LogViewMode,
|
||||
@@ -129,7 +120,7 @@ describe('usePreferenceUpdater', () => {
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
@@ -142,15 +133,16 @@ describe('usePreferenceUpdater', () => {
|
||||
});
|
||||
|
||||
// Should call the logs updater
|
||||
expect(mockLogsUpdateFormatting).toHaveBeenCalledWith(
|
||||
expect(mockUpdateFormatting).toHaveBeenCalledWith(
|
||||
newFormatting,
|
||||
PreferenceMode.DIRECT,
|
||||
);
|
||||
expect(mockTracesUpdateFormatting).not.toHaveBeenCalled();
|
||||
expect(setReSync).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('should call the traces updater for updateColumns with the traces list key', () => {
|
||||
it('should call the traces updater for updateColumns with traces dataSource', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
const newColumns: TelemetryFieldKey[] = [
|
||||
{
|
||||
name: 'new-trace-column',
|
||||
@@ -161,7 +153,7 @@ describe('usePreferenceUpdater', () => {
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
@@ -174,15 +166,16 @@ describe('usePreferenceUpdater', () => {
|
||||
});
|
||||
|
||||
// Should call the traces updater
|
||||
expect(mockTracesUpdateColumns).toHaveBeenCalledWith(
|
||||
expect(mockUpdateColumns).toHaveBeenCalledWith(
|
||||
newColumns,
|
||||
PreferenceMode.DIRECT,
|
||||
);
|
||||
expect(mockLogsUpdateColumns).not.toHaveBeenCalled();
|
||||
expect(setReSync).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('should call the traces updater for updateFormatting with the traces list key', () => {
|
||||
it('should call the traces updater for updateFormatting with traces dataSource', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
const newFormatting: FormattingOptions = {
|
||||
maxLines: 10,
|
||||
format: 'table' as LogViewMode,
|
||||
@@ -192,7 +185,7 @@ describe('usePreferenceUpdater', () => {
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
@@ -205,18 +198,20 @@ describe('usePreferenceUpdater', () => {
|
||||
});
|
||||
|
||||
// Should call the traces updater
|
||||
expect(mockTracesUpdateFormatting).toHaveBeenCalledWith(
|
||||
expect(mockUpdateFormatting).toHaveBeenCalledWith(
|
||||
newFormatting,
|
||||
PreferenceMode.DIRECT,
|
||||
);
|
||||
expect(mockLogsUpdateFormatting).not.toHaveBeenCalled();
|
||||
expect(setReSync).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('should increment reSync counter when updates are called', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { isPreferenceSourcePage } from '../utils';
|
||||
|
||||
describe('isPreferenceSourcePage', () => {
|
||||
it.each([SavedviewtypesSourceDTO.logs, SavedviewtypesSourceDTO.traces])(
|
||||
'is true for %s',
|
||||
(source) => {
|
||||
expect(isPreferenceSourcePage(source)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
SavedviewtypesSourceDTO.metrics,
|
||||
SavedviewtypesSourceDTO.meter,
|
||||
SavedviewtypesSourceDTO.ai_observability,
|
||||
])('is false for %s', (source) => {
|
||||
expect(isPreferenceSourcePage(source)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
// Only the logs and traces explorers keep column and formatting preferences.
|
||||
export const PREFERENCE_SOURCE_PAGES = [
|
||||
SavedviewtypesSourceDTO.logs,
|
||||
SavedviewtypesSourceDTO.traces,
|
||||
] as const;
|
||||
@@ -5,12 +5,12 @@ import React, {
|
||||
useContext,
|
||||
useMemo,
|
||||
} from 'react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import {
|
||||
PreferenceContextValue,
|
||||
PreferenceMode,
|
||||
} from 'providers/preferences/types';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { usePreferenceSync } from '../sync/usePreferenceSync';
|
||||
|
||||
@@ -38,19 +38,19 @@ export function PreferenceContextProvider({
|
||||
const logsSlice = usePreferenceSync({
|
||||
mode: savedViewId ? PreferenceMode.SAVED_VIEW : PreferenceMode.DIRECT,
|
||||
savedViewId: savedViewId || undefined,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
});
|
||||
|
||||
const tracesSlice = usePreferenceSync({
|
||||
mode: savedViewId ? PreferenceMode.SAVED_VIEW : PreferenceMode.DIRECT,
|
||||
savedViewId: savedViewId || undefined,
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
});
|
||||
|
||||
const value = useMemo<PreferenceContextValue>(
|
||||
() => ({
|
||||
[SavedviewtypesSourceDTO.logs]: logsSlice,
|
||||
[SavedviewtypesSourceDTO.traces]: tracesSlice,
|
||||
logs: logsSlice,
|
||||
traces: tracesSlice,
|
||||
}),
|
||||
[logsSlice, tracesSlice],
|
||||
);
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { PreferenceSlice } from '../types';
|
||||
import { isPreferenceSourcePage } from '../utils';
|
||||
import { usePreferenceContext } from './PreferenceContextProvider';
|
||||
|
||||
export function usePreferenceSlice(
|
||||
sourcePage: SavedviewtypesSourceDTO,
|
||||
): PreferenceSlice | undefined {
|
||||
const context = usePreferenceContext();
|
||||
return isPreferenceSourcePage(sourcePage) ? context[sourcePage] : undefined;
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { ensureLogsRequiredColumns } from 'container/OptionsMenu/constants';
|
||||
import { has } from 'lodash-es';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import logsLoaderConfig from '../configs/logsLoaderConfig';
|
||||
import tracesLoaderConfig from '../configs/tracesLoaderConfig';
|
||||
import { FormattingOptions, Preferences, PreferenceSourcePage } from '../types';
|
||||
import { FormattingOptions, Preferences } from '../types';
|
||||
|
||||
const migrateColumns = (columns: any): any =>
|
||||
columns.map((column: any) => {
|
||||
@@ -62,21 +62,15 @@ function logsPreferencesLoader(): {
|
||||
function tracesPreferencesLoader(): {
|
||||
columns: TelemetryFieldKey[];
|
||||
} {
|
||||
const { columns } = preferencesLoader<Preferences>(tracesLoaderConfig);
|
||||
return { columns };
|
||||
return preferencesLoader(tracesLoaderConfig);
|
||||
}
|
||||
|
||||
const PREFERENCE_LOADERS: Record<PreferenceSourcePage, () => Preferences> = {
|
||||
[SavedviewtypesSourceDTO.logs]: logsPreferencesLoader,
|
||||
[SavedviewtypesSourceDTO.traces]: tracesPreferencesLoader,
|
||||
};
|
||||
|
||||
export function usePreferenceLoader({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
reSync,
|
||||
setReSync,
|
||||
}: {
|
||||
sourcePage: PreferenceSourcePage;
|
||||
dataSource: DataSource;
|
||||
reSync: boolean;
|
||||
setReSync: (value: boolean) => void;
|
||||
}): {
|
||||
@@ -84,10 +78,17 @@ export function usePreferenceLoader({
|
||||
loading: boolean;
|
||||
error: Error | null;
|
||||
} {
|
||||
const loadSlicePreferences = PREFERENCE_LOADERS[sourcePage];
|
||||
const [preferences, setPreferences] = useState<Preferences | null>(
|
||||
loadSlicePreferences,
|
||||
);
|
||||
const [preferences, setPreferences] = useState<Preferences | null>(() => {
|
||||
if (dataSource === DataSource.LOGS) {
|
||||
const { columns, formatting } = logsPreferencesLoader();
|
||||
return { columns, formatting };
|
||||
}
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
const { columns } = tracesPreferencesLoader();
|
||||
return { columns };
|
||||
}
|
||||
return null;
|
||||
});
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
useEffect((): void => {
|
||||
@@ -95,7 +96,15 @@ export function usePreferenceLoader({
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
setPreferences(loadSlicePreferences());
|
||||
if (dataSource === DataSource.LOGS) {
|
||||
const { columns, formatting } = logsPreferencesLoader();
|
||||
setPreferences({ columns, formatting });
|
||||
}
|
||||
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
const { columns } = tracesPreferencesLoader();
|
||||
setPreferences({ columns });
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e as Error);
|
||||
} finally {
|
||||
@@ -110,7 +119,7 @@ export function usePreferenceLoader({
|
||||
if (reSync) {
|
||||
loadPreferences();
|
||||
}
|
||||
}, [loadSlicePreferences, reSync, setReSync]);
|
||||
}, [dataSource, reSync, setReSync]);
|
||||
|
||||
return { preferences, loading: false, error };
|
||||
}
|
||||
|
||||
@@ -3,23 +3,19 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { useGetSavedView } from 'api/generated/services/saved-view';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { getViewColumnsAndFormatting } from 'container/SavedViews/utils/getViewColumnsAndFormatting';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { usePreferenceLoader } from '../loader/usePreferenceLoader';
|
||||
import {
|
||||
FormattingOptions,
|
||||
PreferenceMode,
|
||||
Preferences,
|
||||
PreferenceSourcePage,
|
||||
} from '../types';
|
||||
import { FormattingOptions, PreferenceMode, Preferences } from '../types';
|
||||
import { usePreferenceUpdater } from '../updater/usePreferenceUpdater';
|
||||
|
||||
export function usePreferenceSync({
|
||||
mode,
|
||||
sourcePage,
|
||||
dataSource,
|
||||
savedViewId,
|
||||
}: {
|
||||
mode: PreferenceMode;
|
||||
sourcePage: PreferenceSourcePage;
|
||||
dataSource: DataSource;
|
||||
savedViewId: string | undefined;
|
||||
}): {
|
||||
preferences: Preferences | null;
|
||||
@@ -45,25 +41,25 @@ export function usePreferenceSync({
|
||||
if (view && view.id === savedViewId) {
|
||||
if (seededViewId.current !== savedViewId) {
|
||||
seededViewId.current = savedViewId;
|
||||
setSavedViewPreferences(getViewColumnsAndFormatting(view.spec, sourcePage));
|
||||
setSavedViewPreferences(getViewColumnsAndFormatting(view.spec, dataSource));
|
||||
}
|
||||
return;
|
||||
}
|
||||
seededViewId.current = undefined;
|
||||
setSavedViewPreferences(getViewColumnsAndFormatting(undefined, sourcePage));
|
||||
}, [viewData, sourcePage, savedViewId]);
|
||||
setSavedViewPreferences(getViewColumnsAndFormatting(undefined, dataSource));
|
||||
}, [viewData, dataSource, savedViewId]);
|
||||
|
||||
// We are using a reSync state because we have URL updates as well as local storage updates
|
||||
// and we want to make sure we are always using the latest preferences
|
||||
const [reSync, setReSync] = useState(false);
|
||||
const { preferences, loading, error } = usePreferenceLoader({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
reSync,
|
||||
setReSync,
|
||||
});
|
||||
|
||||
const { updateColumns, updateFormatting } = usePreferenceUpdater({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
mode,
|
||||
preferences,
|
||||
setReSync,
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { LogViewMode, FontSize } from 'container/OptionsMenu/types';
|
||||
|
||||
import { PREFERENCE_SOURCE_PAGES } from '../constants';
|
||||
import { LogViewMode } from 'container/OptionsMenu/types';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
|
||||
export enum PreferenceMode {
|
||||
SAVED_VIEW = 'savedView',
|
||||
DIRECT = 'direct',
|
||||
}
|
||||
|
||||
export type PreferenceSourcePage = (typeof PREFERENCE_SOURCE_PAGES)[number];
|
||||
|
||||
export interface PreferenceSlice {
|
||||
preferences: Preferences | null;
|
||||
loading: boolean;
|
||||
@@ -18,10 +15,10 @@ export interface PreferenceSlice {
|
||||
updateFormatting: (newFormatting: FormattingOptions) => void;
|
||||
}
|
||||
|
||||
export type PreferenceContextValue = Record<
|
||||
PreferenceSourcePage,
|
||||
PreferenceSlice
|
||||
>;
|
||||
export interface PreferenceContextValue {
|
||||
logs: PreferenceSlice;
|
||||
traces: PreferenceSlice;
|
||||
}
|
||||
|
||||
export interface FormattingOptions {
|
||||
maxLines?: number;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import {
|
||||
defaultOptionsQuery,
|
||||
@@ -7,41 +6,48 @@ import {
|
||||
} from 'container/OptionsMenu/constants';
|
||||
import { OptionsQuery } from 'container/OptionsMenu/types';
|
||||
import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import getLogsUpdaterConfig from '../configs/logsUpdaterConfig';
|
||||
import getTracesUpdaterConfig from '../configs/tracesUpdaterConfig';
|
||||
import { FormattingOptions, Preferences, PreferenceSourcePage } from '../types';
|
||||
import { FormattingOptions, Preferences } from '../types';
|
||||
|
||||
const metricsUpdater = {
|
||||
updateColumns: (): void => {}, // no-op for metrics
|
||||
updateFormatting: (): void => {}, // no-op for metrics
|
||||
};
|
||||
|
||||
const getUpdaterConfig = (
|
||||
preferences: Preferences | null,
|
||||
redirectWithOptionsData: (options: OptionsQuery) => void,
|
||||
setSavedViewPreferences: Dispatch<SetStateAction<Preferences | null>>,
|
||||
): Record<
|
||||
PreferenceSourcePage,
|
||||
DataSource,
|
||||
{
|
||||
updateColumns: (newColumns: TelemetryFieldKey[], mode: string) => void;
|
||||
updateFormatting: (newFormatting: FormattingOptions, mode: string) => void;
|
||||
}
|
||||
> => ({
|
||||
[SavedviewtypesSourceDTO.logs]: getLogsUpdaterConfig(
|
||||
[DataSource.LOGS]: getLogsUpdaterConfig(
|
||||
preferences,
|
||||
redirectWithOptionsData,
|
||||
setSavedViewPreferences,
|
||||
),
|
||||
[SavedviewtypesSourceDTO.traces]: getTracesUpdaterConfig(
|
||||
[DataSource.TRACES]: getTracesUpdaterConfig(
|
||||
redirectWithOptionsData,
|
||||
setSavedViewPreferences,
|
||||
),
|
||||
[DataSource.METRICS]: metricsUpdater,
|
||||
});
|
||||
|
||||
export function usePreferenceUpdater({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
mode,
|
||||
preferences,
|
||||
setReSync,
|
||||
setSavedViewPreferences,
|
||||
}: {
|
||||
sourcePage: PreferenceSourcePage;
|
||||
dataSource: DataSource;
|
||||
mode: string;
|
||||
preferences: Preferences | null;
|
||||
setReSync: Dispatch<SetStateAction<boolean>>;
|
||||
@@ -56,7 +62,7 @@ export function usePreferenceUpdater({
|
||||
preferences,
|
||||
redirectWithOptionsData,
|
||||
setSavedViewPreferences,
|
||||
)[sourcePage];
|
||||
)[dataSource];
|
||||
|
||||
return {
|
||||
updateColumns: (newColumns: TelemetryFieldKey[]): void => {
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { PREFERENCE_SOURCE_PAGES } from './constants';
|
||||
import { PreferenceSourcePage } from './types';
|
||||
|
||||
export function isPreferenceSourcePage(
|
||||
sourcePage: SavedviewtypesSourceDTO,
|
||||
): sourcePage is PreferenceSourcePage {
|
||||
return (
|
||||
PREFERENCE_SOURCE_PAGES as readonly SavedviewtypesSourceDTO[]
|
||||
).includes(sourcePage);
|
||||
}
|
||||
@@ -74,7 +74,9 @@
|
||||
"meter-metrics",
|
||||
"logs-field",
|
||||
"traces-field",
|
||||
"metrics-field"
|
||||
"metrics-field",
|
||||
"span-mapper-group",
|
||||
"span-mapper"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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/spantypes"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
|
||||
if err := router.Handle("/api/v1/span_mapper_groups", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.spanMapperHandler.ListGroups),
|
||||
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.ListGroups, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "ListSpanMapperGroups",
|
||||
Tags: []string{"spanmapper"},
|
||||
@@ -25,14 +26,20 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbList)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
|
||||
Verb: coretypes.VerbList,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/span_mapper_groups", handler.New(
|
||||
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.CreateGroup),
|
||||
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.CreateGroup, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "CreateSpanMapperGroup",
|
||||
Tags: []string{"spanmapper"},
|
||||
@@ -45,19 +52,26 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusCreated,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusConflict},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbCreate)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
|
||||
Verb: coretypes.VerbCreate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.ResponseJSONPath("data.id"),
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/span_mapper_groups/test", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.spanMapperHandler.TestMappers),
|
||||
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.TestMappers, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "TestSpanMappers",
|
||||
Tags: []string{"spanmapper"},
|
||||
Summary: "Test span mappers against sample spans",
|
||||
Description: "Tests how span mappers would transform sample spans",
|
||||
Description: "Tests how span mappers would transform sample spans. Groups sent without mappers are read from the store by name.",
|
||||
Request: new(spantypes.PostableSpanMapperTest),
|
||||
RequestContentType: "application/json",
|
||||
Response: new(spantypes.GettableSpanMapperTest),
|
||||
@@ -65,14 +79,20 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbRead)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
Selector: coretypes.WildcardSelector,
|
||||
}),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}", handler.New(
|
||||
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.UpdateGroup),
|
||||
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.UpdateGroup, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "UpdateSpanMapperGroup",
|
||||
Tags: []string{"spanmapper"},
|
||||
@@ -83,14 +103,21 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbUpdate)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
|
||||
Verb: coretypes.VerbUpdate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("groupId"),
|
||||
Selector: coretypes.IDSelector,
|
||||
}),
|
||||
)).Methods(http.MethodPatch).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}", handler.New(
|
||||
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.DeleteGroup),
|
||||
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.DeleteGroup, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "DeleteSpanMapperGroup",
|
||||
Tags: []string{"spanmapper"},
|
||||
@@ -103,14 +130,21 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbDelete)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
|
||||
Verb: coretypes.VerbDelete,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("groupId"),
|
||||
Selector: coretypes.IDSelector,
|
||||
}),
|
||||
)).Methods(http.MethodDelete).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}/span_mappers", handler.New(
|
||||
provider.authzMiddleware.ViewAccess(provider.spanMapperHandler.ListMappers),
|
||||
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.ListMappers, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "ListSpanMappers",
|
||||
Tags: []string{"spanmapper"},
|
||||
@@ -123,14 +157,21 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbRead)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceSpanMapperGroup,
|
||||
Verb: coretypes.VerbRead,
|
||||
Category: coretypes.ActionCategoryDataAccess,
|
||||
ID: coretypes.PathParam("groupId"),
|
||||
Selector: coretypes.IDSelector,
|
||||
}),
|
||||
)).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}/span_mappers", handler.New(
|
||||
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.CreateMapper),
|
||||
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.CreateMapper, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "CreateSpanMapper",
|
||||
Tags: []string{"spanmapper"},
|
||||
@@ -143,14 +184,32 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusCreated,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound, http.StatusConflict},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapper.Scope(coretypes.VerbCreate), coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbAttach)}),
|
||||
},
|
||||
handler.WithResourceDefs(
|
||||
handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceSpanMapper,
|
||||
Verb: coretypes.VerbCreate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.ResponseJSONPath("data.id"),
|
||||
Selector: coretypes.WildcardSelector,
|
||||
},
|
||||
handler.AttachDetachParentChildResourceDef{
|
||||
Verb: coretypes.VerbAttach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ParentResource: coretypes.ResourceMetaResourceSpanMapperGroup,
|
||||
ParentID: coretypes.PathParam("groupId"),
|
||||
ParentSelector: coretypes.IDSelector,
|
||||
ChildResource: coretypes.ResourceMetaResourceSpanMapper,
|
||||
ChildIDs: coretypes.OneID(coretypes.ResponseJSONPath("data.id")),
|
||||
},
|
||||
),
|
||||
)).Methods(http.MethodPost).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}/span_mappers/{mapperId}", handler.New(
|
||||
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.UpdateMapper),
|
||||
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.UpdateMapper, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "UpdateSpanMapper",
|
||||
Tags: []string{"spanmapper"},
|
||||
@@ -161,14 +220,21 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapper.Scope(coretypes.VerbUpdate)}),
|
||||
},
|
||||
handler.WithResourceDefs(handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceSpanMapper,
|
||||
Verb: coretypes.VerbUpdate,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("mapperId"),
|
||||
Selector: coretypes.IDSelector,
|
||||
}),
|
||||
)).Methods(http.MethodPatch).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/span_mapper_groups/{groupId}/span_mappers/{mapperId}", handler.New(
|
||||
provider.authzMiddleware.AdminAccess(provider.spanMapperHandler.DeleteMapper),
|
||||
provider.authzMiddleware.CheckResources(provider.spanMapperHandler.DeleteMapper, authtypes.SigNozAdminRoleName),
|
||||
handler.OpenAPIDef{
|
||||
ID: "DeleteSpanMapper",
|
||||
Tags: []string{"spanmapper"},
|
||||
@@ -181,8 +247,26 @@ func (provider *provider) addSpanMapperRoutes(router *mux.Router) error {
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
|
||||
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSpanMapper.Scope(coretypes.VerbDelete), coretypes.ResourceMetaResourceSpanMapperGroup.Scope(coretypes.VerbDetach)}),
|
||||
},
|
||||
handler.WithResourceDefs(
|
||||
handler.BasicResourceDef{
|
||||
Resource: coretypes.ResourceMetaResourceSpanMapper,
|
||||
Verb: coretypes.VerbDelete,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ID: coretypes.PathParam("mapperId"),
|
||||
Selector: coretypes.IDSelector,
|
||||
},
|
||||
handler.AttachDetachParentChildResourceDef{
|
||||
Verb: coretypes.VerbDetach,
|
||||
Category: coretypes.ActionCategoryConfigurationChange,
|
||||
ParentResource: coretypes.ResourceMetaResourceSpanMapperGroup,
|
||||
ParentID: coretypes.PathParam("groupId"),
|
||||
ParentSelector: coretypes.IDSelector,
|
||||
ChildResource: coretypes.ResourceMetaResourceSpanMapper,
|
||||
ChildIDs: coretypes.OneID(coretypes.PathParam("mapperId")),
|
||||
},
|
||||
),
|
||||
)).Methods(http.MethodDelete).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -266,6 +266,7 @@ func NewSQLMigrationProviderFactories(
|
||||
sqlmigration.NewAddMetricsFieldTuplesFactory(sqlstore),
|
||||
sqlmigration.NewAddGCPConnectionMethodFactory(),
|
||||
sqlmigration.NewDeleteOrphanSARolesFactory(),
|
||||
sqlmigration.NewAddSpanMapperTuplesFactory(sqlstore),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
168
pkg/sqlmigration/141_add_span_mapper_tuples.go
Normal file
168
pkg/sqlmigration/141_add_span_mapper_tuples.go
Normal file
@@ -0,0 +1,168 @@
|
||||
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 addSpanMapperTuples struct {
|
||||
sqlstore sqlstore.SQLStore
|
||||
}
|
||||
|
||||
func NewAddSpanMapperTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
|
||||
return factory.NewProviderFactory(factory.MustNewName("add_span_mapper_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
|
||||
return &addSpanMapperTuples{sqlstore: sqlstore}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (migration *addSpanMapperTuples) Register(migrations *migrate.Migrations) error {
|
||||
return migrations.Register(migration.Up, migration.Down)
|
||||
}
|
||||
|
||||
func (migration *addSpanMapperTuples) 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", "span-mapper-group", "read"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "update"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "delete"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "create"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "list"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "attach"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper-group", "detach"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper", "update"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper", "delete"},
|
||||
{authtypes.SigNozAdminRoleName, "metaresource", "span-mapper", "create"},
|
||||
{authtypes.SigNozEditorRoleName, "metaresource", "span-mapper-group", "read"},
|
||||
{authtypes.SigNozEditorRoleName, "metaresource", "span-mapper-group", "list"},
|
||||
{authtypes.SigNozViewerRoleName, "metaresource", "span-mapper-group", "read"},
|
||||
{authtypes.SigNozViewerRoleName, "metaresource", "span-mapper-group", "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 *addSpanMapperTuples) Down(context.Context, *bun.DB) error {
|
||||
return nil
|
||||
}
|
||||
@@ -80,6 +80,8 @@ func (name Kind) Enum() []any {
|
||||
KindLogsField,
|
||||
KindTracesField,
|
||||
KindMetricsField,
|
||||
KindSpanMapperGroup,
|
||||
KindSpanMapper,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,8 @@ var Kinds = []Kind{
|
||||
KindLogsField,
|
||||
KindTracesField,
|
||||
KindMetricsField,
|
||||
KindSpanMapperGroup,
|
||||
KindSpanMapper,
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -82,4 +84,6 @@ var (
|
||||
KindLogsField = MustNewKind("logs-field")
|
||||
KindTracesField = MustNewKind("traces-field")
|
||||
KindMetricsField = MustNewKind("metrics-field")
|
||||
KindSpanMapperGroup = MustNewKind("span-mapper-group")
|
||||
KindSpanMapper = MustNewKind("span-mapper")
|
||||
)
|
||||
|
||||
@@ -218,6 +218,17 @@ 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)},
|
||||
// span-mapper-group and span-mapper — admin manages, viewer reads
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
{Verb: VerbCreate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
{Verb: VerbAttach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
{Verb: VerbDetach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapper}, WildCardSelectorString)},
|
||||
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapper}, WildCardSelectorString)},
|
||||
{Verb: VerbCreate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapper}, WildCardSelectorString)},
|
||||
},
|
||||
SigNozEditorRoleName: {
|
||||
// cloud-integration — editor can read accounts
|
||||
@@ -317,6 +328,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)},
|
||||
// span-mapper-group — read only (admin manages)
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
},
|
||||
SigNozViewerRoleName: {
|
||||
// cloud-integration — viewer can read accounts
|
||||
@@ -381,6 +395,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)},
|
||||
// span-mapper-group — read only
|
||||
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSpanMapperGroup}, WildCardSelectorString)},
|
||||
},
|
||||
SigNozAnonymousRoleName: {
|
||||
// public-dashboard — anonymous read
|
||||
|
||||
@@ -40,6 +40,8 @@ var Resources = []Resource{
|
||||
ResourceMetaResourceLogsField,
|
||||
ResourceMetaResourceTracesField,
|
||||
ResourceMetaResourceMetricsField,
|
||||
ResourceMetaResourceSpanMapperGroup,
|
||||
ResourceMetaResourceSpanMapper,
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -82,4 +84,6 @@ var (
|
||||
ResourceMetaResourceLogsField = NewResourceMetaResource(KindLogsField)
|
||||
ResourceMetaResourceTracesField = NewResourceMetaResource(KindTracesField)
|
||||
ResourceMetaResourceMetricsField = NewResourceMetaResource(KindMetricsField, VerbList, VerbRead, VerbUpdate)
|
||||
ResourceMetaResourceSpanMapperGroup = NewResourceMetaResource(KindSpanMapperGroup)
|
||||
ResourceMetaResourceSpanMapper = NewResourceMetaResource(KindSpanMapper, VerbCreate, VerbUpdate, VerbDelete)
|
||||
)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -297,6 +297,28 @@
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "span-mapper-group",
|
||||
"verbs": [
|
||||
"read",
|
||||
"update",
|
||||
"delete",
|
||||
"create",
|
||||
"list",
|
||||
"attach",
|
||||
"detach"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "span-mapper",
|
||||
"verbs": [
|
||||
"update",
|
||||
"delete",
|
||||
"create"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "ttl-setting",
|
||||
@@ -528,6 +550,14 @@
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "span-mapper-group",
|
||||
"verbs": [
|
||||
"read",
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "ttl-setting",
|
||||
@@ -707,6 +737,14 @@
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "span-mapper-group",
|
||||
"verbs": [
|
||||
"read",
|
||||
"list"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "metaresource",
|
||||
"kind": "ttl-setting",
|
||||
|
||||
355
tests/integration/tests/spanmapper/03_authz.py
Normal file
355
tests/integration/tests/spanmapper/03_authz.py
Normal file
@@ -0,0 +1,355 @@
|
||||
from collections.abc import Callable
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
from wiremock.resources.mappings import Mapping
|
||||
|
||||
from fixtures.auth import (
|
||||
USER_ADMIN_EMAIL,
|
||||
USER_ADMIN_PASSWORD,
|
||||
add_license,
|
||||
change_user_role,
|
||||
create_active_user,
|
||||
find_user_by_email,
|
||||
)
|
||||
from fixtures.role import find_role_by_name, transaction_group
|
||||
from fixtures.types import Operation, SigNoz, TestContainerDocker
|
||||
|
||||
GROUPS_PATH = "/api/v1/span_mapper_groups"
|
||||
|
||||
_EDITOR_EMAIL = "editor+spanmapperauthz@integration.test"
|
||||
_VIEWER_EMAIL = "viewer+spanmapperauthz@integration.test"
|
||||
_ACTOR_ROLE_NAME = "span-mapper-fga-actor"
|
||||
_ACTOR_EMAIL = "customrole+spanmapperauthz@integration.test"
|
||||
_PASSWORD = "password123Z$"
|
||||
|
||||
# Instance verbs are granted on _TARGET_A and its mapper only; _TARGET_B must stay forbidden.
|
||||
_TARGET_A = "span-mapper-authz-target-a"
|
||||
_TARGET_B = "span-mapper-authz-target-b"
|
||||
|
||||
_MAPPER = {
|
||||
"name": "span_mapper_authz.target",
|
||||
"fieldContext": "attribute",
|
||||
"config": {"sources": [{"key": "authz.source", "context": "attribute", "operation": "copy", "priority": 1, "enabled": True}]},
|
||||
"enabled": True,
|
||||
}
|
||||
|
||||
_SIMULATE = {
|
||||
"spans": [{"attributes": {"authz.source": "x"}, "resource": {}}],
|
||||
"groups": [{"name": _TARGET_A, "condition": {"attributes": [{"value": "authz.a", "enabled": True}], "resource": []}, "enabled": True}],
|
||||
}
|
||||
|
||||
|
||||
def test_setup_users_and_targets(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
headers = {"Authorization": f"Bearer {admin_token}"}
|
||||
|
||||
# A --reuse stack may already hold part of this state; create only what is missing.
|
||||
response = requests.get(signoz.self.host_configs["8080"].get("/api/v2/users"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
existing_emails = {user["email"] for user in response.json()["data"]}
|
||||
for email, role in ((_EDITOR_EMAIL, "signoz-editor"), (_VIEWER_EMAIL, "signoz-viewer")):
|
||||
if email not in existing_emails:
|
||||
create_active_user(signoz, admin_token, email=email, role=role, password=_PASSWORD)
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
existing_groups = {group["name"] for group in response.json()["data"]["items"]}
|
||||
for name, substring in ((_TARGET_A, "authz.a"), (_TARGET_B, "authz.b")):
|
||||
if name in existing_groups:
|
||||
continue
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(GROUPS_PATH),
|
||||
json={"name": name, "condition": {"attributes": [{"value": substring, "enabled": True}], "resource": []}, "enabled": True},
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
ids = {group["name"]: group["id"] for group in response.json()["data"]["items"]}
|
||||
for name in (_TARGET_A, _TARGET_B):
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[name]}/span_mappers"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
if any(mapper["name"] == _MAPPER["name"] for mapper in response.json()["data"]["items"]):
|
||||
continue
|
||||
response = requests.post(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[name]}/span_mappers"), json=_MAPPER, headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
|
||||
|
||||
def test_mapper_is_only_reachable_through_its_own_group(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
# The authz check on the mapper routes trusts the group id in the path, so the
|
||||
# store must refuse a mapper addressed through another group.
|
||||
headers = {"Authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
ids = {group["name"]: group["id"] for group in response.json()["data"]["items"]}
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
mapper_b = response.json()["data"]["items"][0]["id"]
|
||||
|
||||
response = requests.patch(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers/{mapper_b}"), json={"enabled": True}, headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND, f"update B's mapper via A: expected 404, got {response.status_code}: {response.text}"
|
||||
|
||||
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers/{mapper_b}"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND, f"delete B's mapper via A: expected 404, got {response.status_code}: {response.text}"
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert {mapper["id"] for mapper in response.json()["data"]["items"]} == {mapper_b}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("email", [_VIEWER_EMAIL, _EDITOR_EMAIL], ids=["viewer", "editor"])
|
||||
def test_managed_readers_allowed_on_reads_and_simulate(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
email: str,
|
||||
):
|
||||
headers = {"Authorization": f"Bearer {get_token(email, _PASSWORD)}"}
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
target_a = {group["name"]: group["id"] for group in response.json()["data"]["items"]}[_TARGET_A]
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{target_a}/span_mappers"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert {mapper["name"] for mapper in response.json()["data"]["items"]} == {_MAPPER["name"]}
|
||||
|
||||
response = requests.post(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/test"), json=_SIMULATE, headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("email", [_VIEWER_EMAIL, _EDITOR_EMAIL], ids=["viewer", "editor"])
|
||||
def test_managed_readers_forbidden_on_mutations(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
email: str,
|
||||
):
|
||||
headers = {"Authorization": f"Bearer {get_token(email, _PASSWORD)}"}
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
target_a = {group["name"]: group["id"] for group in response.json()["data"]["items"]}[_TARGET_A]
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{target_a}/span_mappers"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
mapper_id = response.json()["data"]["items"][0]["id"]
|
||||
|
||||
for method, path, body in (
|
||||
("POST", GROUPS_PATH, {"name": "span-mapper-authz-denied", "condition": {"attributes": [{"value": "authz.denied", "enabled": True}], "resource": []}, "enabled": True}),
|
||||
("PATCH", f"{GROUPS_PATH}/{target_a}", {"enabled": True}),
|
||||
("DELETE", f"{GROUPS_PATH}/{target_a}", None),
|
||||
("POST", f"{GROUPS_PATH}/{target_a}/span_mappers", {**_MAPPER, "name": "span_mapper_authz.denied"}),
|
||||
("PATCH", f"{GROUPS_PATH}/{target_a}/span_mappers/{mapper_id}", {"enabled": True}),
|
||||
("DELETE", f"{GROUPS_PATH}/{target_a}/span_mappers/{mapper_id}", None),
|
||||
):
|
||||
response = requests.request(method, signoz.self.host_configs["8080"].get(path), json=body, headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"{method} {path}: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
|
||||
def test_apply_license(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
make_http_mocks: Callable[[TestContainerDocker, list[Mapping]], None],
|
||||
get_token: Callable[[str, str], str],
|
||||
) -> None:
|
||||
add_license(signoz, make_http_mocks, get_token)
|
||||
|
||||
|
||||
def test_setup_scoped_actor(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
create_role: Callable[..., str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
headers = {"Authorization": f"Bearer {admin_token}"}
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
target_a = {group["name"]: group["id"] for group in response.json()["data"]["items"]}[_TARGET_A]
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{target_a}/span_mappers"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
mapper_a = response.json()["data"]["items"][0]["id"]
|
||||
|
||||
# Adding a mapper needs create on the collection plus attach on the group;
|
||||
# removing one needs delete on the mapper plus detach on the group.
|
||||
response = requests.get(signoz.self.host_configs["8080"].get("/api/v1/roles"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
if not any(role["name"] == _ACTOR_ROLE_NAME for role in response.json()["data"]):
|
||||
create_role(
|
||||
admin_token,
|
||||
_ACTOR_ROLE_NAME,
|
||||
[
|
||||
transaction_group("list", "metaresource", "span-mapper-group", ["*"]),
|
||||
transaction_group("read", "metaresource", "span-mapper-group", [target_a]),
|
||||
transaction_group("update", "metaresource", "span-mapper-group", [target_a]),
|
||||
transaction_group("attach", "metaresource", "span-mapper-group", [target_a]),
|
||||
transaction_group("detach", "metaresource", "span-mapper-group", [target_a]),
|
||||
transaction_group("create", "metaresource", "span-mapper", ["*"]),
|
||||
transaction_group("delete", "metaresource", "span-mapper", ["*"]),
|
||||
transaction_group("update", "metaresource", "span-mapper", [mapper_a]),
|
||||
],
|
||||
)
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get("/api/v2/users"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
actor = next((user for user in response.json()["data"] if user["email"] == _ACTOR_EMAIL), None)
|
||||
user_id = actor["id"] if actor else create_active_user(signoz, admin_token, email=_ACTOR_EMAIL, role="signoz-viewer", password=_PASSWORD)
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"/api/v2/users/{user_id}"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
if not any(ur["role"]["name"] == _ACTOR_ROLE_NAME for ur in response.json()["data"]["userRoles"]):
|
||||
change_user_role(signoz, admin_token, user_id, "signoz-viewer", _ACTOR_ROLE_NAME)
|
||||
|
||||
|
||||
def test_access_scoped_to_granted_group_and_mapper(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
headers = {"Authorization": f"Bearer {get_token(_ACTOR_EMAIL, _PASSWORD)}"}
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
ids = {group["name"]: group["id"] for group in response.json()["data"]["items"]}
|
||||
assert {_TARGET_A, _TARGET_B} <= set(ids)
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, f"list granted group's mappers: {response.text}"
|
||||
mapper_a = response.json()["data"]["items"][0]["id"]
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"list other group's mappers: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
# Simulate reads saved groups by name, so it needs read on every group.
|
||||
response = requests.post(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/test"), json=_SIMULATE, headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"simulate: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
response = requests.patch(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}"), json={"enabled": True}, headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, f"update granted group: {response.text}"
|
||||
|
||||
response = requests.patch(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}"), json={"enabled": True}, headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"update other group: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers"),
|
||||
json={**_MAPPER, "name": "span_mapper_authz.actor"},
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.CREATED, f"create mapper in granted group: {response.text}"
|
||||
created = response.json()["data"]["id"]
|
||||
|
||||
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers/{created}"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, f"delete mapper in granted group: {response.text}"
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers"),
|
||||
json={**_MAPPER, "name": "span_mapper_authz.actor"},
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"create mapper in other group: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
# Mapper update is checked on the mapper itself, so the grant on A's mapper
|
||||
# does not extend to B's.
|
||||
response = requests.patch(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers/{mapper_a}"), json={"enabled": True}, headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, f"update granted mapper: {response.text}"
|
||||
|
||||
admin_headers = {"Authorization": f"Bearer {get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)}"}
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers"), headers=admin_headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
mapper_b = response.json()["data"]["items"][0]["id"]
|
||||
|
||||
response = requests.patch(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers/{mapper_b}"), json={"enabled": True}, headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"update other mapper: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_B]}/span_mappers/{mapper_b}"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"delete other mapper: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
# detach on A plus delete on "*" passes authz for B's mapper addressed through
|
||||
# A's path; the store must still refuse it.
|
||||
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}/span_mappers/{mapper_b}"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND, f"delete B's mapper via A: expected 404, got {response.status_code}: {response.text}"
|
||||
|
||||
response = requests.post(
|
||||
signoz.self.host_configs["8080"].get(GROUPS_PATH),
|
||||
json={"name": "span-mapper-authz-actor", "condition": {"attributes": [{"value": "authz.actor", "enabled": True}], "resource": []}, "enabled": True},
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"create group: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[_TARGET_A]}"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"delete granted group: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
|
||||
def test_revoke_group_read(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
admin_headers = {"Authorization": f"Bearer {admin_token}"}
|
||||
headers = {"Authorization": f"Bearer {get_token(_ACTOR_EMAIL, _PASSWORD)}"}
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=admin_headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
target_a = {group["name"]: group["id"] for group in response.json()["data"]["items"]}[_TARGET_A]
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{target_a}/span_mappers"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, f"read before revoke: {response.text}"
|
||||
|
||||
response = requests.put(
|
||||
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)}"),
|
||||
json={"description": "", "transactionGroups": [transaction_group("list", "metaresource", "span-mapper-group", ["*"])]},
|
||||
headers=admin_headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{target_a}/span_mappers"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN, f"read after revoke: expected 403, got {response.status_code}: {response.text}"
|
||||
|
||||
|
||||
def test_span_mapper_authz_cleanup(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
headers = {"Authorization": f"Bearer {admin_token}"}
|
||||
actor = find_user_by_email(signoz, admin_token, _ACTOR_EMAIL)
|
||||
|
||||
# Back to viewer so a rerun on the same stack can set the actor up again.
|
||||
change_user_role(signoz, admin_token, actor["id"], _ACTOR_ROLE_NAME, "signoz-viewer")
|
||||
|
||||
response = requests.delete(
|
||||
signoz.self.host_configs["8080"].get(f"/api/v1/roles/{find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)}"),
|
||||
headers=headers,
|
||||
timeout=5,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, f"delete {_ACTOR_ROLE_NAME}: {response.text}"
|
||||
|
||||
response = requests.get(signoz.self.host_configs["8080"].get(GROUPS_PATH), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
ids = {group["name"]: group["id"] for group in response.json()["data"]["items"]}
|
||||
for name in (_TARGET_A, _TARGET_B):
|
||||
response = requests.delete(signoz.self.host_configs["8080"].get(f"{GROUPS_PATH}/{ids[name]}"), headers=headers, timeout=5)
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT, f"delete {name}: {response.text}"
|
||||
Reference in New Issue
Block a user