mirror of
https://github.com/SigNoz/signoz.git
synced 2026-06-12 11:50:28 +01:00
Compare commits
4 Commits
feat/trace
...
feat/llm-o
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1dd887f7fd | ||
|
|
b22eef6a65 | ||
|
|
4d3d1ef423 | ||
|
|
c775d7e398 |
@@ -2496,10 +2496,17 @@ components:
|
||||
$ref: '#/components/schemas/DashboardtypesTimePreference'
|
||||
type: object
|
||||
DashboardtypesBuilderQuerySpec:
|
||||
discriminator:
|
||||
mapping:
|
||||
logs: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregation'
|
||||
metrics: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregation'
|
||||
traces: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregation'
|
||||
propertyName: signal
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregation'
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregation'
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregation'
|
||||
type: object
|
||||
DashboardtypesComparisonOperator:
|
||||
enum:
|
||||
- above
|
||||
@@ -2588,8 +2595,13 @@ components:
|
||||
type: array
|
||||
type: object
|
||||
DashboardtypesDatasourcePlugin:
|
||||
discriminator:
|
||||
mapping:
|
||||
signoz/Datasource: '#/components/schemas/DashboardtypesDatasourcePluginVariantStruct'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesDatasourcePluginVariantStruct'
|
||||
type: object
|
||||
DashboardtypesDatasourcePluginKind:
|
||||
enum:
|
||||
- signoz/Datasource
|
||||
@@ -2656,7 +2668,7 @@ components:
|
||||
$ref: '#/components/schemas/DashboardtypesDashboardSpec'
|
||||
tags:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagtypesPostableTag'
|
||||
$ref: '#/components/schemas/TagtypesGettableTag'
|
||||
nullable: true
|
||||
type: array
|
||||
updatedAt:
|
||||
@@ -2733,8 +2745,13 @@ components:
|
||||
- path
|
||||
type: object
|
||||
DashboardtypesLayout:
|
||||
discriminator:
|
||||
mapping:
|
||||
Grid: '#/components/schemas/DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpec'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpec'
|
||||
type: object
|
||||
DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpec:
|
||||
properties:
|
||||
kind:
|
||||
@@ -2774,6 +2791,11 @@ components:
|
||||
- solid
|
||||
- dashed
|
||||
type: string
|
||||
DashboardtypesListOrder:
|
||||
enum:
|
||||
- asc
|
||||
- desc
|
||||
type: string
|
||||
DashboardtypesListPanelSpec:
|
||||
properties:
|
||||
selectFields:
|
||||
@@ -2781,6 +2803,12 @@ components:
|
||||
$ref: '#/components/schemas/TelemetrytypesTelemetryFieldKey'
|
||||
type: array
|
||||
type: object
|
||||
DashboardtypesListSort:
|
||||
enum:
|
||||
- updated_at
|
||||
- created_at
|
||||
- name
|
||||
type: string
|
||||
DashboardtypesListVariableSpec:
|
||||
properties:
|
||||
allowAllValue:
|
||||
@@ -2803,6 +2831,134 @@ components:
|
||||
nullable: true
|
||||
type: string
|
||||
type: object
|
||||
DashboardtypesListableDashboardForUserV2:
|
||||
properties:
|
||||
dashboards:
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardtypesListedDashboardForUserV2'
|
||||
type: array
|
||||
tags:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagtypesGettableTag'
|
||||
type: array
|
||||
total:
|
||||
format: int64
|
||||
type: integer
|
||||
required:
|
||||
- dashboards
|
||||
- total
|
||||
- tags
|
||||
type: object
|
||||
DashboardtypesListableDashboardV2:
|
||||
properties:
|
||||
dashboards:
|
||||
items:
|
||||
$ref: '#/components/schemas/DashboardtypesListedDashboardV2'
|
||||
type: array
|
||||
tags:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagtypesGettableTag'
|
||||
type: array
|
||||
total:
|
||||
format: int64
|
||||
type: integer
|
||||
required:
|
||||
- dashboards
|
||||
- total
|
||||
- tags
|
||||
type: object
|
||||
DashboardtypesListedDashboardForUserV2:
|
||||
properties:
|
||||
createdAt:
|
||||
format: date-time
|
||||
type: string
|
||||
createdBy:
|
||||
type: string
|
||||
id:
|
||||
type: string
|
||||
image:
|
||||
type: string
|
||||
locked:
|
||||
type: boolean
|
||||
name:
|
||||
type: string
|
||||
orgId:
|
||||
type: string
|
||||
pinned:
|
||||
type: boolean
|
||||
schemaVersion:
|
||||
type: string
|
||||
source:
|
||||
$ref: '#/components/schemas/DashboardtypesSource'
|
||||
spec:
|
||||
$ref: '#/components/schemas/DashboardtypesListedDashboardV2Spec'
|
||||
tags:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagtypesGettableTag'
|
||||
type: array
|
||||
updatedAt:
|
||||
format: date-time
|
||||
type: string
|
||||
updatedBy:
|
||||
type: string
|
||||
required:
|
||||
- id
|
||||
- orgId
|
||||
- locked
|
||||
- source
|
||||
- schemaVersion
|
||||
- name
|
||||
- tags
|
||||
- spec
|
||||
- pinned
|
||||
type: object
|
||||
DashboardtypesListedDashboardV2:
|
||||
properties:
|
||||
createdAt:
|
||||
format: date-time
|
||||
type: string
|
||||
createdBy:
|
||||
type: string
|
||||
id:
|
||||
type: string
|
||||
image:
|
||||
type: string
|
||||
locked:
|
||||
type: boolean
|
||||
name:
|
||||
type: string
|
||||
orgId:
|
||||
type: string
|
||||
schemaVersion:
|
||||
type: string
|
||||
source:
|
||||
$ref: '#/components/schemas/DashboardtypesSource'
|
||||
spec:
|
||||
$ref: '#/components/schemas/DashboardtypesListedDashboardV2Spec'
|
||||
tags:
|
||||
items:
|
||||
$ref: '#/components/schemas/TagtypesGettableTag'
|
||||
type: array
|
||||
updatedAt:
|
||||
format: date-time
|
||||
type: string
|
||||
updatedBy:
|
||||
type: string
|
||||
required:
|
||||
- id
|
||||
- orgId
|
||||
- locked
|
||||
- source
|
||||
- schemaVersion
|
||||
- name
|
||||
- tags
|
||||
- spec
|
||||
type: object
|
||||
DashboardtypesListedDashboardV2Spec:
|
||||
properties:
|
||||
display:
|
||||
$ref: '#/components/schemas/CommonDisplay'
|
||||
type: object
|
||||
DashboardtypesNumberPanelSpec:
|
||||
properties:
|
||||
formatting:
|
||||
@@ -2834,6 +2990,16 @@ components:
|
||||
- Panel
|
||||
type: string
|
||||
DashboardtypesPanelPlugin:
|
||||
discriminator:
|
||||
mapping:
|
||||
signoz/BarChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec'
|
||||
signoz/HistogramPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec'
|
||||
signoz/ListPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec'
|
||||
signoz/NumberPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpec'
|
||||
signoz/PieChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesPieChartPanelSpec'
|
||||
signoz/TablePanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec'
|
||||
signoz/TimeSeriesPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec'
|
||||
@@ -2842,6 +3008,7 @@ components:
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec'
|
||||
type: object
|
||||
DashboardtypesPanelPluginKind:
|
||||
enum:
|
||||
- signoz/TimeSeriesPanel
|
||||
@@ -3020,6 +3187,15 @@ components:
|
||||
$ref: '#/components/schemas/DashboardtypesQuerySpec'
|
||||
type: object
|
||||
DashboardtypesQueryPlugin:
|
||||
discriminator:
|
||||
mapping:
|
||||
signoz/BuilderQuery: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBuilderQuerySpec'
|
||||
signoz/ClickHouseSQL: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5ClickHouseQuery'
|
||||
signoz/CompositeQuery: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5CompositeQuery'
|
||||
signoz/Formula: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5QueryBuilderFormula'
|
||||
signoz/PromQLQuery: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5PromQuery'
|
||||
signoz/TraceOperator: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5QueryBuilderTraceOperator'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBuilderQuerySpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5CompositeQuery'
|
||||
@@ -3027,6 +3203,7 @@ components:
|
||||
- $ref: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5PromQuery'
|
||||
- $ref: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5ClickHouseQuery'
|
||||
- $ref: '#/components/schemas/DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5QueryBuilderTraceOperator'
|
||||
type: object
|
||||
DashboardtypesQueryPluginKind:
|
||||
enum:
|
||||
- signoz/BuilderQuery
|
||||
@@ -3281,9 +3458,15 @@ components:
|
||||
type: boolean
|
||||
type: object
|
||||
DashboardtypesVariable:
|
||||
discriminator:
|
||||
mapping:
|
||||
ListVariable: '#/components/schemas/DashboardtypesVariableEnvelopeGithubComSigNozSignozPkgTypesDashboardtypesListVariableSpec'
|
||||
TextVariable: '#/components/schemas/DashboardtypesVariableEnvelopeGithubComPersesSpecGoDashboardTextVariableSpec'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesVariableEnvelopeGithubComSigNozSignozPkgTypesDashboardtypesListVariableSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesVariableEnvelopeGithubComPersesSpecGoDashboardTextVariableSpec'
|
||||
type: object
|
||||
DashboardtypesVariableEnvelopeGithubComPersesSpecGoDashboardTextVariableSpec:
|
||||
properties:
|
||||
kind:
|
||||
@@ -3309,10 +3492,17 @@ components:
|
||||
- spec
|
||||
type: object
|
||||
DashboardtypesVariablePlugin:
|
||||
discriminator:
|
||||
mapping:
|
||||
signoz/CustomVariable: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesCustomVariableSpec'
|
||||
signoz/DynamicVariable: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDynamicVariableSpec'
|
||||
signoz/QueryVariable: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesQueryVariableSpec'
|
||||
propertyName: kind
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDynamicVariableSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesQueryVariableSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesCustomVariableSpec'
|
||||
type: object
|
||||
DashboardtypesVariablePluginKind:
|
||||
enum:
|
||||
- signoz/DynamicVariable
|
||||
@@ -5515,11 +5705,15 @@ components:
|
||||
$ref: '#/components/schemas/TelemetrytypesTelemetryFieldKey'
|
||||
type: array
|
||||
signal:
|
||||
$ref: '#/components/schemas/TelemetrytypesSignal'
|
||||
enum:
|
||||
- logs
|
||||
type: string
|
||||
source:
|
||||
$ref: '#/components/schemas/TelemetrytypesSource'
|
||||
stepInterval:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5Step'
|
||||
required:
|
||||
- signal
|
||||
type: object
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregation:
|
||||
properties:
|
||||
@@ -5566,11 +5760,15 @@ components:
|
||||
$ref: '#/components/schemas/TelemetrytypesTelemetryFieldKey'
|
||||
type: array
|
||||
signal:
|
||||
$ref: '#/components/schemas/TelemetrytypesSignal'
|
||||
enum:
|
||||
- metrics
|
||||
type: string
|
||||
source:
|
||||
$ref: '#/components/schemas/TelemetrytypesSource'
|
||||
stepInterval:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5Step'
|
||||
required:
|
||||
- signal
|
||||
type: object
|
||||
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregation:
|
||||
properties:
|
||||
@@ -5617,11 +5815,15 @@ components:
|
||||
$ref: '#/components/schemas/TelemetrytypesTelemetryFieldKey'
|
||||
type: array
|
||||
signal:
|
||||
$ref: '#/components/schemas/TelemetrytypesSignal'
|
||||
enum:
|
||||
- traces
|
||||
type: string
|
||||
source:
|
||||
$ref: '#/components/schemas/TelemetrytypesSource'
|
||||
stepInterval:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5Step'
|
||||
required:
|
||||
- signal
|
||||
type: object
|
||||
Querybuildertypesv5QueryBuilderTraceOperator:
|
||||
properties:
|
||||
@@ -7062,6 +7264,16 @@ components:
|
||||
required:
|
||||
- references
|
||||
type: object
|
||||
TagtypesGettableTag:
|
||||
properties:
|
||||
key:
|
||||
type: string
|
||||
value:
|
||||
type: string
|
||||
required:
|
||||
- key
|
||||
- value
|
||||
type: object
|
||||
TagtypesPostableTag:
|
||||
properties:
|
||||
key:
|
||||
@@ -13097,6 +13309,82 @@ paths:
|
||||
tags:
|
||||
- preferences
|
||||
/api/v2/dashboards:
|
||||
get:
|
||||
deprecated: false
|
||||
description: Returns a page of v2-shape dashboards for the org. This is the
|
||||
pure, user-independent list — it carries no pin state. Use ListDashboardsForUserV2
|
||||
for the personalized, pin-aware list. Supports a filter DSL (`query`), sort
|
||||
(`updated_at`/`created_at`/`name`), order (`asc`/`desc`), and offset-based
|
||||
pagination (`limit`/`offset`).
|
||||
operationId: ListDashboardsV2
|
||||
parameters:
|
||||
- in: query
|
||||
name: query
|
||||
schema:
|
||||
type: string
|
||||
- in: query
|
||||
name: sort
|
||||
schema:
|
||||
$ref: '#/components/schemas/DashboardtypesListSort'
|
||||
- in: query
|
||||
name: order
|
||||
schema:
|
||||
$ref: '#/components/schemas/DashboardtypesListOrder'
|
||||
- in: query
|
||||
name: limit
|
||||
schema:
|
||||
type: integer
|
||||
- in: query
|
||||
name: offset
|
||||
schema:
|
||||
type: integer
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
data:
|
||||
$ref: '#/components/schemas/DashboardtypesListableDashboardV2'
|
||||
status:
|
||||
type: string
|
||||
required:
|
||||
- status
|
||||
- data
|
||||
type: object
|
||||
description: OK
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
summary: List dashboards (v2)
|
||||
tags:
|
||||
- dashboard
|
||||
post:
|
||||
deprecated: false
|
||||
description: This endpoint creates a dashboard in the v2 format that follows
|
||||
@@ -13155,6 +13443,62 @@ paths:
|
||||
tags:
|
||||
- dashboard
|
||||
/api/v2/dashboards/{id}:
|
||||
delete:
|
||||
deprecated: false
|
||||
description: This endpoint deletes a v2-shape dashboard along with its tag relations.
|
||||
Locked dashboards are rejected.
|
||||
operationId: DeleteDashboardV2
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: string
|
||||
description: No Content
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"404":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Not Found
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- EDITOR
|
||||
- tokenizer:
|
||||
- EDITOR
|
||||
summary: Delete dashboard (v2)
|
||||
tags:
|
||||
- dashboard
|
||||
get:
|
||||
deprecated: false
|
||||
description: This endpoint returns a v2-shape dashboard.
|
||||
@@ -20377,6 +20721,196 @@ paths:
|
||||
summary: Update my user v2
|
||||
tags:
|
||||
- users
|
||||
/api/v2/users/me/dashboards:
|
||||
get:
|
||||
deprecated: false
|
||||
description: 'Same as ListDashboardsV2 but personalized for the calling user:
|
||||
each dashboard carries the caller''s `pinned` state, and pinned dashboards
|
||||
float to the top of the requested ordering. Supports the same filter DSL,
|
||||
sort, order, and pagination.'
|
||||
operationId: ListDashboardsForUserV2
|
||||
parameters:
|
||||
- in: query
|
||||
name: query
|
||||
schema:
|
||||
type: string
|
||||
- in: query
|
||||
name: sort
|
||||
schema:
|
||||
$ref: '#/components/schemas/DashboardtypesListSort'
|
||||
- in: query
|
||||
name: order
|
||||
schema:
|
||||
$ref: '#/components/schemas/DashboardtypesListOrder'
|
||||
- in: query
|
||||
name: limit
|
||||
schema:
|
||||
type: integer
|
||||
- in: query
|
||||
name: offset
|
||||
schema:
|
||||
type: integer
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
data:
|
||||
$ref: '#/components/schemas/DashboardtypesListableDashboardForUserV2'
|
||||
status:
|
||||
type: string
|
||||
required:
|
||||
- status
|
||||
- data
|
||||
type: object
|
||||
description: OK
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
summary: List dashboards for the current user (v2)
|
||||
tags:
|
||||
- dashboard
|
||||
/api/v2/users/me/dashboards/{id}/pins:
|
||||
delete:
|
||||
deprecated: false
|
||||
description: Removes the pin for the calling user. Idempotent — unpinning a
|
||||
dashboard that wasn't pinned still returns 204.
|
||||
operationId: UnpinDashboardV2
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: string
|
||||
description: No Content
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
summary: Unpin a dashboard for the current user (v2)
|
||||
tags:
|
||||
- dashboard
|
||||
put:
|
||||
deprecated: false
|
||||
description: Pins the dashboard for the calling user. A user can pin at most
|
||||
10 dashboards; pinning when at the limit returns 409. Re-pinning an already-pinned
|
||||
dashboard is a no-op success.
|
||||
operationId: PinDashboardV2
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: string
|
||||
description: No Content
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"404":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Not Found
|
||||
"409":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Conflict
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
summary: Pin a dashboard for the current user (v2)
|
||||
tags:
|
||||
- dashboard
|
||||
/api/v2/users/me/factor_password:
|
||||
put:
|
||||
deprecated: false
|
||||
|
||||
@@ -333,6 +333,50 @@ func (Step) JSONSchema() (jsonschema.Schema, error) {
|
||||
}
|
||||
```
|
||||
|
||||
### `oneOf` with a discriminator
|
||||
|
||||
For a sum type whose variants are keyed by a property (e.g. `kind`), expose the variants via `JSONSchemaOneOf()` and add a discriminator. Without it, code generators intersect the variants (`A & B & C`) instead of producing a clean discriminated union (`A | B | C`).
|
||||
|
||||
The parent keeps its `JSONSchemaOneOf()` (the `oneOf` itself) and *additionally* tags it via `PrepareJSONSchema` with the `x-signoz-discriminator` extension; `signoz.attachDiscriminators` then promotes that marker to a real OpenAPI 3 `discriminator` (and strips the duplicate parent properties) after reflection.
|
||||
|
||||
```go
|
||||
// On the parent: expose the oneOf variants...
|
||||
func (Plugin) JSONSchemaOneOf() []any {
|
||||
return []any{FooVariant{}}
|
||||
}
|
||||
|
||||
// ...and tag that same oneOf with the discriminator marker.
|
||||
func (Plugin) PrepareJSONSchema(s *jsonschema.Schema) error {
|
||||
if s.ExtraProperties == nil {
|
||||
s.ExtraProperties = map[string]any{}
|
||||
}
|
||||
s.ExtraProperties["x-signoz-discriminator"] = map[string]any{
|
||||
"propertyName": "kind",
|
||||
"mapping": map[string]string{
|
||||
"signoz/Foo": "#/components/schemas/FooVariant",
|
||||
},
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
Each variant must declare the discriminator property (`kind`) and mark it `required`.
|
||||
|
||||
This produces the following in the generated OpenAPI spec:
|
||||
|
||||
```yaml
|
||||
Plugin:
|
||||
discriminator:
|
||||
propertyName: kind
|
||||
mapping:
|
||||
signoz/Foo: '#/components/schemas/FooVariant'
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/FooVariant'
|
||||
type: object
|
||||
```
|
||||
|
||||
Note the discriminator property lives in the variants, not on the parent — the parent is only the union.
|
||||
|
||||
|
||||
## What should I remember?
|
||||
|
||||
|
||||
@@ -229,10 +229,39 @@ func (module *module) PatchV2(ctx context.Context, orgID valuer.UUID, id valuer.
|
||||
return module.pkgDashboardModule.PatchV2(ctx, orgID, id, updatedBy, patch)
|
||||
}
|
||||
|
||||
func (module *module) DeleteV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) error {
|
||||
return module.store.RunInTx(ctx, func(ctx context.Context) error {
|
||||
if err := module.store.DeletePublic(ctx, id.String()); err != nil && !errors.Ast(err, errors.TypeNotFound) {
|
||||
return err
|
||||
}
|
||||
return module.pkgDashboardModule.DeleteV2(ctx, orgID, id)
|
||||
})
|
||||
}
|
||||
|
||||
func (module *module) LockUnlockV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, isAdmin bool, lock bool) error {
|
||||
return module.pkgDashboardModule.LockUnlockV2(ctx, orgID, id, updatedBy, isAdmin, lock)
|
||||
}
|
||||
|
||||
func (module *module) ListV2(ctx context.Context, orgID valuer.UUID, params *dashboardtypes.ListDashboardsV2Params) (*dashboardtypes.ListableDashboardV2, error) {
|
||||
return module.pkgDashboardModule.ListV2(ctx, orgID, params)
|
||||
}
|
||||
|
||||
func (module *module) ListForUserV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, params *dashboardtypes.ListDashboardsV2Params) (*dashboardtypes.ListableDashboardForUserV2, error) {
|
||||
return module.pkgDashboardModule.ListForUserV2(ctx, orgID, userID, params)
|
||||
}
|
||||
|
||||
func (module *module) PinV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, id valuer.UUID) error {
|
||||
return module.pkgDashboardModule.PinV2(ctx, orgID, userID, id)
|
||||
}
|
||||
|
||||
func (module *module) UnpinV2(ctx context.Context, userID valuer.UUID, id valuer.UUID) error {
|
||||
return module.pkgDashboardModule.UnpinV2(ctx, userID, id)
|
||||
}
|
||||
|
||||
func (module *module) DeletePreferencesForUser(ctx context.Context, userID valuer.UUID) error {
|
||||
return module.pkgDashboardModule.DeletePreferencesForUser(ctx, userID)
|
||||
}
|
||||
|
||||
func (module *module) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.Dashboard, error) {
|
||||
return module.pkgDashboardModule.Get(ctx, orgID, id)
|
||||
}
|
||||
|
||||
@@ -16,10 +16,11 @@ func newFormatter(dialect schema.Dialect) sqlstore.SQLFormatter {
|
||||
}
|
||||
|
||||
func (f *formatter) JSONExtractString(column, path string) []byte {
|
||||
var sql []byte
|
||||
sql = f.bunf.AppendIdent(sql, column)
|
||||
sql = append(sql, f.convertJSONPathToPostgres(path)...)
|
||||
return sql
|
||||
ops := f.convertJSONPathToPostgres(path)
|
||||
if len(ops) == 0 {
|
||||
return f.bunf.AppendIdent(nil, column)
|
||||
}
|
||||
return append(f.TextToJsonColumn(column), ops...)
|
||||
}
|
||||
|
||||
func (f *formatter) JSONType(column, path string) []byte {
|
||||
|
||||
@@ -18,19 +18,19 @@ func TestJSONExtractString(t *testing.T) {
|
||||
name: "simple path",
|
||||
column: "data",
|
||||
path: "$.field",
|
||||
expected: `"data"->>'field'`,
|
||||
expected: `"data"::jsonb->>'field'`,
|
||||
},
|
||||
{
|
||||
name: "nested path",
|
||||
column: "metadata",
|
||||
path: "$.user.name",
|
||||
expected: `"metadata"->'user'->>'name'`,
|
||||
expected: `"metadata"::jsonb->'user'->>'name'`,
|
||||
},
|
||||
{
|
||||
name: "deeply nested path",
|
||||
column: "json_col",
|
||||
path: "$.level1.level2.level3",
|
||||
expected: `"json_col"->'level1'->'level2'->>'level3'`,
|
||||
expected: `"json_col"::jsonb->'level1'->'level2'->>'level3'`,
|
||||
},
|
||||
{
|
||||
name: "root path",
|
||||
|
||||
@@ -323,3 +323,10 @@ export const AIAssistantPage = Loadable(
|
||||
/* webpackChunkName: "AI Assistant Page" */ 'pages/AIAssistantPage/AIAssistantPage'
|
||||
),
|
||||
);
|
||||
|
||||
export const LLMObservabilityModelPricingPage = Loadable(
|
||||
() =>
|
||||
import(
|
||||
/* webpackChunkName: "LLM Observability Model Pricing Page" */ 'pages/LLMObservabilityModelPricing'
|
||||
),
|
||||
);
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
IntegrationsDetailsPage,
|
||||
LicensePage,
|
||||
ListAllALertsPage,
|
||||
LLMObservabilityModelPricingPage,
|
||||
LiveLogs,
|
||||
Login,
|
||||
Logs,
|
||||
@@ -507,6 +508,13 @@ const routes: AppRoutes[] = [
|
||||
key: 'AI_ASSISTANT',
|
||||
isPrivate: true,
|
||||
},
|
||||
{
|
||||
path: ROUTES.LLM_OBSERVABILITY_MODEL_PRICING,
|
||||
exact: true,
|
||||
component: LLMObservabilityModelPricingPage,
|
||||
key: 'LLM_OBSERVABILITY_MODEL_PRICING',
|
||||
isPrivate: true,
|
||||
},
|
||||
];
|
||||
|
||||
export const SUPPORT_ROUTE: AppRoutes = {
|
||||
|
||||
@@ -26,6 +26,7 @@ import type {
|
||||
DashboardtypesPostablePublicDashboardDTO,
|
||||
DashboardtypesUpdatableDashboardV2DTO,
|
||||
DashboardtypesUpdatablePublicDashboardDTO,
|
||||
DeleteDashboardV2PathParameters,
|
||||
DeletePublicDashboardPathParameters,
|
||||
GetDashboardV2200,
|
||||
GetDashboardV2PathParameters,
|
||||
@@ -35,11 +36,17 @@ import type {
|
||||
GetPublicDashboardPathParameters,
|
||||
GetPublicDashboardWidgetQueryRange200,
|
||||
GetPublicDashboardWidgetQueryRangePathParameters,
|
||||
ListDashboardsForUserV2200,
|
||||
ListDashboardsForUserV2Params,
|
||||
ListDashboardsV2200,
|
||||
ListDashboardsV2Params,
|
||||
LockDashboardV2PathParameters,
|
||||
PatchDashboardV2200,
|
||||
PatchDashboardV2PathParameters,
|
||||
PinDashboardV2PathParameters,
|
||||
RenderErrorResponseDTO,
|
||||
UnlockDashboardV2PathParameters,
|
||||
UnpinDashboardV2PathParameters,
|
||||
UpdateDashboardV2200,
|
||||
UpdateDashboardV2PathParameters,
|
||||
UpdatePublicDashboardPathParameters,
|
||||
@@ -641,6 +648,103 @@ export const invalidateGetPublicDashboardWidgetQueryRange = async (
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a page of v2-shape dashboards for the org. This is the pure, user-independent list — it carries no pin state. Use ListDashboardsForUserV2 for the personalized, pin-aware list. Supports a filter DSL (`query`), sort (`updated_at`/`created_at`/`name`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`).
|
||||
* @summary List dashboards (v2)
|
||||
*/
|
||||
export const listDashboardsV2 = (
|
||||
params?: ListDashboardsV2Params,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<ListDashboardsV2200>({
|
||||
url: `/api/v2/dashboards`,
|
||||
method: 'GET',
|
||||
params,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getListDashboardsV2QueryKey = (
|
||||
params?: ListDashboardsV2Params,
|
||||
) => {
|
||||
return [`/api/v2/dashboards`, ...(params ? [params] : [])] as const;
|
||||
};
|
||||
|
||||
export const getListDashboardsV2QueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof listDashboardsV2>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
params?: ListDashboardsV2Params,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsV2>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getListDashboardsV2QueryKey(params);
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof listDashboardsV2>>> = ({
|
||||
signal,
|
||||
}) => listDashboardsV2(params, signal);
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsV2>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type ListDashboardsV2QueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof listDashboardsV2>>
|
||||
>;
|
||||
export type ListDashboardsV2QueryError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary List dashboards (v2)
|
||||
*/
|
||||
|
||||
export function useListDashboardsV2<
|
||||
TData = Awaited<ReturnType<typeof listDashboardsV2>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
params?: ListDashboardsV2Params,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsV2>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListDashboardsV2QueryOptions(params, options);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return { ...query, queryKey: queryOptions.queryKey };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary List dashboards (v2)
|
||||
*/
|
||||
export const invalidateListDashboardsV2 = async (
|
||||
queryClient: QueryClient,
|
||||
params?: ListDashboardsV2Params,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getListDashboardsV2QueryKey(params) },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* This endpoint creates a dashboard in the v2 format that follows Perses spec.
|
||||
* @summary Create dashboard (v2)
|
||||
@@ -724,6 +828,85 @@ export const useCreateDashboardV2 = <
|
||||
> => {
|
||||
return useMutation(getCreateDashboardV2MutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* This endpoint deletes a v2-shape dashboard along with its tag relations. Locked dashboards are rejected.
|
||||
* @summary Delete dashboard (v2)
|
||||
*/
|
||||
export const deleteDashboardV2 = (
|
||||
{ id }: DeleteDashboardV2PathParameters,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<string>({
|
||||
url: `/api/v2/dashboards/${id}`,
|
||||
method: 'DELETE',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getDeleteDashboardV2MutationOptions = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: DeleteDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: DeleteDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ['deleteDashboardV2'];
|
||||
const { mutation: mutationOptions } = options
|
||||
? options.mutation &&
|
||||
'mutationKey' in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey } };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>,
|
||||
{ pathParams: DeleteDashboardV2PathParameters }
|
||||
> = (props) => {
|
||||
const { pathParams } = props ?? {};
|
||||
|
||||
return deleteDashboardV2(pathParams);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type DeleteDashboardV2MutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>
|
||||
>;
|
||||
|
||||
export type DeleteDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Delete dashboard (v2)
|
||||
*/
|
||||
export const useDeleteDashboardV2 = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: DeleteDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationResult<
|
||||
Awaited<ReturnType<typeof deleteDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: DeleteDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getDeleteDashboardV2MutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* This endpoint returns a v2-shape dashboard.
|
||||
* @summary Get dashboard (v2)
|
||||
@@ -1181,3 +1364,260 @@ export const useLockDashboardV2 = <
|
||||
> => {
|
||||
return useMutation(getLockDashboardV2MutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* Same as ListDashboardsV2 but personalized for the calling user: each dashboard carries the caller's `pinned` state, and pinned dashboards float to the top of the requested ordering. Supports the same filter DSL, sort, order, and pagination.
|
||||
* @summary List dashboards for the current user (v2)
|
||||
*/
|
||||
export const listDashboardsForUserV2 = (
|
||||
params?: ListDashboardsForUserV2Params,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<ListDashboardsForUserV2200>({
|
||||
url: `/api/v2/users/me/dashboards`,
|
||||
method: 'GET',
|
||||
params,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getListDashboardsForUserV2QueryKey = (
|
||||
params?: ListDashboardsForUserV2Params,
|
||||
) => {
|
||||
return [`/api/v2/users/me/dashboards`, ...(params ? [params] : [])] as const;
|
||||
};
|
||||
|
||||
export const getListDashboardsForUserV2QueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof listDashboardsForUserV2>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
params?: ListDashboardsForUserV2Params,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsForUserV2>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getListDashboardsForUserV2QueryKey(params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof listDashboardsForUserV2>>
|
||||
> = ({ signal }) => listDashboardsForUserV2(params, signal);
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsForUserV2>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type ListDashboardsForUserV2QueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof listDashboardsForUserV2>>
|
||||
>;
|
||||
export type ListDashboardsForUserV2QueryError =
|
||||
ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary List dashboards for the current user (v2)
|
||||
*/
|
||||
|
||||
export function useListDashboardsForUserV2<
|
||||
TData = Awaited<ReturnType<typeof listDashboardsForUserV2>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
params?: ListDashboardsForUserV2Params,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listDashboardsForUserV2>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListDashboardsForUserV2QueryOptions(params, options);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return { ...query, queryKey: queryOptions.queryKey };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary List dashboards for the current user (v2)
|
||||
*/
|
||||
export const invalidateListDashboardsForUserV2 = async (
|
||||
queryClient: QueryClient,
|
||||
params?: ListDashboardsForUserV2Params,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getListDashboardsForUserV2QueryKey(params) },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes the pin for the calling user. Idempotent — unpinning a dashboard that wasn't pinned still returns 204.
|
||||
* @summary Unpin a dashboard for the current user (v2)
|
||||
*/
|
||||
export const unpinDashboardV2 = (
|
||||
{ id }: UnpinDashboardV2PathParameters,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<string>({
|
||||
url: `/api/v2/users/me/dashboards/${id}/pins`,
|
||||
method: 'DELETE',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getUnpinDashboardV2MutationOptions = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: UnpinDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: UnpinDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ['unpinDashboardV2'];
|
||||
const { mutation: mutationOptions } = options
|
||||
? options.mutation &&
|
||||
'mutationKey' in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey } };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>,
|
||||
{ pathParams: UnpinDashboardV2PathParameters }
|
||||
> = (props) => {
|
||||
const { pathParams } = props ?? {};
|
||||
|
||||
return unpinDashboardV2(pathParams);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type UnpinDashboardV2MutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>
|
||||
>;
|
||||
|
||||
export type UnpinDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Unpin a dashboard for the current user (v2)
|
||||
*/
|
||||
export const useUnpinDashboardV2 = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: UnpinDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationResult<
|
||||
Awaited<ReturnType<typeof unpinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: UnpinDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getUnpinDashboardV2MutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* Pins the dashboard for the calling user. A user can pin at most 10 dashboards; pinning when at the limit returns 409. Re-pinning an already-pinned dashboard is a no-op success.
|
||||
* @summary Pin a dashboard for the current user (v2)
|
||||
*/
|
||||
export const pinDashboardV2 = (
|
||||
{ id }: PinDashboardV2PathParameters,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<string>({
|
||||
url: `/api/v2/users/me/dashboards/${id}/pins`,
|
||||
method: 'PUT',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getPinDashboardV2MutationOptions = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: PinDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: PinDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ['pinDashboardV2'];
|
||||
const { mutation: mutationOptions } = options
|
||||
? options.mutation &&
|
||||
'mutationKey' in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey } };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>,
|
||||
{ pathParams: PinDashboardV2PathParameters }
|
||||
> = (props) => {
|
||||
const { pathParams } = props ?? {};
|
||||
|
||||
return pinDashboardV2(pathParams);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PinDashboardV2MutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>
|
||||
>;
|
||||
|
||||
export type PinDashboardV2MutationError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Pin a dashboard for the current user (v2)
|
||||
*/
|
||||
export const usePinDashboardV2 = <
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: PinDashboardV2PathParameters },
|
||||
TContext
|
||||
>;
|
||||
}): UseMutationResult<
|
||||
Awaited<ReturnType<typeof pinDashboardV2>>,
|
||||
TError,
|
||||
{ pathParams: PinDashboardV2PathParameters },
|
||||
TContext
|
||||
> => {
|
||||
return useMutation(getPinDashboardV2MutationOptions(options));
|
||||
};
|
||||
|
||||
@@ -3495,6 +3495,9 @@ export interface TelemetrytypesTelemetryFieldKeyDTO {
|
||||
unit?: string;
|
||||
}
|
||||
|
||||
export enum Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTOSignal {
|
||||
logs = 'logs',
|
||||
}
|
||||
export enum TelemetrytypesSourceDTO {
|
||||
meter = 'meter',
|
||||
}
|
||||
@@ -3550,7 +3553,11 @@ export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTyp
|
||||
* @type array
|
||||
*/
|
||||
selectFields?: TelemetrytypesTelemetryFieldKeyDTO[];
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
/**
|
||||
* @enum logs
|
||||
* @type string
|
||||
*/
|
||||
signal: Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTOSignal;
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
stepInterval?: Querybuildertypesv5StepDTO;
|
||||
}
|
||||
@@ -3616,6 +3623,9 @@ export interface Querybuildertypesv5MetricAggregationDTO {
|
||||
timeAggregation?: MetrictypesTimeAggregationDTO;
|
||||
}
|
||||
|
||||
export enum Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal {
|
||||
metrics = 'metrics',
|
||||
}
|
||||
export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTO {
|
||||
/**
|
||||
* @type array
|
||||
@@ -3668,7 +3678,11 @@ export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTyp
|
||||
* @type array
|
||||
*/
|
||||
selectFields?: TelemetrytypesTelemetryFieldKeyDTO[];
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
/**
|
||||
* @enum metrics
|
||||
* @type string
|
||||
*/
|
||||
signal: Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal;
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
stepInterval?: Querybuildertypesv5StepDTO;
|
||||
}
|
||||
@@ -3684,6 +3698,9 @@ export interface Querybuildertypesv5TraceAggregationDTO {
|
||||
expression?: string;
|
||||
}
|
||||
|
||||
export enum Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal {
|
||||
traces = 'traces',
|
||||
}
|
||||
export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTO {
|
||||
/**
|
||||
* @type array
|
||||
@@ -3736,7 +3753,11 @@ export interface Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTyp
|
||||
* @type array
|
||||
*/
|
||||
selectFields?: TelemetrytypesTelemetryFieldKeyDTO[];
|
||||
signal?: TelemetrytypesSignalDTO;
|
||||
/**
|
||||
* @enum traces
|
||||
* @type string
|
||||
*/
|
||||
signal: Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTOSignal;
|
||||
source?: TelemetrytypesSourceDTO;
|
||||
stepInterval?: Querybuildertypesv5StepDTO;
|
||||
}
|
||||
@@ -4623,7 +4644,7 @@ export interface DashboardtypesDashboardSpecDTO {
|
||||
export enum DashboardtypesDatasourcePluginKindDTO {
|
||||
'signoz/Datasource' = 'signoz/Datasource',
|
||||
}
|
||||
export interface TagtypesPostableTagDTO {
|
||||
export interface TagtypesGettableTagDTO {
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
@@ -4673,7 +4694,7 @@ export interface DashboardtypesGettableDashboardV2DTO {
|
||||
/**
|
||||
* @type array,null
|
||||
*/
|
||||
tags: TagtypesPostableTagDTO[] | null;
|
||||
tags: TagtypesGettableTagDTO[] | null;
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
@@ -4731,6 +4752,157 @@ export interface DashboardtypesJSONPatchOperationDTO {
|
||||
value?: unknown;
|
||||
}
|
||||
|
||||
export enum DashboardtypesListOrderDTO {
|
||||
asc = 'asc',
|
||||
desc = 'desc',
|
||||
}
|
||||
export enum DashboardtypesListSortDTO {
|
||||
updated_at = 'updated_at',
|
||||
created_at = 'created_at',
|
||||
name = 'name',
|
||||
}
|
||||
export interface DashboardtypesListedDashboardV2SpecDTO {
|
||||
display?: CommonDisplayDTO;
|
||||
}
|
||||
|
||||
export interface DashboardtypesListedDashboardForUserV2DTO {
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
*/
|
||||
createdAt?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
createdBy?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
image?: string;
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
locked: boolean;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
orgId: string;
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
pinned: boolean;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
schemaVersion: string;
|
||||
source: DashboardtypesSourceDTO;
|
||||
spec: DashboardtypesListedDashboardV2SpecDTO;
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
tags: TagtypesGettableTagDTO[];
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
*/
|
||||
updatedAt?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
updatedBy?: string;
|
||||
}
|
||||
|
||||
export interface DashboardtypesListableDashboardForUserV2DTO {
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
dashboards: DashboardtypesListedDashboardForUserV2DTO[];
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
tags: TagtypesGettableTagDTO[];
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
*/
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface DashboardtypesListedDashboardV2DTO {
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
*/
|
||||
createdAt?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
createdBy?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
image?: string;
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
locked: boolean;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
orgId: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
schemaVersion: string;
|
||||
source: DashboardtypesSourceDTO;
|
||||
spec: DashboardtypesListedDashboardV2SpecDTO;
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
tags: TagtypesGettableTagDTO[];
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
*/
|
||||
updatedAt?: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
updatedBy?: string;
|
||||
}
|
||||
|
||||
export interface DashboardtypesListableDashboardV2DTO {
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
dashboards: DashboardtypesListedDashboardV2DTO[];
|
||||
/**
|
||||
* @type array
|
||||
*/
|
||||
tags: TagtypesGettableTagDTO[];
|
||||
/**
|
||||
* @type integer
|
||||
* @format int64
|
||||
*/
|
||||
total: number;
|
||||
}
|
||||
|
||||
export enum DashboardtypesPanelPluginKindDTO {
|
||||
'signoz/TimeSeriesPanel' = 'signoz/TimeSeriesPanel',
|
||||
'signoz/BarChartPanel' = 'signoz/BarChartPanel',
|
||||
@@ -4747,6 +4919,17 @@ export type DashboardtypesPatchableDashboardV2DTO =
|
||||
| DashboardtypesJSONPatchOperationDTO[]
|
||||
| null;
|
||||
|
||||
export interface TagtypesPostableTagDTO {
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
key: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface DashboardtypesPostableDashboardV2DTO {
|
||||
/**
|
||||
* @type boolean
|
||||
@@ -9649,6 +9832,40 @@ export type GetUserPreference200 = {
|
||||
export type UpdateUserPreferencePathParameters = {
|
||||
name: string;
|
||||
};
|
||||
export type ListDashboardsV2Params = {
|
||||
/**
|
||||
* @type string
|
||||
* @description undefined
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @description undefined
|
||||
*/
|
||||
sort?: DashboardtypesListSortDTO;
|
||||
/**
|
||||
* @description undefined
|
||||
*/
|
||||
order?: DashboardtypesListOrderDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @description undefined
|
||||
*/
|
||||
limit?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @description undefined
|
||||
*/
|
||||
offset?: number;
|
||||
};
|
||||
|
||||
export type ListDashboardsV2200 = {
|
||||
data: DashboardtypesListableDashboardV2DTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type CreateDashboardV2201 = {
|
||||
data: DashboardtypesGettableDashboardV2DTO;
|
||||
/**
|
||||
@@ -9657,6 +9874,9 @@ export type CreateDashboardV2201 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type DeleteDashboardV2PathParameters = {
|
||||
id: string;
|
||||
};
|
||||
export type GetDashboardV2PathParameters = {
|
||||
id: string;
|
||||
};
|
||||
@@ -10489,6 +10709,46 @@ export type GetMyUser200 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type ListDashboardsForUserV2Params = {
|
||||
/**
|
||||
* @type string
|
||||
* @description undefined
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @description undefined
|
||||
*/
|
||||
sort?: DashboardtypesListSortDTO;
|
||||
/**
|
||||
* @description undefined
|
||||
*/
|
||||
order?: DashboardtypesListOrderDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @description undefined
|
||||
*/
|
||||
limit?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @description undefined
|
||||
*/
|
||||
offset?: number;
|
||||
};
|
||||
|
||||
export type ListDashboardsForUserV2200 = {
|
||||
data: DashboardtypesListableDashboardForUserV2DTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type UnpinDashboardV2PathParameters = {
|
||||
id: string;
|
||||
};
|
||||
export type PinDashboardV2PathParameters = {
|
||||
id: string;
|
||||
};
|
||||
export type GetHosts200 = {
|
||||
data: ZeustypesGettableHostDTO;
|
||||
/**
|
||||
|
||||
@@ -91,6 +91,7 @@ const ROUTES = {
|
||||
AI_ASSISTANT_BASE: '/ai-assistant',
|
||||
AI_ASSISTANT_ICON_PREVIEW: '/ai-assistant-icon-preview',
|
||||
MCP_SERVER: '/settings/mcp-server',
|
||||
LLM_OBSERVABILITY_MODEL_PRICING: '/llm-observability/model-pricing',
|
||||
} as const;
|
||||
|
||||
export default ROUTES;
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
.llm-observability-model-pricing {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding: 24px 32px;
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
|
||||
&__title {
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 4px 0 0;
|
||||
color: var(--bg-vanilla-400);
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
&__actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.page-tabs {
|
||||
.ant-tabs-nav {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.filters-bar {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
|
||||
&__search {
|
||||
flex: 1;
|
||||
max-width: 360px;
|
||||
}
|
||||
|
||||
&__source,
|
||||
&__currency {
|
||||
min-width: 160px;
|
||||
}
|
||||
|
||||
&__add {
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.page-error {
|
||||
padding: 12px 16px;
|
||||
border-radius: 4px;
|
||||
background: rgba(255, 90, 90, 0.08);
|
||||
color: var(--bg-cherry-400);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.page-footer {
|
||||
color: var(--bg-vanilla-400);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.model-costs-table {
|
||||
.model-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
|
||||
&__name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&__canonical-id {
|
||||
color: var(--bg-vanilla-400);
|
||||
font-family: var(--code-font-family, monospace);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.price-cell {
|
||||
font-family: var(--code-font-family, monospace);
|
||||
}
|
||||
|
||||
.extra-buckets {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
|
||||
&__chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
&__key {
|
||||
font-family: var(--code-font-family, monospace);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
&__price {
|
||||
font-family: var(--code-font-family, monospace);
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
.source-badge {
|
||||
margin: 0;
|
||||
|
||||
&--auto {
|
||||
background: rgba(78, 116, 248, 0.12);
|
||||
color: var(--bg-robin-400);
|
||||
border-color: rgba(78, 116, 248, 0.24);
|
||||
}
|
||||
|
||||
&--override {
|
||||
background: rgba(245, 175, 25, 0.12);
|
||||
color: var(--bg-amber-400);
|
||||
border-color: rgba(245, 175, 25, 0.24);
|
||||
}
|
||||
}
|
||||
|
||||
&__row--selected {
|
||||
background: rgba(78, 116, 248, 0.06);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Button, Input, Select, Tabs } from 'antd';
|
||||
import { Plus, Search } from '@signozhq/icons';
|
||||
import { useListLLMPricingRules } from 'api/generated/services/llmpricingrules';
|
||||
|
||||
import ModelCostDrawer from './ModelCostDrawer';
|
||||
import ModelCostsTable from './ModelCostsTable';
|
||||
import { useModelCostDrawer } from './useModelCostDrawer';
|
||||
import { filterRules, type PricingRule, type SourceFilter } from './utils';
|
||||
|
||||
import './LLMObservabilityModelPricing.styles.scss';
|
||||
|
||||
const SOURCE_OPTIONS: { value: SourceFilter; label: string }[] = [
|
||||
{ value: 'all', label: 'Source: All' },
|
||||
{ value: 'auto', label: 'Auto-populated' },
|
||||
{ value: 'override', label: 'User override' },
|
||||
];
|
||||
|
||||
const CURRENCY_OPTIONS = [
|
||||
{ value: 'USD', label: 'USD' },
|
||||
{ value: 'EUR', label: 'EUR', disabled: true },
|
||||
{ value: 'INR', label: 'INR', disabled: true },
|
||||
];
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
function LLMObservabilityModelPricing(): JSX.Element {
|
||||
const [search, setSearch] = useState<string>('');
|
||||
const [source, setSource] = useState<SourceFilter>('all');
|
||||
const [currency, setCurrency] = useState<string>('USD');
|
||||
|
||||
const { data, isLoading, isError } = useListLLMPricingRules({
|
||||
offset: 0,
|
||||
limit: PAGE_SIZE,
|
||||
});
|
||||
|
||||
const rules: PricingRule[] = useMemo(() => data?.data?.items || [], [data]);
|
||||
|
||||
const filteredRules = useMemo(
|
||||
() => filterRules(rules, search, source),
|
||||
[rules, search, source],
|
||||
);
|
||||
|
||||
const drawer = useModelCostDrawer();
|
||||
|
||||
return (
|
||||
<div
|
||||
className="llm-observability-model-pricing"
|
||||
data-testid="llm-observability-model-pricing-page"
|
||||
>
|
||||
<header className="page-header">
|
||||
<div className="page-header__title">
|
||||
<h1>Configuration</h1>
|
||||
<p>Model pricing and cost estimation settings</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<Tabs
|
||||
className="page-tabs"
|
||||
defaultActiveKey="model-costs"
|
||||
items={[
|
||||
{ key: 'model-costs', label: 'Model costs' },
|
||||
{
|
||||
key: 'unpriced-models',
|
||||
label: 'Unpriced models',
|
||||
disabled: true,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="filters-bar">
|
||||
<Input
|
||||
className="filters-bar__search"
|
||||
placeholder="Search by model or provider…"
|
||||
prefix={<Search size={14} />}
|
||||
value={search}
|
||||
onChange={(event): void => setSearch(event.target.value)}
|
||||
data-testid="search-input"
|
||||
allowClear
|
||||
/>
|
||||
<Select<SourceFilter>
|
||||
className="filters-bar__source"
|
||||
value={source}
|
||||
onChange={(value): void => setSource(value)}
|
||||
options={SOURCE_OPTIONS}
|
||||
data-testid="source-select"
|
||||
/>
|
||||
<Select<string>
|
||||
className="filters-bar__currency"
|
||||
value={currency}
|
||||
onChange={(value): void => setCurrency(value)}
|
||||
options={CURRENCY_OPTIONS}
|
||||
data-testid="currency-select"
|
||||
/>
|
||||
<Button
|
||||
type="primary"
|
||||
className="filters-bar__add"
|
||||
icon={<Plus size={14} />}
|
||||
onClick={(): void => drawer.openForAdd()}
|
||||
data-testid="add-model-cost-btn"
|
||||
>
|
||||
Add model cost
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isError && (
|
||||
<div className="page-error" role="alert">
|
||||
Failed to load pricing rules. Please try again.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ModelCostsTable
|
||||
rules={filteredRules}
|
||||
isLoading={isLoading}
|
||||
selectedRuleId={drawer.selectedRuleId}
|
||||
onEdit={drawer.openForEdit}
|
||||
/>
|
||||
|
||||
<footer className="page-footer">
|
||||
Showing {filteredRules.length} model{filteredRules.length === 1 ? '' : 's'}
|
||||
{' · '}All prices per 1M tokens (USD)
|
||||
</footer>
|
||||
|
||||
<ModelCostDrawer
|
||||
isOpen={drawer.isOpen}
|
||||
mode={drawer.mode}
|
||||
draft={drawer.draft}
|
||||
setDraft={drawer.setDraft}
|
||||
onClose={drawer.close}
|
||||
onSave={drawer.save}
|
||||
onDelete={drawer.deleteRule}
|
||||
isSaving={drawer.isSaving}
|
||||
isDeleting={drawer.isDeleting}
|
||||
saveError={drawer.saveError}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LLMObservabilityModelPricing;
|
||||
@@ -0,0 +1,256 @@
|
||||
.model-cost-drawer {
|
||||
.ant-drawer-body {
|
||||
padding: 20px 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
&__title {
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 4px 0 0;
|
||||
color: var(--bg-vanilla-400);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
&__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 12px 16px;
|
||||
border-top: 1px solid var(--bg-slate-300);
|
||||
|
||||
&-right {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.drawer-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
|
||||
label,
|
||||
.field-label {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--bg-vanilla-200);
|
||||
}
|
||||
|
||||
.help {
|
||||
margin: 0;
|
||||
font-size: 11px;
|
||||
}
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
.required {
|
||||
color: var(--bg-cherry-400);
|
||||
}
|
||||
|
||||
.full-width {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.drawer-surface {
|
||||
padding: 14px;
|
||||
border-radius: 6px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border: 1px solid var(--bg-slate-300);
|
||||
|
||||
&__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 10px;
|
||||
|
||||
h4 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--bg-vanilla-300);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.managed-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
.pattern-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
min-height: 28px;
|
||||
}
|
||||
|
||||
.pattern-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
|
||||
&__remove {
|
||||
background: transparent;
|
||||
border: none;
|
||||
padding: 0;
|
||||
margin-left: 2px;
|
||||
cursor: pointer;
|
||||
color: inherit;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
&:hover {
|
||||
color: var(--bg-cherry-400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.pattern-add {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.pattern-test {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 6px;
|
||||
|
||||
&__result {
|
||||
font-size: 12px;
|
||||
|
||||
&--match {
|
||||
color: var(--bg-forest-400);
|
||||
}
|
||||
|
||||
&--no-match {
|
||||
color: var(--bg-cherry-400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.source-radio-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.source-radio {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid transparent;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
|
||||
&__title {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
&__desc {
|
||||
font-size: 12px;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
&.ant-radio-wrapper-checked.source-radio--auto {
|
||||
background: rgba(78, 116, 248, 0.1);
|
||||
border-color: rgba(78, 116, 248, 0.3);
|
||||
}
|
||||
|
||||
&.ant-radio-wrapper-checked.source-radio--override {
|
||||
background: rgba(245, 175, 25, 0.1);
|
||||
border-color: rgba(245, 175, 25, 0.3);
|
||||
}
|
||||
}
|
||||
|
||||
.reset-confirm {
|
||||
margin-top: 12px;
|
||||
padding: 12px;
|
||||
border-radius: 4px;
|
||||
background: rgba(78, 116, 248, 0.06);
|
||||
border: 1px solid rgba(78, 116, 248, 0.2);
|
||||
|
||||
p {
|
||||
margin: 0 0 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
&__actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
.pricing-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.pricing-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
|
||||
.ant-input-number {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.cache-mode-field {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.extras-divider {
|
||||
margin-top: 14px;
|
||||
margin-bottom: 6px;
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--bg-vanilla-400);
|
||||
}
|
||||
|
||||
.cost-preview {
|
||||
&__line {
|
||||
font-family: var(--code-font-family, monospace);
|
||||
font-size: 12px;
|
||||
|
||||
strong {
|
||||
margin-left: 4px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.drawer-error {
|
||||
padding: 10px 12px;
|
||||
border-radius: 4px;
|
||||
background: rgba(255, 90, 90, 0.08);
|
||||
color: var(--bg-cherry-400);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Button, Drawer, Input, InputNumber, Select, Tooltip } from 'antd';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { RadioGroup, RadioGroupItem } from '@signozhq/ui/radio-group';
|
||||
import { Lock, Trash2, X } from '@signozhq/icons';
|
||||
import { LlmpricingruletypesLLMPricingRuleCacheModeDTO as CacheModeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import {
|
||||
CACHE_MODE_OPTIONS,
|
||||
computeCostPreview,
|
||||
matchesAnyPattern,
|
||||
PROVIDER_OPTIONS,
|
||||
validateDraft,
|
||||
type DrawerDraft,
|
||||
type DrawerMode,
|
||||
} from './drawerUtils';
|
||||
import './ModelCostDrawer.styles.scss';
|
||||
|
||||
interface ModelCostDrawerProps {
|
||||
isOpen: boolean;
|
||||
mode: DrawerMode;
|
||||
draft: DrawerDraft;
|
||||
setDraft: (next: DrawerDraft) => void;
|
||||
onClose: () => void;
|
||||
onSave: () => void;
|
||||
onDelete: () => void;
|
||||
isSaving: boolean;
|
||||
isDeleting: boolean;
|
||||
saveError: string | null;
|
||||
}
|
||||
|
||||
function ModelCostDrawer({
|
||||
isOpen,
|
||||
mode,
|
||||
draft,
|
||||
setDraft,
|
||||
onClose,
|
||||
onSave,
|
||||
onDelete,
|
||||
isSaving,
|
||||
isDeleting,
|
||||
saveError,
|
||||
}: ModelCostDrawerProps): JSX.Element {
|
||||
const [patternInput, setPatternInput] = useState<string>('');
|
||||
const [testInput, setTestInput] = useState<string>('');
|
||||
const [showResetConfirm, setShowResetConfirm] = useState<boolean>(false);
|
||||
const isReadOnly = !draft.isOverride;
|
||||
|
||||
const validation = validateDraft(draft, mode);
|
||||
const preview = useMemo(() => computeCostPreview(draft), [draft]);
|
||||
const testMatch = useMemo(
|
||||
() => (testInput ? matchesAnyPattern(testInput, draft.patterns) : null),
|
||||
[testInput, draft.patterns],
|
||||
);
|
||||
|
||||
const update = (patch: Partial<DrawerDraft>): void => {
|
||||
setDraft({ ...draft, ...patch });
|
||||
};
|
||||
|
||||
const updatePricing = (patch: Partial<DrawerDraft['pricing']>): void => {
|
||||
setDraft({ ...draft, pricing: { ...draft.pricing, ...patch } });
|
||||
};
|
||||
|
||||
const addPattern = (): void => {
|
||||
const next = patternInput.trim();
|
||||
if (!next || draft.patterns.includes(next)) {
|
||||
setPatternInput('');
|
||||
return;
|
||||
}
|
||||
update({ patterns: [...draft.patterns, next] });
|
||||
setPatternInput('');
|
||||
};
|
||||
|
||||
const removePattern = (pattern: string): void => {
|
||||
update({ patterns: draft.patterns.filter((p) => p !== pattern) });
|
||||
};
|
||||
|
||||
const handleSourceChange = (value: 'auto' | 'override'): void => {
|
||||
if (value === 'auto' && draft.isOverride) {
|
||||
setShowResetConfirm(true);
|
||||
return;
|
||||
}
|
||||
if (value === 'override' && !draft.isOverride) {
|
||||
update({ isOverride: true });
|
||||
}
|
||||
};
|
||||
|
||||
const confirmReset = (): void => {
|
||||
update({ isOverride: false });
|
||||
setShowResetConfirm(false);
|
||||
};
|
||||
|
||||
const hasCacheBucket =
|
||||
draft.pricing.cacheRead !== null || draft.pricing.cacheWrite !== null;
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
width={520}
|
||||
open={isOpen}
|
||||
onClose={onClose}
|
||||
placement="right"
|
||||
className="model-cost-drawer"
|
||||
destroyOnClose
|
||||
closeIcon={<X size={16} />}
|
||||
title={
|
||||
<div className="model-cost-drawer__title">
|
||||
<h3>{mode === 'edit' ? 'Edit model cost' : 'Add model cost'}</h3>
|
||||
<p>Pricing computes gen_ai.estimated_total_cost at ingest.</p>
|
||||
</div>
|
||||
}
|
||||
footer={
|
||||
<div className="model-cost-drawer__footer">
|
||||
{mode === 'edit' && (
|
||||
<Button
|
||||
danger
|
||||
type="text"
|
||||
icon={<Trash2 size={14} />}
|
||||
onClick={onDelete}
|
||||
loading={isDeleting}
|
||||
data-testid="drawer-delete-btn"
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
)}
|
||||
<div className="model-cost-drawer__footer-right">
|
||||
<Button onClick={onClose} data-testid="drawer-cancel-btn">
|
||||
Cancel
|
||||
</Button>
|
||||
<Tooltip title={validation.ok ? '' : validation.message}>
|
||||
<Button
|
||||
type="primary"
|
||||
onClick={onSave}
|
||||
loading={isSaving}
|
||||
disabled={!validation.ok}
|
||||
data-testid="drawer-save-btn"
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="drawer-section">
|
||||
<label htmlFor="billing-model-id">Billing model ID</label>
|
||||
<Input
|
||||
id="billing-model-id"
|
||||
placeholder="e.g. openai:gpt-4o"
|
||||
value={draft.modelName}
|
||||
disabled={mode === 'edit'}
|
||||
onChange={(e): void => update({ modelName: e.target.value })}
|
||||
data-testid="drawer-model-id-input"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="drawer-section">
|
||||
<label htmlFor="provider-select">Provider</label>
|
||||
<Select
|
||||
id="provider-select"
|
||||
value={draft.provider}
|
||||
onChange={(value): void => update({ provider: value })}
|
||||
options={PROVIDER_OPTIONS}
|
||||
disabled={isReadOnly}
|
||||
className="full-width"
|
||||
data-testid="drawer-provider-select"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="drawer-section">
|
||||
<span className="field-label">
|
||||
Model name patterns <span className="muted">(prefix match)</span>
|
||||
</span>
|
||||
<div className="pattern-chips">
|
||||
{draft.patterns.map((pattern) => (
|
||||
<Badge
|
||||
key={pattern}
|
||||
color="forest"
|
||||
variant="outline"
|
||||
className="pattern-chip"
|
||||
>
|
||||
{pattern}*
|
||||
{!isReadOnly && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Remove pattern ${pattern}`}
|
||||
className="pattern-chip__remove"
|
||||
onClick={(): void => removePattern(pattern)}
|
||||
>
|
||||
<X size={10} />
|
||||
</button>
|
||||
)}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
{!isReadOnly && (
|
||||
<div className="pattern-add">
|
||||
<Input
|
||||
placeholder="Add pattern…"
|
||||
value={patternInput}
|
||||
onChange={(e): void => setPatternInput(e.target.value)}
|
||||
onPressEnter={addPattern}
|
||||
data-testid="drawer-pattern-input"
|
||||
/>
|
||||
<Button onClick={addPattern} data-testid="drawer-pattern-add-btn">
|
||||
+ Add
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<p className="muted help">
|
||||
Each pattern uses prefix matching against gen_ai.request.model.
|
||||
</p>
|
||||
{!isReadOnly && (
|
||||
<div className="pattern-test">
|
||||
<Input
|
||||
placeholder="Test: type a model name…"
|
||||
value={testInput}
|
||||
onChange={(e): void => setTestInput(e.target.value)}
|
||||
data-testid="drawer-pattern-test-input"
|
||||
/>
|
||||
{testInput && (
|
||||
<span
|
||||
className={`pattern-test__result ${
|
||||
testMatch
|
||||
? 'pattern-test__result--match'
|
||||
: 'pattern-test__result--no-match'
|
||||
}`}
|
||||
data-testid="drawer-pattern-test-result"
|
||||
>
|
||||
{testMatch ? `Matched: ${testMatch}*` : 'No matching pattern'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="drawer-section drawer-surface">
|
||||
<div className="drawer-surface__head">
|
||||
<h4>Source</h4>
|
||||
{isReadOnly && (
|
||||
<span className="managed-label">
|
||||
<Lock size={12} />
|
||||
Managed by SigNoz
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<RadioGroup
|
||||
value={draft.isOverride ? 'override' : 'auto'}
|
||||
onChange={(value): void =>
|
||||
handleSourceChange(value as 'auto' | 'override')
|
||||
}
|
||||
className="source-radio-group"
|
||||
>
|
||||
<RadioGroupItem
|
||||
value="auto"
|
||||
className="source-radio source-radio--auto"
|
||||
testId="drawer-source-auto"
|
||||
>
|
||||
<div className="source-radio__title">Auto-populated</div>
|
||||
<div className="source-radio__desc">
|
||||
Default pricing from SigNoz. Updated automatically.
|
||||
</div>
|
||||
</RadioGroupItem>
|
||||
<RadioGroupItem
|
||||
value="override"
|
||||
className="source-radio source-radio--override"
|
||||
testId="drawer-source-override"
|
||||
>
|
||||
<div className="source-radio__title">User override</div>
|
||||
<div className="source-radio__desc">
|
||||
Custom pricing. Takes precedence.
|
||||
</div>
|
||||
</RadioGroupItem>
|
||||
</RadioGroup>
|
||||
{showResetConfirm && (
|
||||
<div
|
||||
className="reset-confirm"
|
||||
role="dialog"
|
||||
aria-label="Reset to default pricing"
|
||||
>
|
||||
<p>Reset to default pricing? Custom values will be discarded.</p>
|
||||
<div className="reset-confirm__actions">
|
||||
<Button
|
||||
onClick={(): void => setShowResetConfirm(false)}
|
||||
data-testid="drawer-reset-keep-btn"
|
||||
>
|
||||
Keep
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
onClick={confirmReset}
|
||||
data-testid="drawer-reset-confirm-btn"
|
||||
>
|
||||
Reset
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="drawer-section drawer-surface">
|
||||
<div className="drawer-surface__head">
|
||||
<h4>Pricing (per 1M tokens, USD)</h4>
|
||||
{isReadOnly && (
|
||||
<span className="managed-label">
|
||||
<Lock size={12} />
|
||||
Read-only
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="pricing-grid">
|
||||
<div className="pricing-field">
|
||||
<label htmlFor="input-cost">
|
||||
Input cost <span className="required">*</span>
|
||||
</label>
|
||||
<InputNumber
|
||||
id="input-cost"
|
||||
min={0}
|
||||
step={0.01}
|
||||
value={draft.pricing.input}
|
||||
onChange={(v): void => updatePricing({ input: Number(v) || 0 })}
|
||||
disabled={isReadOnly}
|
||||
data-testid="drawer-input-cost"
|
||||
/>
|
||||
</div>
|
||||
<div className="pricing-field">
|
||||
<label htmlFor="output-cost">
|
||||
Output cost <span className="required">*</span>
|
||||
</label>
|
||||
<InputNumber
|
||||
id="output-cost"
|
||||
min={0}
|
||||
step={0.01}
|
||||
value={draft.pricing.output}
|
||||
onChange={(v): void => updatePricing({ output: Number(v) || 0 })}
|
||||
disabled={isReadOnly}
|
||||
data-testid="drawer-output-cost"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="extras-divider">Extra pricing buckets</div>
|
||||
<div className="pricing-grid">
|
||||
<div className="pricing-field">
|
||||
<label htmlFor="cache-read">cache_read</label>
|
||||
<InputNumber
|
||||
id="cache-read"
|
||||
min={0}
|
||||
step={0.01}
|
||||
value={draft.pricing.cacheRead ?? undefined}
|
||||
placeholder="—"
|
||||
onChange={(v): void =>
|
||||
updatePricing({ cacheRead: v === null ? null : Number(v) })
|
||||
}
|
||||
disabled={isReadOnly}
|
||||
data-testid="drawer-cache-read-cost"
|
||||
/>
|
||||
</div>
|
||||
<div className="pricing-field">
|
||||
<label htmlFor="cache-write">cache_write</label>
|
||||
<InputNumber
|
||||
id="cache-write"
|
||||
min={0}
|
||||
step={0.01}
|
||||
value={draft.pricing.cacheWrite ?? undefined}
|
||||
placeholder="—"
|
||||
onChange={(v): void =>
|
||||
updatePricing({ cacheWrite: v === null ? null : Number(v) })
|
||||
}
|
||||
disabled={isReadOnly}
|
||||
data-testid="drawer-cache-write-cost"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{hasCacheBucket && (
|
||||
<div className="pricing-field cache-mode-field">
|
||||
<label htmlFor="cache-mode">Cache mode</label>
|
||||
<Select
|
||||
id="cache-mode"
|
||||
value={draft.pricing.cacheMode}
|
||||
options={CACHE_MODE_OPTIONS}
|
||||
onChange={(v): void => updatePricing({ cacheMode: v as CacheModeDTO })}
|
||||
disabled={isReadOnly}
|
||||
className="full-width"
|
||||
data-testid="drawer-cache-mode"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<p className="muted help">Image tokens may be priced differently (v2).</p>
|
||||
</div>
|
||||
|
||||
<div className="drawer-section drawer-surface cost-preview">
|
||||
<div className="drawer-surface__head">
|
||||
<h4>Cost preview</h4>
|
||||
</div>
|
||||
<div className="cost-preview__line">
|
||||
{preview.breakdown.map((part) => part.label).join(' + ')} ={' '}
|
||||
<strong>≈ ${preview.total.toFixed(4)}</strong>
|
||||
</div>
|
||||
<p className="muted help">
|
||||
Write-time attribution. Changes only affect new spans.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{saveError && (
|
||||
<div className="drawer-error" role="alert">
|
||||
{saveError}
|
||||
</div>
|
||||
)}
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
export default ModelCostDrawer;
|
||||
@@ -0,0 +1,146 @@
|
||||
import { Button, Table, type TableColumnsType } from 'antd';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { ChevronDown } from '@signozhq/icons';
|
||||
|
||||
import {
|
||||
formatPricePerMillion,
|
||||
getCanonicalId,
|
||||
getExtraBuckets,
|
||||
getRelativeLastSeen,
|
||||
getSourceLabel,
|
||||
type PricingRule,
|
||||
} from './utils';
|
||||
|
||||
interface ModelCostsTableProps {
|
||||
rules: PricingRule[];
|
||||
isLoading: boolean;
|
||||
selectedRuleId: string | null;
|
||||
onEdit: (rule: PricingRule) => void;
|
||||
}
|
||||
|
||||
function ModelCostsTable({
|
||||
rules,
|
||||
isLoading,
|
||||
selectedRuleId,
|
||||
onEdit,
|
||||
}: ModelCostsTableProps): JSX.Element {
|
||||
const columns: TableColumnsType<PricingRule> = [
|
||||
{
|
||||
title: 'Model',
|
||||
dataIndex: 'modelName',
|
||||
key: 'model',
|
||||
render: (_value, rule): JSX.Element => (
|
||||
<div className="model-cell">
|
||||
<div className="model-cell__name">{rule.modelName}</div>
|
||||
<div className="model-cell__canonical-id">{getCanonicalId(rule)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Provider',
|
||||
dataIndex: 'provider',
|
||||
key: 'provider',
|
||||
},
|
||||
{
|
||||
title: 'Input / 1M',
|
||||
key: 'input',
|
||||
render: (_value, rule): JSX.Element => (
|
||||
<span className="price-cell">
|
||||
{formatPricePerMillion(rule.pricing?.input)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Output / 1M',
|
||||
key: 'output',
|
||||
render: (_value, rule): JSX.Element => (
|
||||
<span className="price-cell">
|
||||
{formatPricePerMillion(rule.pricing?.output)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Extra buckets',
|
||||
key: 'extra-buckets',
|
||||
render: (_value, rule): JSX.Element => {
|
||||
const buckets = getExtraBuckets(rule);
|
||||
if (buckets.length === 0) {
|
||||
return <span className="muted">—</span>;
|
||||
}
|
||||
return (
|
||||
<div className="extra-buckets">
|
||||
{buckets.map((bucket) => (
|
||||
<Badge
|
||||
key={bucket.key}
|
||||
color="vanilla"
|
||||
variant="outline"
|
||||
className="extra-buckets__chip"
|
||||
>
|
||||
<span className="extra-buckets__key">{bucket.key}</span>
|
||||
<span className="extra-buckets__price">
|
||||
{formatPricePerMillion(bucket.pricePerMillion)}
|
||||
</span>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Source',
|
||||
dataIndex: 'isOverride',
|
||||
key: 'source',
|
||||
render: (_value, rule): JSX.Element => {
|
||||
const label = getSourceLabel(rule);
|
||||
return (
|
||||
<Badge
|
||||
color={rule.isOverride ? 'amber' : 'robin'}
|
||||
variant="outline"
|
||||
className="source-badge"
|
||||
data-testid={`source-badge-${rule.id}`}
|
||||
>
|
||||
{label}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Last seen',
|
||||
key: 'last-seen',
|
||||
render: (_value, rule): string => getRelativeLastSeen(rule),
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
key: 'actions',
|
||||
width: 80,
|
||||
render: (_value, rule): JSX.Element => (
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
data-testid={`edit-rule-${rule.id}`}
|
||||
onClick={(): void => onEdit(rule)}
|
||||
>
|
||||
Edit
|
||||
<ChevronDown size={14} />
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Table<PricingRule>
|
||||
className="model-costs-table"
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={rules}
|
||||
loading={isLoading}
|
||||
pagination={false}
|
||||
rowClassName={(row): string =>
|
||||
row.id === selectedRuleId ? 'model-costs-table__row--selected' : ''
|
||||
}
|
||||
data-testid="model-costs-table"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default ModelCostsTable;
|
||||
@@ -0,0 +1,108 @@
|
||||
import {
|
||||
LlmpricingruletypesLLMPricingRuleUnitDTO as UnitDTO,
|
||||
type LlmpricingruletypesLLMPricingRuleDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
|
||||
import LLMObservabilityModelPricing from '../LLMObservabilityModelPricing';
|
||||
|
||||
const ENDPOINT = '*/api/v1/llm_pricing_rules';
|
||||
|
||||
const mockRules: LlmpricingruletypesLLMPricingRuleDTO[] = [
|
||||
{
|
||||
id: 'rule-gpt4o',
|
||||
orgId: 'org-1',
|
||||
modelName: 'gpt-4o',
|
||||
provider: 'OpenAI',
|
||||
modelPattern: ['gpt-4o'],
|
||||
isOverride: false,
|
||||
enabled: true,
|
||||
unit: UnitDTO.per_million_tokens,
|
||||
pricing: { input: 15, output: 60 },
|
||||
},
|
||||
{
|
||||
id: 'rule-llama',
|
||||
orgId: 'org-1',
|
||||
modelName: 'llama-3.1-70b',
|
||||
provider: 'Self-hosted',
|
||||
modelPattern: ['llama-3.1'],
|
||||
isOverride: true,
|
||||
enabled: true,
|
||||
unit: UnitDTO.per_million_tokens,
|
||||
pricing: { input: 0, output: 0 },
|
||||
},
|
||||
];
|
||||
|
||||
describe('LLMObservabilityModelPricing', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.get(ENDPOINT, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: {
|
||||
items: mockRules,
|
||||
limit: 100,
|
||||
offset: 0,
|
||||
total: mockRules.length,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('renders the page header and both rules', async () => {
|
||||
render(<LLMObservabilityModelPricing />);
|
||||
|
||||
await screen.findByText('gpt-4o');
|
||||
expect(screen.getByText('Configuration')).toBeInTheDocument();
|
||||
expect(screen.getByText('llama-3.1-70b')).toBeInTheDocument();
|
||||
expect(screen.getByText('openai:gpt-4o')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('filters rules by the search input', async () => {
|
||||
render(<LLMObservabilityModelPricing />);
|
||||
|
||||
await screen.findByText('gpt-4o');
|
||||
|
||||
fireEvent.change(screen.getByTestId('search-input'), {
|
||||
target: { value: 'llama' },
|
||||
});
|
||||
|
||||
expect(screen.queryByText('gpt-4o')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('llama-3.1-70b')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the drawer in Add mode when the Add button is clicked', async () => {
|
||||
render(<LLMObservabilityModelPricing />);
|
||||
|
||||
await screen.findByText('gpt-4o');
|
||||
fireEvent.click(screen.getByTestId('add-model-cost-btn'));
|
||||
|
||||
const input = (await screen.findByTestId(
|
||||
'drawer-model-id-input',
|
||||
)) as HTMLInputElement;
|
||||
expect(input).toBeInTheDocument();
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
|
||||
it('opens the drawer in Edit mode with prefilled values when a row Edit is clicked', async () => {
|
||||
render(<LLMObservabilityModelPricing />);
|
||||
|
||||
await screen.findByText('gpt-4o');
|
||||
fireEvent.click(screen.getByTestId('edit-rule-rule-gpt4o'));
|
||||
|
||||
const input = (await screen.findByTestId(
|
||||
'drawer-model-id-input',
|
||||
)) as HTMLInputElement;
|
||||
expect(input).toBeInTheDocument();
|
||||
expect(input.value).toBe('gpt-4o');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { useState } from 'react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
|
||||
import { EMPTY_DRAFT, type DrawerDraft } from '../drawerUtils';
|
||||
import ModelCostDrawer from '../ModelCostDrawer';
|
||||
|
||||
interface HarnessProps {
|
||||
initialDraft?: DrawerDraft;
|
||||
mode?: 'add' | 'edit';
|
||||
onSave?: () => void;
|
||||
onDelete?: () => void;
|
||||
}
|
||||
|
||||
function Harness({
|
||||
initialDraft = { ...EMPTY_DRAFT, modelName: 'gpt-4o' },
|
||||
mode = 'add',
|
||||
onSave = jest.fn(),
|
||||
onDelete = jest.fn(),
|
||||
}: HarnessProps): JSX.Element {
|
||||
const [draft, setDraft] = useState<DrawerDraft>(initialDraft);
|
||||
return (
|
||||
<ModelCostDrawer
|
||||
isOpen
|
||||
mode={mode}
|
||||
draft={draft}
|
||||
setDraft={setDraft}
|
||||
onClose={jest.fn()}
|
||||
onSave={onSave}
|
||||
onDelete={onDelete}
|
||||
isSaving={false}
|
||||
isDeleting={false}
|
||||
saveError={null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ModelCostDrawer', () => {
|
||||
it('adds a pattern chip when the user types and presses Enter', () => {
|
||||
render(<Harness />);
|
||||
|
||||
fireEvent.change(screen.getByTestId('drawer-pattern-input'), {
|
||||
target: { value: 'gpt-4o-mini' },
|
||||
});
|
||||
fireEvent.keyDown(screen.getByTestId('drawer-pattern-input'), {
|
||||
key: 'Enter',
|
||||
code: 'Enter',
|
||||
});
|
||||
|
||||
expect(screen.getByText('gpt-4o-mini*')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows a match result when the test input matches an existing pattern', () => {
|
||||
render(
|
||||
<Harness
|
||||
initialDraft={{
|
||||
...EMPTY_DRAFT,
|
||||
modelName: 'gpt-4o',
|
||||
patterns: ['gpt-4o'],
|
||||
isOverride: true,
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByTestId('drawer-pattern-test-input'), {
|
||||
target: { value: 'gpt-4o-2024-08-06' },
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('drawer-pattern-test-result')).toHaveTextContent(
|
||||
/matched: gpt-4o\*/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('shows a no-match result when nothing matches', () => {
|
||||
render(
|
||||
<Harness
|
||||
initialDraft={{
|
||||
...EMPTY_DRAFT,
|
||||
modelName: 'gpt-4o',
|
||||
patterns: ['gpt-4o'],
|
||||
isOverride: true,
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByTestId('drawer-pattern-test-input'), {
|
||||
target: { value: 'claude' },
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('drawer-pattern-test-result')).toHaveTextContent(
|
||||
/no matching pattern/i,
|
||||
);
|
||||
});
|
||||
|
||||
it('shows a reset confirmation when switching from Override to Auto', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(
|
||||
<Harness
|
||||
initialDraft={{
|
||||
...EMPTY_DRAFT,
|
||||
modelName: 'gpt-4o',
|
||||
isOverride: true,
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('drawer-source-auto'));
|
||||
|
||||
expect(screen.getByTestId('drawer-reset-confirm-btn')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('drawer-reset-keep-btn')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides the Delete action in Add mode', () => {
|
||||
render(<Harness mode="add" />);
|
||||
expect(screen.queryByTestId('drawer-delete-btn')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the Delete action in Edit mode', () => {
|
||||
render(
|
||||
<Harness
|
||||
mode="edit"
|
||||
initialDraft={{
|
||||
...EMPTY_DRAFT,
|
||||
id: 'rule-1',
|
||||
modelName: 'gpt-4o',
|
||||
isOverride: true,
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('drawer-delete-btn')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onSave when the Save button is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onSave = jest.fn();
|
||||
render(<Harness onSave={onSave} />);
|
||||
|
||||
await user.click(screen.getByTestId('drawer-save-btn'));
|
||||
expect(onSave).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
import {
|
||||
LlmpricingruletypesLLMPricingRuleCacheModeDTO as CacheModeDTO,
|
||||
LlmpricingruletypesLLMPricingRuleUnitDTO as UnitDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import {
|
||||
buildPricingPayload,
|
||||
buildRulePayload,
|
||||
computeCostPreview,
|
||||
draftFromRule,
|
||||
EMPTY_DRAFT,
|
||||
matchesAnyPattern,
|
||||
validateDraft,
|
||||
type DrawerDraft,
|
||||
} from '../drawerUtils';
|
||||
import type { PricingRule } from '../utils';
|
||||
|
||||
const makeRule = (overrides: Partial<PricingRule> = {}): PricingRule => ({
|
||||
id: 'rule-1',
|
||||
orgId: 'org-1',
|
||||
modelName: 'gpt-4o',
|
||||
provider: 'OpenAI',
|
||||
modelPattern: ['gpt-4o'],
|
||||
isOverride: false,
|
||||
enabled: true,
|
||||
unit: UnitDTO.per_million_tokens,
|
||||
pricing: { input: 15, output: 60 },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('drawerUtils', () => {
|
||||
describe('draftFromRule', () => {
|
||||
it('maps a rule to a draft with cache values when present', () => {
|
||||
const rule = makeRule({
|
||||
pricing: {
|
||||
input: 3,
|
||||
output: 15,
|
||||
cache: {
|
||||
mode: CacheModeDTO.additive,
|
||||
read: 0.3,
|
||||
write: 3.75,
|
||||
},
|
||||
},
|
||||
});
|
||||
const draft = draftFromRule(rule);
|
||||
expect(draft.modelName).toBe('gpt-4o');
|
||||
expect(draft.pricing.input).toBe(3);
|
||||
expect(draft.pricing.cacheRead).toBe(0.3);
|
||||
expect(draft.pricing.cacheWrite).toBe(3.75);
|
||||
expect(draft.pricing.cacheMode).toBe(CacheModeDTO.additive);
|
||||
});
|
||||
|
||||
it('falls back to defaults when cache is missing', () => {
|
||||
const draft = draftFromRule(makeRule());
|
||||
expect(draft.pricing.cacheRead).toBeNull();
|
||||
expect(draft.pricing.cacheWrite).toBeNull();
|
||||
expect(draft.pricing.cacheMode).toBe(CacheModeDTO.unknown);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildPricingPayload', () => {
|
||||
it('omits the cache block when no cache values are set', () => {
|
||||
const payload = buildPricingPayload(EMPTY_DRAFT);
|
||||
expect(payload.cache).toBeUndefined();
|
||||
});
|
||||
|
||||
it('includes only the cache values that are > 0', () => {
|
||||
const draft: DrawerDraft = {
|
||||
...EMPTY_DRAFT,
|
||||
pricing: {
|
||||
...EMPTY_DRAFT.pricing,
|
||||
cacheRead: 1.5,
|
||||
cacheWrite: 0,
|
||||
cacheMode: CacheModeDTO.subtract,
|
||||
},
|
||||
};
|
||||
const payload = buildPricingPayload(draft);
|
||||
expect(payload.cache?.read).toBe(1.5);
|
||||
expect(payload.cache?.write).toBeUndefined();
|
||||
expect(payload.cache?.mode).toBe(CacheModeDTO.subtract);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildRulePayload', () => {
|
||||
it('uses the modelName as a default pattern when no patterns are supplied', () => {
|
||||
const draft: DrawerDraft = {
|
||||
...EMPTY_DRAFT,
|
||||
modelName: 'gpt-4o',
|
||||
patterns: [],
|
||||
provider: 'OpenAI',
|
||||
};
|
||||
const payload = buildRulePayload(draft);
|
||||
expect(payload.modelPattern).toStrictEqual(['gpt-4o']);
|
||||
expect(payload.unit).toBe(UnitDTO.per_million_tokens);
|
||||
expect(payload.enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('omits id and sourceId for an Add draft', () => {
|
||||
const payload = buildRulePayload(EMPTY_DRAFT);
|
||||
expect(payload.id).toBeUndefined();
|
||||
expect(payload.sourceId).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateDraft', () => {
|
||||
it('requires a model name in Add mode', () => {
|
||||
const result = validateDraft(EMPTY_DRAFT, 'add');
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.message).toMatch(/billing model id/i);
|
||||
});
|
||||
|
||||
it('rejects negative pricing', () => {
|
||||
const draft: DrawerDraft = {
|
||||
...EMPTY_DRAFT,
|
||||
modelName: 'gpt-4o',
|
||||
pricing: { ...EMPTY_DRAFT.pricing, input: -1 },
|
||||
};
|
||||
expect(validateDraft(draft, 'add').ok).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts a valid Add draft', () => {
|
||||
const draft: DrawerDraft = {
|
||||
...EMPTY_DRAFT,
|
||||
modelName: 'gpt-4o',
|
||||
pricing: { ...EMPTY_DRAFT.pricing, input: 1, output: 2 },
|
||||
};
|
||||
expect(validateDraft(draft, 'add').ok).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('matchesAnyPattern', () => {
|
||||
it('returns the matching prefix pattern, case-insensitive', () => {
|
||||
expect(matchesAnyPattern('GPT-4o-2024', ['gpt-4o'])).toBe('gpt-4o');
|
||||
});
|
||||
|
||||
it('returns null when nothing matches', () => {
|
||||
expect(matchesAnyPattern('claude', ['gpt-4o'])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('computeCostPreview', () => {
|
||||
it('adds cache buckets when they are set', () => {
|
||||
const draft: DrawerDraft = {
|
||||
...EMPTY_DRAFT,
|
||||
pricing: {
|
||||
...EMPTY_DRAFT.pricing,
|
||||
input: 10,
|
||||
output: 30,
|
||||
cacheRead: 5,
|
||||
},
|
||||
};
|
||||
const preview = computeCostPreview(draft);
|
||||
const labels = preview.breakdown.map((part) => part.label);
|
||||
expect(labels).toContain('2000 input');
|
||||
expect(labels).toContain('500 output');
|
||||
expect(labels).toContain('1000 cache_read');
|
||||
expect(preview.total).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import {
|
||||
LlmpricingruletypesLLMPricingRuleCacheModeDTO as CacheModeDTO,
|
||||
LlmpricingruletypesLLMPricingRuleUnitDTO as UnitDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import {
|
||||
filterRules,
|
||||
formatPricePerMillion,
|
||||
getCanonicalId,
|
||||
getExtraBuckets,
|
||||
getRelativeLastSeen,
|
||||
getSourceLabel,
|
||||
type PricingRule,
|
||||
} from '../utils';
|
||||
|
||||
const makeRule = (overrides: Partial<PricingRule> = {}): PricingRule => ({
|
||||
id: 'rule-1',
|
||||
orgId: 'org-1',
|
||||
modelName: 'gpt-4o',
|
||||
provider: 'OpenAI',
|
||||
modelPattern: ['gpt-4o'],
|
||||
isOverride: false,
|
||||
enabled: true,
|
||||
unit: UnitDTO.per_million_tokens,
|
||||
pricing: { input: 15, output: 60 },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('utils', () => {
|
||||
describe('formatPricePerMillion', () => {
|
||||
it('formats numbers with 2 decimals and dollar prefix', () => {
|
||||
expect(formatPricePerMillion(15)).toBe('$15.00');
|
||||
expect(formatPricePerMillion(0.15)).toBe('$0.15');
|
||||
});
|
||||
|
||||
it('returns em-dash for nullish or NaN', () => {
|
||||
expect(formatPricePerMillion(undefined)).toBe('—');
|
||||
expect(formatPricePerMillion(Number.NaN)).toBe('—');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getExtraBuckets', () => {
|
||||
it('returns an empty array when there is no cache pricing', () => {
|
||||
expect(getExtraBuckets(makeRule())).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('returns only buckets with values > 0', () => {
|
||||
const rule = makeRule({
|
||||
pricing: {
|
||||
input: 3,
|
||||
output: 15,
|
||||
cache: {
|
||||
mode: CacheModeDTO.additive,
|
||||
read: 0.3,
|
||||
write: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
const buckets = getExtraBuckets(rule);
|
||||
expect(buckets).toStrictEqual([{ key: 'cache_read', pricePerMillion: 0.3 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSourceLabel', () => {
|
||||
it('returns "Auto" for non-override and "User override" otherwise', () => {
|
||||
expect(getSourceLabel(makeRule({ isOverride: false }))).toBe('Auto');
|
||||
expect(getSourceLabel(makeRule({ isOverride: true }))).toBe('User override');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCanonicalId', () => {
|
||||
it('lowercases the provider and joins with the model name', () => {
|
||||
expect(getCanonicalId(makeRule({ provider: 'OpenAI' }))).toBe(
|
||||
'openai:gpt-4o',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRelativeLastSeen', () => {
|
||||
it('returns em-dash when no timestamp is present', () => {
|
||||
expect(getRelativeLastSeen(makeRule())).toBe('—');
|
||||
});
|
||||
|
||||
it('formats minutes-old timestamps', () => {
|
||||
const recent = new Date(Date.now() - 5 * 60 * 1000).toISOString();
|
||||
expect(getRelativeLastSeen(makeRule({ updatedAt: recent }))).toMatch(
|
||||
/min ago/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterRules', () => {
|
||||
const auto = makeRule({ id: 'r1', modelName: 'gpt-4o', isOverride: false });
|
||||
const override = makeRule({
|
||||
id: 'r2',
|
||||
modelName: 'llama-3',
|
||||
provider: 'Self-hosted',
|
||||
modelPattern: ['llama-3'],
|
||||
isOverride: true,
|
||||
});
|
||||
|
||||
it('returns everything when no filters are applied', () => {
|
||||
expect(filterRules([auto, override], '', 'all')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('narrows by source = override', () => {
|
||||
expect(filterRules([auto, override], '', 'override')).toStrictEqual([
|
||||
override,
|
||||
]);
|
||||
});
|
||||
|
||||
it('narrows by free-text search across model and provider', () => {
|
||||
expect(filterRules([auto, override], 'self', 'all')).toStrictEqual([
|
||||
override,
|
||||
]);
|
||||
expect(filterRules([auto, override], 'gpt-4', 'all')).toStrictEqual([auto]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import {
|
||||
LlmpricingruletypesLLMPricingRuleCacheModeDTO as CacheModeDTO,
|
||||
LlmpricingruletypesLLMPricingRuleUnitDTO as UnitDTO,
|
||||
type LlmpricingruletypesLLMPricingCacheCostsDTO,
|
||||
type LlmpricingruletypesLLMRulePricingDTO,
|
||||
type LlmpricingruletypesUpdatableLLMPricingRuleDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import type { PricingRule } from './utils';
|
||||
|
||||
export const PROVIDER_OPTIONS = [
|
||||
{ value: 'OpenAI', label: 'OpenAI' },
|
||||
{ value: 'Anthropic', label: 'Anthropic' },
|
||||
{ value: 'Azure OpenAI', label: 'Azure OpenAI' },
|
||||
{ value: 'Google', label: 'Google' },
|
||||
{ value: 'Self-hosted', label: 'Self-hosted' },
|
||||
{ value: 'Other', label: 'Other' },
|
||||
];
|
||||
|
||||
export const CACHE_MODE_OPTIONS = [
|
||||
{
|
||||
value: CacheModeDTO.subtract,
|
||||
label: 'Subtract (OpenAI style)',
|
||||
},
|
||||
{
|
||||
value: CacheModeDTO.additive,
|
||||
label: 'Additive (Anthropic style)',
|
||||
},
|
||||
{
|
||||
value: CacheModeDTO.unknown,
|
||||
label: 'Unknown',
|
||||
},
|
||||
];
|
||||
|
||||
export type DrawerMode = 'add' | 'edit';
|
||||
|
||||
export interface DrawerDraft {
|
||||
id: string | null;
|
||||
sourceId: string | null;
|
||||
modelName: string;
|
||||
provider: string;
|
||||
patterns: string[];
|
||||
isOverride: boolean;
|
||||
pricing: {
|
||||
input: number;
|
||||
output: number;
|
||||
cacheMode: CacheModeDTO;
|
||||
cacheRead: number | null;
|
||||
cacheWrite: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
export const EMPTY_DRAFT: DrawerDraft = {
|
||||
id: null,
|
||||
sourceId: null,
|
||||
modelName: '',
|
||||
provider: 'OpenAI',
|
||||
patterns: [],
|
||||
isOverride: true,
|
||||
pricing: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cacheMode: CacheModeDTO.unknown,
|
||||
cacheRead: null,
|
||||
cacheWrite: null,
|
||||
},
|
||||
};
|
||||
|
||||
export const draftFromRule = (rule: PricingRule): DrawerDraft => ({
|
||||
id: rule.id,
|
||||
sourceId: rule.sourceId ?? null,
|
||||
modelName: rule.modelName,
|
||||
provider: rule.provider || 'OpenAI',
|
||||
patterns: rule.modelPattern || [],
|
||||
isOverride: !!rule.isOverride,
|
||||
pricing: {
|
||||
input: rule.pricing?.input ?? 0,
|
||||
output: rule.pricing?.output ?? 0,
|
||||
cacheMode: rule.pricing?.cache?.mode ?? CacheModeDTO.unknown,
|
||||
cacheRead: rule.pricing?.cache?.read ?? null,
|
||||
cacheWrite: rule.pricing?.cache?.write ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
const hasCacheValue = (value: number | null): boolean =>
|
||||
typeof value === 'number' && value > 0;
|
||||
|
||||
export const buildPricingPayload = (
|
||||
draft: DrawerDraft,
|
||||
): LlmpricingruletypesLLMRulePricingDTO => {
|
||||
const pricing: LlmpricingruletypesLLMRulePricingDTO = {
|
||||
input: draft.pricing.input,
|
||||
output: draft.pricing.output,
|
||||
};
|
||||
if (
|
||||
hasCacheValue(draft.pricing.cacheRead) ||
|
||||
hasCacheValue(draft.pricing.cacheWrite)
|
||||
) {
|
||||
const cache: LlmpricingruletypesLLMPricingCacheCostsDTO = {
|
||||
mode: draft.pricing.cacheMode,
|
||||
};
|
||||
if (hasCacheValue(draft.pricing.cacheRead)) {
|
||||
cache.read = draft.pricing.cacheRead as number;
|
||||
}
|
||||
if (hasCacheValue(draft.pricing.cacheWrite)) {
|
||||
cache.write = draft.pricing.cacheWrite as number;
|
||||
}
|
||||
pricing.cache = cache;
|
||||
}
|
||||
return pricing;
|
||||
};
|
||||
|
||||
export const buildRulePayload = (
|
||||
draft: DrawerDraft,
|
||||
): LlmpricingruletypesUpdatableLLMPricingRuleDTO => ({
|
||||
id: draft.id || undefined,
|
||||
sourceId: draft.sourceId || undefined,
|
||||
modelName: draft.modelName.trim(),
|
||||
provider: draft.provider.trim(),
|
||||
modelPattern:
|
||||
draft.patterns.length > 0 ? draft.patterns : [draft.modelName.trim()],
|
||||
isOverride: draft.isOverride,
|
||||
enabled: true,
|
||||
unit: UnitDTO.per_million_tokens,
|
||||
pricing: buildPricingPayload(draft),
|
||||
});
|
||||
|
||||
export interface ValidationResult {
|
||||
ok: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export const validateDraft = (
|
||||
draft: DrawerDraft,
|
||||
mode: DrawerMode,
|
||||
): ValidationResult => {
|
||||
if (mode === 'add' && !draft.modelName.trim()) {
|
||||
return { ok: false, message: 'Billing model ID is required.' };
|
||||
}
|
||||
if (!draft.provider.trim()) {
|
||||
return { ok: false, message: 'Provider is required.' };
|
||||
}
|
||||
if (draft.pricing.input < 0 || draft.pricing.output < 0) {
|
||||
return { ok: false, message: 'Pricing values must be non-negative.' };
|
||||
}
|
||||
return { ok: true };
|
||||
};
|
||||
|
||||
export const matchesAnyPattern = (
|
||||
candidate: string,
|
||||
patterns: string[],
|
||||
): string | null => {
|
||||
const lowered = candidate.toLowerCase();
|
||||
const match = patterns.find((pattern) =>
|
||||
lowered.startsWith(pattern.toLowerCase()),
|
||||
);
|
||||
return match || null;
|
||||
};
|
||||
|
||||
const EXAMPLE_INPUT_TOKENS = 2000;
|
||||
const EXAMPLE_OUTPUT_TOKENS = 500;
|
||||
const EXAMPLE_CACHE_TOKENS = 1000;
|
||||
const PER_MILLION = 1_000_000;
|
||||
|
||||
export interface CostPreviewParts {
|
||||
total: number;
|
||||
breakdown: { label: string; cost: number }[];
|
||||
}
|
||||
|
||||
export const computeCostPreview = (draft: DrawerDraft): CostPreviewParts => {
|
||||
const breakdown: { label: string; cost: number }[] = [];
|
||||
const inputCost = (EXAMPLE_INPUT_TOKENS / PER_MILLION) * draft.pricing.input;
|
||||
const outputCost =
|
||||
(EXAMPLE_OUTPUT_TOKENS / PER_MILLION) * draft.pricing.output;
|
||||
breakdown.push({ label: `${EXAMPLE_INPUT_TOKENS} input`, cost: inputCost });
|
||||
breakdown.push({ label: `${EXAMPLE_OUTPUT_TOKENS} output`, cost: outputCost });
|
||||
let total = inputCost + outputCost;
|
||||
if (hasCacheValue(draft.pricing.cacheRead)) {
|
||||
const cost =
|
||||
(EXAMPLE_CACHE_TOKENS / PER_MILLION) * (draft.pricing.cacheRead as number);
|
||||
breakdown.push({ label: `${EXAMPLE_CACHE_TOKENS} cache_read`, cost });
|
||||
total += cost;
|
||||
}
|
||||
if (hasCacheValue(draft.pricing.cacheWrite)) {
|
||||
const cost =
|
||||
(EXAMPLE_CACHE_TOKENS / PER_MILLION) * (draft.pricing.cacheWrite as number);
|
||||
breakdown.push({ label: `${EXAMPLE_CACHE_TOKENS} cache_write`, cost });
|
||||
total += cost;
|
||||
}
|
||||
return { total, breakdown };
|
||||
};
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import {
|
||||
getListLLMPricingRulesQueryKey,
|
||||
useCreateOrUpdateLLMPricingRules,
|
||||
useDeleteLLMPricingRule,
|
||||
} from 'api/generated/services/llmpricingrules';
|
||||
|
||||
import {
|
||||
buildRulePayload,
|
||||
draftFromRule,
|
||||
EMPTY_DRAFT,
|
||||
type DrawerDraft,
|
||||
type DrawerMode,
|
||||
} from './drawerUtils';
|
||||
import type { PricingRule } from './utils';
|
||||
|
||||
interface UseModelCostDrawerResult {
|
||||
isOpen: boolean;
|
||||
mode: DrawerMode;
|
||||
draft: DrawerDraft;
|
||||
setDraft: (next: DrawerDraft) => void;
|
||||
openForAdd: (prefillModelName?: string) => void;
|
||||
openForEdit: (rule: PricingRule) => void;
|
||||
close: () => void;
|
||||
save: () => Promise<void>;
|
||||
deleteRule: () => Promise<void>;
|
||||
isSaving: boolean;
|
||||
isDeleting: boolean;
|
||||
saveError: string | null;
|
||||
selectedRuleId: string | null;
|
||||
}
|
||||
|
||||
export function useModelCostDrawer(): UseModelCostDrawerResult {
|
||||
const queryClient = useQueryClient();
|
||||
const [isOpen, setIsOpen] = useState<boolean>(false);
|
||||
const [mode, setMode] = useState<DrawerMode>('add');
|
||||
const [draft, setDraft] = useState<DrawerDraft>(EMPTY_DRAFT);
|
||||
const [selectedRuleId, setSelectedRuleId] = useState<string | null>(null);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
|
||||
const { mutateAsync: createOrUpdate, isLoading: isSaving } =
|
||||
useCreateOrUpdateLLMPricingRules();
|
||||
const { mutateAsync: deleteRuleApi, isLoading: isDeleting } =
|
||||
useDeleteLLMPricingRule();
|
||||
|
||||
const invalidateList = useCallback(async (): Promise<void> => {
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: getListLLMPricingRulesQueryKey(),
|
||||
});
|
||||
}, [queryClient]);
|
||||
|
||||
const openForAdd = useCallback((prefillModelName?: string): void => {
|
||||
setMode('add');
|
||||
setDraft({
|
||||
...EMPTY_DRAFT,
|
||||
modelName: prefillModelName || '',
|
||||
patterns: prefillModelName ? [prefillModelName] : [],
|
||||
});
|
||||
setSelectedRuleId(null);
|
||||
setSaveError(null);
|
||||
setIsOpen(true);
|
||||
}, []);
|
||||
|
||||
const openForEdit = useCallback((rule: PricingRule): void => {
|
||||
setMode('edit');
|
||||
setDraft(draftFromRule(rule));
|
||||
setSelectedRuleId(rule.id);
|
||||
setSaveError(null);
|
||||
setIsOpen(true);
|
||||
}, []);
|
||||
|
||||
const close = useCallback((): void => {
|
||||
setIsOpen(false);
|
||||
setSelectedRuleId(null);
|
||||
setSaveError(null);
|
||||
}, []);
|
||||
|
||||
const save = useCallback(async (): Promise<void> => {
|
||||
setSaveError(null);
|
||||
try {
|
||||
await createOrUpdate({
|
||||
data: { rules: [buildRulePayload(draft)] },
|
||||
});
|
||||
await invalidateList();
|
||||
setIsOpen(false);
|
||||
setSelectedRuleId(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Save failed';
|
||||
setSaveError(message);
|
||||
}
|
||||
}, [createOrUpdate, draft, invalidateList]);
|
||||
|
||||
const deleteRule = useCallback(async (): Promise<void> => {
|
||||
if (!draft.id) {
|
||||
return;
|
||||
}
|
||||
setSaveError(null);
|
||||
try {
|
||||
await deleteRuleApi({ pathParams: { id: draft.id } });
|
||||
await invalidateList();
|
||||
setIsOpen(false);
|
||||
setSelectedRuleId(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Delete failed';
|
||||
setSaveError(message);
|
||||
}
|
||||
}, [deleteRuleApi, draft.id, invalidateList]);
|
||||
|
||||
return {
|
||||
isOpen,
|
||||
mode,
|
||||
draft,
|
||||
setDraft,
|
||||
openForAdd,
|
||||
openForEdit,
|
||||
close,
|
||||
save,
|
||||
deleteRule,
|
||||
isSaving,
|
||||
isDeleting,
|
||||
saveError,
|
||||
selectedRuleId,
|
||||
};
|
||||
}
|
||||
101
frontend/src/container/LLMObservabilityModelPricing/utils.ts
Normal file
101
frontend/src/container/LLMObservabilityModelPricing/utils.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import type { LlmpricingruletypesLLMPricingRuleDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export type PricingRule = LlmpricingruletypesLLMPricingRuleDTO;
|
||||
|
||||
export type SourceFilter = 'all' | 'auto' | 'override';
|
||||
|
||||
export interface ExtraBucket {
|
||||
key: string;
|
||||
pricePerMillion: number;
|
||||
}
|
||||
|
||||
export const formatPricePerMillion = (value: number | undefined): string => {
|
||||
if (value === undefined || value === null || Number.isNaN(value)) {
|
||||
return '—';
|
||||
}
|
||||
return `$${value.toFixed(2)}`;
|
||||
};
|
||||
|
||||
export const getExtraBuckets = (rule: PricingRule): ExtraBucket[] => {
|
||||
const cache = rule.pricing?.cache;
|
||||
if (!cache) {
|
||||
return [];
|
||||
}
|
||||
const buckets: ExtraBucket[] = [];
|
||||
if (typeof cache.read === 'number' && cache.read > 0) {
|
||||
buckets.push({ key: 'cache_read', pricePerMillion: cache.read });
|
||||
}
|
||||
if (typeof cache.write === 'number' && cache.write > 0) {
|
||||
buckets.push({ key: 'cache_write', pricePerMillion: cache.write });
|
||||
}
|
||||
return buckets;
|
||||
};
|
||||
|
||||
export const getSourceLabel = (rule: PricingRule): 'Auto' | 'User override' =>
|
||||
rule.isOverride ? 'User override' : 'Auto';
|
||||
|
||||
const MINUTE = 60;
|
||||
const HOUR = 60 * MINUTE;
|
||||
const DAY = 24 * HOUR;
|
||||
const MONTH = 30 * DAY;
|
||||
const YEAR = 365 * DAY;
|
||||
|
||||
export const getRelativeLastSeen = (rule: PricingRule): string => {
|
||||
const ts = rule.updatedAt || rule.syncedAt || rule.createdAt;
|
||||
if (!ts) {
|
||||
return '—';
|
||||
}
|
||||
const now = Date.now();
|
||||
const target = new Date(ts).getTime();
|
||||
if (Number.isNaN(target)) {
|
||||
return '—';
|
||||
}
|
||||
const seconds = Math.max(0, Math.round((now - target) / 1000));
|
||||
if (seconds < MINUTE) {
|
||||
return 'just now';
|
||||
}
|
||||
if (seconds < HOUR) {
|
||||
return `${Math.floor(seconds / MINUTE)} min ago`;
|
||||
}
|
||||
if (seconds < DAY) {
|
||||
return `${Math.floor(seconds / HOUR)} hr ago`;
|
||||
}
|
||||
if (seconds < MONTH) {
|
||||
return `${Math.floor(seconds / DAY)} days ago`;
|
||||
}
|
||||
if (seconds < YEAR) {
|
||||
return `${Math.floor(seconds / MONTH)} mo ago`;
|
||||
}
|
||||
return `${Math.floor(seconds / YEAR)} yr ago`;
|
||||
};
|
||||
|
||||
const lc = (value: string): string => value.toLowerCase();
|
||||
|
||||
export const filterRules = (
|
||||
rules: PricingRule[],
|
||||
search: string,
|
||||
source: SourceFilter,
|
||||
): PricingRule[] => {
|
||||
const normalized = lc(search.trim());
|
||||
return rules.filter((rule) => {
|
||||
if (source === 'auto' && rule.isOverride) {
|
||||
return false;
|
||||
}
|
||||
if (source === 'override' && !rule.isOverride) {
|
||||
return false;
|
||||
}
|
||||
if (!normalized) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
lc(rule.modelName).includes(normalized) ||
|
||||
lc(rule.provider).includes(normalized) ||
|
||||
(rule.modelPattern || []).some((pattern) => lc(pattern).includes(normalized))
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const getCanonicalId = (rule: PricingRule): string => {
|
||||
const provider = rule.provider?.trim() || 'unknown';
|
||||
return `${lc(provider)}:${rule.modelName}`;
|
||||
};
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
Building2,
|
||||
ChartArea,
|
||||
Cloudy,
|
||||
Coins,
|
||||
DraftingCompass,
|
||||
FileKey2,
|
||||
Github,
|
||||
@@ -365,6 +366,13 @@ export const settingsNavSections: SettingsNavSection[] = [
|
||||
isEnabled: false,
|
||||
itemKey: 'mcp-server',
|
||||
},
|
||||
{
|
||||
key: ROUTES.LLM_OBSERVABILITY_MODEL_PRICING,
|
||||
label: 'Model Pricing',
|
||||
icon: <Coins size={16} />,
|
||||
isEnabled: true,
|
||||
itemKey: 'llm-observability-model-pricing',
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import LLMObservabilityModelPricing from 'container/LLMObservabilityModelPricing/LLMObservabilityModelPricing';
|
||||
|
||||
function LLMObservabilityModelPricingPage(): JSX.Element {
|
||||
return <LLMObservabilityModelPricing />;
|
||||
}
|
||||
|
||||
export default LLMObservabilityModelPricingPage;
|
||||
@@ -136,4 +136,5 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
|
||||
AI_ASSISTANT_ICON_PREVIEW: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
MCP_SERVER: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
AI_ASSISTANT_BASE: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
LLM_OBSERVABILITY_MODEL_PRICING: ['ADMIN', 'EDITOR', 'VIEWER'],
|
||||
};
|
||||
|
||||
@@ -14,6 +14,42 @@ import (
|
||||
)
|
||||
|
||||
func (provider *provider) addDashboardRoutes(router *mux.Router) error {
|
||||
if err := router.Handle("/api/v2/dashboards", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.ListV2), handler.OpenAPIDef{
|
||||
ID: "ListDashboardsV2",
|
||||
Tags: []string{"dashboard"},
|
||||
Summary: "List dashboards (v2)",
|
||||
Description: "Returns a page of v2-shape dashboards for the org. This is the pure, user-independent list — it carries no pin state. Use ListDashboardsForUserV2 for the personalized, pin-aware list. Supports a filter DSL (`query`), sort (`updated_at`/`created_at`/`name`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`).",
|
||||
Request: nil,
|
||||
RequestQuery: new(dashboardtypes.ListDashboardsV2Params),
|
||||
RequestContentType: "",
|
||||
Response: new(dashboardtypes.ListableDashboardV2),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
})).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/users/me/dashboards", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.ListForUserV2), handler.OpenAPIDef{
|
||||
ID: "ListDashboardsForUserV2",
|
||||
Tags: []string{"dashboard"},
|
||||
Summary: "List dashboards for the current user (v2)",
|
||||
Description: "Same as ListDashboardsV2 but personalized for the calling user: each dashboard carries the caller's `pinned` state, and pinned dashboards float to the top of the requested ordering. Supports the same filter DSL, sort, order, and pagination.",
|
||||
Request: nil,
|
||||
RequestQuery: new(dashboardtypes.ListDashboardsV2Params),
|
||||
RequestContentType: "",
|
||||
Response: new(dashboardtypes.ListableDashboardForUserV2),
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusOK,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
})).Methods(http.MethodGet).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/dashboards", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.CreateV2), handler.OpenAPIDef{
|
||||
ID: "CreateDashboardV2",
|
||||
Tags: []string{"dashboard"},
|
||||
@@ -89,6 +125,23 @@ func (provider *provider) addDashboardRoutes(router *mux.Router) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/dashboards/{id}", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.DeleteV2), handler.OpenAPIDef{
|
||||
ID: "DeleteDashboardV2",
|
||||
Tags: []string{"dashboard"},
|
||||
Summary: "Delete dashboard (v2)",
|
||||
Description: "This endpoint deletes a v2-shape dashboard along with its tag relations. Locked dashboards are rejected.",
|
||||
Request: nil,
|
||||
RequestContentType: "",
|
||||
Response: nil,
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleEditor),
|
||||
})).Methods(http.MethodDelete).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/dashboards/{id}/lock", handler.New(provider.authzMiddleware.EditAccess(provider.dashboardHandler.LockV2), handler.OpenAPIDef{
|
||||
ID: "LockDashboardV2",
|
||||
Tags: []string{"dashboard"},
|
||||
@@ -123,6 +176,42 @@ func (provider *provider) addDashboardRoutes(router *mux.Router) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// ViewAccess: pinning only mutates the calling user's pin list, not the
|
||||
// dashboard itself — anyone who can view a dashboard can bookmark it.
|
||||
if err := router.Handle("/api/v2/users/me/dashboards/{id}/pins", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.PinV2), handler.OpenAPIDef{
|
||||
ID: "PinDashboardV2",
|
||||
Tags: []string{"dashboard"},
|
||||
Summary: "Pin a dashboard for the current user (v2)",
|
||||
Description: "Pins the dashboard for the calling user. A user can pin at most 10 dashboards; pinning when at the limit returns 409. Re-pinning an already-pinned dashboard is a no-op success.",
|
||||
Request: nil,
|
||||
RequestContentType: "",
|
||||
Response: nil,
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound, http.StatusConflict},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
})).Methods(http.MethodPut).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v2/users/me/dashboards/{id}/pins", handler.New(provider.authzMiddleware.ViewAccess(provider.dashboardHandler.UnpinV2), handler.OpenAPIDef{
|
||||
ID: "UnpinDashboardV2",
|
||||
Tags: []string{"dashboard"},
|
||||
Summary: "Unpin a dashboard for the current user (v2)",
|
||||
Description: "Removes the pin for the calling user. Idempotent — unpinning a dashboard that wasn't pinned still returns 204.",
|
||||
Request: nil,
|
||||
RequestContentType: "",
|
||||
Response: nil,
|
||||
ResponseContentType: "application/json",
|
||||
SuccessStatusCode: http.StatusNoContent,
|
||||
ErrorStatusCodes: []int{http.StatusBadRequest},
|
||||
Deprecated: false,
|
||||
SecuritySchemes: newSecuritySchemes(types.RoleViewer),
|
||||
})).Methods(http.MethodDelete).GetError(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := router.Handle("/api/v1/dashboards/{id}/public", handler.New(provider.authzMiddleware.AdminAccess(provider.dashboardHandler.CreatePublic), handler.OpenAPIDef{
|
||||
ID: "CreatePublicDashboard",
|
||||
Tags: []string{"dashboard"},
|
||||
|
||||
@@ -61,11 +61,23 @@ type Module interface {
|
||||
|
||||
GetV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.DashboardV2, error)
|
||||
|
||||
ListV2(ctx context.Context, orgID valuer.UUID, params *dashboardtypes.ListDashboardsV2Params) (*dashboardtypes.ListableDashboardV2, error)
|
||||
|
||||
ListForUserV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, params *dashboardtypes.ListDashboardsV2Params) (*dashboardtypes.ListableDashboardForUserV2, error)
|
||||
|
||||
UpdateV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, updatable dashboardtypes.UpdatableDashboardV2) (*dashboardtypes.DashboardV2, error)
|
||||
|
||||
LockUnlockV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, isAdmin bool, lock bool) error
|
||||
|
||||
PatchV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, patch dashboardtypes.PatchableDashboardV2) (*dashboardtypes.DashboardV2, error)
|
||||
|
||||
PinV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, id valuer.UUID) error
|
||||
|
||||
UnpinV2(ctx context.Context, userID valuer.UUID, id valuer.UUID) error
|
||||
|
||||
DeleteV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) error
|
||||
|
||||
DeletePreferencesForUser(ctx context.Context, userID valuer.UUID) error
|
||||
}
|
||||
|
||||
type Handler interface {
|
||||
@@ -96,6 +108,10 @@ type Handler interface {
|
||||
|
||||
GetV2(http.ResponseWriter, *http.Request)
|
||||
|
||||
ListV2(http.ResponseWriter, *http.Request)
|
||||
|
||||
ListForUserV2(http.ResponseWriter, *http.Request)
|
||||
|
||||
UpdateV2(http.ResponseWriter, *http.Request)
|
||||
|
||||
LockV2(http.ResponseWriter, *http.Request)
|
||||
@@ -103,4 +119,10 @@ type Handler interface {
|
||||
UnlockV2(http.ResponseWriter, *http.Request)
|
||||
|
||||
PatchV2(http.ResponseWriter, *http.Request)
|
||||
|
||||
PinV2(http.ResponseWriter, *http.Request)
|
||||
|
||||
UnpinV2(http.ResponseWriter, *http.Request)
|
||||
|
||||
DeleteV2(http.ResponseWriter, *http.Request)
|
||||
}
|
||||
|
||||
40
pkg/modules/dashboard/impldashboard/listfilter.go
Normal file
40
pkg/modules/dashboard/impldashboard/listfilter.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package impldashboard
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/sqlstore"
|
||||
"github.com/SigNoz/signoz/pkg/types/dashboardtypes"
|
||||
)
|
||||
|
||||
type Compiled struct {
|
||||
SQL string
|
||||
Args []any
|
||||
}
|
||||
|
||||
func Compile(query string, formatter sqlstore.SQLFormatter) (*Compiled, error) {
|
||||
if len(query) == 0 {
|
||||
return nil, nil //nolint:nilnil
|
||||
}
|
||||
|
||||
queryVisitor := newVisitor(formatter)
|
||||
sql, args, syntaxErrs := queryVisitor.compile(query)
|
||||
|
||||
if len(syntaxErrs) > 0 {
|
||||
return nil, errors.NewInvalidInputf(dashboardtypes.ErrCodeDashboardListFilterInvalid,
|
||||
"invalid filter query: %s", strings.Join(syntaxErrs, "; "))
|
||||
}
|
||||
if len(queryVisitor.errors) > 0 {
|
||||
return nil, errors.NewInvalidInputf(dashboardtypes.ErrCodeDashboardListFilterInvalid,
|
||||
"invalid filter query: %s", strings.Join(queryVisitor.errors, "; "))
|
||||
}
|
||||
if sql == "" {
|
||||
return nil, nil //nolint:nilnil
|
||||
}
|
||||
|
||||
return &Compiled{
|
||||
SQL: sql,
|
||||
Args: args,
|
||||
}, nil
|
||||
}
|
||||
526
pkg/modules/dashboard/impldashboard/listfilter_test.go
Normal file
526
pkg/modules/dashboard/impldashboard/listfilter_test.go
Normal file
@@ -0,0 +1,526 @@
|
||||
package impldashboard
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/sqlstore"
|
||||
"github.com/SigNoz/signoz/pkg/sqlstore/sqlstoretest"
|
||||
"github.com/SigNoz/signoz/pkg/types/dashboardtypes"
|
||||
)
|
||||
|
||||
type compileCase struct {
|
||||
subtestName string
|
||||
dslQueryToCompile string
|
||||
nilExpected bool
|
||||
expectedSQL string
|
||||
expectedArgs []any
|
||||
expectedErrShouldContain string
|
||||
}
|
||||
|
||||
// kindArg is the tag_relation.kind value bound into every tag EXISTS subquery
|
||||
// (stored double-encoded, hence the embedded quotes). It leads each tag
|
||||
// predicate's args, ahead of the tag key.
|
||||
const kindArg = `"dashboard"`
|
||||
|
||||
func runCompileCases(t *testing.T, cases []compileCase) {
|
||||
t.Helper()
|
||||
for _, c := range cases {
|
||||
t.Run(c.subtestName, func(t *testing.T) {
|
||||
out, err := Compile(c.dslQueryToCompile, formatter(t))
|
||||
|
||||
if c.expectedErrShouldContain != "" {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, strings.ToLower(err.Error()), strings.ToLower(c.expectedErrShouldContain))
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
if c.nilExpected {
|
||||
assert.Nil(t, out)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, out)
|
||||
|
||||
if c.expectedSQL != "" {
|
||||
assert.Equal(t, normalizeSQL(c.expectedSQL), normalizeSQL(out.SQL))
|
||||
}
|
||||
if c.expectedArgs != nil {
|
||||
require.Len(t, out.Args, len(c.expectedArgs))
|
||||
for i, want := range c.expectedArgs {
|
||||
// time.Time values can carry semantically-equal instants
|
||||
// in different *Location representations (UTC vs Local vs
|
||||
// FixedZone). Compare via .Equal() instead of DeepEqual.
|
||||
if wantT, ok := want.(time.Time); ok {
|
||||
gotT, ok := out.Args[i].(time.Time)
|
||||
require.True(t, ok, "arg[%d]: want time.Time, got %T", i, out.Args[i])
|
||||
assert.True(t, wantT.Equal(gotT), "arg[%d]: want %s, got %s", i, wantT, gotT)
|
||||
continue
|
||||
}
|
||||
assert.Equal(t, want, out.Args[i], "arg[%d]", i)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompile_Empty(t *testing.T) {
|
||||
runCompileCases(t, []compileCase{
|
||||
{subtestName: "empty query yields nil", dslQueryToCompile: "", nilExpected: true},
|
||||
})
|
||||
}
|
||||
|
||||
func TestCompile_Name(t *testing.T) {
|
||||
runCompileCases(t, []compileCase{
|
||||
{
|
||||
subtestName: "name =",
|
||||
dslQueryToCompile: `name = 'overview'`,
|
||||
expectedSQL: `json_extract("dashboard"."data", '$.spec.display.name') = ?`,
|
||||
expectedArgs: []any{"overview"},
|
||||
},
|
||||
{
|
||||
// QUOTED_TEXT in the grammar covers both '…' and "…" — visitor
|
||||
// strips whichever quote pair surrounds the value.
|
||||
subtestName: "name = with double-quoted value",
|
||||
dslQueryToCompile: `name = "something"`,
|
||||
expectedSQL: `json_extract("dashboard"."data", '$.spec.display.name') = ?`,
|
||||
expectedArgs: []any{"something"},
|
||||
},
|
||||
{
|
||||
subtestName: "name CONTAINS",
|
||||
dslQueryToCompile: `name CONTAINS 'overview'`,
|
||||
expectedSQL: `json_extract("dashboard"."data", '$.spec.display.name') LIKE ? ESCAPE '\'`,
|
||||
expectedArgs: []any{"%overview%"},
|
||||
},
|
||||
{
|
||||
subtestName: "name ILIKE — emitted as LOWER(col) LIKE LOWER(?) for dialect parity",
|
||||
dslQueryToCompile: `name ILIKE 'Prod%'`,
|
||||
expectedSQL: `lower(json_extract("dashboard"."data", '$.spec.display.name')) LIKE LOWER(?) ESCAPE '\'`,
|
||||
expectedArgs: []any{"Prod%"},
|
||||
},
|
||||
{
|
||||
subtestName: "CONTAINS escapes % in user input",
|
||||
dslQueryToCompile: `name CONTAINS '50%'`,
|
||||
expectedSQL: `json_extract("dashboard"."data", '$.spec.display.name') LIKE ? ESCAPE '\'`,
|
||||
expectedArgs: []any{`%50\%%`},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestCompile_CreatedByLocked(t *testing.T) {
|
||||
runCompileCases(t, []compileCase{
|
||||
{
|
||||
subtestName: "created_by LIKE",
|
||||
dslQueryToCompile: `created_by LIKE '%@signoz.io'`,
|
||||
expectedSQL: `dashboard.created_by LIKE ? ESCAPE '\'`,
|
||||
expectedArgs: []any{"%@signoz.io"},
|
||||
},
|
||||
{
|
||||
subtestName: "locked = true",
|
||||
dslQueryToCompile: `locked = true`,
|
||||
expectedSQL: `dashboard.locked = ?`,
|
||||
expectedArgs: []any{true},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestCompile_Timestamps(t *testing.T) {
|
||||
ist := time.FixedZone("+05:30", 5*60*60+30*60)
|
||||
runCompileCases(t, []compileCase{
|
||||
{
|
||||
subtestName: "created_at >= RFC3339",
|
||||
dslQueryToCompile: `created_at >= '2026-03-10T00:00:00Z'`,
|
||||
expectedSQL: `dashboard.created_at >= ?`,
|
||||
expectedArgs: []any{time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)},
|
||||
},
|
||||
{
|
||||
subtestName: "updated_at BETWEEN",
|
||||
dslQueryToCompile: `updated_at BETWEEN '2026-03-10T00:00:00Z' AND '2026-03-20T00:00:00Z'`,
|
||||
expectedSQL: `dashboard.updated_at BETWEEN ? AND ?`,
|
||||
expectedArgs: []any{
|
||||
time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC),
|
||||
time.Date(2026, 3, 20, 0, 0, 0, 0, time.UTC),
|
||||
},
|
||||
},
|
||||
{
|
||||
subtestName: "created_at >= IST timestamp",
|
||||
dslQueryToCompile: `created_at >= '2026-03-10T05:30:00+05:30'`,
|
||||
expectedSQL: `dashboard.created_at >= ?`,
|
||||
expectedArgs: []any{time.Date(2026, 3, 10, 5, 30, 0, 0, ist)},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Tag operators wrap each predicate in EXISTS / NOT EXISTS. Any non-reserved
|
||||
// key is a tag key — `team = 'pulse'` matches a tag with key=team value=pulse,
|
||||
// `tag = 'prod'` matches a tag with key=tag value=prod, and so on.
|
||||
func TestCompile_Tag(t *testing.T) {
|
||||
runCompileCases(t, []compileCase{
|
||||
{
|
||||
subtestName: "team = wraps in EXISTS",
|
||||
dslQueryToCompile: `team = 'pulse'`,
|
||||
expectedSQL: `
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value = ?
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "team", "pulse"},
|
||||
},
|
||||
{
|
||||
subtestName: "tag = is just a regular tag-key filter",
|
||||
dslQueryToCompile: `tag = 'database'`,
|
||||
expectedSQL: `
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value = ?
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "tag", "database"},
|
||||
},
|
||||
{
|
||||
subtestName: "team != wraps in NOT EXISTS with positive inner",
|
||||
dslQueryToCompile: `team != 'pulse'`,
|
||||
expectedSQL: `
|
||||
NOT EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value = ?
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "team", "pulse"},
|
||||
},
|
||||
{
|
||||
subtestName: "team IN — inner is single placeholder list on t.value",
|
||||
dslQueryToCompile: `team IN ['pulse', 'events']`,
|
||||
expectedSQL: `
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value IN (?, ?)
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "team", "pulse", "events"},
|
||||
},
|
||||
{
|
||||
subtestName: "team NOT IN",
|
||||
dslQueryToCompile: `team NOT IN ['pulse', 'events']`,
|
||||
expectedSQL: `
|
||||
NOT EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value IN (?, ?)
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "team", "pulse", "events"},
|
||||
},
|
||||
{
|
||||
subtestName: "team LIKE — wildcard on value",
|
||||
dslQueryToCompile: `team LIKE 'pulse%'`,
|
||||
expectedSQL: `
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value LIKE ? ESCAPE '\'
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "team", "pulse%"},
|
||||
},
|
||||
{
|
||||
subtestName: "team NOT LIKE",
|
||||
dslQueryToCompile: `team NOT LIKE 'staging%'`,
|
||||
expectedSQL: `
|
||||
NOT EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value LIKE ? ESCAPE '\'
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "team", "staging%"},
|
||||
},
|
||||
{
|
||||
subtestName: "database EXISTS — asserts a tag with key=database is present",
|
||||
dslQueryToCompile: `database EXISTS`,
|
||||
expectedSQL: `
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "database"},
|
||||
},
|
||||
{
|
||||
subtestName: "database NOT EXISTS",
|
||||
dslQueryToCompile: `database NOT EXISTS`,
|
||||
expectedSQL: `
|
||||
NOT EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "database"},
|
||||
},
|
||||
{
|
||||
subtestName: "tag-key matching is case-insensitive — TEAM lowercased",
|
||||
dslQueryToCompile: `TEAM = 'pulse'`,
|
||||
expectedSQL: `
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value = ?
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "team", "pulse"},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestCompile_BooleanComposition(t *testing.T) {
|
||||
runCompileCases(t, []compileCase{
|
||||
{
|
||||
subtestName: "AND chain — flat arg list",
|
||||
dslQueryToCompile: `locked = true AND created_by = 'a@b.com'`,
|
||||
expectedSQL: `(dashboard.locked = ? AND dashboard.created_by = ?)`,
|
||||
expectedArgs: []any{true, "a@b.com"},
|
||||
},
|
||||
{
|
||||
subtestName: "OR chain",
|
||||
dslQueryToCompile: `locked = true OR created_by = 'a@b.com'`,
|
||||
expectedSQL: `(dashboard.locked = ? OR dashboard.created_by = ?)`,
|
||||
expectedArgs: []any{true, "a@b.com"},
|
||||
},
|
||||
{
|
||||
subtestName: "parens preserve precedence",
|
||||
dslQueryToCompile: `(locked = true OR locked = false) AND created_by = 'a@b.com'`,
|
||||
expectedSQL: `((dashboard.locked = ? OR dashboard.locked = ?) AND dashboard.created_by = ?)`,
|
||||
expectedArgs: []any{true, false, "a@b.com"},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Distinct from operator-suffix negation (NOT IN / NOT LIKE / NOT EXISTS).
|
||||
// Driven by the unaryExpression rule (`NOT? primary`), so NOT binds to
|
||||
// exactly one primary and only widens via parens.
|
||||
func TestCompile_NOT(t *testing.T) {
|
||||
runCompileCases(t, []compileCase{
|
||||
{
|
||||
subtestName: "NOT on a single comparison",
|
||||
dslQueryToCompile: `NOT name = 'foo'`,
|
||||
expectedSQL: `NOT (json_extract("dashboard"."data", '$.spec.display.name') = ?)`,
|
||||
expectedArgs: []any{"foo"},
|
||||
},
|
||||
{
|
||||
subtestName: "NOT binds tightly to its primary in an AND chain",
|
||||
dslQueryToCompile: `NOT name = 'foo' AND created_by = 'alice'`,
|
||||
expectedSQL: `(NOT (json_extract("dashboard"."data", '$.spec.display.name') = ?) AND dashboard.created_by = ?)`,
|
||||
expectedArgs: []any{"foo", "alice"},
|
||||
},
|
||||
{
|
||||
subtestName: "NOT applied to the second term in an AND chain",
|
||||
dslQueryToCompile: `locked = true AND NOT name = 'foo'`,
|
||||
expectedSQL: `(dashboard.locked = ? AND NOT (json_extract("dashboard"."data", '$.spec.display.name') = ?))`,
|
||||
expectedArgs: []any{true, "foo"},
|
||||
},
|
||||
{
|
||||
subtestName: "NOT around a parenthesized OR",
|
||||
dslQueryToCompile: `NOT (locked = true OR created_by = 'a@b.com')`,
|
||||
expectedSQL: `NOT ((dashboard.locked = ? OR dashboard.created_by = ?))`,
|
||||
expectedArgs: []any{true, "a@b.com"},
|
||||
},
|
||||
{
|
||||
subtestName: "double NOT via parens",
|
||||
dslQueryToCompile: `NOT (NOT name = 'foo')`,
|
||||
expectedSQL: `NOT (NOT (json_extract("dashboard"."data", '$.spec.display.name') = ?))`,
|
||||
expectedArgs: []any{"foo"},
|
||||
},
|
||||
{
|
||||
subtestName: "NOT on a tag equality",
|
||||
dslQueryToCompile: `NOT team = 'pulse'`,
|
||||
expectedSQL: `
|
||||
NOT (
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value = ?
|
||||
)
|
||||
)`,
|
||||
expectedArgs: []any{kindArg, "team", "pulse"},
|
||||
},
|
||||
{
|
||||
subtestName: "NOT team = ... AND name = ...",
|
||||
dslQueryToCompile: `NOT team = 'pulse' AND name = 'overview'`,
|
||||
expectedSQL: `
|
||||
(
|
||||
NOT (
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value = ?
|
||||
)
|
||||
)
|
||||
AND json_extract("dashboard"."data", '$.spec.display.name') = ?)`,
|
||||
expectedArgs: []any{kindArg, "team", "pulse", "overview"},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestCompile_ComplexExamples(t *testing.T) {
|
||||
runCompileCases(t, []compileCase{
|
||||
{
|
||||
subtestName: "name CONTAINS + tag LIKE + created_by + database =",
|
||||
dslQueryToCompile: `name CONTAINS 'overview' AND tag LIKE 'prod%' AND created_by = 'naman.verma@signoz.io' AND database = 'mongo'`,
|
||||
expectedSQL: `
|
||||
(
|
||||
json_extract("dashboard"."data", '$.spec.display.name') LIKE ? ESCAPE '\'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value LIKE ? ESCAPE '\'
|
||||
)
|
||||
AND dashboard.created_by = ?
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value = ?
|
||||
))`,
|
||||
expectedArgs: []any{"%overview%", kindArg, "tag", "prod%", "naman.verma@signoz.io", kindArg, "database", "mongo"},
|
||||
},
|
||||
{
|
||||
subtestName: "team IN AND database EXISTS",
|
||||
dslQueryToCompile: `team IN ['pulse', 'events'] AND database EXISTS`,
|
||||
expectedSQL: `
|
||||
(
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value IN (?, ?)
|
||||
)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
))`,
|
||||
expectedArgs: []any{kindArg, "team", "pulse", "events", kindArg, "database"},
|
||||
},
|
||||
{
|
||||
subtestName: "nested OR / AND with parens",
|
||||
dslQueryToCompile: `(database IN ['sql', 'redis', 'mongo'] OR name LIKE '%database%') AND (team = 'pulse' OR name LIKE '%pulse%')`,
|
||||
expectedSQL: `
|
||||
(
|
||||
(
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value IN (?, ?, ?)
|
||||
)
|
||||
OR json_extract("dashboard"."data", '$.spec.display.name') LIKE ? ESCAPE '\'
|
||||
)
|
||||
AND (
|
||||
EXISTS (
|
||||
SELECT 1 FROM tag_relation tr
|
||||
JOIN tag t ON t.id = tr.tag_id
|
||||
WHERE tr.kind = ? AND tr.resource_id = dashboard.id
|
||||
AND LOWER(t.key) = LOWER(?)
|
||||
AND t.value = ?
|
||||
)
|
||||
OR json_extract("dashboard"."data", '$.spec.display.name') LIKE ? ESCAPE '\'
|
||||
))`,
|
||||
expectedArgs: []any{kindArg, "database", "sql", "redis", "mongo", "%database%", kindArg, "team", "pulse", "%pulse%"},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestCompile_Rejections(t *testing.T) {
|
||||
runCompileCases(t, []compileCase{
|
||||
{
|
||||
subtestName: "rejects op outside per-reserved-key allowlist",
|
||||
dslQueryToCompile: `name BETWEEN 'a' AND 'z'`,
|
||||
expectedErrShouldContain: "operator",
|
||||
},
|
||||
{
|
||||
subtestName: "rejects BETWEEN on a tag key",
|
||||
dslQueryToCompile: `team BETWEEN 'a' AND 'z'`,
|
||||
expectedErrShouldContain: "operator",
|
||||
},
|
||||
{
|
||||
subtestName: "rejects non-bool on locked",
|
||||
dslQueryToCompile: `locked = 'yes'`,
|
||||
expectedErrShouldContain: "boolean",
|
||||
},
|
||||
{
|
||||
subtestName: "rejects non-RFC3339 timestamp",
|
||||
dslQueryToCompile: `created_at >= 'not-a-date'`,
|
||||
expectedErrShouldContain: "RFC3339",
|
||||
},
|
||||
{
|
||||
subtestName: "rejects REGEXP — not yet supported",
|
||||
dslQueryToCompile: `name REGEXP '.*'`,
|
||||
expectedErrShouldContain: "REGEXP",
|
||||
},
|
||||
{
|
||||
subtestName: "rejects syntax error from grammar",
|
||||
dslQueryToCompile: `name = `,
|
||||
expectedErrShouldContain: "syntax",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Every key in dashboardtypes.ReservedOps must have a matching case in
|
||||
// visitComparisonForReservedKeys; a key that's reserved but unhandled falls
|
||||
// through to the "no handler for reserved key" error. Equal is accepted by all
|
||||
// reserved keys, so `key = 'x'` always reaches the dispatch switch — a missing
|
||||
// handler surfaces as that error regardless of whether the value type-checks.
|
||||
func TestCompileReservedKeysAllHandled(t *testing.T) {
|
||||
for key := range dashboardtypes.ReservedOps {
|
||||
t.Run(string(key), func(t *testing.T) {
|
||||
_, err := Compile(string(key)+` = 'x'`, formatter(t))
|
||||
if err != nil {
|
||||
assert.NotContains(t, err.Error(), "no handler for reserved key",
|
||||
"reserved key %q has no handler in visitComparisonForReservedKeys", key)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func formatter(t *testing.T) sqlstore.SQLFormatter {
|
||||
t.Helper()
|
||||
p := sqlstoretest.New(sqlstore.Config{Provider: "sqlite"}, sqlmock.QueryMatcherEqual)
|
||||
return p.Formatter()
|
||||
}
|
||||
|
||||
func normalizeSQL(s string) string {
|
||||
s = strings.Join(strings.Fields(s), " ")
|
||||
s = strings.ReplaceAll(s, "( ", "(")
|
||||
s = strings.ReplaceAll(s, " )", ")")
|
||||
return s
|
||||
}
|
||||
581
pkg/modules/dashboard/impldashboard/listfilter_visitor.go
Normal file
581
pkg/modules/dashboard/impldashboard/listfilter_visitor.go
Normal file
@@ -0,0 +1,581 @@
|
||||
package impldashboard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/parser/filterquery"
|
||||
grammar "github.com/SigNoz/signoz/pkg/parser/filterquery/grammar"
|
||||
"github.com/SigNoz/signoz/pkg/sqlstore"
|
||||
"github.com/SigNoz/signoz/pkg/types/dashboardtypes"
|
||||
qbtypesv5 "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
|
||||
"github.com/antlr4-go/antlr/v4"
|
||||
sqlbuilder "github.com/huandu/go-sqlbuilder"
|
||||
)
|
||||
|
||||
// bunPlaceholderFlavor is any flavor that renders `?` placeholders, which bun
|
||||
// re-binds to the actual backend (e.g. `$1` for Postgres) at query time.
|
||||
const bunPlaceholderFlavor = sqlbuilder.SQLite
|
||||
|
||||
type visitor struct {
|
||||
grammar.BaseFilterQueryVisitor
|
||||
selectBuilder *sqlbuilder.SelectBuilder
|
||||
formatter sqlstore.SQLFormatter
|
||||
errors []string
|
||||
}
|
||||
|
||||
func newVisitor(formatter sqlstore.SQLFormatter) *visitor {
|
||||
return &visitor{
|
||||
selectBuilder: sqlbuilder.NewSelectBuilder(),
|
||||
formatter: formatter,
|
||||
}
|
||||
}
|
||||
|
||||
// compile turns the parse tree into `?`-placeholder WHERE SQL + arguments for bun.
|
||||
func (v *visitor) compile(query string) (string, []any, []string) {
|
||||
tree, _, collector := filterquery.Parse(query)
|
||||
if len(collector.Errors) > 0 {
|
||||
return "", nil, collector.Errors
|
||||
}
|
||||
condition, _ := v.visit(tree).(string)
|
||||
if condition == "" {
|
||||
return "", nil, nil
|
||||
}
|
||||
sql, arguments := v.selectBuilder.Args.CompileWithFlavor(condition, bunPlaceholderFlavor)
|
||||
return sql, arguments, nil
|
||||
}
|
||||
|
||||
func (v *visitor) visit(tree antlr.ParseTree) any {
|
||||
if tree == nil {
|
||||
return nil
|
||||
}
|
||||
return tree.Accept(v)
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════
|
||||
// methods from grammar.BaseFilterQueryVisitor that are overridden
|
||||
// ════════════════════════════════════════════════════════════════════════
|
||||
|
||||
func (v *visitor) VisitQuery(ctx *grammar.QueryContext) any {
|
||||
return v.visit(ctx.Expression())
|
||||
}
|
||||
|
||||
func (v *visitor) VisitExpression(ctx *grammar.ExpressionContext) any {
|
||||
return v.visit(ctx.OrExpression())
|
||||
}
|
||||
|
||||
func (v *visitor) VisitOrExpression(ctx *grammar.OrExpressionContext) any {
|
||||
parts := ctx.AllAndExpression()
|
||||
conditions := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if condition, ok := v.visit(part).(string); ok && condition != "" {
|
||||
conditions = append(conditions, condition)
|
||||
}
|
||||
}
|
||||
switch len(conditions) {
|
||||
case 0:
|
||||
return ""
|
||||
case 1:
|
||||
return conditions[0]
|
||||
default:
|
||||
return v.selectBuilder.Or(conditions...)
|
||||
}
|
||||
}
|
||||
|
||||
func (v *visitor) VisitAndExpression(ctx *grammar.AndExpressionContext) any {
|
||||
parts := ctx.AllUnaryExpression()
|
||||
conditions := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if condition, ok := v.visit(part).(string); ok && condition != "" {
|
||||
conditions = append(conditions, condition)
|
||||
}
|
||||
}
|
||||
switch len(conditions) {
|
||||
case 0:
|
||||
return ""
|
||||
case 1:
|
||||
return conditions[0]
|
||||
default:
|
||||
return v.selectBuilder.And(conditions...)
|
||||
}
|
||||
}
|
||||
|
||||
func (v *visitor) VisitUnaryExpression(ctx *grammar.UnaryExpressionContext) any {
|
||||
condition, _ := v.visit(ctx.Primary()).(string)
|
||||
if condition == "" {
|
||||
return ""
|
||||
}
|
||||
if ctx.NOT() != nil {
|
||||
return fmt.Sprintf("NOT (%s)", condition)
|
||||
}
|
||||
return condition
|
||||
}
|
||||
|
||||
func (v *visitor) VisitPrimary(ctx *grammar.PrimaryContext) any {
|
||||
if ctx.OrExpression() != nil {
|
||||
return v.visit(ctx.OrExpression())
|
||||
}
|
||||
if ctx.Comparison() != nil {
|
||||
return v.visit(ctx.Comparison())
|
||||
}
|
||||
// Bare keys, values, full text, and function calls are not part of the
|
||||
// dashboard list DSL.
|
||||
v.addError("unsupported expression %q — every term must be of the form `key OP value`", ctx.GetText())
|
||||
return ""
|
||||
}
|
||||
|
||||
// VisitComparison dispatches a single `key OP value` term. A key that matches
|
||||
// a reserved DSL key (name, description, etc.) becomes a column-level
|
||||
// predicate; any other identifier is treated as a tag key — the operator
|
||||
// applies to the tag's value, with a case-insensitive match on the tag's key.
|
||||
func (v *visitor) VisitComparison(ctx *grammar.ComparisonContext) any {
|
||||
key := strings.ToLower(strings.TrimSpace(ctx.Key().GetText()))
|
||||
|
||||
operation, ok := v.extractOperation(ctx)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
if allowedOperations, isReserved := dashboardtypes.ReservedOps[dashboardtypes.DSLKey(key)]; isReserved {
|
||||
return v.visitComparisonForReservedKeys(ctx, operation, dashboardtypes.DSLKey(key), allowedOperations)
|
||||
}
|
||||
return v.visitComparisonForTags(ctx, operation, key)
|
||||
}
|
||||
|
||||
func (v *visitor) visitComparisonForReservedKeys(ctx *grammar.ComparisonContext, operation qbtypesv5.FilterOperator, key dashboardtypes.DSLKey, allowedOperations map[qbtypesv5.FilterOperator]struct{}) string {
|
||||
if _, allowed := allowedOperations[operation]; !allowed {
|
||||
v.addError("operator %s is not allowed for key %q", operationName(operation), key)
|
||||
return ""
|
||||
}
|
||||
switch key {
|
||||
case dashboardtypes.DSLKeyName:
|
||||
return v.buildJSONStringComparison(ctx, operation, dashboardtypes.DSLKeyName, "$.spec.display.name")
|
||||
case dashboardtypes.DSLKeyDescription:
|
||||
return v.buildJSONStringComparison(ctx, operation, dashboardtypes.DSLKeyDescription, "$.spec.display.description")
|
||||
case dashboardtypes.DSLKeyCreatedAt:
|
||||
return v.buildTimestampComparison(ctx, operation, "dashboard.created_at")
|
||||
case dashboardtypes.DSLKeyUpdatedAt:
|
||||
return v.buildTimestampComparison(ctx, operation, "dashboard.updated_at")
|
||||
case dashboardtypes.DSLKeyCreatedBy:
|
||||
return v.buildStringComparison(ctx, operation, dashboardtypes.DSLKeyCreatedBy, "dashboard.created_by")
|
||||
case dashboardtypes.DSLKeyLocked:
|
||||
return v.buildBoolComparison(ctx, operation, "dashboard.locked")
|
||||
}
|
||||
// Unreachable for real input: every dashboardtypes.ReservedOps key has a case above, and
|
||||
// TestCompileReservedKeysAllHandled guards that the two stay in sync.
|
||||
v.addError("no handler for reserved key %q", key)
|
||||
return ""
|
||||
}
|
||||
|
||||
func (v *visitor) visitComparisonForTags(ctx *grammar.ComparisonContext, operation qbtypesv5.FilterOperator, tagKey string) string {
|
||||
if _, allowed := dashboardtypes.TagKeyOps[operation]; !allowed {
|
||||
v.addError("operator %s is not allowed on a tag-key filter", operationName(operation))
|
||||
return ""
|
||||
}
|
||||
return v.buildTagComparison(ctx, operation, tagKey)
|
||||
}
|
||||
|
||||
func (v *visitor) extractOperation(ctx *grammar.ComparisonContext) (qbtypesv5.FilterOperator, bool) {
|
||||
// For operators that take an optional leading NOT, Inverse() maps each to
|
||||
// its Not<X> counterpart.
|
||||
maybeNot := func(operation qbtypesv5.FilterOperator) qbtypesv5.FilterOperator {
|
||||
if ctx.NOT() != nil {
|
||||
return operation.Inverse()
|
||||
}
|
||||
return operation
|
||||
}
|
||||
switch {
|
||||
case ctx.EQUALS() != nil:
|
||||
return qbtypesv5.FilterOperatorEqual, true
|
||||
case ctx.NOT_EQUALS() != nil, ctx.NEQ() != nil:
|
||||
return qbtypesv5.FilterOperatorNotEqual, true
|
||||
case ctx.LT() != nil:
|
||||
return qbtypesv5.FilterOperatorLessThan, true
|
||||
case ctx.LE() != nil:
|
||||
return qbtypesv5.FilterOperatorLessThanOrEq, true
|
||||
case ctx.GT() != nil:
|
||||
return qbtypesv5.FilterOperatorGreaterThan, true
|
||||
case ctx.GE() != nil:
|
||||
return qbtypesv5.FilterOperatorGreaterThanOrEq, true
|
||||
case ctx.BETWEEN() != nil:
|
||||
return maybeNot(qbtypesv5.FilterOperatorBetween), true
|
||||
case ctx.LIKE() != nil:
|
||||
return maybeNot(qbtypesv5.FilterOperatorLike), true
|
||||
case ctx.ILIKE() != nil:
|
||||
return maybeNot(qbtypesv5.FilterOperatorILike), true
|
||||
case ctx.CONTAINS() != nil:
|
||||
return maybeNot(qbtypesv5.FilterOperatorContains), true
|
||||
case ctx.REGEXP() != nil:
|
||||
return maybeNot(qbtypesv5.FilterOperatorRegexp), true
|
||||
case ctx.InClause() != nil:
|
||||
return qbtypesv5.FilterOperatorIn, true
|
||||
case ctx.NotInClause() != nil:
|
||||
return qbtypesv5.FilterOperatorNotIn, true
|
||||
case ctx.EXISTS() != nil:
|
||||
return maybeNot(qbtypesv5.FilterOperatorExists), true
|
||||
}
|
||||
v.addError("could not determine operator in expression %q", ctx.GetText())
|
||||
return qbtypesv5.FilterOperatorUnknown, false
|
||||
}
|
||||
|
||||
// ─── per-key emitters ────────────────────────────────────────────────────────
|
||||
|
||||
func (v *visitor) buildJSONStringComparison(ctx *grammar.ComparisonContext, operation qbtypesv5.FilterOperator, key dashboardtypes.DSLKey, jsonPath string) string {
|
||||
columnExpression := string(v.formatter.JSONExtractString("dashboard.data", jsonPath))
|
||||
return v.buildStringOperation(v.selectBuilder, ctx, operation, columnExpression, string(key))
|
||||
}
|
||||
|
||||
func (v *visitor) buildStringComparison(ctx *grammar.ComparisonContext, operation qbtypesv5.FilterOperator, key dashboardtypes.DSLKey, columnExpression string) string {
|
||||
return v.buildStringOperation(v.selectBuilder, ctx, operation, columnExpression, string(key))
|
||||
}
|
||||
|
||||
// buildStringOperation covers all the operators the spec allows on text-shaped keys
|
||||
// (name, description, created_by, and a tag's value). Placeholders are interned
|
||||
// into builder — the outer builder for column predicates, the subquery builder for
|
||||
// tag-value predicates — so nested EXISTS arguments thread correctly.
|
||||
func (v *visitor) buildStringOperation(builder *sqlbuilder.SelectBuilder, ctx *grammar.ComparisonContext, operation qbtypesv5.FilterOperator, columnExpression, keyForError string) string {
|
||||
switch operation {
|
||||
case qbtypesv5.FilterOperatorEqual:
|
||||
val, ok := v.extractSingleStringValue(ctx, keyForError)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return builder.Equal(columnExpression, val)
|
||||
case qbtypesv5.FilterOperatorNotEqual:
|
||||
val, ok := v.extractSingleStringValue(ctx, keyForError)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return builder.NotEqual(columnExpression, val)
|
||||
case qbtypesv5.FilterOperatorLike, qbtypesv5.FilterOperatorNotLike:
|
||||
val, ok := v.extractSingleStringValue(ctx, keyForError)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
like := "LIKE"
|
||||
if operation == qbtypesv5.FilterOperatorNotLike {
|
||||
like = "NOT LIKE"
|
||||
}
|
||||
// The user's % and _ stay as wildcards; ESCAPE pins backslash as the escape
|
||||
// char so a literal `\` in the pattern is read the same on both dialects —
|
||||
// Postgres defaults to `\`, SQLite has no default escape.
|
||||
return fmt.Sprintf("%s %s %s ESCAPE '\\'", columnExpression, like, builder.Var(val))
|
||||
case qbtypesv5.FilterOperatorILike, qbtypesv5.FilterOperatorNotILike:
|
||||
val, ok := v.extractSingleStringValue(ctx, keyForError)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
// SQLite has no ILIKE keyword and Postgres LIKE is case-sensitive — emit
|
||||
// LOWER(col) LIKE LOWER(?) so behavior is identical on both dialects. ESCAPE
|
||||
// pins backslash as the escape char (Postgres default; SQLite has none).
|
||||
lowerColumn := string(v.formatter.LowerExpression(columnExpression))
|
||||
like := "LIKE"
|
||||
if operation == qbtypesv5.FilterOperatorNotILike {
|
||||
like = "NOT LIKE"
|
||||
}
|
||||
return fmt.Sprintf("%s %s LOWER(%s) ESCAPE '\\'", lowerColumn, like, builder.Var(val))
|
||||
case qbtypesv5.FilterOperatorContains, qbtypesv5.FilterOperatorNotContains:
|
||||
val, ok := v.extractSingleStringValue(ctx, keyForError)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
like := "LIKE"
|
||||
if operation == qbtypesv5.FilterOperatorNotContains {
|
||||
like = "NOT LIKE"
|
||||
}
|
||||
// Escape the user's % and _ so they match literally, then wrap in wildcards.
|
||||
// ESCAPE declares the backslash we just injected as the escape char — needed
|
||||
// on SQLite (no default) and a harmless restatement of the Postgres default.
|
||||
escaped := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(val)
|
||||
return fmt.Sprintf("%s %s %s ESCAPE '\\'", columnExpression, like, builder.Var("%"+escaped+"%"))
|
||||
case qbtypesv5.FilterOperatorRegexp, qbtypesv5.FilterOperatorNotRegexp:
|
||||
v.addError("REGEXP filtering on %q is not yet supported", keyForError)
|
||||
return ""
|
||||
case qbtypesv5.FilterOperatorIn, qbtypesv5.FilterOperatorNotIn:
|
||||
values, ok := v.extractStringValueList(ctx, keyForError)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
arguments := make([]any, len(values))
|
||||
for i, s := range values {
|
||||
arguments[i] = s
|
||||
}
|
||||
if operation == qbtypesv5.FilterOperatorNotIn {
|
||||
return builder.NotIn(columnExpression, arguments...)
|
||||
}
|
||||
return builder.In(columnExpression, arguments...)
|
||||
}
|
||||
v.addError("operator %s on %q is not implemented", operationName(operation), keyForError)
|
||||
return ""
|
||||
}
|
||||
|
||||
func (v *visitor) buildTimestampComparison(ctx *grammar.ComparisonContext, operation qbtypesv5.FilterOperator, columnExpression string) string {
|
||||
switch operation {
|
||||
case qbtypesv5.FilterOperatorEqual, qbtypesv5.FilterOperatorNotEqual,
|
||||
qbtypesv5.FilterOperatorLessThan, qbtypesv5.FilterOperatorLessThanOrEq,
|
||||
qbtypesv5.FilterOperatorGreaterThan, qbtypesv5.FilterOperatorGreaterThanOrEq:
|
||||
t, ok := v.extractSingleTimestampValue(ctx)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
switch operation {
|
||||
case qbtypesv5.FilterOperatorEqual:
|
||||
return v.selectBuilder.Equal(columnExpression, t)
|
||||
case qbtypesv5.FilterOperatorNotEqual:
|
||||
return v.selectBuilder.NotEqual(columnExpression, t)
|
||||
case qbtypesv5.FilterOperatorLessThan:
|
||||
return v.selectBuilder.LessThan(columnExpression, t)
|
||||
case qbtypesv5.FilterOperatorLessThanOrEq:
|
||||
return v.selectBuilder.LessEqualThan(columnExpression, t)
|
||||
case qbtypesv5.FilterOperatorGreaterThan:
|
||||
return v.selectBuilder.GreaterThan(columnExpression, t)
|
||||
case qbtypesv5.FilterOperatorGreaterThanOrEq:
|
||||
return v.selectBuilder.GreaterEqualThan(columnExpression, t)
|
||||
}
|
||||
case qbtypesv5.FilterOperatorBetween, qbtypesv5.FilterOperatorNotBetween:
|
||||
timestamps, ok := v.extractTwoTimestampValues(ctx)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
if operation == qbtypesv5.FilterOperatorNotBetween {
|
||||
return v.selectBuilder.NotBetween(columnExpression, timestamps[0], timestamps[1])
|
||||
}
|
||||
return v.selectBuilder.Between(columnExpression, timestamps[0], timestamps[1])
|
||||
}
|
||||
v.addError("operator %s on timestamp is not implemented", operationName(operation))
|
||||
return ""
|
||||
}
|
||||
|
||||
func (v *visitor) buildBoolComparison(ctx *grammar.ComparisonContext, operation qbtypesv5.FilterOperator, columnExpression string) string {
|
||||
b, ok := v.extractSingleBoolValue(ctx)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
if operation == qbtypesv5.FilterOperatorNotEqual {
|
||||
return v.selectBuilder.NotEqual(columnExpression, b)
|
||||
}
|
||||
return v.selectBuilder.Equal(columnExpression, b)
|
||||
}
|
||||
|
||||
func (v *visitor) buildTagComparison(ctx *grammar.ComparisonContext, operation qbtypesv5.FilterOperator, tagKey string) string {
|
||||
subqueryBuilder := sqlbuilder.NewSelectBuilder()
|
||||
|
||||
if operation == qbtypesv5.FilterOperatorExists || operation == qbtypesv5.FilterOperatorNotExists {
|
||||
buildSubqueryForTagKey(subqueryBuilder, tagKey)
|
||||
} else {
|
||||
// All other tag operators take the positive form of the value predicate
|
||||
// and toggle the EXISTS wrapper for negation. Inverse() flips Not<X> → <X>.
|
||||
positiveOperation := operation
|
||||
if operation.IsNegativeOperator() {
|
||||
positiveOperation = operation.Inverse()
|
||||
}
|
||||
valuePredicate := v.buildStringOperation(subqueryBuilder, ctx, positiveOperation, "t.value", tagKey)
|
||||
if valuePredicate == "" {
|
||||
return ""
|
||||
}
|
||||
buildSubqueryForTagKeyAndValue(subqueryBuilder, tagKey, valuePredicate)
|
||||
}
|
||||
|
||||
if operation.IsNegativeOperator() {
|
||||
return v.selectBuilder.NotExists(subqueryBuilder)
|
||||
}
|
||||
return v.selectBuilder.Exists(subqueryBuilder)
|
||||
}
|
||||
|
||||
func buildSubqueryForTagKey(subqueryBuilder *sqlbuilder.SelectBuilder, tagKey string) *sqlbuilder.SelectBuilder {
|
||||
const dashboardTagKind = `"dashboard"`
|
||||
|
||||
return subqueryBuilder.
|
||||
Select("1").
|
||||
From("tag_relation tr").
|
||||
Join("tag t", "t.id = tr.tag_id").
|
||||
Where(
|
||||
subqueryBuilder.Equal("tr.kind", dashboardTagKind),
|
||||
"tr.resource_id = dashboard.id",
|
||||
"LOWER(t.key) = LOWER("+subqueryBuilder.Var(tagKey)+")",
|
||||
)
|
||||
}
|
||||
|
||||
func buildSubqueryForTagKeyAndValue(subqueryBuilder *sqlbuilder.SelectBuilder, tagKey, valuePredicate string) *sqlbuilder.SelectBuilder {
|
||||
return buildSubqueryForTagKey(subqueryBuilder, tagKey).Where(valuePredicate)
|
||||
}
|
||||
|
||||
// ─── value extraction helpers ───────────────────────────────────────────────
|
||||
|
||||
func (v *visitor) addError(format string, arguments ...any) {
|
||||
v.errors = append(v.errors, fmt.Sprintf(format, arguments...))
|
||||
}
|
||||
|
||||
func (v *visitor) extractSingleStringValue(ctx *grammar.ComparisonContext, keyForError string) (string, bool) {
|
||||
values := ctx.AllValue()
|
||||
if len(values) != 1 {
|
||||
v.addError("expected exactly one value for %q", keyForError)
|
||||
return "", false
|
||||
}
|
||||
return v.extractStringValue(values[0], keyForError)
|
||||
}
|
||||
|
||||
func (v *visitor) extractSingleBoolValue(ctx *grammar.ComparisonContext) (bool, bool) {
|
||||
values := ctx.AllValue()
|
||||
if len(values) != 1 {
|
||||
v.addError("expected a single boolean (true/false)")
|
||||
return false, false
|
||||
}
|
||||
return v.extractBoolValue(values[0])
|
||||
}
|
||||
|
||||
func (v *visitor) extractSingleTimestampValue(ctx *grammar.ComparisonContext) (time.Time, bool) {
|
||||
values := ctx.AllValue()
|
||||
if len(values) != 1 {
|
||||
v.addError("expected a single RFC3339 timestamp")
|
||||
return time.Time{}, false
|
||||
}
|
||||
return v.extractTimestampValue(values[0])
|
||||
}
|
||||
|
||||
func (v *visitor) extractTwoTimestampValues(ctx *grammar.ComparisonContext) ([2]time.Time, bool) {
|
||||
values := ctx.AllValue()
|
||||
if len(values) != 2 {
|
||||
v.addError("BETWEEN expects two RFC3339 timestamps")
|
||||
return [2]time.Time{}, false
|
||||
}
|
||||
a, ok1 := v.extractTimestampValue(values[0])
|
||||
b, ok2 := v.extractTimestampValue(values[1])
|
||||
if !ok1 || !ok2 {
|
||||
return [2]time.Time{}, false
|
||||
}
|
||||
return [2]time.Time{a, b}, true
|
||||
}
|
||||
|
||||
func (v *visitor) extractStringValueList(ctx *grammar.ComparisonContext, keyForError string) ([]string, bool) {
|
||||
var valuesCtx []grammar.IValueContext
|
||||
switch {
|
||||
case ctx.InClause() != nil:
|
||||
inClause := ctx.InClause()
|
||||
if inClause.ValueList() != nil {
|
||||
valuesCtx = inClause.ValueList().AllValue()
|
||||
} else {
|
||||
valuesCtx = []grammar.IValueContext{inClause.Value()}
|
||||
}
|
||||
case ctx.NotInClause() != nil:
|
||||
notInClause := ctx.NotInClause()
|
||||
if notInClause.ValueList() != nil {
|
||||
valuesCtx = notInClause.ValueList().AllValue()
|
||||
} else {
|
||||
valuesCtx = []grammar.IValueContext{notInClause.Value()}
|
||||
}
|
||||
default:
|
||||
v.addError("IN clause is missing for %q", keyForError)
|
||||
return nil, false
|
||||
}
|
||||
if len(valuesCtx) == 0 {
|
||||
v.addError("IN list for %q is empty", keyForError)
|
||||
return nil, false
|
||||
}
|
||||
out := make([]string, 0, len(valuesCtx))
|
||||
for _, valueContext := range valuesCtx {
|
||||
s, ok := v.extractStringValue(valueContext, keyForError)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
func (v *visitor) extractStringValue(ctx grammar.IValueContext, keyForError string) (string, bool) {
|
||||
if ctx.QUOTED_TEXT() != nil {
|
||||
return trimQuotes(ctx.QUOTED_TEXT().GetText()), true
|
||||
}
|
||||
if ctx.KEY() != nil {
|
||||
// Bare tokens are accepted as strings, mirroring the FilterQuery lexer's
|
||||
// treatment of unquoted identifiers on the value side.
|
||||
return ctx.KEY().GetText(), true
|
||||
}
|
||||
v.addError("expected a string value for %q, got %q", keyForError, ctx.GetText())
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (v *visitor) extractBoolValue(ctx grammar.IValueContext) (bool, bool) {
|
||||
if ctx.BOOL() == nil {
|
||||
v.addError("expected a boolean (true/false), got %q", ctx.GetText())
|
||||
return false, false
|
||||
}
|
||||
return strings.EqualFold(ctx.BOOL().GetText(), "true"), true
|
||||
}
|
||||
|
||||
func (v *visitor) extractTimestampValue(ctx grammar.IValueContext) (time.Time, bool) {
|
||||
if ctx.QUOTED_TEXT() == nil {
|
||||
v.addError("expected an RFC3339 timestamp string, got %q", ctx.GetText())
|
||||
return time.Time{}, false
|
||||
}
|
||||
raw := trimQuotes(ctx.QUOTED_TEXT().GetText())
|
||||
t, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
v.addError("invalid RFC3339 timestamp %q: %s", raw, err.Error())
|
||||
return time.Time{}, false
|
||||
}
|
||||
return t, true
|
||||
}
|
||||
|
||||
// ─── operator spelling ───────────────────────────────────────────────────────
|
||||
|
||||
// operationName returns the user-facing spelling of a FilterOperator, used only in
|
||||
// error messages — go-sqlbuilder's Cond helpers emit the SQL keywords.
|
||||
func operationName(operation qbtypesv5.FilterOperator) string {
|
||||
switch operation {
|
||||
case qbtypesv5.FilterOperatorEqual:
|
||||
return "="
|
||||
case qbtypesv5.FilterOperatorNotEqual:
|
||||
return "!="
|
||||
case qbtypesv5.FilterOperatorLessThan:
|
||||
return "<"
|
||||
case qbtypesv5.FilterOperatorLessThanOrEq:
|
||||
return "<="
|
||||
case qbtypesv5.FilterOperatorGreaterThan:
|
||||
return ">"
|
||||
case qbtypesv5.FilterOperatorGreaterThanOrEq:
|
||||
return ">="
|
||||
case qbtypesv5.FilterOperatorBetween:
|
||||
return "BETWEEN"
|
||||
case qbtypesv5.FilterOperatorNotBetween:
|
||||
return "NOT BETWEEN"
|
||||
case qbtypesv5.FilterOperatorLike:
|
||||
return "LIKE"
|
||||
case qbtypesv5.FilterOperatorNotLike:
|
||||
return "NOT LIKE"
|
||||
case qbtypesv5.FilterOperatorILike:
|
||||
return "ILIKE"
|
||||
case qbtypesv5.FilterOperatorNotILike:
|
||||
return "NOT ILIKE"
|
||||
case qbtypesv5.FilterOperatorContains:
|
||||
return "CONTAINS"
|
||||
case qbtypesv5.FilterOperatorNotContains:
|
||||
return "NOT CONTAINS"
|
||||
case qbtypesv5.FilterOperatorRegexp:
|
||||
return "REGEXP"
|
||||
case qbtypesv5.FilterOperatorNotRegexp:
|
||||
return "NOT REGEXP"
|
||||
case qbtypesv5.FilterOperatorIn:
|
||||
return "IN"
|
||||
case qbtypesv5.FilterOperatorNotIn:
|
||||
return "NOT IN"
|
||||
case qbtypesv5.FilterOperatorExists:
|
||||
return "EXISTS"
|
||||
case qbtypesv5.FilterOperatorNotExists:
|
||||
return "NOT EXISTS"
|
||||
}
|
||||
return "?"
|
||||
}
|
||||
|
||||
func trimQuotes(s string) string {
|
||||
if len(s) >= 2 {
|
||||
if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') {
|
||||
s = s[1 : len(s)-1]
|
||||
}
|
||||
}
|
||||
s = strings.ReplaceAll(s, `\\`, `\`)
|
||||
s = strings.ReplaceAll(s, `\'`, `'`)
|
||||
return s
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package impldashboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/sqlstore"
|
||||
@@ -63,6 +64,155 @@ func (store *store) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID)
|
||||
return storableDashboard, nil
|
||||
}
|
||||
|
||||
// ListForUser emits the joined dashboard ⨝ user_dashboard_preference query the
|
||||
// spec calls for. Aliases:
|
||||
//
|
||||
// dashboard — the visitor expects this
|
||||
// user_dashboard_preference AS preference — only used inside this query
|
||||
//
|
||||
// Sort is "is_pinned DESC, <sort> <order>" so pinned dashboards float to the
|
||||
// top inside the requested ordering. Name-sort goes through the same
|
||||
// JSONExtractString path the visitor uses for name/description filtering.
|
||||
func (store *store) ListForUser(
|
||||
ctx context.Context,
|
||||
orgID valuer.UUID,
|
||||
userID valuer.UUID,
|
||||
params *dashboardtypes.ListDashboardsV2Params,
|
||||
) ([]*dashboardtypes.StorableDashboardWithPinInfo, int64, error) {
|
||||
compiled, err := Compile(params.Query, store.sqlstore.Formatter())
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
type listedRow struct {
|
||||
*dashboardtypes.StorableDashboard `bun:",extend"`
|
||||
|
||||
IsPinned bool `bun:"is_pinned"`
|
||||
Total int64 `bun:"total"`
|
||||
}
|
||||
|
||||
rows := make([]*listedRow, 0)
|
||||
|
||||
q := store.sqlstore.
|
||||
BunDB().
|
||||
NewSelect().
|
||||
Model(&rows).
|
||||
ColumnExpr("dashboard.id, dashboard.org_id, dashboard.name, dashboard.data, dashboard.locked, dashboard.source, dashboard.created_at, dashboard.created_by, dashboard.updated_at, dashboard.updated_by").
|
||||
ColumnExpr("CASE WHEN preference.is_pinned THEN 1 ELSE 0 END AS is_pinned").
|
||||
ColumnExpr("COUNT(*) OVER () AS total").
|
||||
Join("LEFT JOIN user_dashboard_preference AS preference ON preference.user_id = ? AND preference.dashboard_id = dashboard.id", userID).
|
||||
Where("dashboard.org_id = ?", orgID).
|
||||
Where("dashboard.source != ?", dashboardtypes.SourceSystem)
|
||||
|
||||
if compiled != nil {
|
||||
q = q.Where(compiled.SQL, compiled.Args...)
|
||||
}
|
||||
|
||||
sortExpr, err := store.sortExprForListV2(params.Sort)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
q = q.
|
||||
OrderExpr("is_pinned DESC").
|
||||
OrderExpr(sortExpr + " " + strings.ToUpper(params.Order.StringValue())).
|
||||
Limit(params.Limit).
|
||||
Offset(params.Offset)
|
||||
|
||||
if err := q.Scan(ctx); err != nil {
|
||||
return nil, 0, errors.WrapInternalf(err, errors.CodeInternal, "couldn't list dashboards")
|
||||
}
|
||||
|
||||
// COUNT(*) OVER () is computed pre-LIMIT, so any returned row carries the
|
||||
// full filter total. Empty result page => zero matches.
|
||||
var total int64
|
||||
if len(rows) > 0 {
|
||||
total = rows[0].Total
|
||||
}
|
||||
|
||||
out := make([]*dashboardtypes.StorableDashboardWithPinInfo, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = &dashboardtypes.StorableDashboardWithPinInfo{
|
||||
Dashboard: r.StorableDashboard,
|
||||
Pinned: r.IsPinned,
|
||||
}
|
||||
}
|
||||
return out, total, nil
|
||||
}
|
||||
|
||||
// ListV2 is the pure (user-independent) list: the same filter/sort/pagination as
|
||||
// ListForUser, but without the per-user pin join or pin-first ordering.
|
||||
func (store *store) ListV2(
|
||||
ctx context.Context,
|
||||
orgID valuer.UUID,
|
||||
params *dashboardtypes.ListDashboardsV2Params,
|
||||
) ([]*dashboardtypes.StorableDashboard, int64, error) {
|
||||
compiled, err := Compile(params.Query, store.sqlstore.Formatter())
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
type listedRow struct {
|
||||
*dashboardtypes.StorableDashboard `bun:",extend"`
|
||||
|
||||
Total int64 `bun:"total"`
|
||||
}
|
||||
|
||||
rows := make([]*listedRow, 0)
|
||||
|
||||
q := store.sqlstore.
|
||||
BunDB().
|
||||
NewSelect().
|
||||
Model(&rows).
|
||||
ColumnExpr("dashboard.id, dashboard.org_id, dashboard.name, dashboard.data, dashboard.locked, dashboard.source, dashboard.created_at, dashboard.created_by, dashboard.updated_at, dashboard.updated_by").
|
||||
ColumnExpr("COUNT(*) OVER () AS total").
|
||||
Where("dashboard.org_id = ?", orgID).
|
||||
Where("dashboard.source != ?", dashboardtypes.SourceSystem)
|
||||
|
||||
if compiled != nil {
|
||||
q = q.Where(compiled.SQL, compiled.Args...)
|
||||
}
|
||||
|
||||
sortExpr, err := store.sortExprForListV2(params.Sort)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
q = q.
|
||||
OrderExpr(sortExpr + " " + strings.ToUpper(params.Order.StringValue())).
|
||||
Limit(params.Limit).
|
||||
Offset(params.Offset)
|
||||
|
||||
if err := q.Scan(ctx); err != nil {
|
||||
return nil, 0, errors.WrapInternalf(err, errors.CodeInternal, "couldn't list dashboards")
|
||||
}
|
||||
|
||||
// COUNT(*) OVER () is computed pre-LIMIT, so any returned row carries the
|
||||
// full filter total. Empty result page => zero matches.
|
||||
var total int64
|
||||
if len(rows) > 0 {
|
||||
total = rows[0].Total
|
||||
}
|
||||
|
||||
out := make([]*dashboardtypes.StorableDashboard, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = r.StorableDashboard
|
||||
}
|
||||
return out, total, nil
|
||||
}
|
||||
|
||||
// sortExprForListV2 maps a sort enum to the SQL expression to plug into
|
||||
// ORDER BY. Title-sort routes through the SQLFormatter so it stays
|
||||
// dialect-aware (matches what the filter visitor does for the name filter).
|
||||
func (store *store) sortExprForListV2(sort dashboardtypes.ListSort) (string, error) {
|
||||
switch sort {
|
||||
case dashboardtypes.ListSortUpdatedAt:
|
||||
return "dashboard.updated_at", nil
|
||||
case dashboardtypes.ListSortCreatedAt:
|
||||
return "dashboard.created_at", nil
|
||||
case dashboardtypes.ListSortName:
|
||||
return string(store.sqlstore.Formatter().JSONExtractString("dashboard.data", "$.spec.display.name")), nil
|
||||
}
|
||||
return "", errors.Newf(errors.TypeInvalidInput, dashboardtypes.ErrCodeDashboardListInvalid,
|
||||
"unsupported sort field %q", sort)
|
||||
}
|
||||
|
||||
func (store *store) GetPublic(ctx context.Context, dashboardID string) (*dashboardtypes.StorablePublicDashboard, error) {
|
||||
storable := new(dashboardtypes.StorablePublicDashboard)
|
||||
err := store.
|
||||
@@ -217,3 +367,82 @@ func (store *store) RunInTx(ctx context.Context, cb func(ctx context.Context) er
|
||||
return cb(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
// PinForUser combines the count check, the existence check, and the upsert in
|
||||
// a single statement so the limit gate and the insert can't drift between two
|
||||
// round-trips. The count and existence checks gate on is_pinned = true so they
|
||||
// stay correct once the row carries preferences other than the pin.
|
||||
//
|
||||
// pin exists? | pinned count < 10? | WHERE passes? | effect | rows
|
||||
// ------------|--------------------|-------------------------|-------------------------------------|-----
|
||||
// no | yes | yes (count branch) | INSERT new pinned row | 1
|
||||
// no | no | no | nothing (limit hit) | 0
|
||||
// yes | yes | yes (count branch) | INSERT → conflict → UPDATE is_pinned| 1
|
||||
// yes | no | yes (EXISTS OR branch) | INSERT → conflict → UPDATE is_pinned| 1
|
||||
//
|
||||
// rows = 0 is the only signal of a real limit hit.
|
||||
func (store *store) PinForUser(ctx context.Context, preference *dashboardtypes.UserDashboardPreference) error {
|
||||
res, err := store.sqlstore.BunDBCtx(ctx).NewRaw(`
|
||||
INSERT INTO user_dashboard_preference (user_id, dashboard_id, is_pinned)
|
||||
SELECT ?, ?, true
|
||||
WHERE (SELECT COUNT(*) FROM user_dashboard_preference WHERE user_id = ? AND is_pinned = true) < ?
|
||||
OR EXISTS (SELECT 1 FROM user_dashboard_preference WHERE user_id = ? AND dashboard_id = ? AND is_pinned = true)
|
||||
ON CONFLICT (user_id, dashboard_id) DO UPDATE SET is_pinned = true
|
||||
`,
|
||||
preference.UserID, preference.DashboardID,
|
||||
preference.UserID, dashboardtypes.MaxPinnedDashboardsPerUser,
|
||||
preference.UserID, preference.DashboardID,
|
||||
).Exec(ctx)
|
||||
if err != nil {
|
||||
return errors.WrapInternalf(err, errors.CodeInternal, "couldn't pin dashboard for user")
|
||||
}
|
||||
rows, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return errors.WrapInternalf(err, errors.CodeInternal, "couldn't read pin result")
|
||||
}
|
||||
if rows == 0 {
|
||||
return errors.Newf(errors.TypeAlreadyExists, dashboardtypes.ErrCodePinnedDashboardLimitHit,
|
||||
"cannot pin more than %d dashboards", dashboardtypes.MaxPinnedDashboardsPerUser)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnpinForUser deletes the user's preference row. This is fine while is_pinned
|
||||
// is the only preference stored; once the row carries other preferences this
|
||||
// must become an UPDATE that clears is_pinned instead of dropping the row.
|
||||
func (store *store) UnpinForUser(ctx context.Context, userID valuer.UUID, dashboardID valuer.UUID) error {
|
||||
_, err := store.sqlstore.BunDBCtx(ctx).
|
||||
NewDelete().
|
||||
Model((*dashboardtypes.UserDashboardPreference)(nil)).
|
||||
Where("user_id = ?", userID).
|
||||
Where("dashboard_id = ?", dashboardID).
|
||||
Exec(ctx)
|
||||
if err != nil {
|
||||
return errors.WrapInternalf(err, errors.CodeInternal, "couldn't unpin dashboard for user")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *store) DeletePreferencesForDashboard(ctx context.Context, dashboardID valuer.UUID) error {
|
||||
_, err := store.sqlstore.BunDBCtx(ctx).
|
||||
NewDelete().
|
||||
Model((*dashboardtypes.UserDashboardPreference)(nil)).
|
||||
Where("dashboard_id = ?", dashboardID).
|
||||
Exec(ctx)
|
||||
if err != nil {
|
||||
return errors.WrapInternalf(err, errors.CodeInternal, "couldn't delete dashboard preferences")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *store) DeletePreferencesForUser(ctx context.Context, userID valuer.UUID) error {
|
||||
_, err := store.sqlstore.BunDBCtx(ctx).
|
||||
NewDelete().
|
||||
Model((*dashboardtypes.UserDashboardPreference)(nil)).
|
||||
Where("user_id = ?", userID).
|
||||
Exec(ctx)
|
||||
if err != nil {
|
||||
return errors.WrapInternalf(err, errors.CodeInternal, "couldn't delete dashboard preferences")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -42,6 +42,69 @@ func (handler *handler) CreateV2(rw http.ResponseWriter, r *http.Request) {
|
||||
render.Success(rw, http.StatusCreated, dashboard.ToGettableDashboardV2())
|
||||
}
|
||||
|
||||
func (handler *handler) ListV2(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
claims, err := authtypes.ClaimsFromContext(ctx)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
orgID := valuer.MustNewUUID(claims.OrgID)
|
||||
|
||||
params := new(dashboardtypes.ListDashboardsV2Params)
|
||||
if err := binding.Query.BindQuery(r.URL.Query(), params); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
if err := params.Validate(); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
out, err := handler.module.ListV2(ctx, orgID, params)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (handler *handler) ListForUserV2(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
claims, err := authtypes.ClaimsFromContext(ctx)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
orgID := valuer.MustNewUUID(claims.OrgID)
|
||||
userID := valuer.MustNewUUID(claims.IdentityID())
|
||||
|
||||
params := new(dashboardtypes.ListDashboardsV2Params)
|
||||
if err := binding.Query.BindQuery(r.URL.Query(), params); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
if err := params.Validate(); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
out, err := handler.module.ListForUserV2(ctx, orgID, userID, params)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (handler *handler) GetV2(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
@@ -205,3 +268,79 @@ func (handler *handler) PatchV2(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
render.Success(rw, http.StatusOK, dashboard.ToGettableDashboardV2())
|
||||
}
|
||||
|
||||
func (handler *handler) PinV2(rw http.ResponseWriter, r *http.Request) {
|
||||
handler.pinUnpinV2(rw, r, true)
|
||||
}
|
||||
|
||||
func (handler *handler) UnpinV2(rw http.ResponseWriter, r *http.Request) {
|
||||
handler.pinUnpinV2(rw, r, false)
|
||||
}
|
||||
|
||||
func (handler *handler) pinUnpinV2(rw http.ResponseWriter, r *http.Request, pin bool) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
claims, err := authtypes.ClaimsFromContext(ctx)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
orgID := valuer.MustNewUUID(claims.OrgID)
|
||||
userID := valuer.MustNewUUID(claims.IdentityID())
|
||||
|
||||
id := mux.Vars(r)["id"]
|
||||
if id == "" {
|
||||
render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is missing in the path"))
|
||||
return
|
||||
}
|
||||
dashboardID, err := valuer.NewUUID(id)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
if pin {
|
||||
err = handler.module.PinV2(ctx, orgID, userID, dashboardID)
|
||||
} else {
|
||||
err = handler.module.UnpinV2(ctx, userID, dashboardID)
|
||||
}
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusNoContent, nil)
|
||||
}
|
||||
|
||||
func (handler *handler) DeleteV2(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
claims, err := authtypes.ClaimsFromContext(ctx)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
orgID := valuer.MustNewUUID(claims.OrgID)
|
||||
|
||||
id := mux.Vars(r)["id"]
|
||||
if id == "" {
|
||||
render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is missing in the path"))
|
||||
return
|
||||
}
|
||||
dashboardID, err := valuer.NewUUID(id)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := handler.module.DeleteV2(ctx, orgID, dashboardID); err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
render.Success(rw, http.StatusNoContent, nil)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/dashboardtypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/tagtypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
@@ -42,6 +43,58 @@ func (m *module) CreateV2(ctx context.Context, orgID valuer.UUID, createdBy stri
|
||||
return dashboard, nil
|
||||
}
|
||||
|
||||
func (module *module) ListV2(ctx context.Context, orgID valuer.UUID, params *dashboardtypes.ListDashboardsV2Params) (*dashboardtypes.ListableDashboardV2, error) {
|
||||
dashboards, total, err := module.store.ListV2(ctx, orgID, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dashboardIDs := make([]valuer.UUID, len(dashboards))
|
||||
for i, d := range dashboards {
|
||||
dashboardIDs[i] = d.ID
|
||||
}
|
||||
|
||||
tagsByDashboard, allTags, err := module.fetchDashboardTags(ctx, orgID, dashboardIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dashboardtypes.NewListableDashboardV2(dashboards, total, tagsByDashboard, allTags)
|
||||
}
|
||||
|
||||
func (module *module) ListForUserV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, params *dashboardtypes.ListDashboardsV2Params) (*dashboardtypes.ListableDashboardForUserV2, error) {
|
||||
rows, total, err := module.store.ListForUser(ctx, orgID, userID, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dashboardIDs := make([]valuer.UUID, len(rows))
|
||||
for i, r := range rows {
|
||||
dashboardIDs[i] = r.Dashboard.ID
|
||||
}
|
||||
|
||||
tagsByDashboard, allTags, err := module.fetchDashboardTags(ctx, orgID, dashboardIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dashboardtypes.NewListableDashboardForUserV2(rows, total, tagsByDashboard, allTags)
|
||||
}
|
||||
|
||||
func (module *module) fetchDashboardTags(ctx context.Context, orgID valuer.UUID, dashboardIDs []valuer.UUID) (map[valuer.UUID][]*tagtypes.Tag, []*tagtypes.Tag, error) {
|
||||
tagsByDashboard, err := module.tagModule.ListForResources(ctx, orgID, coretypes.KindDashboard, dashboardIDs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
allTags, err := module.tagModule.List(ctx, orgID, coretypes.KindDashboard)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return tagsByDashboard, allTags, nil
|
||||
}
|
||||
|
||||
func (module *module) GetV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*dashboardtypes.DashboardV2, error) {
|
||||
storable, err := module.store.Get(ctx, orgID, id)
|
||||
if err != nil {
|
||||
@@ -135,6 +188,27 @@ func (module *module) PatchV2(ctx context.Context, orgID valuer.UUID, id valuer.
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
func (module *module) DeleteV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID) error {
|
||||
existing, err := module.GetV2(ctx, orgID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := existing.CanDelete(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return module.store.RunInTx(ctx, func(ctx context.Context) error {
|
||||
// Syncing to an empty tag set drops every tag link for the dashboard.
|
||||
if _, err := module.tagModule.SyncTags(ctx, orgID, coretypes.KindDashboard, id, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := module.store.DeletePreferencesForDashboard(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return module.store.Delete(ctx, orgID, id)
|
||||
})
|
||||
}
|
||||
|
||||
func (module *module) LockUnlockV2(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, isAdmin bool, lock bool) error {
|
||||
existing, err := module.GetV2(ctx, orgID, id)
|
||||
if err != nil {
|
||||
@@ -149,3 +223,18 @@ func (module *module) LockUnlockV2(ctx context.Context, orgID valuer.UUID, id va
|
||||
}
|
||||
return module.store.Update(ctx, orgID, storable)
|
||||
}
|
||||
|
||||
func (module *module) PinV2(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, id valuer.UUID) error {
|
||||
if _, err := module.GetV2(ctx, orgID, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return module.store.PinForUser(ctx, dashboardtypes.NewUserDashboardPreference(userID, id))
|
||||
}
|
||||
|
||||
func (module *module) UnpinV2(ctx context.Context, userID valuer.UUID, id valuer.UUID) error {
|
||||
return module.store.UnpinForUser(ctx, userID, id)
|
||||
}
|
||||
|
||||
func (module *module) DeletePreferencesForUser(ctx context.Context, userID valuer.UUID) error {
|
||||
return module.store.DeletePreferencesForUser(ctx, userID)
|
||||
}
|
||||
|
||||
@@ -67,6 +67,10 @@ func (m *module) syncLinksForResource(ctx context.Context, orgID valuer.UUID, ki
|
||||
})
|
||||
}
|
||||
|
||||
func (m *module) List(ctx context.Context, orgID valuer.UUID, kind coretypes.Kind) ([]*tagtypes.Tag, error) {
|
||||
return m.store.List(ctx, orgID, kind)
|
||||
}
|
||||
|
||||
func (m *module) ListForResource(ctx context.Context, orgID valuer.UUID, kind coretypes.Kind, resourceID valuer.UUID) ([]*tagtypes.Tag, error) {
|
||||
return m.store.ListByResource(ctx, orgID, kind, resourceID)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,9 @@ type Module interface {
|
||||
// and reconciles the resource's links to exactly that set, all in one transaction.
|
||||
SyncTags(ctx context.Context, orgID valuer.UUID, kind coretypes.Kind, resourceID valuer.UUID, postable []tagtypes.PostableTag) ([]*tagtypes.Tag, error)
|
||||
|
||||
// List returns every tag of the given kind in the org.
|
||||
List(ctx context.Context, orgID valuer.UUID, kind coretypes.Kind) ([]*tagtypes.Tag, error)
|
||||
|
||||
ListForResource(ctx context.Context, orgID valuer.UUID, kind coretypes.Kind, resourceID valuer.UUID) ([]*tagtypes.Tag, error)
|
||||
|
||||
// Resources with no tags are absent from the returned map.
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/SigNoz/signoz/pkg/emailing"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
"github.com/SigNoz/signoz/pkg/modules/dashboard"
|
||||
"github.com/SigNoz/signoz/pkg/modules/organization"
|
||||
root "github.com/SigNoz/signoz/pkg/modules/user"
|
||||
"github.com/SigNoz/signoz/pkg/tokenizer"
|
||||
@@ -34,10 +35,11 @@ type setter struct {
|
||||
analytics analytics.Analytics
|
||||
config root.Config
|
||||
getter root.Getter
|
||||
dashboard dashboard.Module
|
||||
}
|
||||
|
||||
// This module is a WIP, don't take inspiration from this.
|
||||
func NewSetter(store types.UserStore, tokenizer tokenizer.Tokenizer, emailing emailing.Emailing, providerSettings factory.ProviderSettings, orgSetter organization.Setter, authz authz.AuthZ, analytics analytics.Analytics, config root.Config, userRoleStore authtypes.UserRoleStore, getter root.Getter) root.Setter {
|
||||
func NewSetter(store types.UserStore, tokenizer tokenizer.Tokenizer, emailing emailing.Emailing, providerSettings factory.ProviderSettings, orgSetter organization.Setter, authz authz.AuthZ, analytics analytics.Analytics, config root.Config, userRoleStore authtypes.UserRoleStore, getter root.Getter, dashboard dashboard.Module) root.Setter {
|
||||
settings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/pkg/modules/user/impluser")
|
||||
return &setter{
|
||||
store: store,
|
||||
@@ -50,6 +52,7 @@ func NewSetter(store types.UserStore, tokenizer tokenizer.Tokenizer, emailing em
|
||||
authz: authz,
|
||||
config: config,
|
||||
getter: getter,
|
||||
dashboard: dashboard,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -406,6 +409,10 @@ func (module *setter) DeleteUser(ctx context.Context, orgID valuer.UUID, id stri
|
||||
return err
|
||||
}
|
||||
|
||||
if err := module.dashboard.DeletePreferencesForUser(ctx, user.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
traitsOrProperties := types.NewTraitsFromUser(user)
|
||||
module.analytics.IdentifyUser(ctx, user.OrgID.String(), user.ID.String(), traitsOrProperties)
|
||||
module.analytics.TrackUser(ctx, user.OrgID.String(), user.ID.String(), "User Deleted", map[string]any{
|
||||
|
||||
33
pkg/parser/filterquery/parse.go
Normal file
33
pkg/parser/filterquery/parse.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package filterquery
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
grammar "github.com/SigNoz/signoz/pkg/parser/filterquery/grammar"
|
||||
"github.com/antlr4-go/antlr/v4"
|
||||
)
|
||||
|
||||
func Parse(query string) (antlr.ParseTree, *antlr.CommonTokenStream, *ErrorCollector) {
|
||||
collector := NewErrorCollector()
|
||||
lexer := grammar.NewFilterQueryLexer(antlr.NewInputStream(query))
|
||||
lexer.RemoveErrorListeners()
|
||||
lexer.AddErrorListener(collector)
|
||||
tokens := antlr.NewCommonTokenStream(lexer, 0)
|
||||
parser := grammar.NewFilterQueryParser(tokens)
|
||||
parser.RemoveErrorListeners()
|
||||
parser.AddErrorListener(collector)
|
||||
return parser.Query(), tokens, collector
|
||||
}
|
||||
|
||||
type ErrorCollector struct {
|
||||
*antlr.DefaultErrorListener
|
||||
Errors []string
|
||||
}
|
||||
|
||||
func NewErrorCollector() *ErrorCollector {
|
||||
return &ErrorCollector{}
|
||||
}
|
||||
|
||||
func (c *ErrorCollector) SyntaxError(_ antlr.Recognizer, _ any, line, column int, msg string, _ antlr.RecognitionException) {
|
||||
c.Errors = append(c.Errors, fmt.Sprintf("syntax error at %d:%d — %s", line, column, msg))
|
||||
}
|
||||
@@ -361,6 +361,10 @@ func (q *querier) resolveMetricMetadata(ctx context.Context, queries []qbtypes.Q
|
||||
missingMetrics = append(missingMetrics, spec.Aggregations[i].MetricName)
|
||||
continue
|
||||
}
|
||||
// Type is resolved now; validate aggregation compatibility against it.
|
||||
if err := spec.Aggregations[i].ValidateForType(); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
presentAggregations = append(presentAggregations, spec.Aggregations[i])
|
||||
}
|
||||
if len(presentAggregations) == 0 {
|
||||
|
||||
@@ -122,7 +122,7 @@ func NewModules(
|
||||
) Modules {
|
||||
quickfilter := implquickfilter.NewModule(implquickfilter.NewStore(sqlstore))
|
||||
orgSetter := implorganization.NewSetter(implorganization.NewStore(sqlstore), alertmanager, quickfilter)
|
||||
userSetter := impluser.NewSetter(impluser.NewStore(sqlstore, providerSettings), tokenizer, emailing, providerSettings, orgSetter, authz, analytics, config.User, userRoleStore, userGetter)
|
||||
userSetter := impluser.NewSetter(impluser.NewStore(sqlstore, providerSettings), tokenizer, emailing, providerSettings, orgSetter, authz, analytics, config.User, userRoleStore, userGetter, dashboard)
|
||||
ruleStore := sqlrulestore.NewRuleStore(sqlstore, queryParser, providerSettings)
|
||||
|
||||
return Modules{
|
||||
|
||||
@@ -211,6 +211,7 @@ func NewSQLMigrationProviderFactories(
|
||||
sqlmigration.NewAddDashboardNameFactory(sqlstore, sqlschema),
|
||||
sqlmigration.NewFixChangelogOperationTypeFactory(sqlstore, sqlschema),
|
||||
sqlmigration.NewCloudIntegrationRemoveCascadeDeleteFactory(sqlschema),
|
||||
sqlmigration.NewAddUserDashboardPreferenceFactory(sqlstore, sqlschema),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
71
pkg/sqlmigration/092_add_user_dashboard_preference.go
Normal file
71
pkg/sqlmigration/092_add_user_dashboard_preference.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package sqlmigration
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
"github.com/SigNoz/signoz/pkg/sqlschema"
|
||||
"github.com/SigNoz/signoz/pkg/sqlstore"
|
||||
"github.com/uptrace/bun"
|
||||
"github.com/uptrace/bun/migrate"
|
||||
)
|
||||
|
||||
type addUserDashboardPreference struct {
|
||||
sqlstore sqlstore.SQLStore
|
||||
sqlschema sqlschema.SQLSchema
|
||||
}
|
||||
|
||||
func NewAddUserDashboardPreferenceFactory(sqlstore sqlstore.SQLStore, sqlschema sqlschema.SQLSchema) factory.ProviderFactory[SQLMigration, Config] {
|
||||
return factory.NewProviderFactory(factory.MustNewName("add_user_dashboard_preference"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
|
||||
return &addUserDashboardPreference{
|
||||
sqlstore: sqlstore,
|
||||
sqlschema: sqlschema,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (migration *addUserDashboardPreference) Register(migrations *migrate.Migrations) error {
|
||||
return migrations.Register(migration.Up, migration.Down)
|
||||
}
|
||||
|
||||
func (migration *addUserDashboardPreference) Up(ctx context.Context, db *bun.DB) error {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
sqls := migration.sqlschema.Operator().CreateTable(&sqlschema.Table{
|
||||
Name: "user_dashboard_preference",
|
||||
Columns: []*sqlschema.Column{
|
||||
{Name: "user_id", DataType: sqlschema.DataTypeText, Nullable: false},
|
||||
{Name: "dashboard_id", DataType: sqlschema.DataTypeText, Nullable: false},
|
||||
{Name: "is_pinned", DataType: sqlschema.DataTypeBoolean, Nullable: false, Default: "false"},
|
||||
},
|
||||
PrimaryKeyConstraint: &sqlschema.PrimaryKeyConstraint{ColumnNames: []sqlschema.ColumnName{"user_id", "dashboard_id"}},
|
||||
ForeignKeyConstraints: []*sqlschema.ForeignKeyConstraint{
|
||||
{
|
||||
ReferencingColumnName: sqlschema.ColumnName("user_id"),
|
||||
ReferencedTableName: sqlschema.TableName("users"),
|
||||
ReferencedColumnName: sqlschema.ColumnName("id"),
|
||||
},
|
||||
{
|
||||
ReferencingColumnName: sqlschema.ColumnName("dashboard_id"),
|
||||
ReferencedTableName: sqlschema.TableName("dashboard"),
|
||||
ReferencedColumnName: sqlschema.ColumnName("id"),
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
for _, sql := range sqls {
|
||||
if _, err := tx.ExecContext(ctx, string(sql)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (migration *addUserDashboardPreference) Down(_ context.Context, _ *bun.DB) error {
|
||||
return nil
|
||||
}
|
||||
59
pkg/types/dashboardtypes/list_filter.go
Normal file
59
pkg/types/dashboardtypes/list_filter.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package dashboardtypes
|
||||
|
||||
import (
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
qbtypesv5 "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
|
||||
)
|
||||
|
||||
var ErrCodeDashboardListFilterInvalid = errors.MustNewCode("dashboard_list_filter_invalid")
|
||||
|
||||
// ReservedOps lists the operators each reserved (column-level) DSL key accepts.
|
||||
// Any non-reserved key is treated as a tag key and uses TagKeyOps.
|
||||
var ReservedOps = map[DSLKey]map[qbtypesv5.FilterOperator]struct{}{
|
||||
DSLKeyName: stringSearchOps(),
|
||||
DSLKeyDescription: stringSearchOps(),
|
||||
DSLKeyCreatedAt: numericRangeOps(),
|
||||
DSLKeyUpdatedAt: numericRangeOps(),
|
||||
DSLKeyCreatedBy: stringSearchOps(),
|
||||
DSLKeyLocked: opsSet(qbtypesv5.FilterOperatorEqual, qbtypesv5.FilterOperatorNotEqual),
|
||||
}
|
||||
|
||||
// TagKeyOps applies to every non-reserved DSL key — the operator targets the
|
||||
// tag's value with an implicit case-insensitive match on the tag's key.
|
||||
var TagKeyOps = opsSet(
|
||||
qbtypesv5.FilterOperatorEqual, qbtypesv5.FilterOperatorNotEqual,
|
||||
qbtypesv5.FilterOperatorLike, qbtypesv5.FilterOperatorNotLike,
|
||||
qbtypesv5.FilterOperatorILike, qbtypesv5.FilterOperatorNotILike,
|
||||
qbtypesv5.FilterOperatorContains, qbtypesv5.FilterOperatorNotContains,
|
||||
qbtypesv5.FilterOperatorRegexp, qbtypesv5.FilterOperatorNotRegexp,
|
||||
qbtypesv5.FilterOperatorIn, qbtypesv5.FilterOperatorNotIn,
|
||||
qbtypesv5.FilterOperatorExists, qbtypesv5.FilterOperatorNotExists,
|
||||
)
|
||||
|
||||
func stringSearchOps() map[qbtypesv5.FilterOperator]struct{} {
|
||||
return opsSet(
|
||||
qbtypesv5.FilterOperatorEqual, qbtypesv5.FilterOperatorNotEqual,
|
||||
qbtypesv5.FilterOperatorLike, qbtypesv5.FilterOperatorNotLike,
|
||||
qbtypesv5.FilterOperatorILike, qbtypesv5.FilterOperatorNotILike,
|
||||
qbtypesv5.FilterOperatorContains, qbtypesv5.FilterOperatorNotContains,
|
||||
qbtypesv5.FilterOperatorRegexp, qbtypesv5.FilterOperatorNotRegexp,
|
||||
qbtypesv5.FilterOperatorIn, qbtypesv5.FilterOperatorNotIn,
|
||||
)
|
||||
}
|
||||
|
||||
func numericRangeOps() map[qbtypesv5.FilterOperator]struct{} {
|
||||
return opsSet(
|
||||
qbtypesv5.FilterOperatorEqual, qbtypesv5.FilterOperatorNotEqual,
|
||||
qbtypesv5.FilterOperatorLessThan, qbtypesv5.FilterOperatorLessThanOrEq,
|
||||
qbtypesv5.FilterOperatorGreaterThan, qbtypesv5.FilterOperatorGreaterThanOrEq,
|
||||
qbtypesv5.FilterOperatorBetween, qbtypesv5.FilterOperatorNotBetween,
|
||||
)
|
||||
}
|
||||
|
||||
func opsSet(ops ...qbtypesv5.FilterOperator) map[qbtypesv5.FilterOperator]struct{} {
|
||||
m := make(map[qbtypesv5.FilterOperator]struct{}, len(ops))
|
||||
for _, op := range ops {
|
||||
m[op] = struct{}{}
|
||||
}
|
||||
return m
|
||||
}
|
||||
192
pkg/types/dashboardtypes/list_v2.go
Normal file
192
pkg/types/dashboardtypes/list_v2.go
Normal file
@@ -0,0 +1,192 @@
|
||||
package dashboardtypes
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/types"
|
||||
"github.com/SigNoz/signoz/pkg/types/tagtypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/perses/spec/go/common"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultListLimit = 20
|
||||
MaxListLimit = 200
|
||||
)
|
||||
|
||||
// ListSort is the sort field for the dashboard list endpoint. The value is a
|
||||
// stable enum so callers can't ask for arbitrary columns.
|
||||
type ListSort struct{ valuer.String }
|
||||
|
||||
var (
|
||||
ListSortUpdatedAt = ListSort{valuer.NewString("updated_at")}
|
||||
ListSortCreatedAt = ListSort{valuer.NewString("created_at")}
|
||||
ListSortName = ListSort{valuer.NewString("name")}
|
||||
)
|
||||
|
||||
func (ListSort) Enum() []any {
|
||||
return []any{ListSortUpdatedAt, ListSortCreatedAt, ListSortName}
|
||||
}
|
||||
|
||||
func (s ListSort) IsValid() bool {
|
||||
return slices.ContainsFunc(s.Enum(), func(v any) bool { return v == s })
|
||||
}
|
||||
|
||||
type ListOrder struct{ valuer.String }
|
||||
|
||||
var (
|
||||
ListOrderAsc = ListOrder{valuer.NewString("asc")}
|
||||
ListOrderDesc = ListOrder{valuer.NewString("desc")}
|
||||
)
|
||||
|
||||
func (ListOrder) Enum() []any {
|
||||
return []any{ListOrderAsc, ListOrderDesc}
|
||||
}
|
||||
|
||||
func (o ListOrder) IsValid() bool {
|
||||
return slices.ContainsFunc(o.Enum(), func(v any) bool { return v == o })
|
||||
}
|
||||
|
||||
var ErrCodeDashboardListInvalid = errors.MustNewCode("dashboard_list_invalid")
|
||||
|
||||
type ListDashboardsV2Params struct {
|
||||
Query string `query:"query"`
|
||||
Sort ListSort `query:"sort"`
|
||||
Order ListOrder `query:"order"`
|
||||
Limit int `query:"limit"`
|
||||
Offset int `query:"offset"`
|
||||
}
|
||||
|
||||
// Validate fills in defaults (sort=updated_at, order=desc, limit=20) and
|
||||
// rejects out-of-allowlist sort/order values and bad limit/offset. Limit is
|
||||
// clamped to MaxListLimit on the high side. Sort/order are case-insensitive —
|
||||
// valuer.String lowercases them at bind time.
|
||||
func (p *ListDashboardsV2Params) Validate() error {
|
||||
if p.Sort.IsZero() {
|
||||
p.Sort = ListSortUpdatedAt
|
||||
} else if !p.Sort.IsValid() {
|
||||
return errors.NewInvalidInputf(ErrCodeDashboardListInvalid,
|
||||
"invalid sort %q — expected one of: `updated_at`, `created_at`, `name`", p.Sort)
|
||||
}
|
||||
|
||||
if p.Order.IsZero() {
|
||||
p.Order = ListOrderDesc
|
||||
} else if !p.Order.IsValid() {
|
||||
return errors.NewInvalidInputf(ErrCodeDashboardListInvalid,
|
||||
"invalid order %q — expected `asc` or `desc`", p.Order)
|
||||
}
|
||||
|
||||
if p.Limit == 0 {
|
||||
p.Limit = DefaultListLimit
|
||||
} else if p.Limit < 0 {
|
||||
return errors.NewInvalidInputf(ErrCodeDashboardListInvalid,
|
||||
"invalid limit %d — must be a positive integer", p.Limit)
|
||||
} else if p.Limit > MaxListLimit {
|
||||
p.Limit = MaxListLimit
|
||||
}
|
||||
|
||||
if p.Offset < 0 {
|
||||
return errors.NewInvalidInputf(ErrCodeDashboardListInvalid,
|
||||
"invalid offset %d — must be a non-negative integer", p.Offset)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type listedDashboardV2 struct {
|
||||
types.Identifiable
|
||||
types.TimeAuditable
|
||||
types.UserAuditable
|
||||
|
||||
OrgID valuer.UUID `json:"orgId" required:"true"`
|
||||
Locked bool `json:"locked" required:"true"`
|
||||
Source Source `json:"source" required:"true"`
|
||||
SchemaVersion string `json:"schemaVersion" required:"true"`
|
||||
Name string `json:"name" required:"true"`
|
||||
Image string `json:"image,omitempty"`
|
||||
Tags []*tagtypes.GettableTag `json:"tags" required:"true" nullable:"false"`
|
||||
Spec listedDashboardV2Spec `json:"spec" required:"true"`
|
||||
}
|
||||
|
||||
type listedDashboardV2Spec struct {
|
||||
Display *common.Display `json:"display,omitempty"`
|
||||
}
|
||||
|
||||
func newListedDashboardV2(v2 *DashboardV2) *listedDashboardV2 {
|
||||
return &listedDashboardV2{
|
||||
Identifiable: v2.Identifiable,
|
||||
TimeAuditable: v2.TimeAuditable,
|
||||
UserAuditable: v2.UserAuditable,
|
||||
OrgID: v2.OrgID,
|
||||
Locked: v2.Locked,
|
||||
Source: v2.Source,
|
||||
SchemaVersion: v2.SchemaVersion,
|
||||
Name: v2.Name,
|
||||
Image: v2.Image,
|
||||
Tags: tagtypes.NewGettableTagsFromTags(v2.Tags),
|
||||
Spec: listedDashboardV2Spec{Display: v2.Spec.Display},
|
||||
}
|
||||
}
|
||||
|
||||
type ListableDashboardV2 struct {
|
||||
Dashboards []*listedDashboardV2 `json:"dashboards" required:"true" nullable:"false"`
|
||||
Total int64 `json:"total" required:"true"`
|
||||
Tags []*tagtypes.GettableTag `json:"tags" required:"true" nullable:"false"`
|
||||
}
|
||||
|
||||
func NewListableDashboardV2(dashboards []*StorableDashboard, total int64, tagsByEntity map[valuer.UUID][]*tagtypes.Tag, allTags []*tagtypes.Tag) (*ListableDashboardV2, error) {
|
||||
items := make([]*listedDashboardV2, len(dashboards))
|
||||
for i, d := range dashboards {
|
||||
v2, err := d.ToDashboardV2(tagsByEntity[d.ID])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items[i] = newListedDashboardV2(v2)
|
||||
}
|
||||
return &ListableDashboardV2{
|
||||
Dashboards: items,
|
||||
Total: total,
|
||||
Tags: tagtypes.NewGettableTagsFromTags(allTags),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// listedDashboardForUserV2 is a listed dashboard plus the calling user's pin
|
||||
// state. Only the per-user list endpoint emits this; the pure list omits pins.
|
||||
type listedDashboardForUserV2 struct {
|
||||
listedDashboardV2
|
||||
Pinned bool `json:"pinned" required:"true"`
|
||||
}
|
||||
|
||||
type ListableDashboardForUserV2 struct {
|
||||
Dashboards []*listedDashboardForUserV2 `json:"dashboards" required:"true" nullable:"false"`
|
||||
Total int64 `json:"total" required:"true"`
|
||||
Tags []*tagtypes.GettableTag `json:"tags" required:"true" nullable:"false"`
|
||||
}
|
||||
|
||||
// StorableDashboardWithPinInfo is the per-row shape Store.ListForUser returns: the dashboard
|
||||
// joined with the calling user's pin state, so the module layer can attach tags
|
||||
// and assemble the gettable view.
|
||||
type StorableDashboardWithPinInfo struct {
|
||||
Dashboard *StorableDashboard
|
||||
Pinned bool
|
||||
}
|
||||
|
||||
func NewListableDashboardForUserV2(rows []*StorableDashboardWithPinInfo, total int64, tagsByEntity map[valuer.UUID][]*tagtypes.Tag, allTags []*tagtypes.Tag) (*ListableDashboardForUserV2, error) {
|
||||
items := make([]*listedDashboardForUserV2, len(rows))
|
||||
for i, r := range rows {
|
||||
v2, err := r.Dashboard.ToDashboardV2(tagsByEntity[r.Dashboard.ID])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items[i] = &listedDashboardForUserV2{
|
||||
listedDashboardV2: *newListedDashboardV2(v2),
|
||||
Pinned: r.Pinned,
|
||||
}
|
||||
}
|
||||
return &ListableDashboardForUserV2{
|
||||
Dashboards: items,
|
||||
Total: total,
|
||||
Tags: tagtypes.NewGettableTagsFromTags(allTags),
|
||||
}, nil
|
||||
}
|
||||
@@ -31,7 +31,7 @@ const (
|
||||
DSLKeyUpdatedAt DSLKey = "updated_at"
|
||||
DSLKeyCreatedBy DSLKey = "created_by"
|
||||
DSLKeyLocked DSLKey = "locked"
|
||||
DSLKeyPublic DSLKey = "public"
|
||||
DSLKeySource DSLKey = "source"
|
||||
)
|
||||
|
||||
// reservedDSLKeys are dashboard column-level filter names in the list-query DSL.
|
||||
@@ -44,7 +44,7 @@ var reservedDSLKeys = map[DSLKey]struct{}{
|
||||
DSLKeyUpdatedAt: {},
|
||||
DSLKeyCreatedBy: {},
|
||||
DSLKeyLocked: {},
|
||||
DSLKeyPublic: {},
|
||||
DSLKeySource: {},
|
||||
}
|
||||
|
||||
type DashboardV2 struct {
|
||||
@@ -110,6 +110,16 @@ func (d *DashboardV2) LockUnlock(lock bool, isAdmin bool, updatedBy string) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DashboardV2) CanDelete() error {
|
||||
if d.Locked {
|
||||
return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot delete a locked dashboard, please unlock the dashboard to delete")
|
||||
}
|
||||
if !d.Source.isUserDeletable() {
|
||||
return errors.Newf(errors.TypeInvalidInput, ErrCodeDashboardImmutable, "%s dashboards cannot be deleted", d.Source)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type DashboardV2MetadataBase struct {
|
||||
SchemaVersion string `json:"schemaVersion" required:"true"`
|
||||
Image string `json:"image,omitempty"`
|
||||
|
||||
@@ -22,10 +22,19 @@ type PanelPlugin struct {
|
||||
Spec any `json:"spec"`
|
||||
}
|
||||
|
||||
// PrepareJSONSchema drops the reflected struct shape (type: object, properties)
|
||||
// from the envelope so that only the JSONSchemaOneOf result binds.
|
||||
// PrepareJSONSchema marks the envelope with x-signoz-discriminator;
|
||||
// signoz.attachDiscriminators promotes it to a real OpenAPI 3 discriminator
|
||||
// (and strips the duplicate parent properties) after reflection.
|
||||
func (PanelPlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
|
||||
return clearOneOfParentShape(s)
|
||||
return markDiscriminator(s, "kind", map[string]string{
|
||||
string(PanelKindTimeSeries): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpec"),
|
||||
string(PanelKindBarChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec"),
|
||||
string(PanelKindNumber): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpec"),
|
||||
string(PanelKindPieChart): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesPieChartPanelSpec"),
|
||||
string(PanelKindTable): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpec"),
|
||||
string(PanelKindHistogram): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec"),
|
||||
string(PanelKindList): schemaRef("DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec"),
|
||||
})
|
||||
}
|
||||
|
||||
func (p *PanelPlugin) UnmarshalJSON(data []byte) error {
|
||||
@@ -77,7 +86,14 @@ type QueryPlugin struct {
|
||||
}
|
||||
|
||||
func (QueryPlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
|
||||
return clearOneOfParentShape(s)
|
||||
return markDiscriminator(s, "kind", map[string]string{
|
||||
string(QueryKindBuilder): schemaRef("DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBuilderQuerySpec"),
|
||||
string(QueryKindComposite): schemaRef("DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5CompositeQuery"),
|
||||
string(QueryKindFormula): schemaRef("DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5QueryBuilderFormula"),
|
||||
string(QueryKindPromQL): schemaRef("DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5PromQuery"),
|
||||
string(QueryKindClickHouseSQL): schemaRef("DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5ClickHouseQuery"),
|
||||
string(QueryKindTraceOperator): schemaRef("DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5QueryBuilderTraceOperator"),
|
||||
})
|
||||
}
|
||||
|
||||
func (p *QueryPlugin) UnmarshalJSON(data []byte) error {
|
||||
@@ -128,7 +144,11 @@ type VariablePlugin struct {
|
||||
}
|
||||
|
||||
func (VariablePlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
|
||||
return clearOneOfParentShape(s)
|
||||
return markDiscriminator(s, "kind", map[string]string{
|
||||
string(VariableKindDynamic): schemaRef("DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDynamicVariableSpec"),
|
||||
string(VariableKindQuery): schemaRef("DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesQueryVariableSpec"),
|
||||
string(VariableKindCustom): schemaRef("DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesCustomVariableSpec"),
|
||||
})
|
||||
}
|
||||
|
||||
func (p *VariablePlugin) UnmarshalJSON(data []byte) error {
|
||||
@@ -176,7 +196,9 @@ type DatasourcePlugin struct {
|
||||
}
|
||||
|
||||
func (DatasourcePlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
|
||||
return clearOneOfParentShape(s)
|
||||
return markDiscriminator(s, "kind", map[string]string{
|
||||
string(DatasourceKindSigNoz): schemaRef("DashboardtypesDatasourcePluginVariantStruct"),
|
||||
})
|
||||
}
|
||||
|
||||
func (p *DatasourcePlugin) UnmarshalJSON(data []byte) error {
|
||||
@@ -291,10 +313,28 @@ func decodeSpec(specJSON []byte, target any, kind string) (any, error) {
|
||||
return target, nil
|
||||
}
|
||||
|
||||
// clearOneOfParentShape drops Type and Properties on a schema that also has a JSONSchemaOneOf.
|
||||
func clearOneOfParentShape(s *jsonschema.Schema) error {
|
||||
s.Type = nil
|
||||
s.Properties = nil
|
||||
// signozDiscriminatorKey is the extension key that signoz.attachDiscriminators
|
||||
// promotes into a native OpenAPI 3 discriminator after reflection.
|
||||
const signozDiscriminatorKey = "x-signoz-discriminator"
|
||||
|
||||
// schemaRef builds a local component schema reference for a discriminator mapping.
|
||||
func schemaRef(name string) string {
|
||||
return "#/components/schemas/" + name
|
||||
}
|
||||
|
||||
// markDiscriminator tags a oneOf envelope schema with x-signoz-discriminator so
|
||||
// signoz.attachDiscriminators promotes it to a real OpenAPI 3 discriminator,
|
||||
// keyed on propertyName, with the given value -> schema-ref mapping. This turns
|
||||
// the union into a discriminated DTO (instead of an intersection) for generated
|
||||
// clients.
|
||||
func markDiscriminator(s *jsonschema.Schema, propertyName string, mapping map[string]string) error {
|
||||
if s.ExtraProperties == nil {
|
||||
s.ExtraProperties = map[string]any{}
|
||||
}
|
||||
s.ExtraProperties[signozDiscriminatorKey] = map[string]any{
|
||||
"propertyName": propertyName,
|
||||
"mapping": mapping,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -87,7 +87,10 @@ type Variable struct {
|
||||
}
|
||||
|
||||
func (Variable) PrepareJSONSchema(s *jsonschema.Schema) error {
|
||||
return clearOneOfParentShape(s)
|
||||
return markDiscriminator(s, "kind", map[string]string{
|
||||
string(variable.KindList): schemaRef("DashboardtypesVariableEnvelopeGithubComSigNozSignozPkgTypesDashboardtypesListVariableSpec"),
|
||||
string(variable.KindText): schemaRef("DashboardtypesVariableEnvelopeGithubComPersesSpecGoDashboardTextVariableSpec"),
|
||||
})
|
||||
}
|
||||
|
||||
func (v *Variable) UnmarshalJSON(data []byte) error {
|
||||
@@ -167,7 +170,9 @@ var layoutSpecs = map[dashboard.LayoutKind]func() any{
|
||||
}
|
||||
|
||||
func (Layout) PrepareJSONSchema(s *jsonschema.Schema) error {
|
||||
return clearOneOfParentShape(s)
|
||||
return markDiscriminator(s, "kind", map[string]string{
|
||||
string(dashboard.KindGridLayout): schemaRef("DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpec"),
|
||||
})
|
||||
}
|
||||
|
||||
func (l *Layout) UnmarshalJSON(data []byte) error {
|
||||
|
||||
@@ -93,14 +93,21 @@ func (b BuilderQuerySpec) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(b.Spec)
|
||||
}
|
||||
|
||||
// PrepareJSONSchema drops the reflected struct shape so only the
|
||||
// JSONSchemaOneOf result binds.
|
||||
// PrepareJSONSchema marks the envelope with x-signoz-discriminator keyed on
|
||||
// `signal`. Each QueryBuilderQuery[T] variant pins `signal` to its one value
|
||||
// (via its own PrepareJSONSchema in the qb package), so the union resolves
|
||||
// cleanly even though it doesn't carry a `kind`.
|
||||
func (BuilderQuerySpec) PrepareJSONSchema(s *jsonschema.Schema) error {
|
||||
return clearOneOfParentShape(s)
|
||||
return markDiscriminator(s, "signal", map[string]string{
|
||||
telemetrytypes.SignalLogs.StringValue(): schemaRef("Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregation"),
|
||||
telemetrytypes.SignalMetrics.StringValue(): schemaRef("Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregation"),
|
||||
telemetrytypes.SignalTraces.StringValue(): schemaRef("Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregation"),
|
||||
})
|
||||
}
|
||||
|
||||
// JSONSchemaOneOf exposes the three signal-dispatched shapes a builder query
|
||||
// can take. Mirrors qb.UnmarshalBuilderQueryBySignal's runtime dispatch.
|
||||
// can take. Mirrors qb.UnmarshalBuilderQueryBySignal's runtime dispatch. Each
|
||||
// QueryBuilderQuery[T] pins its own `signal` enum (see its PrepareJSONSchema).
|
||||
func (BuilderQuerySpec) JSONSchemaOneOf() []any {
|
||||
return []any{
|
||||
qb.QueryBuilderQuery[qb.LogAggregation]{},
|
||||
|
||||
@@ -51,6 +51,10 @@ func (s *Source) UnmarshalJSON(data []byte) error {
|
||||
return s.s.UnmarshalJSON(data)
|
||||
}
|
||||
|
||||
func (s Source) isUserDeletable() bool {
|
||||
return s == SourceUser
|
||||
}
|
||||
|
||||
func NewSource(source string) (Source, error) {
|
||||
candidate := Source{s: valuer.NewString(source)}
|
||||
if !candidate.IsValid() {
|
||||
|
||||
@@ -32,4 +32,23 @@ type Store interface {
|
||||
DeletePublic(context.Context, string) error
|
||||
|
||||
RunInTx(context.Context, func(context.Context) error) error
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════
|
||||
// v2 dashboard methods
|
||||
// ════════════════════════════════════════════════════════════════════════
|
||||
|
||||
// int64 return is the total row count for the filter (pre-limit/offset).
|
||||
// ListV2 is the pure list; ListForUser additionally joins the caller's pins.
|
||||
ListV2(ctx context.Context, orgID valuer.UUID, params *ListDashboardsV2Params) ([]*StorableDashboard, int64, error)
|
||||
|
||||
ListForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, params *ListDashboardsV2Params) ([]*StorableDashboardWithPinInfo, int64, error)
|
||||
|
||||
// Returns ErrCodePinnedDashboardLimitHit when the user is at MaxPinnedDashboardsPerUser.
|
||||
PinForUser(ctx context.Context, preference *UserDashboardPreference) error
|
||||
|
||||
UnpinForUser(ctx context.Context, userID valuer.UUID, dashboardID valuer.UUID) error
|
||||
|
||||
DeletePreferencesForDashboard(ctx context.Context, dashboardID valuer.UUID) error
|
||||
|
||||
DeletePreferencesForUser(ctx context.Context, userID valuer.UUID) error
|
||||
}
|
||||
|
||||
28
pkg/types/dashboardtypes/user_dashboard_preference.go
Normal file
28
pkg/types/dashboardtypes/user_dashboard_preference.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package dashboardtypes
|
||||
|
||||
import (
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
const MaxPinnedDashboardsPerUser = 10
|
||||
|
||||
var ErrCodePinnedDashboardLimitHit = errors.MustNewCode("pinned_dashboard_limit_hit")
|
||||
|
||||
// Only the pin is tracked for now; more preferences can be added later.
|
||||
type UserDashboardPreference struct {
|
||||
bun.BaseModel `bun:"table:user_dashboard_preference,alias:user_dashboard_preference"`
|
||||
|
||||
UserID valuer.UUID `bun:"user_id,pk,type:text"`
|
||||
DashboardID valuer.UUID `bun:"dashboard_id,pk,type:text"`
|
||||
IsPinned bool `bun:"is_pinned,notnull,default:false"`
|
||||
}
|
||||
|
||||
func NewUserDashboardPreference(userID, dashboardID valuer.UUID) *UserDashboardPreference {
|
||||
return &UserDashboardPreference{
|
||||
UserID: userID,
|
||||
DashboardID: dashboardID,
|
||||
IsPinned: true,
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,7 @@ func (t *Type) Scan(src interface{}) error {
|
||||
}
|
||||
|
||||
func (t Type) IsPercentileSpaceAggregationAllowed() bool {
|
||||
return t == HistogramType || t == ExpHistogramType || t == SummaryType
|
||||
return t == HistogramType || t == ExpHistogramType
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
@@ -2,9 +2,11 @@ package querybuildertypesv5
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/types/metrictypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
"github.com/swaggest/jsonschema-go"
|
||||
)
|
||||
|
||||
type QueryBuilderQuery[T any] struct {
|
||||
@@ -69,6 +71,32 @@ type QueryBuilderQuery[T any] struct {
|
||||
ShiftBy int64 `json:"-"`
|
||||
}
|
||||
|
||||
// PrepareJSONSchema pins `signal` to the single value implied by the aggregation
|
||||
// type T, as an inline single-value enum, and marks it required. This lets a
|
||||
// oneOf over the QueryBuilderQuery[T] instantiations be discriminated by signal.
|
||||
func (QueryBuilderQuery[T]) PrepareJSONSchema(s *jsonschema.Schema) error {
|
||||
var signal telemetrytypes.Signal
|
||||
switch any(*new(T)).(type) {
|
||||
case LogAggregation:
|
||||
signal = telemetrytypes.SignalLogs
|
||||
case MetricAggregation:
|
||||
signal = telemetrytypes.SignalMetrics
|
||||
case TraceAggregation:
|
||||
signal = telemetrytypes.SignalTraces
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
if _, ok := s.Properties["signal"]; !ok {
|
||||
return nil
|
||||
}
|
||||
prop := (&jsonschema.Schema{}).WithType(jsonschema.String.Type()).WithEnum(signal.StringValue())
|
||||
s.Properties["signal"] = prop.ToSchemaOrBool()
|
||||
if !slices.Contains(s.Required, "signal") {
|
||||
s.Required = append(s.Required, "signal")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Copy creates a deep copy of the QueryBuilderQuery.
|
||||
func (q QueryBuilderQuery[T]) Copy() QueryBuilderQuery[T] {
|
||||
// start with a shallow copy
|
||||
|
||||
@@ -317,6 +317,19 @@ func (q *QueryBuilderQuery[T]) validateAggregations(cfg validationConfig) error
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m MetricAggregation) ValidateForType() error {
|
||||
if m.SpaceAggregation.IsPercentile() && !m.Type.IsPercentileSpaceAggregationAllowed() {
|
||||
return errors.Newf(
|
||||
errors.TypeInvalidInput,
|
||||
errors.CodeInvalidInput,
|
||||
"invalid space aggregation `%s` for metric type `%s`, percentile space aggregations are only supported for `histogram`, `exponentialhistogram` metric types",
|
||||
m.SpaceAggregation.StringValue(),
|
||||
m.Type.StringValue(),
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (q *QueryBuilderQuery[T]) validateLimitAndPagination(cfg validationConfig) error {
|
||||
if cfg.skipLimitOffsetValidation {
|
||||
return nil
|
||||
|
||||
@@ -1421,3 +1421,62 @@ func TestNonAggregationFieldsSkipped(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMetricAggregationValidateForType(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
metricType metrictypes.Type
|
||||
spaceAggregation metrictypes.SpaceAggregation
|
||||
comparisonParam *metrictypes.ComparisonSpaceAggregationParam
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "percentile on histogram is allowed",
|
||||
metricType: metrictypes.HistogramType,
|
||||
spaceAggregation: metrictypes.SpaceAggregationPercentile95,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "percentile on exponential histogram is allowed",
|
||||
metricType: metrictypes.ExpHistogramType,
|
||||
spaceAggregation: metrictypes.SpaceAggregationPercentile99,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "percentile on summary is not allowed",
|
||||
metricType: metrictypes.SummaryType,
|
||||
spaceAggregation: metrictypes.SpaceAggregationPercentile95,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "percentile on sum is not allowed",
|
||||
metricType: metrictypes.SumType,
|
||||
spaceAggregation: metrictypes.SpaceAggregationPercentile95,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "non-percentile space aggregation on sum is allowed",
|
||||
metricType: metrictypes.SumType,
|
||||
spaceAggregation: metrictypes.SpaceAggregationSum,
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
agg := MetricAggregation{
|
||||
MetricName: "test_metric",
|
||||
Type: tc.metricType,
|
||||
SpaceAggregation: tc.spaceAggregation,
|
||||
ComparisonSpaceAggregationParam: tc.comparisonParam,
|
||||
}
|
||||
err := agg.ValidateForType()
|
||||
if tc.wantErr && err == nil {
|
||||
t.Errorf("expected error, got nil")
|
||||
}
|
||||
if !tc.wantErr && err != nil {
|
||||
t.Errorf("expected no error, got: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ type PostableTag struct {
|
||||
Value string `json:"value" required:"true"`
|
||||
}
|
||||
|
||||
type GettableTag = PostableTag
|
||||
type GettableTag PostableTag
|
||||
|
||||
func NewGettableTagFromTag(tag *Tag) *GettableTag {
|
||||
return &GettableTag{Key: tag.Key, Value: tag.Value}
|
||||
|
||||
695
tests/integration/tests/dashboard/03_v2_dashboard.py
Normal file
695
tests/integration/tests/dashboard/03_v2_dashboard.py
Normal file
@@ -0,0 +1,695 @@
|
||||
import uuid
|
||||
from collections.abc import Callable, Iterator
|
||||
from http import HTTPStatus
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
|
||||
from fixtures.types import Operation, SigNoz
|
||||
|
||||
# The v2 dashboard API. Request shape (current):
|
||||
# {"schemaVersion": "v6", "name": "<dns-1123-label>",
|
||||
# "spec": {"display": {"name": "<human name>"}},
|
||||
# "tags": [{"key": "...", "value": "..."}]}
|
||||
# `name` is a DNS-1123 label identifier and is immutable after create;
|
||||
# `spec.display.name` is the human-facing title used for name-sort/name-filter.
|
||||
|
||||
_BASE = "/api/v2/dashboards"
|
||||
_TIMEOUT = 5
|
||||
|
||||
# This file's tests tag their dashboards with a `suite` marker so list queries
|
||||
# can be scoped server-side. Each test gets its own unique marker (the
|
||||
# suite_marker fixture) so tests stay isolated from each other and from leftovers
|
||||
# in the reused session DB.
|
||||
_SUITE_PREFIX = "dashboardv2"
|
||||
|
||||
|
||||
def _headers(token: str) -> dict:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def _url(signoz: SigNoz, path: str = "") -> str:
|
||||
return signoz.self.host_configs["8080"].get(f"{_BASE}{path}")
|
||||
|
||||
|
||||
def _create(signoz: SigNoz, token: str, body: dict) -> requests.Response:
|
||||
return requests.post(_url(signoz), json=body, headers=_headers(token), timeout=_TIMEOUT)
|
||||
|
||||
|
||||
def _get(signoz: SigNoz, token: str, dashboard_id: str) -> requests.Response:
|
||||
return requests.get(_url(signoz, f"/{dashboard_id}"), headers=_headers(token), timeout=_TIMEOUT)
|
||||
|
||||
|
||||
# The tests exercise the per-user list (carries pin state); the pure list lives
|
||||
# at GET /api/v2/dashboards.
|
||||
def _list(signoz: SigNoz, token: str, **params: object) -> requests.Response:
|
||||
url = signoz.self.host_configs["8080"].get("/api/v2/users/me/dashboards")
|
||||
return requests.get(
|
||||
url,
|
||||
params={k: v for k, v in params.items() if v is not None},
|
||||
headers=_headers(token),
|
||||
timeout=_TIMEOUT,
|
||||
)
|
||||
|
||||
|
||||
# The pure, user-independent list — no pin join, no pinned field.
|
||||
def _list_pure(signoz: SigNoz, token: str, **params: object) -> requests.Response:
|
||||
return requests.get(
|
||||
_url(signoz),
|
||||
params={k: v for k, v in params.items() if v is not None},
|
||||
headers=_headers(token),
|
||||
timeout=_TIMEOUT,
|
||||
)
|
||||
|
||||
|
||||
def _update(signoz: SigNoz, token: str, dashboard_id: str, body: dict) -> requests.Response:
|
||||
return requests.put(
|
||||
_url(signoz, f"/{dashboard_id}"),
|
||||
json=body,
|
||||
headers=_headers(token),
|
||||
timeout=_TIMEOUT,
|
||||
)
|
||||
|
||||
|
||||
def _delete(signoz: SigNoz, token: str, dashboard_id: str) -> requests.Response:
|
||||
return requests.delete(_url(signoz, f"/{dashboard_id}"), headers=_headers(token), timeout=_TIMEOUT)
|
||||
|
||||
|
||||
def _lock(signoz: SigNoz, token: str, dashboard_id: str, lock: bool) -> requests.Response:
|
||||
method = requests.put if lock else requests.delete
|
||||
return method(
|
||||
_url(signoz, f"/{dashboard_id}/lock"),
|
||||
headers=_headers(token),
|
||||
timeout=_TIMEOUT,
|
||||
)
|
||||
|
||||
|
||||
def _pin(signoz: SigNoz, token: str, dashboard_id: str, pin: bool) -> requests.Response:
|
||||
method = requests.put if pin else requests.delete
|
||||
url = signoz.self.host_configs["8080"].get(f"/api/v2/users/me/dashboards/{dashboard_id}/pins")
|
||||
return method(url, headers=_headers(token), timeout=_TIMEOUT)
|
||||
|
||||
|
||||
def _minimal_body(name: str, display: str, tags: list[dict] | None = None) -> dict:
|
||||
return {
|
||||
"schemaVersion": "v6",
|
||||
"name": name,
|
||||
"spec": {"display": {"name": display}},
|
||||
"tags": tags or [],
|
||||
}
|
||||
|
||||
|
||||
# ─── failure cases (create no dashboards) ────────────────────────────────────
|
||||
|
||||
|
||||
def test_create_rejects_wrong_schema_version(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = _create(signoz, token, {})
|
||||
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
body = response.json()
|
||||
assert body["status"] == "error"
|
||||
assert body["error"]["code"] == "dashboard_invalid_input"
|
||||
assert body["error"]["message"] == 'schemaVersion must be "v6", got ""'
|
||||
|
||||
|
||||
def test_create_rejects_missing_name(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = _create(signoz, token, {"schemaVersion": "v6"})
|
||||
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
body = response.json()
|
||||
assert body["error"]["code"] == "dashboard_invalid_input"
|
||||
assert body["error"]["message"] == "name is required"
|
||||
|
||||
|
||||
def test_create_rejects_non_dns_name(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = _create(signoz, token, _minimal_body(name="Not A Label", display="Not A Label"))
|
||||
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert response.json()["error"]["code"] == "dashboard_invalid_input"
|
||||
|
||||
|
||||
def test_create_rejects_unknown_field(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
body = _minimal_body("rejects-unknown", "Rejects Unknown")
|
||||
body["unknownfield"] = "boom"
|
||||
response = _create(signoz, token, body)
|
||||
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert response.json()["error"]["code"] == "dashboard_invalid_input"
|
||||
assert "unknown field" in response.json()["error"]["message"]
|
||||
|
||||
|
||||
def test_create_rejects_reserved_tag_key(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
body = _minimal_body("rejects-reserved", "Rejects Reserved", [{"key": "source", "value": "x"}])
|
||||
response = _create(signoz, token, body)
|
||||
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert response.json()["error"]["code"] == "dashboard_invalid_input"
|
||||
|
||||
|
||||
def test_create_rejects_too_many_tags(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
tags = [{"key": f"k{i}", "value": "v"} for i in range(11)]
|
||||
response = _create(signoz, token, _minimal_body("too-many-tags", "Too Many", tags))
|
||||
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert response.json()["error"]["code"] == "dashboard_invalid_input"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"params",
|
||||
[
|
||||
{"sort": "bogus"},
|
||||
{"order": "bogus"},
|
||||
{"limit": -1},
|
||||
{"offset": -1},
|
||||
],
|
||||
)
|
||||
def test_list_rejects_invalid_params(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
params: dict,
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = _list(signoz, token, **params)
|
||||
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert response.json()["error"]["code"] == "dashboard_list_invalid"
|
||||
|
||||
|
||||
def test_get_rejects_malformed_id(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = _get(signoz, token, "not-a-uuid")
|
||||
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
||||
|
||||
def test_get_missing_dashboard_returns_not_found(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = _get(signoz, token, str(uuid.uuid4()))
|
||||
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
def test_delete_missing_dashboard_returns_not_found(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = _delete(signoz, token, str(uuid.uuid4()))
|
||||
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
def test_pin_missing_dashboard_returns_not_found(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
):
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = _pin(signoz, token, str(uuid.uuid4()), pin=True)
|
||||
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
# ─── lifecycle ───────────────────────────────────────────────────────────────
|
||||
# A single end-to-end flow through create → get → list/filter/sort → pin →
|
||||
# update → lock → delete. Every fixture dashboard carries the shared suite marker
|
||||
# tag so list queries can be scoped server-side, isolating this test from any
|
||||
# other dashboards sharing the session DB.
|
||||
|
||||
|
||||
def _display_names(body: dict) -> list[str]:
|
||||
return [d["spec"]["display"]["name"] for d in body["data"]["dashboards"]]
|
||||
|
||||
|
||||
def _delete_suite(signoz: SigNoz, token: str, suite_filter: str) -> None:
|
||||
response = _list(signoz, token, query=suite_filter, limit=200)
|
||||
if response.status_code != HTTPStatus.OK:
|
||||
return
|
||||
for dashboard in response.json()["data"]["dashboards"]:
|
||||
_delete(signoz, token, dashboard["id"])
|
||||
|
||||
|
||||
@pytest.fixture(name="suite_marker")
|
||||
def _suite_marker(
|
||||
signoz: SigNoz,
|
||||
get_token: Callable[[str, str], str],
|
||||
) -> Iterator[tuple[dict, str]]:
|
||||
"""Yields a per-test unique suite (tag, filter) and deletes its dashboards on teardown.
|
||||
Unique per test so the tests stay isolated from each other and from reused-DB leftovers."""
|
||||
value = f"{_SUITE_PREFIX}-{uuid.uuid4().hex[:8]}"
|
||||
suite_tag = {"key": "suite", "value": value}
|
||||
suite_filter = f"suite = '{value}'"
|
||||
yield suite_tag, suite_filter
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
_delete_suite(signoz, token, suite_filter)
|
||||
|
||||
|
||||
def test_dashboard_v2_lifecycle( # pylint: disable=too-many-locals,too-many-statements
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
suite_marker: tuple[dict, str],
|
||||
):
|
||||
suite_tag, suite_filter = suite_marker
|
||||
|
||||
def _scoped(query: str) -> str:
|
||||
return f"({query}) AND {suite_filter}"
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
dashboard_requests = [
|
||||
(
|
||||
"lc-alpha",
|
||||
"Alpha Overview",
|
||||
[{"key": "team", "value": "pulse"}, {"key": "env", "value": "prod"}],
|
||||
),
|
||||
(
|
||||
"lc-beta",
|
||||
"Beta Overview",
|
||||
[{"key": "team", "value": "pulse"}, {"key": "env", "value": "dev"}],
|
||||
),
|
||||
(
|
||||
"lc-gamma",
|
||||
"Gamma Storage",
|
||||
[{"key": "team", "value": "storage"}, {"key": "env", "value": "prod"}],
|
||||
),
|
||||
(
|
||||
"lc-delta",
|
||||
"Delta Storage",
|
||||
[
|
||||
{"key": "team", "value": "storage"},
|
||||
{"key": "env", "value": "dev"},
|
||||
{"key": "tier", "value": "critical"},
|
||||
],
|
||||
),
|
||||
(
|
||||
"lc-epsilon",
|
||||
"Epsilon Metrics",
|
||||
[
|
||||
{"key": "team", "value": "metrics"},
|
||||
{"key": "env", "value": "staging"},
|
||||
{"key": "tier", "value": "critical"},
|
||||
],
|
||||
),
|
||||
(
|
||||
"lc-zeta",
|
||||
"Zeta Overview",
|
||||
[{"key": "team", "value": "pulse"}, {"key": "env", "value": "staging"}],
|
||||
),
|
||||
]
|
||||
|
||||
# ── stage 1: create ──────────────────────────────────────────────────────
|
||||
ids: dict[str, str] = {}
|
||||
for name, display, tags in dashboard_requests:
|
||||
response = _create(signoz, token, _minimal_body(name, display, [suite_tag, *tags]))
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
ids[name] = response.json()["data"]["id"]
|
||||
|
||||
# TODO: re-enable once the dashboard name unique index lands — creating a
|
||||
# second dashboard with an existing name should conflict (409). Until the
|
||||
# index exists, duplicate names are silently allowed.
|
||||
# response = _create(signoz, token, _minimal_body("lc-alpha", "Alpha Dupe"))
|
||||
# assert response.status_code == HTTPStatus.CONFLICT, response.text
|
||||
|
||||
# ── stage 2: get one and verify the round-tripped shape ──────────────────
|
||||
response = _get(signoz, token, ids["lc-alpha"])
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
alpha = response.json()["data"]
|
||||
assert alpha["id"] == ids["lc-alpha"]
|
||||
assert alpha["name"] == "lc-alpha"
|
||||
assert alpha["spec"]["display"]["name"] == "Alpha Overview"
|
||||
assert alpha["schemaVersion"] == "v6"
|
||||
assert alpha["source"] == "user"
|
||||
assert alpha["locked"] is False
|
||||
assert {"key": "team", "value": "pulse"} in alpha["tags"]
|
||||
|
||||
# ── stage 3: list everything in the suite ────────────────────────────────
|
||||
response = _list(signoz, token, query=suite_filter, limit=200)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
body = response.json()
|
||||
assert body["data"]["total"] == 6
|
||||
assert set(_display_names(body)) == {
|
||||
"Alpha Overview",
|
||||
"Beta Overview",
|
||||
"Gamma Storage",
|
||||
"Delta Storage",
|
||||
"Epsilon Metrics",
|
||||
"Zeta Overview",
|
||||
}
|
||||
|
||||
# ── stage 4: filter DSL ──────────────────────────────────────────────────
|
||||
cases = [
|
||||
(
|
||||
"team = 'pulse'",
|
||||
{"Alpha Overview", "Beta Overview", "Zeta Overview"},
|
||||
),
|
||||
(
|
||||
"env = 'prod'",
|
||||
{"Alpha Overview", "Gamma Storage"},
|
||||
),
|
||||
(
|
||||
"name CONTAINS 'Overview'",
|
||||
{"Alpha Overview", "Beta Overview", "Zeta Overview"},
|
||||
),
|
||||
(
|
||||
"env IN ['dev', 'test']",
|
||||
{"Beta Overview", "Delta Storage"},
|
||||
),
|
||||
(
|
||||
"name LIKE 'Delta%'",
|
||||
{"Delta Storage"},
|
||||
),
|
||||
(
|
||||
"team LIKE 'stor%'",
|
||||
{"Gamma Storage", "Delta Storage"},
|
||||
),
|
||||
(
|
||||
"name ILIKE '%storage'",
|
||||
{"Gamma Storage", "Delta Storage"},
|
||||
),
|
||||
(
|
||||
"name NOT CONTAINS 'Overview'",
|
||||
{"Gamma Storage", "Delta Storage", "Epsilon Metrics"},
|
||||
),
|
||||
(
|
||||
"name NOT LIKE '%Storage'",
|
||||
{
|
||||
"Alpha Overview",
|
||||
"Beta Overview",
|
||||
"Epsilon Metrics",
|
||||
"Zeta Overview",
|
||||
},
|
||||
),
|
||||
(
|
||||
"name NOT ILIKE 'alpha%'",
|
||||
{
|
||||
"Beta Overview",
|
||||
"Gamma Storage",
|
||||
"Delta Storage",
|
||||
"Epsilon Metrics",
|
||||
"Zeta Overview",
|
||||
},
|
||||
),
|
||||
(
|
||||
"team = 'pulse' AND env = 'prod'",
|
||||
{"Alpha Overview"},
|
||||
),
|
||||
(
|
||||
"team = 'storage' OR env = 'staging'",
|
||||
{
|
||||
"Gamma Storage",
|
||||
"Delta Storage",
|
||||
"Epsilon Metrics",
|
||||
"Zeta Overview",
|
||||
},
|
||||
),
|
||||
(
|
||||
"tier EXISTS",
|
||||
{"Delta Storage", "Epsilon Metrics"},
|
||||
),
|
||||
(
|
||||
"tier NOT EXISTS",
|
||||
{
|
||||
"Alpha Overview",
|
||||
"Beta Overview",
|
||||
"Gamma Storage",
|
||||
"Zeta Overview",
|
||||
},
|
||||
),
|
||||
(
|
||||
"NOT team = 'pulse'",
|
||||
{"Gamma Storage", "Delta Storage", "Epsilon Metrics"},
|
||||
),
|
||||
(
|
||||
"(team = 'pulse' OR team = 'storage') AND env = 'prod'",
|
||||
{"Alpha Overview", "Gamma Storage"},
|
||||
),
|
||||
(
|
||||
"NOT (team = 'storage' OR env = 'staging')",
|
||||
{"Alpha Overview", "Beta Overview"},
|
||||
),
|
||||
(
|
||||
"team IN ['pulse', 'metrics'] AND tier EXISTS",
|
||||
{"Epsilon Metrics"},
|
||||
),
|
||||
(
|
||||
"name CONTAINS 'Storage' AND env = 'dev'",
|
||||
{"Delta Storage"},
|
||||
),
|
||||
]
|
||||
for query, expected in cases:
|
||||
response = _list(signoz, token, query=_scoped(query), limit=200)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert set(_display_names(response.json())) == expected, query
|
||||
|
||||
# ── stage 5: name sort honours order ─────────────────────────────────────
|
||||
response = _list(signoz, token, query=suite_filter, sort="name", order="asc", limit=200)
|
||||
assert _display_names(response.json()) == [
|
||||
"Alpha Overview",
|
||||
"Beta Overview",
|
||||
"Delta Storage",
|
||||
"Epsilon Metrics",
|
||||
"Gamma Storage",
|
||||
"Zeta Overview",
|
||||
]
|
||||
response = _list(signoz, token, query=suite_filter, sort="name", order="desc", limit=200)
|
||||
assert _display_names(response.json()) == [
|
||||
"Zeta Overview",
|
||||
"Gamma Storage",
|
||||
"Epsilon Metrics",
|
||||
"Delta Storage",
|
||||
"Beta Overview",
|
||||
"Alpha Overview",
|
||||
]
|
||||
|
||||
# ── stage 6: pinning floats a dashboard to the top of any ordering ───────
|
||||
assert _pin(signoz, token, ids["lc-gamma"], pin=True).status_code == HTTPStatus.NO_CONTENT
|
||||
response = _list(signoz, token, query=suite_filter, sort="name", order="asc", limit=200)
|
||||
dashboards = response.json()["data"]["dashboards"]
|
||||
assert dashboards[0]["name"] == "lc-gamma"
|
||||
assert dashboards[0]["pinned"] is True
|
||||
assert all(d["pinned"] is False for d in dashboards[1:])
|
||||
|
||||
# the pure list is user-independent: the same pin neither reorders it (gamma
|
||||
# stays in natural name order, not floated to the top) nor adds a pinned field.
|
||||
response = _list_pure(signoz, token, query=suite_filter, sort="name", order="asc", limit=200)
|
||||
assert _display_names(response.json()) == [
|
||||
"Alpha Overview",
|
||||
"Beta Overview",
|
||||
"Delta Storage",
|
||||
"Epsilon Metrics",
|
||||
"Gamma Storage",
|
||||
"Zeta Overview",
|
||||
]
|
||||
assert all("pinned" not in d for d in response.json()["data"]["dashboards"])
|
||||
|
||||
# ── stage 7: unpinning restores the natural ordering ─────────────────────
|
||||
assert _pin(signoz, token, ids["lc-gamma"], pin=False).status_code == HTTPStatus.NO_CONTENT
|
||||
response = _list(signoz, token, query=suite_filter, sort="name", order="asc", limit=200)
|
||||
assert _display_names(response.json()) == [
|
||||
"Alpha Overview",
|
||||
"Beta Overview",
|
||||
"Delta Storage",
|
||||
"Epsilon Metrics",
|
||||
"Gamma Storage",
|
||||
"Zeta Overview",
|
||||
]
|
||||
|
||||
# ── stage 8: update mutates the spec but keeps the immutable name ────────
|
||||
update_body = _minimal_body(
|
||||
"lc-alpha",
|
||||
"Alpha Overview",
|
||||
[
|
||||
suite_tag,
|
||||
{"key": "team", "value": "pulse"},
|
||||
{"key": "env", "value": "prod"},
|
||||
],
|
||||
)
|
||||
update_body["spec"]["display"]["description"] = "now with a description"
|
||||
response = _update(signoz, token, ids["lc-alpha"], update_body)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
response = _get(signoz, token, ids["lc-alpha"])
|
||||
assert response.json()["data"]["spec"]["display"]["description"] == "now with a description"
|
||||
|
||||
# ── stage 9: a locked dashboard rejects updates until unlocked ───────────
|
||||
assert _lock(signoz, token, ids["lc-beta"], lock=True).status_code == HTTPStatus.NO_CONTENT
|
||||
beta_body = _minimal_body(
|
||||
"lc-beta",
|
||||
"Beta Overview",
|
||||
[suite_tag, {"key": "team", "value": "pulse"}, {"key": "env", "value": "dev"}],
|
||||
)
|
||||
response = _update(signoz, token, ids["lc-beta"], beta_body)
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert _lock(signoz, token, ids["lc-beta"], lock=False).status_code == HTTPStatus.NO_CONTENT
|
||||
assert _update(signoz, token, ids["lc-beta"], beta_body).status_code == HTTPStatus.OK
|
||||
|
||||
# ── stage 10: delete removes the dashboard from get and list ─────────────
|
||||
assert _delete(signoz, token, ids["lc-gamma"]).status_code == HTTPStatus.NO_CONTENT
|
||||
assert _get(signoz, token, ids["lc-gamma"]).status_code == HTTPStatus.NOT_FOUND
|
||||
response = _list(signoz, token, query=suite_filter, limit=200)
|
||||
assert response.json()["data"]["total"] == 5
|
||||
assert set(_display_names(response.json())) == {
|
||||
"Alpha Overview",
|
||||
"Beta Overview",
|
||||
"Delta Storage",
|
||||
"Epsilon Metrics",
|
||||
"Zeta Overview",
|
||||
}
|
||||
|
||||
|
||||
def test_dashboard_v2_pin_limit(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
suite_marker: tuple[dict, str],
|
||||
):
|
||||
suite_tag, _ = suite_marker
|
||||
max_pinned = 10
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
ids: list[str] = []
|
||||
for i in range(max_pinned + 1):
|
||||
response = _create(signoz, token, _minimal_body(f"pl-{i}", f"Pin Limit {i}", [suite_tag]))
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
ids.append(response.json()["data"]["id"])
|
||||
|
||||
# pinning up to the limit succeeds
|
||||
for dashboard_id in ids[:max_pinned]:
|
||||
assert _pin(signoz, token, dashboard_id, pin=True).status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# re-pinning an already-pinned dashboard is an idempotent no-op, even at the limit
|
||||
assert _pin(signoz, token, ids[0], pin=True).status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# the 11th distinct pin is rejected with the typed limit error
|
||||
response = _pin(signoz, token, ids[max_pinned], pin=True)
|
||||
assert response.status_code == HTTPStatus.CONFLICT, response.text
|
||||
assert response.json()["error"]["code"] == "pinned_dashboard_limit_hit"
|
||||
|
||||
# unpinning frees a slot, so the previously-rejected dashboard can now be pinned
|
||||
assert _pin(signoz, token, ids[0], pin=False).status_code == HTTPStatus.NO_CONTENT
|
||||
assert _pin(signoz, token, ids[max_pinned], pin=True).status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
|
||||
# ─── LIKE escaping ───────────────────────────────────────────────────────────
|
||||
# Backslash is the LIKE escape character, declared explicitly via ESCAPE '\' on
|
||||
# every emitted LIKE/ILIKE. Postgres defaults to backslash; sqlite has no default
|
||||
# escape, so without the clause the two dialects disagree on any pattern carrying
|
||||
# a backslash. Two ways a backslash shows up: CONTAINS injects its own to escape
|
||||
# the user's % and _ (so `50%` matches literally), and LIKE/ILIKE pass through a
|
||||
# user-supplied `\%` / `\_`. These cases assert literal-match semantics so a
|
||||
# dialect that drops the escape fails here. Backslash-bearing queries use raw
|
||||
# python strings so the backslash reaches the DSL verbatim.
|
||||
|
||||
|
||||
def test_dashboard_v2_like_escaping(
|
||||
signoz: SigNoz,
|
||||
create_user_admin: Operation, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
suite_marker: tuple[dict, str],
|
||||
):
|
||||
suite_tag, suite_filter = suite_marker
|
||||
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
dashboard_requests = [
|
||||
("esc-pct", "Cost 50% Report"),
|
||||
("esc-pct-plain", "Cost 5000 Report"),
|
||||
("esc-underscore", "user_id panel"),
|
||||
("esc-underscore-wild", "userXid panel"),
|
||||
]
|
||||
for name, display in dashboard_requests:
|
||||
response = _create(signoz, token, _minimal_body(name, display, [suite_tag]))
|
||||
assert response.status_code == HTTPStatus.CREATED, response.text
|
||||
|
||||
cases = [
|
||||
(
|
||||
"name CONTAINS '50%'",
|
||||
{"Cost 50% Report"},
|
||||
),
|
||||
(
|
||||
"name CONTAINS 'user_id'",
|
||||
{"user_id panel"},
|
||||
),
|
||||
(
|
||||
"name NOT CONTAINS '50%'",
|
||||
{"Cost 5000 Report", "user_id panel", "userXid panel"},
|
||||
),
|
||||
(
|
||||
r"name LIKE 'Cost 50\% Report'",
|
||||
{"Cost 50% Report"},
|
||||
),
|
||||
(
|
||||
r"name ILIKE 'cost 50\% report'",
|
||||
{"Cost 50% Report"},
|
||||
),
|
||||
(
|
||||
r"name LIKE 'user\_id panel'",
|
||||
{"user_id panel"},
|
||||
),
|
||||
(
|
||||
r"name NOT LIKE 'user\_id panel'",
|
||||
{"Cost 50% Report", "Cost 5000 Report", "userXid panel"},
|
||||
),
|
||||
]
|
||||
for query, expected in cases:
|
||||
response = _list(
|
||||
signoz,
|
||||
token,
|
||||
query=f"({query}) AND {suite_filter}",
|
||||
limit=200,
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert set(_display_names(response.json())) == expected, query
|
||||
Reference in New Issue
Block a user