Compare commits

..

12 Commits

Author SHA1 Message Date
Naman Verma
3b38b2a59f Merge branch 'main' into nv/10282 2026-02-23 16:43:57 +05:30
Naman Verma
4b665812b6 Merge branch 'main' into nv/10282 2026-02-18 11:33:00 +05:30
Naman Verma
d5d9215d03 Merge branch 'main' into nv/10282 2026-02-17 18:02:16 +05:30
Naman Verma
3f3b46b4ea fix: remove other instances of metric type being changed 2026-02-17 18:00:58 +05:30
Naman Verma
a9616c1984 test: include ismonotonic in UT query 2026-02-17 18:00:50 +05:30
Naman Verma
c1136c5add Merge branch 'main' into nv/10282 2026-02-17 17:42:04 +05:30
Naman Verma
db9d3e1fca fix: take IsMonotonic from updated metadata as well 2026-02-17 17:41:43 +05:30
Naman Verma
ffccf44c6c fix: change json key to camelCase to match other fields 2026-02-17 11:06:34 +05:30
Naman Verma
cbe564b498 fix: same change for meters 2026-02-17 11:05:59 +05:30
Naman Verma
b6f9023c9b Merge branch 'main' into nv/10282 2026-02-17 10:59:26 +05:30
Naman Verma
da7f62a5d3 Merge branch 'main' into nv/10282 2026-02-16 11:48:33 +05:30
Naman Verma
052cb01e00 feat: include monotonicity in metrics' properties API responses 2026-02-16 09:16:17 +05:30
196 changed files with 3605 additions and 9458 deletions

View File

@@ -41,23 +41,31 @@ services:
interval: 30s
timeout: 5s
retries: 3
telemetrystore-migrator:
image: signoz/signoz-otel-collector:v0.142.0
container_name: telemetrystore-migrator
environment:
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_REPLICATION=true
- SIGNOZ_OTEL_COLLECTOR_TIMEOUT=10m
entrypoint:
- /bin/sh
schema-migrator-sync:
image: signoz/signoz-schema-migrator:v0.142.0
container_name: schema-migrator-sync
command:
- -c
- |
/signoz-otel-collector migrate bootstrap &&
/signoz-otel-collector migrate sync up &&
/signoz-otel-collector migrate async up
- sync
- --cluster-name=cluster
- --dsn=tcp://clickhouse:9000
- --replication=true
- --up=
depends_on:
clickhouse:
condition: service_healthy
restart: on-failure
schema-migrator-async:
image: signoz/signoz-schema-migrator:v0.142.0
container_name: schema-migrator-async
command:
- async
- --cluster-name=cluster
- --dsn=tcp://clickhouse:9000
- --replication=true
- --up=
depends_on:
clickhouse:
condition: service_healthy
schema-migrator-sync:
condition: service_completed_successfully
restart: on-failure

View File

@@ -1,23 +1,14 @@
services:
signoz-otel-collector:
image: signoz/signoz-otel-collector:v0.142.0
image: signoz/signoz-otel-collector:v0.129.6
container_name: signoz-otel-collector-dev
entrypoint:
- /bin/sh
command:
- -c
- |
/signoz-otel-collector migrate sync check &&
/signoz-otel-collector --config=/etc/otel-collector-config.yaml
- --config=/etc/otel-collector-config.yaml
volumes:
- ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
environment:
- OTEL_RESOURCE_ATTRIBUTES=host.name=signoz-host,os.type=linux
- LOW_CARDINAL_EXCEPTION_GROUPING=false
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_REPLICATION=true
- SIGNOZ_OTEL_COLLECTOR_TIMEOUT=10m
ports:
- "4317:4317" # OTLP gRPC receiver
- "4318:4318" # OTLP HTTP receiver

View File

@@ -48,13 +48,12 @@ jobs:
- role
- ttl
- alerts
- ingestionkeys
sqlstore-provider:
- postgres
- sqlite
clickhouse-version:
- 25.5.6
- 25.12.5
- 25.10.5
schema-migrator-version:
- v0.142.0
postgres-version:

View File

@@ -318,6 +318,4 @@ user:
# The password of the root user. Must meet password requirements.
password: ""
# The name of the organization to create or look up for the root user.
org:
name: default
id: 00000000-0000-0000-0000-000000000000
org_name: default

View File

@@ -61,6 +61,7 @@ x-db-depend: &db-depend
- clickhouse
- clickhouse-2
- clickhouse-3
- schema-migrator
services:
init-clickhouse:
!!merge <<: *common
@@ -135,17 +136,12 @@ services:
# - "9000:9000"
# - "8123:8123"
# - "9181:9181"
configs:
- source: clickhouse-config
target: /etc/clickhouse-server/config.xml
- source: clickhouse-users
target: /etc/clickhouse-server/users.xml
- source: clickhouse-custom-function
target: /etc/clickhouse-server/custom-function.xml
- source: clickhouse-cluster
target: /etc/clickhouse-server/config.d/cluster.ha.xml
volumes:
- ../common/clickhouse/config.xml:/etc/clickhouse-server/config.xml
- ../common/clickhouse/users.xml:/etc/clickhouse-server/users.xml
- ../common/clickhouse/custom-function.xml:/etc/clickhouse-server/custom-function.xml
- ../common/clickhouse/user_scripts:/var/lib/clickhouse/user_scripts/
- ../common/clickhouse/cluster.ha.xml:/etc/clickhouse-server/config.d/cluster.xml
- ./clickhouse-setup/data/clickhouse/:/var/lib/clickhouse/
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
clickhouse-2:
@@ -155,17 +151,12 @@ services:
# - "9001:9000"
# - "8124:8123"
# - "9182:9181"
configs:
- source: clickhouse-config
target: /etc/clickhouse-server/config.xml
- source: clickhouse-users
target: /etc/clickhouse-server/users.xml
- source: clickhouse-custom-function
target: /etc/clickhouse-server/custom-function.xml
- source: clickhouse-cluster
target: /etc/clickhouse-server/config.d/cluster.ha.xml
volumes:
- ../common/clickhouse/config.xml:/etc/clickhouse-server/config.xml
- ../common/clickhouse/users.xml:/etc/clickhouse-server/users.xml
- ../common/clickhouse/custom-function.xml:/etc/clickhouse-server/custom-function.xml
- ../common/clickhouse/user_scripts:/var/lib/clickhouse/user_scripts/
- ../common/clickhouse/cluster.ha.xml:/etc/clickhouse-server/config.d/cluster.xml
- ./clickhouse-setup/data/clickhouse-2/:/var/lib/clickhouse/
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
clickhouse-3:
@@ -175,32 +166,37 @@ services:
# - "9002:9000"
# - "8125:8123"
# - "9183:9181"
configs:
- source: clickhouse-config
target: /etc/clickhouse-server/config.xml
- source: clickhouse-users
target: /etc/clickhouse-server/users.xml
- source: clickhouse-custom-function
target: /etc/clickhouse-server/custom-function.xml
- source: clickhouse-cluster
target: /etc/clickhouse-server/config.d/cluster.ha.xml
volumes:
- ../common/clickhouse/config.xml:/etc/clickhouse-server/config.xml
- ../common/clickhouse/users.xml:/etc/clickhouse-server/users.xml
- ../common/clickhouse/custom-function.xml:/etc/clickhouse-server/custom-function.xml
- ../common/clickhouse/user_scripts:/var/lib/clickhouse/user_scripts/
- ../common/clickhouse/cluster.ha.xml:/etc/clickhouse-server/config.d/cluster.xml
- ./clickhouse-setup/data/clickhouse-3/:/var/lib/clickhouse/
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
signoz:
!!merge <<: *db-depend
image: signoz/signoz:v0.113.0
image: signoz/signoz:v0.112.0
command:
- --config=/root/config/prometheus.yml
ports:
- "8080:8080" # signoz port
# - "6060:6060" # pprof port
volumes:
- ../common/signoz/prometheus.yml:/root/config/prometheus.yml
- ../common/dashboards:/root/config/dashboards
- ./clickhouse-setup/data/signoz/:/var/lib/signoz/
environment:
- SIGNOZ_ALERTMANAGER_PROVIDER=signoz
- SIGNOZ_TELEMETRYSTORE_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_SQLSTORE_SQLITE_PATH=/var/lib/signoz/signoz.db
- DASHBOARDS_PATH=/root/config/dashboards
- STORAGE=clickhouse
- GODEBUG=netdns=go
- TELEMETRY_ENABLED=true
- DEPLOYMENT_TYPE=docker-swarm
- SIGNOZ_TOKENIZER_JWT_SECRET=secret
- DOT_METRICS_ENABLED=true
healthcheck:
test:
- CMD
@@ -213,48 +209,40 @@ services:
retries: 3
otel-collector:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:v0.144.1
entrypoint:
- /bin/sh
image: signoz/signoz-otel-collector:v0.142.0
command:
- -c
- |
/signoz-otel-collector migrate sync check &&
/signoz-otel-collector --config=/etc/otel-collector-config.yaml --manager-config=/etc/manager-config.yaml --copy-path=/var/tmp/collector-config.yaml
configs:
- source: otel-collector-config
target: /etc/otel-collector-config.yaml
- source: otel-manager-config
target: /etc/manager-config.yaml
- --config=/etc/otel-collector-config.yaml
- --manager-config=/etc/manager-config.yaml
- --copy-path=/var/tmp/collector-config.yaml
volumes:
- ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
- ../common/signoz/otel-collector-opamp-config.yaml:/etc/manager-config.yaml
environment:
- OTEL_RESOURCE_ATTRIBUTES=host.name={{.Node.Hostname}},os.type={{.Node.Platform.OS}}
- LOW_CARDINAL_EXCEPTION_GROUPING=false
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_REPLICATION=true
- SIGNOZ_OTEL_COLLECTOR_TIMEOUT=10m
ports:
# - "1777:1777" # pprof extension
- "4317:4317" # OTLP gRPC receiver
- "4318:4318" # OTLP HTTP receiver
deploy:
replicas: 3
signoz-telemetrystore-migrator:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:v0.144.1
environment:
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_REPLICATION=true
- SIGNOZ_OTEL_COLLECTOR_TIMEOUT=10m
entrypoint:
- /bin/sh
depends_on:
- clickhouse
- schema-migrator
- signoz
schema-migrator:
!!merge <<: *common
image: signoz/signoz-schema-migrator:v0.142.0
deploy:
restart_policy:
condition: on-failure
delay: 5s
entrypoint: sh
command:
- -c
- |
/signoz-otel-collector migrate bootstrap &&
/signoz-otel-collector migrate sync up &&
/signoz-otel-collector migrate async up
- "/signoz-schema-migrator sync --dsn=tcp://clickhouse:9000 --up= && /signoz-schema-migrator async --dsn=tcp://clickhouse:9000 --up="
depends_on:
- clickhouse
networks:
signoz-net:
name: signoz-net
@@ -273,16 +261,3 @@ volumes:
name: signoz-zookeeper-2
zookeeper-3:
name: signoz-zookeeper-3
configs:
clickhouse-config:
file: ../common/clickhouse/config.xml
clickhouse-users:
file: ../common/clickhouse/users.xml
clickhouse-custom-function:
file: ../common/clickhouse/custom-function.xml
clickhouse-cluster:
file: ../common/clickhouse/cluster.ha.xml
otel-collector-config:
file: ./otel-collector-config.yaml
otel-manager-config:
file: ../common/signoz/otel-collector-opamp-config.yaml

View File

@@ -58,6 +58,7 @@ x-db-depend: &db-depend
!!merge <<: *common
depends_on:
- clickhouse
- schema-migrator
services:
init-clickhouse:
!!merge <<: *common
@@ -113,20 +114,30 @@ services:
target: /etc/clickhouse-server/config.d/cluster.xml
volumes:
- clickhouse:/var/lib/clickhouse/
- ../common/clickhouse/user_scripts:/var/lib/clickhouse/user_scripts/
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
signoz:
!!merge <<: *db-depend
image: signoz/signoz:v0.113.0
image: signoz/signoz:v0.112.0
command:
- --config=/root/config/prometheus.yml
ports:
- "8080:8080" # signoz port
# - "6060:6060" # pprof port
volumes:
- sqlite:/var/lib/signoz/
configs:
- source: signoz-prometheus-config
target: /root/config/prometheus.yml
environment:
- SIGNOZ_ALERTMANAGER_PROVIDER=signoz
- SIGNOZ_TELEMETRYSTORE_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_SQLSTORE_SQLITE_PATH=/var/lib/signoz/signoz.db
- SIGNOZ_TOKENIZER_JWT_SECRET=secret
- DASHBOARDS_PATH=/root/config/dashboards
- STORAGE=clickhouse
- GODEBUG=netdns=go
- TELEMETRY_ENABLED=true
- DEPLOYMENT_TYPE=docker-swarm
- DOT_METRICS_ENABLED=true
healthcheck:
test:
- CMD
@@ -139,14 +150,11 @@ services:
retries: 3
otel-collector:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:v0.144.1
entrypoint:
- /bin/sh
image: signoz/signoz-otel-collector:v0.142.0
command:
- -c
- |
/signoz-otel-collector migrate sync check &&
/signoz-otel-collector --config=/etc/otel-collector-config.yaml --manager-config=/etc/manager-config.yaml --copy-path=/var/tmp/collector-config.yaml
- --config=/etc/otel-collector-config.yaml
- --manager-config=/etc/manager-config.yaml
- --copy-path=/var/tmp/collector-config.yaml
configs:
- source: otel-collector-config
target: /etc/otel-collector-config.yaml
@@ -155,32 +163,29 @@ services:
environment:
- OTEL_RESOURCE_ATTRIBUTES=host.name={{.Node.Hostname}},os.type={{.Node.Platform.OS}}
- LOW_CARDINAL_EXCEPTION_GROUPING=false
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_REPLICATION=true
- SIGNOZ_OTEL_COLLECTOR_TIMEOUT=10m
ports:
# - "1777:1777" # pprof extension
- "4317:4317" # OTLP gRPC receiver
- "4318:4318" # OTLP HTTP receiver
deploy:
replicas: 3
signoz-telemetrystore-migrator:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:v0.144.1
environment:
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_REPLICATION=true
- SIGNOZ_OTEL_COLLECTOR_TIMEOUT=10m
entrypoint:
- /bin/sh
depends_on:
- clickhouse
- schema-migrator
- signoz
schema-migrator:
!!merge <<: *common
image: signoz/signoz-schema-migrator:v0.142.0
deploy:
restart_policy:
condition: on-failure
delay: 5s
entrypoint: sh
command:
- -c
- |
/signoz-otel-collector migrate bootstrap &&
/signoz-otel-collector migrate sync up &&
/signoz-otel-collector migrate async up
- "/signoz-schema-migrator sync --dsn=tcp://clickhouse:9000 --up= && /signoz-schema-migrator async --dsn=tcp://clickhouse:9000 --up="
depends_on:
- clickhouse
networks:
signoz-net:
name: signoz-net
@@ -200,6 +205,14 @@ configs:
file: ../common/clickhouse/custom-function.xml
clickhouse-cluster:
file: ../common/clickhouse/cluster.xml
signoz-prometheus-config:
file: ../common/signoz/prometheus.yml
# If you have multiple dashboard files, you can list them individually:
# dashboard-foo:
# file: ../common/dashboards/foo.json
# dashboard-bar:
# file: ../common/dashboards/bar.json
otel-collector-config:
file: ./otel-collector-config.yaml
otel-manager-config:

View File

@@ -82,12 +82,6 @@ exporters:
timeout: 45s
sending_queue:
enabled: false
metadataexporter:
cache:
provider: in_memory
dsn: tcp://clickhouse:9000/signoz_metadata
enabled: true
timeout: 45s
service:
telemetry:
logs:
@@ -99,19 +93,19 @@ service:
traces:
receivers: [otlp]
processors: [signozspanmetrics/delta, batch]
exporters: [clickhousetraces, metadataexporter, signozmeter]
exporters: [clickhousetraces, signozmeter]
metrics:
receivers: [otlp]
processors: [batch]
exporters: [signozclickhousemetrics, metadataexporter, signozmeter]
exporters: [signozclickhousemetrics, signozmeter]
metrics/prometheus:
receivers: [prometheus]
processors: [batch]
exporters: [signozclickhousemetrics, metadataexporter, signozmeter]
exporters: [signozclickhousemetrics, signozmeter]
logs:
receivers: [otlp]
processors: [batch]
exporters: [clickhouselogsexporter, metadataexporter, signozmeter]
exporters: [clickhouselogsexporter, signozmeter]
metrics/meter:
receivers: [signozmeter]
processors: [batch/meter]

View File

@@ -62,10 +62,8 @@ x-db-depend: &db-depend
depends_on:
clickhouse:
condition: service_healthy
clickhouse-2:
condition: service_healthy
clickhouse-3:
condition: service_healthy
schema-migrator-sync:
condition: service_completed_successfully
services:
init-clickhouse:
!!merge <<: *common
@@ -181,17 +179,27 @@ services:
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
signoz:
!!merge <<: *db-depend
image: signoz/signoz:${VERSION:-v0.113.0}
image: signoz/signoz:${VERSION:-v0.112.0}
container_name: signoz
command:
- --config=/root/config/prometheus.yml
ports:
- "8080:8080" # signoz port
# - "6060:6060" # pprof port
volumes:
- ../common/signoz/prometheus.yml:/root/config/prometheus.yml
- ../common/dashboards:/root/config/dashboards
- sqlite:/var/lib/signoz/
environment:
- SIGNOZ_ALERTMANAGER_PROVIDER=signoz
- SIGNOZ_TELEMETRYSTORE_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_SQLSTORE_SQLITE_PATH=/var/lib/signoz/signoz.db
- SIGNOZ_TOKENIZER_JWT_SECRET=secret
- DASHBOARDS_PATH=/root/config/dashboards
- STORAGE=clickhouse
- GODEBUG=netdns=go
- TELEMETRY_ENABLED=true
- DEPLOYMENT_TYPE=docker-standalone-amd
- DOT_METRICS_ENABLED=true
healthcheck:
test:
- CMD
@@ -202,48 +210,51 @@ services:
interval: 30s
timeout: 5s
retries: 3
# TODO: support otel-collector multiple replicas. Nginx/Traefik for loadbalancing?
otel-collector:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.1}
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.142.0}
container_name: signoz-otel-collector
entrypoint:
- /bin/sh
command:
- -c
- |
/signoz-otel-collector migrate sync check &&
/signoz-otel-collector --config=/etc/otel-collector-config.yaml --manager-config=/etc/manager-config.yaml --copy-path=/var/tmp/collector-config.yaml
- --config=/etc/otel-collector-config.yaml
- --manager-config=/etc/manager-config.yaml
- --copy-path=/var/tmp/collector-config.yaml
volumes:
- ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
- ../common/signoz/otel-collector-opamp-config.yaml:/etc/manager-config.yaml
environment:
- OTEL_RESOURCE_ATTRIBUTES=host.name=signoz-host,os.type=linux
- LOW_CARDINAL_EXCEPTION_GROUPING=false
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_REPLICATION=true
- SIGNOZ_OTEL_COLLECTOR_TIMEOUT=10m
ports:
# - "1777:1777" # pprof extension
- "4317:4317" # OTLP gRPC receiver
- "4318:4318" # OTLP HTTP receiver
signoz-telemetrystore-migrator:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.1}
container_name: signoz-telemetrystore-migrator
environment:
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_REPLICATION=true
- SIGNOZ_OTEL_COLLECTOR_TIMEOUT=10m
entrypoint:
- /bin/sh
depends_on:
clickhouse:
condition: service_healthy
schema-migrator-sync:
condition: service_completed_successfully
signoz:
condition: service_healthy
schema-migrator-sync:
!!merge <<: *common
image: signoz/signoz-schema-migrator:${OTELCOL_TAG:-v0.142.0}
container_name: schema-migrator-sync
command:
- -c
- |
/signoz-otel-collector migrate bootstrap &&
/signoz-otel-collector migrate sync up &&
/signoz-otel-collector migrate async up
- sync
- --dsn=tcp://clickhouse:9000
- --up=
depends_on:
clickhouse:
condition: service_healthy
schema-migrator-async:
!!merge <<: *db-depend
image: signoz/signoz-schema-migrator:${OTELCOL_TAG:-v0.142.0}
container_name: schema-migrator-async
command:
- async
- --dsn=tcp://clickhouse:9000
- --up=
restart: on-failure
networks:
signoz-net:

View File

@@ -57,6 +57,8 @@ x-db-depend: &db-depend
depends_on:
clickhouse:
condition: service_healthy
schema-migrator-sync:
condition: service_completed_successfully
services:
init-clickhouse:
!!merge <<: *common
@@ -109,17 +111,27 @@ services:
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
signoz:
!!merge <<: *db-depend
image: signoz/signoz:${VERSION:-v0.113.0}
image: signoz/signoz:${VERSION:-v0.112.0}
container_name: signoz
command:
- --config=/root/config/prometheus.yml
ports:
- "8080:8080" # signoz port
# - "6060:6060" # pprof port
volumes:
- ../common/signoz/prometheus.yml:/root/config/prometheus.yml
- ../common/dashboards:/root/config/dashboards
- sqlite:/var/lib/signoz/
environment:
- SIGNOZ_ALERTMANAGER_PROVIDER=signoz
- SIGNOZ_TELEMETRYSTORE_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_SQLSTORE_SQLITE_PATH=/var/lib/signoz/signoz.db
- SIGNOZ_TOKENIZER_JWT_SECRET=secret
- DASHBOARDS_PATH=/root/config/dashboards
- STORAGE=clickhouse
- GODEBUG=netdns=go
- TELEMETRY_ENABLED=true
- DEPLOYMENT_TYPE=docker-standalone-amd
- DOT_METRICS_ENABLED=true
healthcheck:
test:
- CMD
@@ -132,46 +144,45 @@ services:
retries: 3
otel-collector:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.1}
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.142.0}
container_name: signoz-otel-collector
entrypoint:
- /bin/sh
command:
- -c
- |
/signoz-otel-collector migrate sync check &&
/signoz-otel-collector --config=/etc/otel-collector-config.yaml --manager-config=/etc/manager-config.yaml --copy-path=/var/tmp/collector-config.yaml
- --config=/etc/otel-collector-config.yaml
- --manager-config=/etc/manager-config.yaml
- --copy-path=/var/tmp/collector-config.yaml
volumes:
- ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
- ../common/signoz/otel-collector-opamp-config.yaml:/etc/manager-config.yaml
environment:
- OTEL_RESOURCE_ATTRIBUTES=host.name=signoz-host,os.type=linux
- LOW_CARDINAL_EXCEPTION_GROUPING=false
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_REPLICATION=true
- SIGNOZ_OTEL_COLLECTOR_TIMEOUT=10m
ports:
# - "1777:1777" # pprof extension
- "4317:4317" # OTLP gRPC receiver
- "4318:4318" # OTLP HTTP receiver
signoz-telemetrystore-migrator:
!!merge <<: *db-depend
image: signoz/signoz-otel-collector:${OTELCOL_TAG:-v0.144.1}
container_name: signoz-telemetrystore-migrator
environment:
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_DSN=tcp://clickhouse:9000
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_CLUSTER=cluster
- SIGNOZ_OTEL_COLLECTOR_CLICKHOUSE_REPLICATION=true
- SIGNOZ_OTEL_COLLECTOR_TIMEOUT=10m
entrypoint:
- /bin/sh
depends_on:
signoz:
condition: service_healthy
schema-migrator-sync:
!!merge <<: *common
image: signoz/signoz-schema-migrator:${OTELCOL_TAG:-v0.142.0}
container_name: schema-migrator-sync
command:
- -c
- |
/signoz-otel-collector migrate bootstrap &&
/signoz-otel-collector migrate sync up &&
/signoz-otel-collector migrate async up
- sync
- --dsn=tcp://clickhouse:9000
- --up=
depends_on:
clickhouse:
condition: service_healthy
restart: on-failure
schema-migrator-async:
!!merge <<: *db-depend
image: signoz/signoz-schema-migrator:${OTELCOL_TAG:-v0.142.0}
container_name: schema-migrator-async
command:
- async
- --dsn=tcp://clickhouse:9000
- --up=
restart: on-failure
networks:
signoz-net:

View File

@@ -82,12 +82,6 @@ exporters:
timeout: 45s
sending_queue:
enabled: false
metadataexporter:
cache:
provider: in_memory
dsn: tcp://clickhouse:9000/signoz_metadata
enabled: true
timeout: 45s
service:
telemetry:
logs:
@@ -99,19 +93,19 @@ service:
traces:
receivers: [otlp]
processors: [signozspanmetrics/delta, batch]
exporters: [clickhousetraces, metadataexporter, signozmeter]
exporters: [clickhousetraces, signozmeter]
metrics:
receivers: [otlp]
processors: [batch]
exporters: [signozclickhousemetrics, metadataexporter, signozmeter]
exporters: [signozclickhousemetrics, signozmeter]
metrics/prometheus:
receivers: [prometheus]
processors: [batch]
exporters: [signozclickhousemetrics, metadataexporter, signozmeter]
exporters: [signozclickhousemetrics, signozmeter]
logs:
receivers: [otlp]
processors: [batch]
exporters: [clickhouselogsexporter, metadataexporter, signozmeter]
exporters: [clickhouselogsexporter, signozmeter]
metrics/meter:
receivers: [signozmeter]
processors: [batch/meter]

View File

@@ -80,37 +80,6 @@ components:
updatedAt:
format: date-time
type: string
required:
- id
type: object
AuthtypesGettableObjects:
properties:
resource:
$ref: '#/components/schemas/AuthtypesResource'
selectors:
items:
type: string
type: array
required:
- resource
- selectors
type: object
AuthtypesGettableResources:
properties:
relations:
additionalProperties:
items:
type: string
type: array
nullable: true
type: object
resources:
items:
$ref: '#/components/schemas/AuthtypesResource'
type: array
required:
- resources
- relations
type: object
AuthtypesGettableToken:
properties:
@@ -161,6 +130,8 @@ components:
serviceAccountJson:
type: string
type: object
AuthtypesName:
type: object
AuthtypesOIDCConfig:
properties:
claimMapping:
@@ -183,7 +154,7 @@ components:
resource:
$ref: '#/components/schemas/AuthtypesResource'
selector:
type: string
$ref: '#/components/schemas/AuthtypesSelector'
required:
- resource
- selector
@@ -204,22 +175,6 @@ components:
provider:
type: string
type: object
AuthtypesPatchableObjects:
properties:
additions:
items:
$ref: '#/components/schemas/AuthtypesGettableObjects'
nullable: true
type: array
deletions:
items:
$ref: '#/components/schemas/AuthtypesGettableObjects'
nullable: true
type: array
required:
- additions
- deletions
type: object
AuthtypesPostableAuthDomain:
properties:
config:
@@ -244,7 +199,7 @@ components:
AuthtypesResource:
properties:
name:
type: string
$ref: '#/components/schemas/AuthtypesName'
type:
type: string
required:
@@ -276,6 +231,8 @@ components:
samlIdp:
type: string
type: object
AuthtypesSelector:
type: object
AuthtypesSessionContext:
properties:
exists:
@@ -288,6 +245,8 @@ components:
type: object
AuthtypesTransaction:
properties:
id:
type: string
object:
$ref: '#/components/schemas/AuthtypesObject'
relation:
@@ -367,9 +326,6 @@ components:
type: string
url:
type: string
required:
- code
- message
type: object
ErrorsResponseerroradditional:
properties:
@@ -501,10 +457,10 @@ components:
GatewaytypesLimitValue:
properties:
count:
nullable: true
format: int64
type: integer
size:
nullable: true
format: int64
type: integer
type: object
GatewaytypesPagination:
@@ -842,17 +798,6 @@ components:
- temporality
- isMonotonic
type: object
MetrictypesComparisonSpaceAggregationParam:
properties:
operator:
type: string
threshold:
format: double
type: number
required:
- operator
- threshold
type: object
MetrictypesSpaceAggregation:
enum:
- sum
@@ -1149,8 +1094,6 @@ components:
type: object
Querybuildertypesv5MetricAggregation:
properties:
comparisonSpaceAggregationParam:
$ref: '#/components/schemas/MetrictypesComparisonSpaceAggregationParam'
metricName:
type: string
reduceTo:
@@ -1718,9 +1661,40 @@ components:
$ref: '#/components/schemas/ErrorsJSON'
status:
type: string
type: object
RoletypesGettableResources:
properties:
relations:
additionalProperties:
items:
type: string
type: array
nullable: true
type: object
resources:
items:
$ref: '#/components/schemas/AuthtypesResource'
nullable: true
type: array
required:
- status
- error
- resources
- relations
type: object
RoletypesPatchableObjects:
properties:
additions:
items:
$ref: '#/components/schemas/AuthtypesObject'
nullable: true
type: array
deletions:
items:
$ref: '#/components/schemas/AuthtypesObject'
nullable: true
type: array
required:
- additions
- deletions
type: object
RoletypesPatchableRole:
properties:
@@ -1757,7 +1731,6 @@ components:
format: date-time
type: string
required:
- id
- name
- description
- type
@@ -1895,8 +1868,6 @@ components:
$ref: '#/components/schemas/TypesUser'
userId:
type: string
required:
- id
type: object
TypesGettableGlobalConfig:
properties:
@@ -1909,8 +1880,6 @@ components:
properties:
id:
type: string
required:
- id
type: object
TypesInvite:
properties:
@@ -1934,8 +1903,6 @@ components:
updatedAt:
format: date-time
type: string
required:
- id
type: object
TypesOrganization:
properties:
@@ -1956,8 +1923,6 @@ components:
updatedAt:
format: date-time
type: string
required:
- id
type: object
TypesPostableAPIKey:
properties:
@@ -2021,8 +1986,6 @@ components:
type: string
token:
type: string
required:
- id
type: object
TypesStorableAPIKey:
properties:
@@ -2048,8 +2011,6 @@ components:
type: string
userId:
type: string
required:
- id
type: object
TypesUser:
properties:
@@ -2071,8 +2032,6 @@ components:
updatedAt:
format: date-time
type: string
required:
- id
type: object
ZeustypesGettableHost:
properties:
@@ -2205,35 +2164,6 @@ paths:
summary: Check permissions
tags:
- authz
/api/v1/authz/resources:
get:
deprecated: false
description: Gets all the available resources
operationId: AuthzResources
responses:
"200":
content:
application/json:
schema:
properties:
data:
$ref: '#/components/schemas/AuthtypesGettableResources'
status:
type: string
required:
- status
- data
type: object
description: OK
"500":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Internal Server Error
summary: Get resources
tags:
- authz
/api/v1/changePassword/{id}:
post:
deprecated: false
@@ -4406,7 +4336,7 @@ paths:
properties:
data:
items:
$ref: '#/components/schemas/AuthtypesGettableObjects'
$ref: '#/components/schemas/AuthtypesObject'
type: array
status:
type: string
@@ -4479,7 +4409,7 @@ paths:
content:
application/json:
schema:
$ref: '#/components/schemas/AuthtypesPatchableObjects'
$ref: '#/components/schemas/RoletypesPatchableObjects'
responses:
"204":
content:
@@ -4537,6 +4467,52 @@ paths:
summary: Patch objects for a role by relation
tags:
- role
/api/v1/roles/resources:
get:
deprecated: false
description: Gets all the available resources for role assignment
operationId: GetResources
responses:
"200":
content:
application/json:
schema:
properties:
data:
$ref: '#/components/schemas/RoletypesGettableResources'
status:
type: string
required:
- status
- data
type: object
description: OK
"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:
- ADMIN
- tokenizer:
- ADMIN
summary: Get resources
tags:
- role
/api/v1/user:
get:
deprecated: false
@@ -5109,7 +5085,7 @@ paths:
schema:
$ref: '#/components/schemas/GatewaytypesPostableIngestionKey'
responses:
"201":
"200":
content:
application/json:
schema:
@@ -5122,7 +5098,7 @@ paths:
- status
- data
type: object
description: Created
description: OK
"401":
content:
application/json:
@@ -5550,12 +5526,6 @@ paths:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Forbidden
"404":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Not Found
"500":
content:
application/json:
@@ -5625,12 +5595,6 @@ paths:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Forbidden
"404":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Not Found
"500":
content:
application/json:
@@ -5689,12 +5653,6 @@ paths:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Forbidden
"404":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Not Found
"500":
content:
application/json:
@@ -5754,12 +5712,6 @@ paths:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Forbidden
"404":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Not Found
"500":
content:
application/json:

View File

@@ -171,6 +171,8 @@ func (provider *provider) GetResources(_ context.Context) []*authtypes.Resource
for _, register := range provider.registry {
typeables = append(typeables, register.MustGetTypeables()...)
}
// role module cannot self register itself!
typeables = append(typeables, provider.MustGetTypeables()...)
resources := make([]*authtypes.Resource, 0)
for _, typeable := range typeables {
@@ -257,7 +259,7 @@ func (provider *provider) Delete(ctx context.Context, orgID valuer.UUID, id valu
}
role := roletypes.NewRoleFromStorableRole(storableRole)
err = role.ErrIfManaged()
err = role.CanEditDelete()
if err != nil {
return err
}

View File

@@ -25,13 +25,13 @@ export default defineConfig({
useMutation: true,
useInvalidate: true,
signal: true,
useOperationIdAsQueryKey: false,
useOperationIdAsQueryKey: true,
},
useDates: true,
useNamedParameters: true,
enumGenerationType: 'enum',
mutator: {
path: './src/api/generatedAPIInstance.ts',
path: './src/api/index.ts',
name: 'GeneratedAPIInstance',
},

View File

@@ -308,15 +308,3 @@ export const PublicDashboardPage = Loadable(
/* webpackChunkName: "Public Dashboard Page" */ 'pages/PublicDashboard'
),
);
export const AlertTypeSelectionPage = Loadable(
() =>
import(
/* webpackChunkName: "Alert Type Selection Page" */ 'pages/AlertTypeSelection'
),
);
export const MeterExplorerPage = Loadable(
() =>
import(/* webpackChunkName: "Meter Explorer Page" */ 'pages/MeterExplorer'),
);

View File

@@ -1,10 +1,12 @@
import { RouteProps } from 'react-router-dom';
import ROUTES from 'constants/routes';
import AlertTypeSelectionPage from 'pages/AlertTypeSelection';
import MessagingQueues from 'pages/MessagingQueues';
import MeterExplorer from 'pages/MeterExplorer';
import {
AlertHistory,
AlertOverview,
AlertTypeSelectionPage,
AllAlertChannels,
AllErrors,
ApiMonitoring,
@@ -27,8 +29,6 @@ import {
LogsExplorer,
LogsIndexToFields,
LogsSaveViews,
MessagingQueuesMainPage,
MeterExplorerPage,
MetricsExplorer,
OldLogsExplorer,
Onboarding,
@@ -399,28 +399,28 @@ const routes: AppRoutes[] = [
{
path: ROUTES.MESSAGING_QUEUES_KAFKA,
exact: true,
component: MessagingQueuesMainPage,
component: MessagingQueues,
key: 'MESSAGING_QUEUES_KAFKA',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_CELERY_TASK,
exact: true,
component: MessagingQueuesMainPage,
component: MessagingQueues,
key: 'MESSAGING_QUEUES_CELERY_TASK',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_OVERVIEW,
exact: true,
component: MessagingQueuesMainPage,
component: MessagingQueues,
key: 'MESSAGING_QUEUES_OVERVIEW',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_KAFKA_DETAIL,
exact: true,
component: MessagingQueuesMainPage,
component: MessagingQueues,
key: 'MESSAGING_QUEUES_KAFKA_DETAIL',
isPrivate: true,
},
@@ -463,21 +463,21 @@ const routes: AppRoutes[] = [
{
path: ROUTES.METER,
exact: true,
component: MeterExplorerPage,
component: MeterExplorer,
key: 'METER',
isPrivate: true,
},
{
path: ROUTES.METER_EXPLORER,
exact: true,
component: MeterExplorerPage,
component: MeterExplorer,
key: 'METER_EXPLORER',
isPrivate: true,
},
{
path: ROUTES.METER_EXPLORER_VIEWS,
exact: true,
component: MeterExplorerPage,
component: MeterExplorer,
key: 'METER_EXPLORER_VIEWS',
isPrivate: true,
},

View File

@@ -1,48 +0,0 @@
import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
import { AxiosError } from 'axios';
import APIError from 'types/api/error';
// Handles errors from generated API hooks (which use RenderErrorResponseDTO)
export function ErrorResponseHandlerForGeneratedAPIs(
error: AxiosError<RenderErrorResponseDTO>,
): never {
const { response, request } = error;
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
if (response) {
throw new APIError({
httpStatusCode: response.status || 500,
error: {
code: response.data.error.code,
message: response.data.error.message,
url: response.data.error.url ?? '',
errors: (response.data.error.errors ?? []).map((e) => ({
message: e.message ?? '',
})),
},
});
}
// The request was made but no response was received
if (request) {
throw new APIError({
httpStatusCode: error.status || 500,
error: {
code: error.code || error.name,
message: error.message,
url: '',
errors: [],
},
});
}
// Something happened in setting up the request that triggered an Error
throw new APIError({
httpStatusCode: error.status || 500,
error: {
code: error.name,
message: error.message,
url: '',
errors: [],
},
});
}

View File

@@ -17,8 +17,7 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
AuthtypesPostableAuthDomainDTO,
AuthtypesUpdateableAuthDomainDTO,
@@ -46,12 +45,12 @@ export const listAuthDomains = (signal?: AbortSignal) => {
};
export const getListAuthDomainsQueryKey = () => {
return [`/api/v1/domains`] as const;
return ['listAuthDomains'] as const;
};
export const getListAuthDomainsQueryOptions = <
TData = Awaited<ReturnType<typeof listAuthDomains>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listAuthDomains>>,
@@ -77,7 +76,7 @@ export const getListAuthDomainsQueryOptions = <
export type ListAuthDomainsQueryResult = NonNullable<
Awaited<ReturnType<typeof listAuthDomains>>
>;
export type ListAuthDomainsQueryError = ErrorType<RenderErrorResponseDTO>;
export type ListAuthDomainsQueryError = RenderErrorResponseDTO;
/**
* @summary List all auth domains
@@ -85,7 +84,7 @@ export type ListAuthDomainsQueryError = ErrorType<RenderErrorResponseDTO>;
export function useListAuthDomains<
TData = Awaited<ReturnType<typeof listAuthDomains>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listAuthDomains>>,
@@ -124,7 +123,7 @@ export const invalidateListAuthDomains = async (
* @summary Create auth domain
*/
export const createAuthDomain = (
authtypesPostableAuthDomainDTO: BodyType<AuthtypesPostableAuthDomainDTO>,
authtypesPostableAuthDomainDTO: AuthtypesPostableAuthDomainDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateAuthDomain200>({
@@ -137,19 +136,19 @@ export const createAuthDomain = (
};
export const getCreateAuthDomainMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createAuthDomain>>,
TError,
{ data: BodyType<AuthtypesPostableAuthDomainDTO> },
{ data: AuthtypesPostableAuthDomainDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createAuthDomain>>,
TError,
{ data: BodyType<AuthtypesPostableAuthDomainDTO> },
{ data: AuthtypesPostableAuthDomainDTO },
TContext
> => {
const mutationKey = ['createAuthDomain'];
@@ -163,7 +162,7 @@ export const getCreateAuthDomainMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createAuthDomain>>,
{ data: BodyType<AuthtypesPostableAuthDomainDTO> }
{ data: AuthtypesPostableAuthDomainDTO }
> = (props) => {
const { data } = props ?? {};
@@ -176,26 +175,26 @@ export const getCreateAuthDomainMutationOptions = <
export type CreateAuthDomainMutationResult = NonNullable<
Awaited<ReturnType<typeof createAuthDomain>>
>;
export type CreateAuthDomainMutationBody = BodyType<AuthtypesPostableAuthDomainDTO>;
export type CreateAuthDomainMutationError = ErrorType<RenderErrorResponseDTO>;
export type CreateAuthDomainMutationBody = AuthtypesPostableAuthDomainDTO;
export type CreateAuthDomainMutationError = RenderErrorResponseDTO;
/**
* @summary Create auth domain
*/
export const useCreateAuthDomain = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createAuthDomain>>,
TError,
{ data: BodyType<AuthtypesPostableAuthDomainDTO> },
{ data: AuthtypesPostableAuthDomainDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createAuthDomain>>,
TError,
{ data: BodyType<AuthtypesPostableAuthDomainDTO> },
{ data: AuthtypesPostableAuthDomainDTO },
TContext
> => {
const mutationOptions = getCreateAuthDomainMutationOptions(options);
@@ -214,7 +213,7 @@ export const deleteAuthDomain = ({ id }: DeleteAuthDomainPathParameters) => {
};
export const getDeleteAuthDomainMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -254,13 +253,13 @@ export type DeleteAuthDomainMutationResult = NonNullable<
Awaited<ReturnType<typeof deleteAuthDomain>>
>;
export type DeleteAuthDomainMutationError = ErrorType<RenderErrorResponseDTO>;
export type DeleteAuthDomainMutationError = RenderErrorResponseDTO;
/**
* @summary Delete auth domain
*/
export const useDeleteAuthDomain = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -285,7 +284,7 @@ export const useDeleteAuthDomain = <
*/
export const updateAuthDomain = (
{ id }: UpdateAuthDomainPathParameters,
authtypesUpdateableAuthDomainDTO: BodyType<AuthtypesUpdateableAuthDomainDTO>,
authtypesUpdateableAuthDomainDTO: AuthtypesUpdateableAuthDomainDTO,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/domains/${id}`,
@@ -296,7 +295,7 @@ export const updateAuthDomain = (
};
export const getUpdateAuthDomainMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -304,7 +303,7 @@ export const getUpdateAuthDomainMutationOptions = <
TError,
{
pathParams: UpdateAuthDomainPathParameters;
data: BodyType<AuthtypesUpdateableAuthDomainDTO>;
data: AuthtypesUpdateableAuthDomainDTO;
},
TContext
>;
@@ -313,7 +312,7 @@ export const getUpdateAuthDomainMutationOptions = <
TError,
{
pathParams: UpdateAuthDomainPathParameters;
data: BodyType<AuthtypesUpdateableAuthDomainDTO>;
data: AuthtypesUpdateableAuthDomainDTO;
},
TContext
> => {
@@ -330,7 +329,7 @@ export const getUpdateAuthDomainMutationOptions = <
Awaited<ReturnType<typeof updateAuthDomain>>,
{
pathParams: UpdateAuthDomainPathParameters;
data: BodyType<AuthtypesUpdateableAuthDomainDTO>;
data: AuthtypesUpdateableAuthDomainDTO;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -344,14 +343,14 @@ export const getUpdateAuthDomainMutationOptions = <
export type UpdateAuthDomainMutationResult = NonNullable<
Awaited<ReturnType<typeof updateAuthDomain>>
>;
export type UpdateAuthDomainMutationBody = BodyType<AuthtypesUpdateableAuthDomainDTO>;
export type UpdateAuthDomainMutationError = ErrorType<RenderErrorResponseDTO>;
export type UpdateAuthDomainMutationBody = AuthtypesUpdateableAuthDomainDTO;
export type UpdateAuthDomainMutationError = RenderErrorResponseDTO;
/**
* @summary Update auth domain
*/
export const useUpdateAuthDomain = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -359,7 +358,7 @@ export const useUpdateAuthDomain = <
TError,
{
pathParams: UpdateAuthDomainPathParameters;
data: BodyType<AuthtypesUpdateableAuthDomainDTO>;
data: AuthtypesUpdateableAuthDomainDTO;
},
TContext
>;
@@ -368,7 +367,7 @@ export const useUpdateAuthDomain = <
TError,
{
pathParams: UpdateAuthDomainPathParameters;
data: BodyType<AuthtypesUpdateableAuthDomainDTO>;
data: AuthtypesUpdateableAuthDomainDTO;
},
TContext
> => {

View File

@@ -5,24 +5,16 @@
* SigNoz
*/
import type {
InvalidateOptions,
MutationFunction,
QueryClient,
QueryFunction,
QueryKey,
UseMutationOptions,
UseMutationResult,
UseQueryOptions,
UseQueryResult,
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import { useMutation } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
AuthtypesTransactionDTO,
AuthzCheck200,
AuthzResources200,
RenderErrorResponseDTO,
} from '../sigNoz.schemas';
@@ -35,7 +27,7 @@ type Awaited<O> = O extends AwaitedInput<infer T> ? T : never;
* @summary Check permissions
*/
export const authzCheck = (
authtypesTransactionDTO: BodyType<AuthtypesTransactionDTO[]>,
authtypesTransactionDTO: AuthtypesTransactionDTO[],
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<AuthzCheck200>({
@@ -48,19 +40,19 @@ export const authzCheck = (
};
export const getAuthzCheckMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
{ data: AuthtypesTransactionDTO[] },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
{ data: AuthtypesTransactionDTO[] },
TContext
> => {
const mutationKey = ['authzCheck'];
@@ -74,7 +66,7 @@ export const getAuthzCheckMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof authzCheck>>,
{ data: BodyType<AuthtypesTransactionDTO[]> }
{ data: AuthtypesTransactionDTO[] }
> = (props) => {
const { data } = props ?? {};
@@ -87,114 +79,29 @@ export const getAuthzCheckMutationOptions = <
export type AuthzCheckMutationResult = NonNullable<
Awaited<ReturnType<typeof authzCheck>>
>;
export type AuthzCheckMutationBody = BodyType<AuthtypesTransactionDTO[]>;
export type AuthzCheckMutationError = ErrorType<RenderErrorResponseDTO>;
export type AuthzCheckMutationBody = AuthtypesTransactionDTO[];
export type AuthzCheckMutationError = RenderErrorResponseDTO;
/**
* @summary Check permissions
*/
export const useAuthzCheck = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
{ data: AuthtypesTransactionDTO[] },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
{ data: AuthtypesTransactionDTO[] },
TContext
> => {
const mutationOptions = getAuthzCheckMutationOptions(options);
return useMutation(mutationOptions);
};
/**
* Gets all the available resources
* @summary Get resources
*/
export const authzResources = (signal?: AbortSignal) => {
return GeneratedAPIInstance<AuthzResources200>({
url: `/api/v1/authz/resources`,
method: 'GET',
signal,
});
};
export const getAuthzResourcesQueryKey = () => {
return [`/api/v1/authz/resources`] as const;
};
export const getAuthzResourcesQueryOptions = <
TData = Awaited<ReturnType<typeof authzResources>>,
TError = ErrorType<RenderErrorResponseDTO>
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof authzResources>>,
TError,
TData
>;
}) => {
const { query: queryOptions } = options ?? {};
const queryKey = queryOptions?.queryKey ?? getAuthzResourcesQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof authzResources>>> = ({
signal,
}) => authzResources(signal);
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
Awaited<ReturnType<typeof authzResources>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type AuthzResourcesQueryResult = NonNullable<
Awaited<ReturnType<typeof authzResources>>
>;
export type AuthzResourcesQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Get resources
*/
export function useAuthzResources<
TData = Awaited<ReturnType<typeof authzResources>>,
TError = ErrorType<RenderErrorResponseDTO>
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof authzResources>>,
TError,
TData
>;
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getAuthzResourcesQueryOptions(options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
}
/**
* @summary Get resources
*/
export const invalidateAuthzResources = async (
queryClient: QueryClient,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getAuthzResourcesQueryKey() },
options,
);
return queryClient;
};

View File

@@ -17,8 +17,7 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
CreatePublicDashboard201,
CreatePublicDashboardPathParameters,
@@ -53,7 +52,7 @@ export const deletePublicDashboard = ({
};
export const getDeletePublicDashboardMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -93,13 +92,13 @@ export type DeletePublicDashboardMutationResult = NonNullable<
Awaited<ReturnType<typeof deletePublicDashboard>>
>;
export type DeletePublicDashboardMutationError = ErrorType<RenderErrorResponseDTO>;
export type DeletePublicDashboardMutationError = RenderErrorResponseDTO;
/**
* @summary Delete public dashboard
*/
export const useDeletePublicDashboard = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -136,12 +135,12 @@ export const getPublicDashboard = (
export const getGetPublicDashboardQueryKey = ({
id,
}: GetPublicDashboardPathParameters) => {
return [`/api/v1/dashboards/${id}/public`] as const;
return ['getPublicDashboard'] as const;
};
export const getGetPublicDashboardQueryOptions = <
TData = Awaited<ReturnType<typeof getPublicDashboard>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetPublicDashboardPathParameters,
options?: {
@@ -176,7 +175,7 @@ export const getGetPublicDashboardQueryOptions = <
export type GetPublicDashboardQueryResult = NonNullable<
Awaited<ReturnType<typeof getPublicDashboard>>
>;
export type GetPublicDashboardQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetPublicDashboardQueryError = RenderErrorResponseDTO;
/**
* @summary Get public dashboard
@@ -184,7 +183,7 @@ export type GetPublicDashboardQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetPublicDashboard<
TData = Awaited<ReturnType<typeof getPublicDashboard>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetPublicDashboardPathParameters,
options?: {
@@ -228,7 +227,7 @@ export const invalidateGetPublicDashboard = async (
*/
export const createPublicDashboard = (
{ id }: CreatePublicDashboardPathParameters,
dashboardtypesPostablePublicDashboardDTO: BodyType<DashboardtypesPostablePublicDashboardDTO>,
dashboardtypesPostablePublicDashboardDTO: DashboardtypesPostablePublicDashboardDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreatePublicDashboard201>({
@@ -241,7 +240,7 @@ export const createPublicDashboard = (
};
export const getCreatePublicDashboardMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -249,7 +248,7 @@ export const getCreatePublicDashboardMutationOptions = <
TError,
{
pathParams: CreatePublicDashboardPathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
data: DashboardtypesPostablePublicDashboardDTO;
},
TContext
>;
@@ -258,7 +257,7 @@ export const getCreatePublicDashboardMutationOptions = <
TError,
{
pathParams: CreatePublicDashboardPathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
data: DashboardtypesPostablePublicDashboardDTO;
},
TContext
> => {
@@ -275,7 +274,7 @@ export const getCreatePublicDashboardMutationOptions = <
Awaited<ReturnType<typeof createPublicDashboard>>,
{
pathParams: CreatePublicDashboardPathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
data: DashboardtypesPostablePublicDashboardDTO;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -289,14 +288,14 @@ export const getCreatePublicDashboardMutationOptions = <
export type CreatePublicDashboardMutationResult = NonNullable<
Awaited<ReturnType<typeof createPublicDashboard>>
>;
export type CreatePublicDashboardMutationBody = BodyType<DashboardtypesPostablePublicDashboardDTO>;
export type CreatePublicDashboardMutationError = ErrorType<RenderErrorResponseDTO>;
export type CreatePublicDashboardMutationBody = DashboardtypesPostablePublicDashboardDTO;
export type CreatePublicDashboardMutationError = RenderErrorResponseDTO;
/**
* @summary Create public dashboard
*/
export const useCreatePublicDashboard = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -304,7 +303,7 @@ export const useCreatePublicDashboard = <
TError,
{
pathParams: CreatePublicDashboardPathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
data: DashboardtypesPostablePublicDashboardDTO;
},
TContext
>;
@@ -313,7 +312,7 @@ export const useCreatePublicDashboard = <
TError,
{
pathParams: CreatePublicDashboardPathParameters;
data: BodyType<DashboardtypesPostablePublicDashboardDTO>;
data: DashboardtypesPostablePublicDashboardDTO;
},
TContext
> => {
@@ -327,7 +326,7 @@ export const useCreatePublicDashboard = <
*/
export const updatePublicDashboard = (
{ id }: UpdatePublicDashboardPathParameters,
dashboardtypesUpdatablePublicDashboardDTO: BodyType<DashboardtypesUpdatablePublicDashboardDTO>,
dashboardtypesUpdatablePublicDashboardDTO: DashboardtypesUpdatablePublicDashboardDTO,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/dashboards/${id}/public`,
@@ -338,7 +337,7 @@ export const updatePublicDashboard = (
};
export const getUpdatePublicDashboardMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -346,7 +345,7 @@ export const getUpdatePublicDashboardMutationOptions = <
TError,
{
pathParams: UpdatePublicDashboardPathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
data: DashboardtypesUpdatablePublicDashboardDTO;
},
TContext
>;
@@ -355,7 +354,7 @@ export const getUpdatePublicDashboardMutationOptions = <
TError,
{
pathParams: UpdatePublicDashboardPathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
data: DashboardtypesUpdatablePublicDashboardDTO;
},
TContext
> => {
@@ -372,7 +371,7 @@ export const getUpdatePublicDashboardMutationOptions = <
Awaited<ReturnType<typeof updatePublicDashboard>>,
{
pathParams: UpdatePublicDashboardPathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
data: DashboardtypesUpdatablePublicDashboardDTO;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -386,14 +385,14 @@ export const getUpdatePublicDashboardMutationOptions = <
export type UpdatePublicDashboardMutationResult = NonNullable<
Awaited<ReturnType<typeof updatePublicDashboard>>
>;
export type UpdatePublicDashboardMutationBody = BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
export type UpdatePublicDashboardMutationError = ErrorType<RenderErrorResponseDTO>;
export type UpdatePublicDashboardMutationBody = DashboardtypesUpdatablePublicDashboardDTO;
export type UpdatePublicDashboardMutationError = RenderErrorResponseDTO;
/**
* @summary Update public dashboard
*/
export const useUpdatePublicDashboard = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -401,7 +400,7 @@ export const useUpdatePublicDashboard = <
TError,
{
pathParams: UpdatePublicDashboardPathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
data: DashboardtypesUpdatablePublicDashboardDTO;
},
TContext
>;
@@ -410,7 +409,7 @@ export const useUpdatePublicDashboard = <
TError,
{
pathParams: UpdatePublicDashboardPathParameters;
data: BodyType<DashboardtypesUpdatablePublicDashboardDTO>;
data: DashboardtypesUpdatablePublicDashboardDTO;
},
TContext
> => {
@@ -436,12 +435,12 @@ export const getPublicDashboardData = (
export const getGetPublicDashboardDataQueryKey = ({
id,
}: GetPublicDashboardDataPathParameters) => {
return [`/api/v1/public/dashboards/${id}`] as const;
return ['getPublicDashboardData'] as const;
};
export const getGetPublicDashboardDataQueryOptions = <
TData = Awaited<ReturnType<typeof getPublicDashboardData>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetPublicDashboardDataPathParameters,
options?: {
@@ -476,7 +475,7 @@ export const getGetPublicDashboardDataQueryOptions = <
export type GetPublicDashboardDataQueryResult = NonNullable<
Awaited<ReturnType<typeof getPublicDashboardData>>
>;
export type GetPublicDashboardDataQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetPublicDashboardDataQueryError = RenderErrorResponseDTO;
/**
* @summary Get public dashboard data
@@ -484,7 +483,7 @@ export type GetPublicDashboardDataQueryError = ErrorType<RenderErrorResponseDTO>
export function useGetPublicDashboardData<
TData = Awaited<ReturnType<typeof getPublicDashboardData>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetPublicDashboardDataPathParameters,
options?: {
@@ -541,12 +540,12 @@ export const getGetPublicDashboardWidgetQueryRangeQueryKey = ({
id,
idx,
}: GetPublicDashboardWidgetQueryRangePathParameters) => {
return [`/api/v1/public/dashboards/${id}/widgets/${idx}/query_range`] as const;
return ['getPublicDashboardWidgetQueryRange'] as const;
};
export const getGetPublicDashboardWidgetQueryRangeQueryOptions = <
TData = Awaited<ReturnType<typeof getPublicDashboardWidgetQueryRange>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id, idx }: GetPublicDashboardWidgetQueryRangePathParameters,
options?: {
@@ -582,7 +581,7 @@ export const getGetPublicDashboardWidgetQueryRangeQueryOptions = <
export type GetPublicDashboardWidgetQueryRangeQueryResult = NonNullable<
Awaited<ReturnType<typeof getPublicDashboardWidgetQueryRange>>
>;
export type GetPublicDashboardWidgetQueryRangeQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetPublicDashboardWidgetQueryRangeQueryError = RenderErrorResponseDTO;
/**
* @summary Get query range result
@@ -590,7 +589,7 @@ export type GetPublicDashboardWidgetQueryRangeQueryError = ErrorType<RenderError
export function useGetPublicDashboardWidgetQueryRange<
TData = Awaited<ReturnType<typeof getPublicDashboardWidgetQueryRange>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id, idx }: GetPublicDashboardWidgetQueryRangePathParameters,
options?: {

View File

@@ -14,8 +14,7 @@ import type {
} from 'react-query';
import { useQuery } from 'react-query';
import type { ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type { GetFeatures200, RenderErrorResponseDTO } from '../sigNoz.schemas';
type AwaitedInput<T> = PromiseLike<T> | T;
@@ -35,12 +34,12 @@ export const getFeatures = (signal?: AbortSignal) => {
};
export const getGetFeaturesQueryKey = () => {
return [`/api/v2/features`] as const;
return ['getFeatures'] as const;
};
export const getGetFeaturesQueryOptions = <
TData = Awaited<ReturnType<typeof getFeatures>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getFeatures>>,
@@ -66,7 +65,7 @@ export const getGetFeaturesQueryOptions = <
export type GetFeaturesQueryResult = NonNullable<
Awaited<ReturnType<typeof getFeatures>>
>;
export type GetFeaturesQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetFeaturesQueryError = RenderErrorResponseDTO;
/**
* @summary Get features
@@ -74,7 +73,7 @@ export type GetFeaturesQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetFeatures<
TData = Awaited<ReturnType<typeof getFeatures>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getFeatures>>,

View File

@@ -14,8 +14,7 @@ import type {
} from 'react-query';
import { useQuery } from 'react-query';
import type { ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
GetFieldsKeys200,
GetFieldsKeysParams,
@@ -45,12 +44,12 @@ export const getFieldsKeys = (
};
export const getGetFieldsKeysQueryKey = (params?: GetFieldsKeysParams) => {
return [`/api/v1/fields/keys`, ...(params ? [params] : [])] as const;
return ['getFieldsKeys', ...(params ? [params] : [])] as const;
};
export const getGetFieldsKeysQueryOptions = <
TData = Awaited<ReturnType<typeof getFieldsKeys>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params?: GetFieldsKeysParams,
options?: {
@@ -79,7 +78,7 @@ export const getGetFieldsKeysQueryOptions = <
export type GetFieldsKeysQueryResult = NonNullable<
Awaited<ReturnType<typeof getFieldsKeys>>
>;
export type GetFieldsKeysQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetFieldsKeysQueryError = RenderErrorResponseDTO;
/**
* @summary Get field keys
@@ -87,7 +86,7 @@ export type GetFieldsKeysQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetFieldsKeys<
TData = Awaited<ReturnType<typeof getFieldsKeys>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params?: GetFieldsKeysParams,
options?: {
@@ -142,12 +141,12 @@ export const getFieldsValues = (
};
export const getGetFieldsValuesQueryKey = (params?: GetFieldsValuesParams) => {
return [`/api/v1/fields/values`, ...(params ? [params] : [])] as const;
return ['getFieldsValues', ...(params ? [params] : [])] as const;
};
export const getGetFieldsValuesQueryOptions = <
TData = Awaited<ReturnType<typeof getFieldsValues>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params?: GetFieldsValuesParams,
options?: {
@@ -176,7 +175,7 @@ export const getGetFieldsValuesQueryOptions = <
export type GetFieldsValuesQueryResult = NonNullable<
Awaited<ReturnType<typeof getFieldsValues>>
>;
export type GetFieldsValuesQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetFieldsValuesQueryError = RenderErrorResponseDTO;
/**
* @summary Get field values
@@ -184,7 +183,7 @@ export type GetFieldsValuesQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetFieldsValues<
TData = Awaited<ReturnType<typeof getFieldsValues>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params?: GetFieldsValuesParams,
options?: {

View File

@@ -17,10 +17,9 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
CreateIngestionKey201,
CreateIngestionKey200,
CreateIngestionKeyLimit201,
CreateIngestionKeyLimitPathParameters,
DeleteIngestionKeyLimitPathParameters,
@@ -60,15 +59,12 @@ export const getIngestionKeys = (
export const getGetIngestionKeysQueryKey = (
params?: GetIngestionKeysParams,
) => {
return [
`/api/v2/gateway/ingestion_keys`,
...(params ? [params] : []),
] as const;
return ['getIngestionKeys', ...(params ? [params] : [])] as const;
};
export const getGetIngestionKeysQueryOptions = <
TData = Awaited<ReturnType<typeof getIngestionKeys>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params?: GetIngestionKeysParams,
options?: {
@@ -97,7 +93,7 @@ export const getGetIngestionKeysQueryOptions = <
export type GetIngestionKeysQueryResult = NonNullable<
Awaited<ReturnType<typeof getIngestionKeys>>
>;
export type GetIngestionKeysQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetIngestionKeysQueryError = RenderErrorResponseDTO;
/**
* @summary Get ingestion keys for workspace
@@ -105,7 +101,7 @@ export type GetIngestionKeysQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetIngestionKeys<
TData = Awaited<ReturnType<typeof getIngestionKeys>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params?: GetIngestionKeysParams,
options?: {
@@ -148,10 +144,10 @@ export const invalidateGetIngestionKeys = async (
* @summary Create ingestion key for workspace
*/
export const createIngestionKey = (
gatewaytypesPostableIngestionKeyDTO: BodyType<GatewaytypesPostableIngestionKeyDTO>,
gatewaytypesPostableIngestionKeyDTO: GatewaytypesPostableIngestionKeyDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateIngestionKey201>({
return GeneratedAPIInstance<CreateIngestionKey200>({
url: `/api/v2/gateway/ingestion_keys`,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -161,19 +157,19 @@ export const createIngestionKey = (
};
export const getCreateIngestionKeyMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createIngestionKey>>,
TError,
{ data: BodyType<GatewaytypesPostableIngestionKeyDTO> },
{ data: GatewaytypesPostableIngestionKeyDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createIngestionKey>>,
TError,
{ data: BodyType<GatewaytypesPostableIngestionKeyDTO> },
{ data: GatewaytypesPostableIngestionKeyDTO },
TContext
> => {
const mutationKey = ['createIngestionKey'];
@@ -187,7 +183,7 @@ export const getCreateIngestionKeyMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createIngestionKey>>,
{ data: BodyType<GatewaytypesPostableIngestionKeyDTO> }
{ data: GatewaytypesPostableIngestionKeyDTO }
> = (props) => {
const { data } = props ?? {};
@@ -200,26 +196,26 @@ export const getCreateIngestionKeyMutationOptions = <
export type CreateIngestionKeyMutationResult = NonNullable<
Awaited<ReturnType<typeof createIngestionKey>>
>;
export type CreateIngestionKeyMutationBody = BodyType<GatewaytypesPostableIngestionKeyDTO>;
export type CreateIngestionKeyMutationError = ErrorType<RenderErrorResponseDTO>;
export type CreateIngestionKeyMutationBody = GatewaytypesPostableIngestionKeyDTO;
export type CreateIngestionKeyMutationError = RenderErrorResponseDTO;
/**
* @summary Create ingestion key for workspace
*/
export const useCreateIngestionKey = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createIngestionKey>>,
TError,
{ data: BodyType<GatewaytypesPostableIngestionKeyDTO> },
{ data: GatewaytypesPostableIngestionKeyDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createIngestionKey>>,
TError,
{ data: BodyType<GatewaytypesPostableIngestionKeyDTO> },
{ data: GatewaytypesPostableIngestionKeyDTO },
TContext
> => {
const mutationOptions = getCreateIngestionKeyMutationOptions(options);
@@ -240,7 +236,7 @@ export const deleteIngestionKey = ({
};
export const getDeleteIngestionKeyMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -280,13 +276,13 @@ export type DeleteIngestionKeyMutationResult = NonNullable<
Awaited<ReturnType<typeof deleteIngestionKey>>
>;
export type DeleteIngestionKeyMutationError = ErrorType<RenderErrorResponseDTO>;
export type DeleteIngestionKeyMutationError = RenderErrorResponseDTO;
/**
* @summary Delete ingestion key for workspace
*/
export const useDeleteIngestionKey = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -311,7 +307,7 @@ export const useDeleteIngestionKey = <
*/
export const updateIngestionKey = (
{ keyId }: UpdateIngestionKeyPathParameters,
gatewaytypesPostableIngestionKeyDTO: BodyType<GatewaytypesPostableIngestionKeyDTO>,
gatewaytypesPostableIngestionKeyDTO: GatewaytypesPostableIngestionKeyDTO,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/gateway/ingestion_keys/${keyId}`,
@@ -322,7 +318,7 @@ export const updateIngestionKey = (
};
export const getUpdateIngestionKeyMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -330,7 +326,7 @@ export const getUpdateIngestionKeyMutationOptions = <
TError,
{
pathParams: UpdateIngestionKeyPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyDTO>;
data: GatewaytypesPostableIngestionKeyDTO;
},
TContext
>;
@@ -339,7 +335,7 @@ export const getUpdateIngestionKeyMutationOptions = <
TError,
{
pathParams: UpdateIngestionKeyPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyDTO>;
data: GatewaytypesPostableIngestionKeyDTO;
},
TContext
> => {
@@ -356,7 +352,7 @@ export const getUpdateIngestionKeyMutationOptions = <
Awaited<ReturnType<typeof updateIngestionKey>>,
{
pathParams: UpdateIngestionKeyPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyDTO>;
data: GatewaytypesPostableIngestionKeyDTO;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -370,14 +366,14 @@ export const getUpdateIngestionKeyMutationOptions = <
export type UpdateIngestionKeyMutationResult = NonNullable<
Awaited<ReturnType<typeof updateIngestionKey>>
>;
export type UpdateIngestionKeyMutationBody = BodyType<GatewaytypesPostableIngestionKeyDTO>;
export type UpdateIngestionKeyMutationError = ErrorType<RenderErrorResponseDTO>;
export type UpdateIngestionKeyMutationBody = GatewaytypesPostableIngestionKeyDTO;
export type UpdateIngestionKeyMutationError = RenderErrorResponseDTO;
/**
* @summary Update ingestion key for workspace
*/
export const useUpdateIngestionKey = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -385,7 +381,7 @@ export const useUpdateIngestionKey = <
TError,
{
pathParams: UpdateIngestionKeyPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyDTO>;
data: GatewaytypesPostableIngestionKeyDTO;
},
TContext
>;
@@ -394,7 +390,7 @@ export const useUpdateIngestionKey = <
TError,
{
pathParams: UpdateIngestionKeyPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyDTO>;
data: GatewaytypesPostableIngestionKeyDTO;
},
TContext
> => {
@@ -408,7 +404,7 @@ export const useUpdateIngestionKey = <
*/
export const createIngestionKeyLimit = (
{ keyId }: CreateIngestionKeyLimitPathParameters,
gatewaytypesPostableIngestionKeyLimitDTO: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>,
gatewaytypesPostableIngestionKeyLimitDTO: GatewaytypesPostableIngestionKeyLimitDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateIngestionKeyLimit201>({
@@ -421,7 +417,7 @@ export const createIngestionKeyLimit = (
};
export const getCreateIngestionKeyLimitMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -429,7 +425,7 @@ export const getCreateIngestionKeyLimitMutationOptions = <
TError,
{
pathParams: CreateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
data: GatewaytypesPostableIngestionKeyLimitDTO;
},
TContext
>;
@@ -438,7 +434,7 @@ export const getCreateIngestionKeyLimitMutationOptions = <
TError,
{
pathParams: CreateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
data: GatewaytypesPostableIngestionKeyLimitDTO;
},
TContext
> => {
@@ -455,7 +451,7 @@ export const getCreateIngestionKeyLimitMutationOptions = <
Awaited<ReturnType<typeof createIngestionKeyLimit>>,
{
pathParams: CreateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
data: GatewaytypesPostableIngestionKeyLimitDTO;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -469,14 +465,14 @@ export const getCreateIngestionKeyLimitMutationOptions = <
export type CreateIngestionKeyLimitMutationResult = NonNullable<
Awaited<ReturnType<typeof createIngestionKeyLimit>>
>;
export type CreateIngestionKeyLimitMutationBody = BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
export type CreateIngestionKeyLimitMutationError = ErrorType<RenderErrorResponseDTO>;
export type CreateIngestionKeyLimitMutationBody = GatewaytypesPostableIngestionKeyLimitDTO;
export type CreateIngestionKeyLimitMutationError = RenderErrorResponseDTO;
/**
* @summary Create limit for the ingestion key
*/
export const useCreateIngestionKeyLimit = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -484,7 +480,7 @@ export const useCreateIngestionKeyLimit = <
TError,
{
pathParams: CreateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
data: GatewaytypesPostableIngestionKeyLimitDTO;
},
TContext
>;
@@ -493,7 +489,7 @@ export const useCreateIngestionKeyLimit = <
TError,
{
pathParams: CreateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;
data: GatewaytypesPostableIngestionKeyLimitDTO;
},
TContext
> => {
@@ -515,7 +511,7 @@ export const deleteIngestionKeyLimit = ({
};
export const getDeleteIngestionKeyLimitMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -555,13 +551,13 @@ export type DeleteIngestionKeyLimitMutationResult = NonNullable<
Awaited<ReturnType<typeof deleteIngestionKeyLimit>>
>;
export type DeleteIngestionKeyLimitMutationError = ErrorType<RenderErrorResponseDTO>;
export type DeleteIngestionKeyLimitMutationError = RenderErrorResponseDTO;
/**
* @summary Delete limit for the ingestion key
*/
export const useDeleteIngestionKeyLimit = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -586,7 +582,7 @@ export const useDeleteIngestionKeyLimit = <
*/
export const updateIngestionKeyLimit = (
{ limitId }: UpdateIngestionKeyLimitPathParameters,
gatewaytypesUpdatableIngestionKeyLimitDTO: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>,
gatewaytypesUpdatableIngestionKeyLimitDTO: GatewaytypesUpdatableIngestionKeyLimitDTO,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/gateway/ingestion_keys/limits/${limitId}`,
@@ -597,7 +593,7 @@ export const updateIngestionKeyLimit = (
};
export const getUpdateIngestionKeyLimitMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -605,7 +601,7 @@ export const getUpdateIngestionKeyLimitMutationOptions = <
TError,
{
pathParams: UpdateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
data: GatewaytypesUpdatableIngestionKeyLimitDTO;
},
TContext
>;
@@ -614,7 +610,7 @@ export const getUpdateIngestionKeyLimitMutationOptions = <
TError,
{
pathParams: UpdateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
data: GatewaytypesUpdatableIngestionKeyLimitDTO;
},
TContext
> => {
@@ -631,7 +627,7 @@ export const getUpdateIngestionKeyLimitMutationOptions = <
Awaited<ReturnType<typeof updateIngestionKeyLimit>>,
{
pathParams: UpdateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
data: GatewaytypesUpdatableIngestionKeyLimitDTO;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -645,14 +641,14 @@ export const getUpdateIngestionKeyLimitMutationOptions = <
export type UpdateIngestionKeyLimitMutationResult = NonNullable<
Awaited<ReturnType<typeof updateIngestionKeyLimit>>
>;
export type UpdateIngestionKeyLimitMutationBody = BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
export type UpdateIngestionKeyLimitMutationError = ErrorType<RenderErrorResponseDTO>;
export type UpdateIngestionKeyLimitMutationBody = GatewaytypesUpdatableIngestionKeyLimitDTO;
export type UpdateIngestionKeyLimitMutationError = RenderErrorResponseDTO;
/**
* @summary Update limit for the ingestion key
*/
export const useUpdateIngestionKeyLimit = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -660,7 +656,7 @@ export const useUpdateIngestionKeyLimit = <
TError,
{
pathParams: UpdateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
data: GatewaytypesUpdatableIngestionKeyLimitDTO;
},
TContext
>;
@@ -669,7 +665,7 @@ export const useUpdateIngestionKeyLimit = <
TError,
{
pathParams: UpdateIngestionKeyLimitPathParameters;
data: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;
data: GatewaytypesUpdatableIngestionKeyLimitDTO;
},
TContext
> => {
@@ -696,15 +692,12 @@ export const searchIngestionKeys = (
export const getSearchIngestionKeysQueryKey = (
params?: SearchIngestionKeysParams,
) => {
return [
`/api/v2/gateway/ingestion_keys/search`,
...(params ? [params] : []),
] as const;
return ['searchIngestionKeys', ...(params ? [params] : [])] as const;
};
export const getSearchIngestionKeysQueryOptions = <
TData = Awaited<ReturnType<typeof searchIngestionKeys>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params: SearchIngestionKeysParams,
options?: {
@@ -734,7 +727,7 @@ export const getSearchIngestionKeysQueryOptions = <
export type SearchIngestionKeysQueryResult = NonNullable<
Awaited<ReturnType<typeof searchIngestionKeys>>
>;
export type SearchIngestionKeysQueryError = ErrorType<RenderErrorResponseDTO>;
export type SearchIngestionKeysQueryError = RenderErrorResponseDTO;
/**
* @summary Search ingestion keys for workspace
@@ -742,7 +735,7 @@ export type SearchIngestionKeysQueryError = ErrorType<RenderErrorResponseDTO>;
export function useSearchIngestionKeys<
TData = Awaited<ReturnType<typeof searchIngestionKeys>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params: SearchIngestionKeysParams,
options?: {

View File

@@ -14,8 +14,7 @@ import type {
} from 'react-query';
import { useQuery } from 'react-query';
import type { ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
GetGlobalConfig200,
RenderErrorResponseDTO,
@@ -38,12 +37,12 @@ export const getGlobalConfig = (signal?: AbortSignal) => {
};
export const getGetGlobalConfigQueryKey = () => {
return [`/api/v1/global/config`] as const;
return ['getGlobalConfig'] as const;
};
export const getGetGlobalConfigQueryOptions = <
TData = Awaited<ReturnType<typeof getGlobalConfig>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getGlobalConfig>>,
@@ -69,7 +68,7 @@ export const getGetGlobalConfigQueryOptions = <
export type GetGlobalConfigQueryResult = NonNullable<
Awaited<ReturnType<typeof getGlobalConfig>>
>;
export type GetGlobalConfigQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetGlobalConfigQueryError = RenderErrorResponseDTO;
/**
* @summary Get global config
@@ -77,7 +76,7 @@ export type GetGlobalConfigQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetGlobalConfig<
TData = Awaited<ReturnType<typeof getGlobalConfig>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getGlobalConfig>>,

View File

@@ -17,8 +17,7 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
ListPromotedAndIndexedPaths200,
PromotetypesPromotePathDTO,
@@ -42,12 +41,12 @@ export const listPromotedAndIndexedPaths = (signal?: AbortSignal) => {
};
export const getListPromotedAndIndexedPathsQueryKey = () => {
return [`/api/v1/logs/promote_paths`] as const;
return ['listPromotedAndIndexedPaths'] as const;
};
export const getListPromotedAndIndexedPathsQueryOptions = <
TData = Awaited<ReturnType<typeof listPromotedAndIndexedPaths>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listPromotedAndIndexedPaths>>,
@@ -74,7 +73,7 @@ export const getListPromotedAndIndexedPathsQueryOptions = <
export type ListPromotedAndIndexedPathsQueryResult = NonNullable<
Awaited<ReturnType<typeof listPromotedAndIndexedPaths>>
>;
export type ListPromotedAndIndexedPathsQueryError = ErrorType<RenderErrorResponseDTO>;
export type ListPromotedAndIndexedPathsQueryError = RenderErrorResponseDTO;
/**
* @summary Promote and index paths
@@ -82,7 +81,7 @@ export type ListPromotedAndIndexedPathsQueryError = ErrorType<RenderErrorRespons
export function useListPromotedAndIndexedPaths<
TData = Awaited<ReturnType<typeof listPromotedAndIndexedPaths>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listPromotedAndIndexedPaths>>,
@@ -121,9 +120,7 @@ export const invalidateListPromotedAndIndexedPaths = async (
* @summary Promote and index paths
*/
export const handlePromoteAndIndexPaths = (
promotetypesPromotePathDTONull: BodyType<
PromotetypesPromotePathDTO[] | null
> | null,
promotetypesPromotePathDTONull: PromotetypesPromotePathDTO[] | null,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -136,19 +133,19 @@ export const handlePromoteAndIndexPaths = (
};
export const getHandlePromoteAndIndexPathsMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>,
TError,
{ data: BodyType<PromotetypesPromotePathDTO[] | null> },
{ data: PromotetypesPromotePathDTO[] | null },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>,
TError,
{ data: BodyType<PromotetypesPromotePathDTO[] | null> },
{ data: PromotetypesPromotePathDTO[] | null },
TContext
> => {
const mutationKey = ['handlePromoteAndIndexPaths'];
@@ -162,7 +159,7 @@ export const getHandlePromoteAndIndexPathsMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>,
{ data: BodyType<PromotetypesPromotePathDTO[] | null> }
{ data: PromotetypesPromotePathDTO[] | null }
> = (props) => {
const { data } = props ?? {};
@@ -175,28 +172,28 @@ export const getHandlePromoteAndIndexPathsMutationOptions = <
export type HandlePromoteAndIndexPathsMutationResult = NonNullable<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>
>;
export type HandlePromoteAndIndexPathsMutationBody = BodyType<
PromotetypesPromotePathDTO[] | null
>;
export type HandlePromoteAndIndexPathsMutationError = ErrorType<RenderErrorResponseDTO>;
export type HandlePromoteAndIndexPathsMutationBody =
| PromotetypesPromotePathDTO[]
| null;
export type HandlePromoteAndIndexPathsMutationError = RenderErrorResponseDTO;
/**
* @summary Promote and index paths
*/
export const useHandlePromoteAndIndexPaths = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>,
TError,
{ data: BodyType<PromotetypesPromotePathDTO[] | null> },
{ data: PromotetypesPromotePathDTO[] | null },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof handlePromoteAndIndexPaths>>,
TError,
{ data: BodyType<PromotetypesPromotePathDTO[] | null> },
{ data: PromotetypesPromotePathDTO[] | null },
TContext
> => {
const mutationOptions = getHandlePromoteAndIndexPathsMutationOptions(options);

View File

@@ -17,8 +17,7 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
GetMetricAlerts200,
GetMetricAlertsPathParameters,
@@ -63,12 +62,12 @@ export const listMetrics = (
};
export const getListMetricsQueryKey = (params?: ListMetricsParams) => {
return [`/api/v2/metrics`, ...(params ? [params] : [])] as const;
return ['listMetrics', ...(params ? [params] : [])] as const;
};
export const getListMetricsQueryOptions = <
TData = Awaited<ReturnType<typeof listMetrics>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params?: ListMetricsParams,
options?: {
@@ -97,7 +96,7 @@ export const getListMetricsQueryOptions = <
export type ListMetricsQueryResult = NonNullable<
Awaited<ReturnType<typeof listMetrics>>
>;
export type ListMetricsQueryError = ErrorType<RenderErrorResponseDTO>;
export type ListMetricsQueryError = RenderErrorResponseDTO;
/**
* @summary List metric names
@@ -105,7 +104,7 @@ export type ListMetricsQueryError = ErrorType<RenderErrorResponseDTO>;
export function useListMetrics<
TData = Awaited<ReturnType<typeof listMetrics>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params?: ListMetricsParams,
options?: {
@@ -161,12 +160,12 @@ export const getMetricAlerts = (
export const getGetMetricAlertsQueryKey = ({
metricName,
}: GetMetricAlertsPathParameters) => {
return [`/api/v2/metrics/${metricName}/alerts`] as const;
return ['getMetricAlerts'] as const;
};
export const getGetMetricAlertsQueryOptions = <
TData = Awaited<ReturnType<typeof getMetricAlerts>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ metricName }: GetMetricAlertsPathParameters,
options?: {
@@ -201,7 +200,7 @@ export const getGetMetricAlertsQueryOptions = <
export type GetMetricAlertsQueryResult = NonNullable<
Awaited<ReturnType<typeof getMetricAlerts>>
>;
export type GetMetricAlertsQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetMetricAlertsQueryError = RenderErrorResponseDTO;
/**
* @summary Get metric alerts
@@ -209,7 +208,7 @@ export type GetMetricAlertsQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetMetricAlerts<
TData = Awaited<ReturnType<typeof getMetricAlerts>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ metricName }: GetMetricAlertsPathParameters,
options?: {
@@ -268,15 +267,12 @@ export const getGetMetricAttributesQueryKey = (
{ metricName }: GetMetricAttributesPathParameters,
params?: GetMetricAttributesParams,
) => {
return [
`/api/v2/metrics/${metricName}/attributes`,
...(params ? [params] : []),
] as const;
return ['getMetricAttributes', ...(params ? [params] : [])] as const;
};
export const getGetMetricAttributesQueryOptions = <
TData = Awaited<ReturnType<typeof getMetricAttributes>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ metricName }: GetMetricAttributesPathParameters,
params?: GetMetricAttributesParams,
@@ -313,7 +309,7 @@ export const getGetMetricAttributesQueryOptions = <
export type GetMetricAttributesQueryResult = NonNullable<
Awaited<ReturnType<typeof getMetricAttributes>>
>;
export type GetMetricAttributesQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetMetricAttributesQueryError = RenderErrorResponseDTO;
/**
* @summary Get metric attributes
@@ -321,7 +317,7 @@ export type GetMetricAttributesQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetMetricAttributes<
TData = Awaited<ReturnType<typeof getMetricAttributes>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ metricName }: GetMetricAttributesPathParameters,
params?: GetMetricAttributesParams,
@@ -383,12 +379,12 @@ export const getMetricDashboards = (
export const getGetMetricDashboardsQueryKey = ({
metricName,
}: GetMetricDashboardsPathParameters) => {
return [`/api/v2/metrics/${metricName}/dashboards`] as const;
return ['getMetricDashboards'] as const;
};
export const getGetMetricDashboardsQueryOptions = <
TData = Awaited<ReturnType<typeof getMetricDashboards>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ metricName }: GetMetricDashboardsPathParameters,
options?: {
@@ -423,7 +419,7 @@ export const getGetMetricDashboardsQueryOptions = <
export type GetMetricDashboardsQueryResult = NonNullable<
Awaited<ReturnType<typeof getMetricDashboards>>
>;
export type GetMetricDashboardsQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetMetricDashboardsQueryError = RenderErrorResponseDTO;
/**
* @summary Get metric dashboards
@@ -431,7 +427,7 @@ export type GetMetricDashboardsQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetMetricDashboards<
TData = Awaited<ReturnType<typeof getMetricDashboards>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ metricName }: GetMetricDashboardsPathParameters,
options?: {
@@ -490,12 +486,12 @@ export const getMetricHighlights = (
export const getGetMetricHighlightsQueryKey = ({
metricName,
}: GetMetricHighlightsPathParameters) => {
return [`/api/v2/metrics/${metricName}/highlights`] as const;
return ['getMetricHighlights'] as const;
};
export const getGetMetricHighlightsQueryOptions = <
TData = Awaited<ReturnType<typeof getMetricHighlights>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ metricName }: GetMetricHighlightsPathParameters,
options?: {
@@ -530,7 +526,7 @@ export const getGetMetricHighlightsQueryOptions = <
export type GetMetricHighlightsQueryResult = NonNullable<
Awaited<ReturnType<typeof getMetricHighlights>>
>;
export type GetMetricHighlightsQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetMetricHighlightsQueryError = RenderErrorResponseDTO;
/**
* @summary Get metric highlights
@@ -538,7 +534,7 @@ export type GetMetricHighlightsQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetMetricHighlights<
TData = Awaited<ReturnType<typeof getMetricHighlights>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ metricName }: GetMetricHighlightsPathParameters,
options?: {
@@ -597,12 +593,12 @@ export const getMetricMetadata = (
export const getGetMetricMetadataQueryKey = ({
metricName,
}: GetMetricMetadataPathParameters) => {
return [`/api/v2/metrics/${metricName}/metadata`] as const;
return ['getMetricMetadata'] as const;
};
export const getGetMetricMetadataQueryOptions = <
TData = Awaited<ReturnType<typeof getMetricMetadata>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ metricName }: GetMetricMetadataPathParameters,
options?: {
@@ -637,7 +633,7 @@ export const getGetMetricMetadataQueryOptions = <
export type GetMetricMetadataQueryResult = NonNullable<
Awaited<ReturnType<typeof getMetricMetadata>>
>;
export type GetMetricMetadataQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetMetricMetadataQueryError = RenderErrorResponseDTO;
/**
* @summary Get metric metadata
@@ -645,7 +641,7 @@ export type GetMetricMetadataQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetMetricMetadata<
TData = Awaited<ReturnType<typeof getMetricMetadata>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ metricName }: GetMetricMetadataPathParameters,
options?: {
@@ -689,7 +685,7 @@ export const invalidateGetMetricMetadata = async (
*/
export const updateMetricMetadata = (
{ metricName }: UpdateMetricMetadataPathParameters,
metricsexplorertypesUpdateMetricMetadataRequestDTO: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>,
metricsexplorertypesUpdateMetricMetadataRequestDTO: MetricsexplorertypesUpdateMetricMetadataRequestDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<string>({
@@ -702,7 +698,7 @@ export const updateMetricMetadata = (
};
export const getUpdateMetricMetadataMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -710,7 +706,7 @@ export const getUpdateMetricMetadataMutationOptions = <
TError,
{
pathParams: UpdateMetricMetadataPathParameters;
data: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
data: MetricsexplorertypesUpdateMetricMetadataRequestDTO;
},
TContext
>;
@@ -719,7 +715,7 @@ export const getUpdateMetricMetadataMutationOptions = <
TError,
{
pathParams: UpdateMetricMetadataPathParameters;
data: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
data: MetricsexplorertypesUpdateMetricMetadataRequestDTO;
},
TContext
> => {
@@ -736,7 +732,7 @@ export const getUpdateMetricMetadataMutationOptions = <
Awaited<ReturnType<typeof updateMetricMetadata>>,
{
pathParams: UpdateMetricMetadataPathParameters;
data: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
data: MetricsexplorertypesUpdateMetricMetadataRequestDTO;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -750,14 +746,14 @@ export const getUpdateMetricMetadataMutationOptions = <
export type UpdateMetricMetadataMutationResult = NonNullable<
Awaited<ReturnType<typeof updateMetricMetadata>>
>;
export type UpdateMetricMetadataMutationBody = BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
export type UpdateMetricMetadataMutationError = ErrorType<RenderErrorResponseDTO>;
export type UpdateMetricMetadataMutationBody = MetricsexplorertypesUpdateMetricMetadataRequestDTO;
export type UpdateMetricMetadataMutationError = RenderErrorResponseDTO;
/**
* @summary Update metric metadata
*/
export const useUpdateMetricMetadata = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -765,7 +761,7 @@ export const useUpdateMetricMetadata = <
TError,
{
pathParams: UpdateMetricMetadataPathParameters;
data: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
data: MetricsexplorertypesUpdateMetricMetadataRequestDTO;
},
TContext
>;
@@ -774,7 +770,7 @@ export const useUpdateMetricMetadata = <
TError,
{
pathParams: UpdateMetricMetadataPathParameters;
data: BodyType<MetricsexplorertypesUpdateMetricMetadataRequestDTO>;
data: MetricsexplorertypesUpdateMetricMetadataRequestDTO;
},
TContext
> => {
@@ -787,7 +783,7 @@ export const useUpdateMetricMetadata = <
* @summary Get metrics statistics
*/
export const getMetricsStats = (
metricsexplorertypesStatsRequestDTO: BodyType<MetricsexplorertypesStatsRequestDTO>,
metricsexplorertypesStatsRequestDTO: MetricsexplorertypesStatsRequestDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<GetMetricsStats200>({
@@ -800,19 +796,19 @@ export const getMetricsStats = (
};
export const getGetMetricsStatsMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof getMetricsStats>>,
TError,
{ data: BodyType<MetricsexplorertypesStatsRequestDTO> },
{ data: MetricsexplorertypesStatsRequestDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof getMetricsStats>>,
TError,
{ data: BodyType<MetricsexplorertypesStatsRequestDTO> },
{ data: MetricsexplorertypesStatsRequestDTO },
TContext
> => {
const mutationKey = ['getMetricsStats'];
@@ -826,7 +822,7 @@ export const getGetMetricsStatsMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof getMetricsStats>>,
{ data: BodyType<MetricsexplorertypesStatsRequestDTO> }
{ data: MetricsexplorertypesStatsRequestDTO }
> = (props) => {
const { data } = props ?? {};
@@ -839,26 +835,26 @@ export const getGetMetricsStatsMutationOptions = <
export type GetMetricsStatsMutationResult = NonNullable<
Awaited<ReturnType<typeof getMetricsStats>>
>;
export type GetMetricsStatsMutationBody = BodyType<MetricsexplorertypesStatsRequestDTO>;
export type GetMetricsStatsMutationError = ErrorType<RenderErrorResponseDTO>;
export type GetMetricsStatsMutationBody = MetricsexplorertypesStatsRequestDTO;
export type GetMetricsStatsMutationError = RenderErrorResponseDTO;
/**
* @summary Get metrics statistics
*/
export const useGetMetricsStats = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof getMetricsStats>>,
TError,
{ data: BodyType<MetricsexplorertypesStatsRequestDTO> },
{ data: MetricsexplorertypesStatsRequestDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof getMetricsStats>>,
TError,
{ data: BodyType<MetricsexplorertypesStatsRequestDTO> },
{ data: MetricsexplorertypesStatsRequestDTO },
TContext
> => {
const mutationOptions = getGetMetricsStatsMutationOptions(options);
@@ -870,7 +866,7 @@ export const useGetMetricsStats = <
* @summary Get metrics treemap
*/
export const getMetricsTreemap = (
metricsexplorertypesTreemapRequestDTO: BodyType<MetricsexplorertypesTreemapRequestDTO>,
metricsexplorertypesTreemapRequestDTO: MetricsexplorertypesTreemapRequestDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<GetMetricsTreemap200>({
@@ -883,19 +879,19 @@ export const getMetricsTreemap = (
};
export const getGetMetricsTreemapMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof getMetricsTreemap>>,
TError,
{ data: BodyType<MetricsexplorertypesTreemapRequestDTO> },
{ data: MetricsexplorertypesTreemapRequestDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof getMetricsTreemap>>,
TError,
{ data: BodyType<MetricsexplorertypesTreemapRequestDTO> },
{ data: MetricsexplorertypesTreemapRequestDTO },
TContext
> => {
const mutationKey = ['getMetricsTreemap'];
@@ -909,7 +905,7 @@ export const getGetMetricsTreemapMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof getMetricsTreemap>>,
{ data: BodyType<MetricsexplorertypesTreemapRequestDTO> }
{ data: MetricsexplorertypesTreemapRequestDTO }
> = (props) => {
const { data } = props ?? {};
@@ -922,26 +918,26 @@ export const getGetMetricsTreemapMutationOptions = <
export type GetMetricsTreemapMutationResult = NonNullable<
Awaited<ReturnType<typeof getMetricsTreemap>>
>;
export type GetMetricsTreemapMutationBody = BodyType<MetricsexplorertypesTreemapRequestDTO>;
export type GetMetricsTreemapMutationError = ErrorType<RenderErrorResponseDTO>;
export type GetMetricsTreemapMutationBody = MetricsexplorertypesTreemapRequestDTO;
export type GetMetricsTreemapMutationError = RenderErrorResponseDTO;
/**
* @summary Get metrics treemap
*/
export const useGetMetricsTreemap = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof getMetricsTreemap>>,
TError,
{ data: BodyType<MetricsexplorertypesTreemapRequestDTO> },
{ data: MetricsexplorertypesTreemapRequestDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof getMetricsTreemap>>,
TError,
{ data: BodyType<MetricsexplorertypesTreemapRequestDTO> },
{ data: MetricsexplorertypesTreemapRequestDTO },
TContext
> => {
const mutationOptions = getGetMetricsTreemapMutationOptions(options);

View File

@@ -17,8 +17,7 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
GetMyOrganization200,
RenderErrorResponseDTO,
@@ -42,12 +41,12 @@ export const getMyOrganization = (signal?: AbortSignal) => {
};
export const getGetMyOrganizationQueryKey = () => {
return [`/api/v2/orgs/me`] as const;
return ['getMyOrganization'] as const;
};
export const getGetMyOrganizationQueryOptions = <
TData = Awaited<ReturnType<typeof getMyOrganization>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getMyOrganization>>,
@@ -73,7 +72,7 @@ export const getGetMyOrganizationQueryOptions = <
export type GetMyOrganizationQueryResult = NonNullable<
Awaited<ReturnType<typeof getMyOrganization>>
>;
export type GetMyOrganizationQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetMyOrganizationQueryError = RenderErrorResponseDTO;
/**
* @summary Get my organization
@@ -81,7 +80,7 @@ export type GetMyOrganizationQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetMyOrganization<
TData = Awaited<ReturnType<typeof getMyOrganization>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getMyOrganization>>,
@@ -120,7 +119,7 @@ export const invalidateGetMyOrganization = async (
* @summary Update my organization
*/
export const updateMyOrganization = (
typesOrganizationDTO: BodyType<TypesOrganizationDTO>,
typesOrganizationDTO: TypesOrganizationDTO,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/orgs/me`,
@@ -131,19 +130,19 @@ export const updateMyOrganization = (
};
export const getUpdateMyOrganizationMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateMyOrganization>>,
TError,
{ data: BodyType<TypesOrganizationDTO> },
{ data: TypesOrganizationDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof updateMyOrganization>>,
TError,
{ data: BodyType<TypesOrganizationDTO> },
{ data: TypesOrganizationDTO },
TContext
> => {
const mutationKey = ['updateMyOrganization'];
@@ -157,7 +156,7 @@ export const getUpdateMyOrganizationMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof updateMyOrganization>>,
{ data: BodyType<TypesOrganizationDTO> }
{ data: TypesOrganizationDTO }
> = (props) => {
const { data } = props ?? {};
@@ -170,26 +169,26 @@ export const getUpdateMyOrganizationMutationOptions = <
export type UpdateMyOrganizationMutationResult = NonNullable<
Awaited<ReturnType<typeof updateMyOrganization>>
>;
export type UpdateMyOrganizationMutationBody = BodyType<TypesOrganizationDTO>;
export type UpdateMyOrganizationMutationError = ErrorType<RenderErrorResponseDTO>;
export type UpdateMyOrganizationMutationBody = TypesOrganizationDTO;
export type UpdateMyOrganizationMutationError = RenderErrorResponseDTO;
/**
* @summary Update my organization
*/
export const useUpdateMyOrganization = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateMyOrganization>>,
TError,
{ data: BodyType<TypesOrganizationDTO> },
{ data: TypesOrganizationDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof updateMyOrganization>>,
TError,
{ data: BodyType<TypesOrganizationDTO> },
{ data: TypesOrganizationDTO },
TContext
> => {
const mutationOptions = getUpdateMyOrganizationMutationOptions(options);

View File

@@ -17,8 +17,7 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
GetOrgPreference200,
GetOrgPreferencePathParameters,
@@ -49,12 +48,12 @@ export const listOrgPreferences = (signal?: AbortSignal) => {
};
export const getListOrgPreferencesQueryKey = () => {
return [`/api/v1/org/preferences`] as const;
return ['listOrgPreferences'] as const;
};
export const getListOrgPreferencesQueryOptions = <
TData = Awaited<ReturnType<typeof listOrgPreferences>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listOrgPreferences>>,
@@ -80,7 +79,7 @@ export const getListOrgPreferencesQueryOptions = <
export type ListOrgPreferencesQueryResult = NonNullable<
Awaited<ReturnType<typeof listOrgPreferences>>
>;
export type ListOrgPreferencesQueryError = ErrorType<RenderErrorResponseDTO>;
export type ListOrgPreferencesQueryError = RenderErrorResponseDTO;
/**
* @summary List org preferences
@@ -88,7 +87,7 @@ export type ListOrgPreferencesQueryError = ErrorType<RenderErrorResponseDTO>;
export function useListOrgPreferences<
TData = Awaited<ReturnType<typeof listOrgPreferences>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listOrgPreferences>>,
@@ -140,12 +139,12 @@ export const getOrgPreference = (
export const getGetOrgPreferenceQueryKey = ({
name,
}: GetOrgPreferencePathParameters) => {
return [`/api/v1/org/preferences/${name}`] as const;
return ['getOrgPreference'] as const;
};
export const getGetOrgPreferenceQueryOptions = <
TData = Awaited<ReturnType<typeof getOrgPreference>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ name }: GetOrgPreferencePathParameters,
options?: {
@@ -180,7 +179,7 @@ export const getGetOrgPreferenceQueryOptions = <
export type GetOrgPreferenceQueryResult = NonNullable<
Awaited<ReturnType<typeof getOrgPreference>>
>;
export type GetOrgPreferenceQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetOrgPreferenceQueryError = RenderErrorResponseDTO;
/**
* @summary Get org preference
@@ -188,7 +187,7 @@ export type GetOrgPreferenceQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetOrgPreference<
TData = Awaited<ReturnType<typeof getOrgPreference>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ name }: GetOrgPreferencePathParameters,
options?: {
@@ -232,7 +231,7 @@ export const invalidateGetOrgPreference = async (
*/
export const updateOrgPreference = (
{ name }: UpdateOrgPreferencePathParameters,
preferencetypesUpdatablePreferenceDTO: BodyType<PreferencetypesUpdatablePreferenceDTO>,
preferencetypesUpdatablePreferenceDTO: PreferencetypesUpdatablePreferenceDTO,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/org/preferences/${name}`,
@@ -243,7 +242,7 @@ export const updateOrgPreference = (
};
export const getUpdateOrgPreferenceMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -251,7 +250,7 @@ export const getUpdateOrgPreferenceMutationOptions = <
TError,
{
pathParams: UpdateOrgPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data: PreferencetypesUpdatablePreferenceDTO;
},
TContext
>;
@@ -260,7 +259,7 @@ export const getUpdateOrgPreferenceMutationOptions = <
TError,
{
pathParams: UpdateOrgPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data: PreferencetypesUpdatablePreferenceDTO;
},
TContext
> => {
@@ -277,7 +276,7 @@ export const getUpdateOrgPreferenceMutationOptions = <
Awaited<ReturnType<typeof updateOrgPreference>>,
{
pathParams: UpdateOrgPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data: PreferencetypesUpdatablePreferenceDTO;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -291,14 +290,14 @@ export const getUpdateOrgPreferenceMutationOptions = <
export type UpdateOrgPreferenceMutationResult = NonNullable<
Awaited<ReturnType<typeof updateOrgPreference>>
>;
export type UpdateOrgPreferenceMutationBody = BodyType<PreferencetypesUpdatablePreferenceDTO>;
export type UpdateOrgPreferenceMutationError = ErrorType<RenderErrorResponseDTO>;
export type UpdateOrgPreferenceMutationBody = PreferencetypesUpdatablePreferenceDTO;
export type UpdateOrgPreferenceMutationError = RenderErrorResponseDTO;
/**
* @summary Update org preference
*/
export const useUpdateOrgPreference = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -306,7 +305,7 @@ export const useUpdateOrgPreference = <
TError,
{
pathParams: UpdateOrgPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data: PreferencetypesUpdatablePreferenceDTO;
},
TContext
>;
@@ -315,7 +314,7 @@ export const useUpdateOrgPreference = <
TError,
{
pathParams: UpdateOrgPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data: PreferencetypesUpdatablePreferenceDTO;
},
TContext
> => {
@@ -336,12 +335,12 @@ export const listUserPreferences = (signal?: AbortSignal) => {
};
export const getListUserPreferencesQueryKey = () => {
return [`/api/v1/user/preferences`] as const;
return ['listUserPreferences'] as const;
};
export const getListUserPreferencesQueryOptions = <
TData = Awaited<ReturnType<typeof listUserPreferences>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listUserPreferences>>,
@@ -367,7 +366,7 @@ export const getListUserPreferencesQueryOptions = <
export type ListUserPreferencesQueryResult = NonNullable<
Awaited<ReturnType<typeof listUserPreferences>>
>;
export type ListUserPreferencesQueryError = ErrorType<RenderErrorResponseDTO>;
export type ListUserPreferencesQueryError = RenderErrorResponseDTO;
/**
* @summary List user preferences
@@ -375,7 +374,7 @@ export type ListUserPreferencesQueryError = ErrorType<RenderErrorResponseDTO>;
export function useListUserPreferences<
TData = Awaited<ReturnType<typeof listUserPreferences>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listUserPreferences>>,
@@ -427,12 +426,12 @@ export const getUserPreference = (
export const getGetUserPreferenceQueryKey = ({
name,
}: GetUserPreferencePathParameters) => {
return [`/api/v1/user/preferences/${name}`] as const;
return ['getUserPreference'] as const;
};
export const getGetUserPreferenceQueryOptions = <
TData = Awaited<ReturnType<typeof getUserPreference>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ name }: GetUserPreferencePathParameters,
options?: {
@@ -467,7 +466,7 @@ export const getGetUserPreferenceQueryOptions = <
export type GetUserPreferenceQueryResult = NonNullable<
Awaited<ReturnType<typeof getUserPreference>>
>;
export type GetUserPreferenceQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetUserPreferenceQueryError = RenderErrorResponseDTO;
/**
* @summary Get user preference
@@ -475,7 +474,7 @@ export type GetUserPreferenceQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetUserPreference<
TData = Awaited<ReturnType<typeof getUserPreference>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ name }: GetUserPreferencePathParameters,
options?: {
@@ -519,7 +518,7 @@ export const invalidateGetUserPreference = async (
*/
export const updateUserPreference = (
{ name }: UpdateUserPreferencePathParameters,
preferencetypesUpdatablePreferenceDTO: BodyType<PreferencetypesUpdatablePreferenceDTO>,
preferencetypesUpdatablePreferenceDTO: PreferencetypesUpdatablePreferenceDTO,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v1/user/preferences/${name}`,
@@ -530,7 +529,7 @@ export const updateUserPreference = (
};
export const getUpdateUserPreferenceMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -538,7 +537,7 @@ export const getUpdateUserPreferenceMutationOptions = <
TError,
{
pathParams: UpdateUserPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data: PreferencetypesUpdatablePreferenceDTO;
},
TContext
>;
@@ -547,7 +546,7 @@ export const getUpdateUserPreferenceMutationOptions = <
TError,
{
pathParams: UpdateUserPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data: PreferencetypesUpdatablePreferenceDTO;
},
TContext
> => {
@@ -564,7 +563,7 @@ export const getUpdateUserPreferenceMutationOptions = <
Awaited<ReturnType<typeof updateUserPreference>>,
{
pathParams: UpdateUserPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data: PreferencetypesUpdatablePreferenceDTO;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -578,14 +577,14 @@ export const getUpdateUserPreferenceMutationOptions = <
export type UpdateUserPreferenceMutationResult = NonNullable<
Awaited<ReturnType<typeof updateUserPreference>>
>;
export type UpdateUserPreferenceMutationBody = BodyType<PreferencetypesUpdatablePreferenceDTO>;
export type UpdateUserPreferenceMutationError = ErrorType<RenderErrorResponseDTO>;
export type UpdateUserPreferenceMutationBody = PreferencetypesUpdatablePreferenceDTO;
export type UpdateUserPreferenceMutationError = RenderErrorResponseDTO;
/**
* @summary Update user preference
*/
export const useUpdateUserPreference = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -593,7 +592,7 @@ export const useUpdateUserPreference = <
TError,
{
pathParams: UpdateUserPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data: PreferencetypesUpdatablePreferenceDTO;
},
TContext
>;
@@ -602,7 +601,7 @@ export const useUpdateUserPreference = <
TError,
{
pathParams: UpdateUserPreferencePathParameters;
data: BodyType<PreferencetypesUpdatablePreferenceDTO>;
data: PreferencetypesUpdatablePreferenceDTO;
},
TContext
> => {

View File

@@ -11,8 +11,7 @@ import type {
} from 'react-query';
import { useMutation } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
Querybuildertypesv5QueryRangeRequestDTO,
QueryRangeV5200,
@@ -29,7 +28,7 @@ type Awaited<O> = O extends AwaitedInput<infer T> ? T : never;
* @summary Query range
*/
export const queryRangeV5 = (
querybuildertypesv5QueryRangeRequestDTO: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
querybuildertypesv5QueryRangeRequestDTO: Querybuildertypesv5QueryRangeRequestDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<QueryRangeV5200>({
@@ -42,19 +41,19 @@ export const queryRangeV5 = (
};
export const getQueryRangeV5MutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
> => {
const mutationKey = ['queryRangeV5'];
@@ -68,7 +67,7 @@ export const getQueryRangeV5MutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof queryRangeV5>>,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> }
{ data: Querybuildertypesv5QueryRangeRequestDTO }
> = (props) => {
const { data } = props ?? {};
@@ -81,26 +80,26 @@ export const getQueryRangeV5MutationOptions = <
export type QueryRangeV5MutationResult = NonNullable<
Awaited<ReturnType<typeof queryRangeV5>>
>;
export type QueryRangeV5MutationBody = BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
export type QueryRangeV5MutationError = ErrorType<RenderErrorResponseDTO>;
export type QueryRangeV5MutationBody = Querybuildertypesv5QueryRangeRequestDTO;
export type QueryRangeV5MutationError = RenderErrorResponseDTO;
/**
* @summary Query range
*/
export const useQueryRangeV5 = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
> => {
const mutationOptions = getQueryRangeV5MutationOptions(options);
@@ -112,7 +111,7 @@ export const useQueryRangeV5 = <
* @summary Replace variables
*/
export const replaceVariables = (
querybuildertypesv5QueryRangeRequestDTO: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
querybuildertypesv5QueryRangeRequestDTO: Querybuildertypesv5QueryRangeRequestDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ReplaceVariables200>({
@@ -125,19 +124,19 @@ export const replaceVariables = (
};
export const getReplaceVariablesMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
> => {
const mutationKey = ['replaceVariables'];
@@ -151,7 +150,7 @@ export const getReplaceVariablesMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof replaceVariables>>,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> }
{ data: Querybuildertypesv5QueryRangeRequestDTO }
> = (props) => {
const { data } = props ?? {};
@@ -164,26 +163,26 @@ export const getReplaceVariablesMutationOptions = <
export type ReplaceVariablesMutationResult = NonNullable<
Awaited<ReturnType<typeof replaceVariables>>
>;
export type ReplaceVariablesMutationBody = BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
export type ReplaceVariablesMutationError = ErrorType<RenderErrorResponseDTO>;
export type ReplaceVariablesMutationBody = Querybuildertypesv5QueryRangeRequestDTO;
export type ReplaceVariablesMutationError = RenderErrorResponseDTO;
/**
* @summary Replace variables
*/
export const useReplaceVariables = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
> => {
const mutationOptions = getReplaceVariablesMutationOptions(options);

View File

@@ -17,20 +17,20 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
AuthtypesPatchableObjectsDTO,
CreateRole201,
DeleteRolePathParameters,
GetObjects200,
GetObjectsPathParameters,
GetResources200,
GetRole200,
GetRolePathParameters,
ListRoles200,
PatchObjectsPathParameters,
PatchRolePathParameters,
RenderErrorResponseDTO,
RoletypesPatchableObjectsDTO,
RoletypesPatchableRoleDTO,
RoletypesPostableRoleDTO,
} from '../sigNoz.schemas';
@@ -52,12 +52,12 @@ export const listRoles = (signal?: AbortSignal) => {
};
export const getListRolesQueryKey = () => {
return [`/api/v1/roles`] as const;
return ['listRoles'] as const;
};
export const getListRolesQueryOptions = <
TData = Awaited<ReturnType<typeof listRoles>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof listRoles>>, TError, TData>;
}) => {
@@ -79,7 +79,7 @@ export const getListRolesQueryOptions = <
export type ListRolesQueryResult = NonNullable<
Awaited<ReturnType<typeof listRoles>>
>;
export type ListRolesQueryError = ErrorType<RenderErrorResponseDTO>;
export type ListRolesQueryError = RenderErrorResponseDTO;
/**
* @summary List roles
@@ -87,7 +87,7 @@ export type ListRolesQueryError = ErrorType<RenderErrorResponseDTO>;
export function useListRoles<
TData = Awaited<ReturnType<typeof listRoles>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof listRoles>>, TError, TData>;
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
@@ -122,7 +122,7 @@ export const invalidateListRoles = async (
* @summary Create role
*/
export const createRole = (
roletypesPostableRoleDTO: BodyType<RoletypesPostableRoleDTO>,
roletypesPostableRoleDTO: RoletypesPostableRoleDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateRole201>({
@@ -135,19 +135,19 @@ export const createRole = (
};
export const getCreateRoleMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<RoletypesPostableRoleDTO> },
{ data: RoletypesPostableRoleDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<RoletypesPostableRoleDTO> },
{ data: RoletypesPostableRoleDTO },
TContext
> => {
const mutationKey = ['createRole'];
@@ -161,7 +161,7 @@ export const getCreateRoleMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createRole>>,
{ data: BodyType<RoletypesPostableRoleDTO> }
{ data: RoletypesPostableRoleDTO }
> = (props) => {
const { data } = props ?? {};
@@ -174,26 +174,26 @@ export const getCreateRoleMutationOptions = <
export type CreateRoleMutationResult = NonNullable<
Awaited<ReturnType<typeof createRole>>
>;
export type CreateRoleMutationBody = BodyType<RoletypesPostableRoleDTO>;
export type CreateRoleMutationError = ErrorType<RenderErrorResponseDTO>;
export type CreateRoleMutationBody = RoletypesPostableRoleDTO;
export type CreateRoleMutationError = RenderErrorResponseDTO;
/**
* @summary Create role
*/
export const useCreateRole = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<RoletypesPostableRoleDTO> },
{ data: RoletypesPostableRoleDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<RoletypesPostableRoleDTO> },
{ data: RoletypesPostableRoleDTO },
TContext
> => {
const mutationOptions = getCreateRoleMutationOptions(options);
@@ -212,7 +212,7 @@ export const deleteRole = ({ id }: DeleteRolePathParameters) => {
};
export const getDeleteRoleMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -252,13 +252,13 @@ export type DeleteRoleMutationResult = NonNullable<
Awaited<ReturnType<typeof deleteRole>>
>;
export type DeleteRoleMutationError = ErrorType<RenderErrorResponseDTO>;
export type DeleteRoleMutationError = RenderErrorResponseDTO;
/**
* @summary Delete role
*/
export const useDeleteRole = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -293,12 +293,12 @@ export const getRole = (
};
export const getGetRoleQueryKey = ({ id }: GetRolePathParameters) => {
return [`/api/v1/roles/${id}`] as const;
return ['getRole'] as const;
};
export const getGetRoleQueryOptions = <
TData = Awaited<ReturnType<typeof getRole>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetRolePathParameters,
options?: {
@@ -326,7 +326,7 @@ export const getGetRoleQueryOptions = <
export type GetRoleQueryResult = NonNullable<
Awaited<ReturnType<typeof getRole>>
>;
export type GetRoleQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetRoleQueryError = RenderErrorResponseDTO;
/**
* @summary Get role
@@ -334,7 +334,7 @@ export type GetRoleQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetRole<
TData = Awaited<ReturnType<typeof getRole>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetRolePathParameters,
options?: {
@@ -374,7 +374,7 @@ export const invalidateGetRole = async (
*/
export const patchRole = (
{ id }: PatchRolePathParameters,
roletypesPatchableRoleDTO: BodyType<RoletypesPatchableRoleDTO>,
roletypesPatchableRoleDTO: RoletypesPatchableRoleDTO,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/roles/${id}`,
@@ -385,25 +385,19 @@ export const patchRole = (
};
export const getPatchRoleMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof patchRole>>,
TError,
{
pathParams: PatchRolePathParameters;
data: BodyType<RoletypesPatchableRoleDTO>;
},
{ pathParams: PatchRolePathParameters; data: RoletypesPatchableRoleDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof patchRole>>,
TError,
{
pathParams: PatchRolePathParameters;
data: BodyType<RoletypesPatchableRoleDTO>;
},
{ pathParams: PatchRolePathParameters; data: RoletypesPatchableRoleDTO },
TContext
> => {
const mutationKey = ['patchRole'];
@@ -417,10 +411,7 @@ export const getPatchRoleMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof patchRole>>,
{
pathParams: PatchRolePathParameters;
data: BodyType<RoletypesPatchableRoleDTO>;
}
{ pathParams: PatchRolePathParameters; data: RoletypesPatchableRoleDTO }
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -433,32 +424,26 @@ export const getPatchRoleMutationOptions = <
export type PatchRoleMutationResult = NonNullable<
Awaited<ReturnType<typeof patchRole>>
>;
export type PatchRoleMutationBody = BodyType<RoletypesPatchableRoleDTO>;
export type PatchRoleMutationError = ErrorType<RenderErrorResponseDTO>;
export type PatchRoleMutationBody = RoletypesPatchableRoleDTO;
export type PatchRoleMutationError = RenderErrorResponseDTO;
/**
* @summary Patch role
*/
export const usePatchRole = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof patchRole>>,
TError,
{
pathParams: PatchRolePathParameters;
data: BodyType<RoletypesPatchableRoleDTO>;
},
{ pathParams: PatchRolePathParameters; data: RoletypesPatchableRoleDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof patchRole>>,
TError,
{
pathParams: PatchRolePathParameters;
data: BodyType<RoletypesPatchableRoleDTO>;
},
{ pathParams: PatchRolePathParameters; data: RoletypesPatchableRoleDTO },
TContext
> => {
const mutationOptions = getPatchRoleMutationOptions(options);
@@ -484,12 +469,12 @@ export const getGetObjectsQueryKey = ({
id,
relation,
}: GetObjectsPathParameters) => {
return [`/api/v1/roles/${id}/relation/${relation}/objects`] as const;
return ['getObjects'] as const;
};
export const getGetObjectsQueryOptions = <
TData = Awaited<ReturnType<typeof getObjects>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id, relation }: GetObjectsPathParameters,
options?: {
@@ -522,7 +507,7 @@ export const getGetObjectsQueryOptions = <
export type GetObjectsQueryResult = NonNullable<
Awaited<ReturnType<typeof getObjects>>
>;
export type GetObjectsQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetObjectsQueryError = RenderErrorResponseDTO;
/**
* @summary Get objects for a role by relation
@@ -530,7 +515,7 @@ export type GetObjectsQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetObjects<
TData = Awaited<ReturnType<typeof getObjects>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id, relation }: GetObjectsPathParameters,
options?: {
@@ -574,18 +559,18 @@ export const invalidateGetObjects = async (
*/
export const patchObjects = (
{ id, relation }: PatchObjectsPathParameters,
authtypesPatchableObjectsDTO: BodyType<AuthtypesPatchableObjectsDTO>,
roletypesPatchableObjectsDTO: RoletypesPatchableObjectsDTO,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/roles/${id}/relation/${relation}/objects`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: authtypesPatchableObjectsDTO,
data: roletypesPatchableObjectsDTO,
});
};
export const getPatchObjectsMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -593,17 +578,14 @@ export const getPatchObjectsMutationOptions = <
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<AuthtypesPatchableObjectsDTO>;
data: RoletypesPatchableObjectsDTO;
},
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof patchObjects>>,
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<AuthtypesPatchableObjectsDTO>;
},
{ pathParams: PatchObjectsPathParameters; data: RoletypesPatchableObjectsDTO },
TContext
> => {
const mutationKey = ['patchObjects'];
@@ -617,10 +599,7 @@ export const getPatchObjectsMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof patchObjects>>,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<AuthtypesPatchableObjectsDTO>;
}
{ pathParams: PatchObjectsPathParameters; data: RoletypesPatchableObjectsDTO }
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -633,14 +612,14 @@ export const getPatchObjectsMutationOptions = <
export type PatchObjectsMutationResult = NonNullable<
Awaited<ReturnType<typeof patchObjects>>
>;
export type PatchObjectsMutationBody = BodyType<AuthtypesPatchableObjectsDTO>;
export type PatchObjectsMutationError = ErrorType<RenderErrorResponseDTO>;
export type PatchObjectsMutationBody = RoletypesPatchableObjectsDTO;
export type PatchObjectsMutationError = RenderErrorResponseDTO;
/**
* @summary Patch objects for a role by relation
*/
export const usePatchObjects = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -648,20 +627,102 @@ export const usePatchObjects = <
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<AuthtypesPatchableObjectsDTO>;
data: RoletypesPatchableObjectsDTO;
},
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof patchObjects>>,
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<AuthtypesPatchableObjectsDTO>;
},
{ pathParams: PatchObjectsPathParameters; data: RoletypesPatchableObjectsDTO },
TContext
> => {
const mutationOptions = getPatchObjectsMutationOptions(options);
return useMutation(mutationOptions);
};
/**
* Gets all the available resources for role assignment
* @summary Get resources
*/
export const getResources = (signal?: AbortSignal) => {
return GeneratedAPIInstance<GetResources200>({
url: `/api/v1/roles/resources`,
method: 'GET',
signal,
});
};
export const getGetResourcesQueryKey = () => {
return ['getResources'] as const;
};
export const getGetResourcesQueryOptions = <
TData = Awaited<ReturnType<typeof getResources>>,
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getResources>>,
TError,
TData
>;
}) => {
const { query: queryOptions } = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetResourcesQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof getResources>>> = ({
signal,
}) => getResources(signal);
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
Awaited<ReturnType<typeof getResources>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type GetResourcesQueryResult = NonNullable<
Awaited<ReturnType<typeof getResources>>
>;
export type GetResourcesQueryError = RenderErrorResponseDTO;
/**
* @summary Get resources
*/
export function useGetResources<
TData = Awaited<ReturnType<typeof getResources>>,
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getResources>>,
TError,
TData
>;
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getGetResourcesQueryOptions(options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
}
/**
* @summary Get resources
*/
export const invalidateGetResources = async (
queryClient: QueryClient,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getGetResourcesQueryKey() },
options,
);
return queryClient;
};

View File

@@ -17,8 +17,7 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
AuthtypesPostableEmailPasswordSessionDTO,
AuthtypesPostableRotateTokenDTO,
@@ -50,12 +49,12 @@ export const createSessionByGoogleCallback = (signal?: AbortSignal) => {
};
export const getCreateSessionByGoogleCallbackQueryKey = () => {
return [`/api/v1/complete/google`] as const;
return ['createSessionByGoogleCallback'] as const;
};
export const getCreateSessionByGoogleCallbackQueryOptions = <
TData = Awaited<ReturnType<typeof createSessionByGoogleCallback>>,
TError = ErrorType<CreateSessionByGoogleCallback303 | RenderErrorResponseDTO>
TError = CreateSessionByGoogleCallback303 | RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof createSessionByGoogleCallback>>,
@@ -82,9 +81,9 @@ export const getCreateSessionByGoogleCallbackQueryOptions = <
export type CreateSessionByGoogleCallbackQueryResult = NonNullable<
Awaited<ReturnType<typeof createSessionByGoogleCallback>>
>;
export type CreateSessionByGoogleCallbackQueryError = ErrorType<
CreateSessionByGoogleCallback303 | RenderErrorResponseDTO
>;
export type CreateSessionByGoogleCallbackQueryError =
| CreateSessionByGoogleCallback303
| RenderErrorResponseDTO;
/**
* @summary Create session by google callback
@@ -92,7 +91,7 @@ export type CreateSessionByGoogleCallbackQueryError = ErrorType<
export function useCreateSessionByGoogleCallback<
TData = Awaited<ReturnType<typeof createSessionByGoogleCallback>>,
TError = ErrorType<CreateSessionByGoogleCallback303 | RenderErrorResponseDTO>
TError = CreateSessionByGoogleCallback303 | RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof createSessionByGoogleCallback>>,
@@ -139,12 +138,12 @@ export const createSessionByOIDCCallback = (signal?: AbortSignal) => {
};
export const getCreateSessionByOIDCCallbackQueryKey = () => {
return [`/api/v1/complete/oidc`] as const;
return ['createSessionByOIDCCallback'] as const;
};
export const getCreateSessionByOIDCCallbackQueryOptions = <
TData = Awaited<ReturnType<typeof createSessionByOIDCCallback>>,
TError = ErrorType<CreateSessionByOIDCCallback303 | RenderErrorResponseDTO>
TError = CreateSessionByOIDCCallback303 | RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof createSessionByOIDCCallback>>,
@@ -171,9 +170,9 @@ export const getCreateSessionByOIDCCallbackQueryOptions = <
export type CreateSessionByOIDCCallbackQueryResult = NonNullable<
Awaited<ReturnType<typeof createSessionByOIDCCallback>>
>;
export type CreateSessionByOIDCCallbackQueryError = ErrorType<
CreateSessionByOIDCCallback303 | RenderErrorResponseDTO
>;
export type CreateSessionByOIDCCallbackQueryError =
| CreateSessionByOIDCCallback303
| RenderErrorResponseDTO;
/**
* @summary Create session by oidc callback
@@ -181,7 +180,7 @@ export type CreateSessionByOIDCCallbackQueryError = ErrorType<
export function useCreateSessionByOIDCCallback<
TData = Awaited<ReturnType<typeof createSessionByOIDCCallback>>,
TError = ErrorType<CreateSessionByOIDCCallback303 | RenderErrorResponseDTO>
TError = CreateSessionByOIDCCallback303 | RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof createSessionByOIDCCallback>>,
@@ -220,7 +219,7 @@ export const invalidateCreateSessionByOIDCCallback = async (
* @summary Create session by saml callback
*/
export const createSessionBySAMLCallback = (
createSessionBySAMLCallbackBody: BodyType<CreateSessionBySAMLCallbackBody>,
createSessionBySAMLCallbackBody: CreateSessionBySAMLCallbackBody,
params?: CreateSessionBySAMLCallbackParams,
signal?: AbortSignal,
) => {
@@ -249,14 +248,14 @@ export const createSessionBySAMLCallback = (
};
export const getCreateSessionBySAMLCallbackMutationOptions = <
TError = ErrorType<CreateSessionBySAMLCallback303 | RenderErrorResponseDTO>,
TError = CreateSessionBySAMLCallback303 | RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createSessionBySAMLCallback>>,
TError,
{
data: BodyType<CreateSessionBySAMLCallbackBody>;
data: CreateSessionBySAMLCallbackBody;
params?: CreateSessionBySAMLCallbackParams;
},
TContext
@@ -265,7 +264,7 @@ export const getCreateSessionBySAMLCallbackMutationOptions = <
Awaited<ReturnType<typeof createSessionBySAMLCallback>>,
TError,
{
data: BodyType<CreateSessionBySAMLCallbackBody>;
data: CreateSessionBySAMLCallbackBody;
params?: CreateSessionBySAMLCallbackParams;
},
TContext
@@ -282,7 +281,7 @@ export const getCreateSessionBySAMLCallbackMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createSessionBySAMLCallback>>,
{
data: BodyType<CreateSessionBySAMLCallbackBody>;
data: CreateSessionBySAMLCallbackBody;
params?: CreateSessionBySAMLCallbackParams;
}
> = (props) => {
@@ -297,23 +296,23 @@ export const getCreateSessionBySAMLCallbackMutationOptions = <
export type CreateSessionBySAMLCallbackMutationResult = NonNullable<
Awaited<ReturnType<typeof createSessionBySAMLCallback>>
>;
export type CreateSessionBySAMLCallbackMutationBody = BodyType<CreateSessionBySAMLCallbackBody>;
export type CreateSessionBySAMLCallbackMutationError = ErrorType<
CreateSessionBySAMLCallback303 | RenderErrorResponseDTO
>;
export type CreateSessionBySAMLCallbackMutationBody = CreateSessionBySAMLCallbackBody;
export type CreateSessionBySAMLCallbackMutationError =
| CreateSessionBySAMLCallback303
| RenderErrorResponseDTO;
/**
* @summary Create session by saml callback
*/
export const useCreateSessionBySAMLCallback = <
TError = ErrorType<CreateSessionBySAMLCallback303 | RenderErrorResponseDTO>,
TError = CreateSessionBySAMLCallback303 | RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createSessionBySAMLCallback>>,
TError,
{
data: BodyType<CreateSessionBySAMLCallbackBody>;
data: CreateSessionBySAMLCallbackBody;
params?: CreateSessionBySAMLCallbackParams;
},
TContext
@@ -322,7 +321,7 @@ export const useCreateSessionBySAMLCallback = <
Awaited<ReturnType<typeof createSessionBySAMLCallback>>,
TError,
{
data: BodyType<CreateSessionBySAMLCallbackBody>;
data: CreateSessionBySAMLCallbackBody;
params?: CreateSessionBySAMLCallbackParams;
},
TContext
@@ -343,7 +342,7 @@ export const deleteSession = () => {
};
export const getDeleteSessionMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -381,13 +380,13 @@ export type DeleteSessionMutationResult = NonNullable<
Awaited<ReturnType<typeof deleteSession>>
>;
export type DeleteSessionMutationError = ErrorType<RenderErrorResponseDTO>;
export type DeleteSessionMutationError = RenderErrorResponseDTO;
/**
* @summary Delete session
*/
export const useDeleteSession = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -419,12 +418,12 @@ export const getSessionContext = (signal?: AbortSignal) => {
};
export const getGetSessionContextQueryKey = () => {
return [`/api/v2/sessions/context`] as const;
return ['getSessionContext'] as const;
};
export const getGetSessionContextQueryOptions = <
TData = Awaited<ReturnType<typeof getSessionContext>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getSessionContext>>,
@@ -450,7 +449,7 @@ export const getGetSessionContextQueryOptions = <
export type GetSessionContextQueryResult = NonNullable<
Awaited<ReturnType<typeof getSessionContext>>
>;
export type GetSessionContextQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetSessionContextQueryError = RenderErrorResponseDTO;
/**
* @summary Get session context
@@ -458,7 +457,7 @@ export type GetSessionContextQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetSessionContext<
TData = Awaited<ReturnType<typeof getSessionContext>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getSessionContext>>,
@@ -497,7 +496,7 @@ export const invalidateGetSessionContext = async (
* @summary Create session by email and password
*/
export const createSessionByEmailPassword = (
authtypesPostableEmailPasswordSessionDTO: BodyType<AuthtypesPostableEmailPasswordSessionDTO>,
authtypesPostableEmailPasswordSessionDTO: AuthtypesPostableEmailPasswordSessionDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateSessionByEmailPassword200>({
@@ -510,19 +509,19 @@ export const createSessionByEmailPassword = (
};
export const getCreateSessionByEmailPasswordMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createSessionByEmailPassword>>,
TError,
{ data: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
{ data: AuthtypesPostableEmailPasswordSessionDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createSessionByEmailPassword>>,
TError,
{ data: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
{ data: AuthtypesPostableEmailPasswordSessionDTO },
TContext
> => {
const mutationKey = ['createSessionByEmailPassword'];
@@ -536,7 +535,7 @@ export const getCreateSessionByEmailPasswordMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createSessionByEmailPassword>>,
{ data: BodyType<AuthtypesPostableEmailPasswordSessionDTO> }
{ data: AuthtypesPostableEmailPasswordSessionDTO }
> = (props) => {
const { data } = props ?? {};
@@ -549,26 +548,26 @@ export const getCreateSessionByEmailPasswordMutationOptions = <
export type CreateSessionByEmailPasswordMutationResult = NonNullable<
Awaited<ReturnType<typeof createSessionByEmailPassword>>
>;
export type CreateSessionByEmailPasswordMutationBody = BodyType<AuthtypesPostableEmailPasswordSessionDTO>;
export type CreateSessionByEmailPasswordMutationError = ErrorType<RenderErrorResponseDTO>;
export type CreateSessionByEmailPasswordMutationBody = AuthtypesPostableEmailPasswordSessionDTO;
export type CreateSessionByEmailPasswordMutationError = RenderErrorResponseDTO;
/**
* @summary Create session by email and password
*/
export const useCreateSessionByEmailPassword = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createSessionByEmailPassword>>,
TError,
{ data: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
{ data: AuthtypesPostableEmailPasswordSessionDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createSessionByEmailPassword>>,
TError,
{ data: BodyType<AuthtypesPostableEmailPasswordSessionDTO> },
{ data: AuthtypesPostableEmailPasswordSessionDTO },
TContext
> => {
const mutationOptions = getCreateSessionByEmailPasswordMutationOptions(
@@ -582,7 +581,7 @@ export const useCreateSessionByEmailPassword = <
* @summary Rotate session
*/
export const rotateSession = (
authtypesPostableRotateTokenDTO: BodyType<AuthtypesPostableRotateTokenDTO>,
authtypesPostableRotateTokenDTO: AuthtypesPostableRotateTokenDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<RotateSession200>({
@@ -595,19 +594,19 @@ export const rotateSession = (
};
export const getRotateSessionMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof rotateSession>>,
TError,
{ data: BodyType<AuthtypesPostableRotateTokenDTO> },
{ data: AuthtypesPostableRotateTokenDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof rotateSession>>,
TError,
{ data: BodyType<AuthtypesPostableRotateTokenDTO> },
{ data: AuthtypesPostableRotateTokenDTO },
TContext
> => {
const mutationKey = ['rotateSession'];
@@ -621,7 +620,7 @@ export const getRotateSessionMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof rotateSession>>,
{ data: BodyType<AuthtypesPostableRotateTokenDTO> }
{ data: AuthtypesPostableRotateTokenDTO }
> = (props) => {
const { data } = props ?? {};
@@ -634,26 +633,26 @@ export const getRotateSessionMutationOptions = <
export type RotateSessionMutationResult = NonNullable<
Awaited<ReturnType<typeof rotateSession>>
>;
export type RotateSessionMutationBody = BodyType<AuthtypesPostableRotateTokenDTO>;
export type RotateSessionMutationError = ErrorType<RenderErrorResponseDTO>;
export type RotateSessionMutationBody = AuthtypesPostableRotateTokenDTO;
export type RotateSessionMutationError = RenderErrorResponseDTO;
/**
* @summary Rotate session
*/
export const useRotateSession = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof rotateSession>>,
TError,
{ data: BodyType<AuthtypesPostableRotateTokenDTO> },
{ data: AuthtypesPostableRotateTokenDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof rotateSession>>,
TError,
{ data: BodyType<AuthtypesPostableRotateTokenDTO> },
{ data: AuthtypesPostableRotateTokenDTO },
TContext
> => {
const mutationOptions = getRotateSessionMutationOptions(options);

View File

@@ -81,7 +81,7 @@ export interface AuthtypesGettableAuthDomainDTO {
/**
* @type string
*/
id: string;
id?: string;
/**
* @type string
*/
@@ -108,33 +108,6 @@ export interface AuthtypesGettableAuthDomainDTO {
updatedAt?: Date;
}
export interface AuthtypesGettableObjectsDTO {
resource: AuthtypesResourceDTO;
/**
* @type array
*/
selectors: string[];
}
/**
* @nullable
*/
export type AuthtypesGettableResourcesDTORelations = {
[key: string]: string[];
} | null;
export interface AuthtypesGettableResourcesDTO {
/**
* @type object
* @nullable true
*/
relations: AuthtypesGettableResourcesDTORelations;
/**
* @type array
*/
resources: AuthtypesResourceDTO[];
}
export interface AuthtypesGettableTokenDTO {
/**
* @type string
@@ -209,6 +182,10 @@ export interface AuthtypesGoogleConfigDTO {
serviceAccountJson?: string;
}
export interface AuthtypesNameDTO {
[key: string]: unknown;
}
export interface AuthtypesOIDCConfigDTO {
claimMapping?: AuthtypesAttributeMappingDTO;
/**
@@ -239,10 +216,7 @@ export interface AuthtypesOIDCConfigDTO {
export interface AuthtypesObjectDTO {
resource: AuthtypesResourceDTO;
/**
* @type string
*/
selector: string;
selector: AuthtypesSelectorDTO;
}
export interface AuthtypesOrgSessionContextDTO {
@@ -265,19 +239,6 @@ export interface AuthtypesPasswordAuthNSupportDTO {
provider?: string;
}
export interface AuthtypesPatchableObjectsDTO {
/**
* @type array
* @nullable true
*/
additions: AuthtypesGettableObjectsDTO[] | null;
/**
* @type array
* @nullable true
*/
deletions: AuthtypesGettableObjectsDTO[] | null;
}
export interface AuthtypesPostableAuthDomainDTO {
config?: AuthtypesAuthDomainConfigDTO;
/**
@@ -309,10 +270,7 @@ export interface AuthtypesPostableRotateTokenDTO {
}
export interface AuthtypesResourceDTO {
/**
* @type string
*/
name: string;
name: AuthtypesNameDTO;
/**
* @type string
*/
@@ -362,6 +320,10 @@ export interface AuthtypesSamlConfigDTO {
samlIdp?: string;
}
export interface AuthtypesSelectorDTO {
[key: string]: unknown;
}
export interface AuthtypesSessionContextDTO {
/**
* @type boolean
@@ -375,6 +337,10 @@ export interface AuthtypesSessionContextDTO {
}
export interface AuthtypesTransactionDTO {
/**
* @type string
*/
id?: string;
object: AuthtypesObjectDTO;
/**
* @type string
@@ -470,7 +436,7 @@ export interface ErrorsJSONDTO {
/**
* @type string
*/
code: string;
code?: string;
/**
* @type array
*/
@@ -478,7 +444,7 @@ export interface ErrorsJSONDTO {
/**
* @type string
*/
message: string;
message?: string;
/**
* @type string
*/
@@ -657,14 +623,14 @@ export interface GatewaytypesLimitMetricValueDTO {
export interface GatewaytypesLimitValueDTO {
/**
* @type integer
* @nullable true
* @format int64
*/
count?: number | null;
count?: number;
/**
* @type integer
* @nullable true
* @format int64
*/
size?: number | null;
size?: number;
}
export interface GatewaytypesPaginationDTO {
@@ -1006,18 +972,6 @@ export interface MetricsexplorertypesUpdateMetricMetadataRequestDTO {
unit: string;
}
export interface MetrictypesComparisonSpaceAggregationParamDTO {
/**
* @type string
*/
operator: string;
/**
* @type number
* @format double
*/
threshold: number;
}
export enum MetrictypesSpaceAggregationDTO {
sum = 'sum',
avg = 'avg',
@@ -1379,7 +1333,6 @@ export interface Querybuildertypesv5LogAggregationDTO {
}
export interface Querybuildertypesv5MetricAggregationDTO {
comparisonSpaceAggregationParam?: MetrictypesComparisonSpaceAggregationParamDTO;
/**
* @type string
*/
@@ -2032,11 +1985,44 @@ export enum Querybuildertypesv5VariableTypeDTO {
text = 'text',
}
export interface RenderErrorResponseDTO {
error: ErrorsJSONDTO;
error?: ErrorsJSONDTO;
/**
* @type string
*/
status: string;
status?: string;
}
/**
* @nullable
*/
export type RoletypesGettableResourcesDTORelations = {
[key: string]: string[];
} | null;
export interface RoletypesGettableResourcesDTO {
/**
* @type object
* @nullable true
*/
relations: RoletypesGettableResourcesDTORelations;
/**
* @type array
* @nullable true
*/
resources: AuthtypesResourceDTO[] | null;
}
export interface RoletypesPatchableObjectsDTO {
/**
* @type array
* @nullable true
*/
additions: AuthtypesObjectDTO[] | null;
/**
* @type array
* @nullable true
*/
deletions: AuthtypesObjectDTO[] | null;
}
export interface RoletypesPatchableRoleDTO {
@@ -2070,7 +2056,7 @@ export interface RoletypesRoleDTO {
/**
* @type string
*/
id: string;
id?: string;
/**
* @type string
*/
@@ -2211,7 +2197,7 @@ export interface TypesGettableAPIKeyDTO {
/**
* @type string
*/
id: string;
id?: string;
/**
* @type integer
* @format int64
@@ -2264,7 +2250,7 @@ export interface TypesIdentifiableDTO {
/**
* @type string
*/
id: string;
id?: string;
}
export interface TypesInviteDTO {
@@ -2280,7 +2266,7 @@ export interface TypesInviteDTO {
/**
* @type string
*/
id: string;
id?: string;
/**
* @type string
*/
@@ -2325,7 +2311,7 @@ export interface TypesOrganizationDTO {
/**
* @type string
*/
id: string;
id?: string;
/**
* @type integer
* @minimum 0
@@ -2431,7 +2417,7 @@ export interface TypesResetPasswordTokenDTO {
/**
* @type string
*/
id: string;
id?: string;
/**
* @type string
*/
@@ -2455,7 +2441,7 @@ export interface TypesStorableAPIKeyDTO {
/**
* @type string
*/
id: string;
id?: string;
/**
* @type string
*/
@@ -2504,7 +2490,7 @@ export interface TypesUserDTO {
/**
* @type string
*/
id: string;
id?: string;
/**
* @type boolean
*/
@@ -2620,14 +2606,6 @@ export type AuthzCheck200 = {
status: string;
};
export type AuthzResources200 = {
data: AuthtypesGettableResourcesDTO;
/**
* @type string
*/
status: string;
};
export type ChangePasswordPathParameters = {
id: string;
};
@@ -3039,7 +3017,7 @@ export type GetObjects200 = {
/**
* @type array
*/
data: AuthtypesGettableObjectsDTO[];
data: AuthtypesObjectDTO[];
/**
* @type string
*/
@@ -3050,6 +3028,14 @@ export type PatchObjectsPathParameters = {
id: string;
relation: string;
};
export type GetResources200 = {
data: RoletypesGettableResourcesDTO;
/**
* @type string
*/
status: string;
};
export type ListUsers200 = {
/**
* @type array
@@ -3151,7 +3137,7 @@ export type GetIngestionKeys200 = {
status: string;
};
export type CreateIngestionKey201 = {
export type CreateIngestionKey200 = {
data: GatewaytypesGettableCreatedIngestionKeyDTO;
/**
* @type string

View File

@@ -17,8 +17,7 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
AcceptInvite201,
ChangePasswordPathParameters,
@@ -61,7 +60,7 @@ type Awaited<O> = O extends AwaitedInput<infer T> ? T : never;
*/
export const changePassword = (
{ id }: ChangePasswordPathParameters,
typesChangePasswordRequestDTO: BodyType<TypesChangePasswordRequestDTO>,
typesChangePasswordRequestDTO: TypesChangePasswordRequestDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -74,7 +73,7 @@ export const changePassword = (
};
export const getChangePasswordMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -82,7 +81,7 @@ export const getChangePasswordMutationOptions = <
TError,
{
pathParams: ChangePasswordPathParameters;
data: BodyType<TypesChangePasswordRequestDTO>;
data: TypesChangePasswordRequestDTO;
},
TContext
>;
@@ -91,7 +90,7 @@ export const getChangePasswordMutationOptions = <
TError,
{
pathParams: ChangePasswordPathParameters;
data: BodyType<TypesChangePasswordRequestDTO>;
data: TypesChangePasswordRequestDTO;
},
TContext
> => {
@@ -108,7 +107,7 @@ export const getChangePasswordMutationOptions = <
Awaited<ReturnType<typeof changePassword>>,
{
pathParams: ChangePasswordPathParameters;
data: BodyType<TypesChangePasswordRequestDTO>;
data: TypesChangePasswordRequestDTO;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -122,14 +121,14 @@ export const getChangePasswordMutationOptions = <
export type ChangePasswordMutationResult = NonNullable<
Awaited<ReturnType<typeof changePassword>>
>;
export type ChangePasswordMutationBody = BodyType<TypesChangePasswordRequestDTO>;
export type ChangePasswordMutationError = ErrorType<RenderErrorResponseDTO>;
export type ChangePasswordMutationBody = TypesChangePasswordRequestDTO;
export type ChangePasswordMutationError = RenderErrorResponseDTO;
/**
* @summary Change password
*/
export const useChangePassword = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -137,7 +136,7 @@ export const useChangePassword = <
TError,
{
pathParams: ChangePasswordPathParameters;
data: BodyType<TypesChangePasswordRequestDTO>;
data: TypesChangePasswordRequestDTO;
},
TContext
>;
@@ -146,7 +145,7 @@ export const useChangePassword = <
TError,
{
pathParams: ChangePasswordPathParameters;
data: BodyType<TypesChangePasswordRequestDTO>;
data: TypesChangePasswordRequestDTO;
},
TContext
> => {
@@ -172,12 +171,12 @@ export const getResetPasswordToken = (
export const getGetResetPasswordTokenQueryKey = ({
id,
}: GetResetPasswordTokenPathParameters) => {
return [`/api/v1/getResetPasswordToken/${id}`] as const;
return ['getResetPasswordToken'] as const;
};
export const getGetResetPasswordTokenQueryOptions = <
TData = Awaited<ReturnType<typeof getResetPasswordToken>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetResetPasswordTokenPathParameters,
options?: {
@@ -212,7 +211,7 @@ export const getGetResetPasswordTokenQueryOptions = <
export type GetResetPasswordTokenQueryResult = NonNullable<
Awaited<ReturnType<typeof getResetPasswordToken>>
>;
export type GetResetPasswordTokenQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetResetPasswordTokenQueryError = RenderErrorResponseDTO;
/**
* @summary Get reset password token
@@ -220,7 +219,7 @@ export type GetResetPasswordTokenQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetResetPasswordToken<
TData = Awaited<ReturnType<typeof getResetPasswordToken>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetResetPasswordTokenPathParameters,
options?: {
@@ -271,12 +270,12 @@ export const listInvite = (signal?: AbortSignal) => {
};
export const getListInviteQueryKey = () => {
return [`/api/v1/invite`] as const;
return ['listInvite'] as const;
};
export const getListInviteQueryOptions = <
TData = Awaited<ReturnType<typeof listInvite>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof listInvite>>, TError, TData>;
}) => {
@@ -298,7 +297,7 @@ export const getListInviteQueryOptions = <
export type ListInviteQueryResult = NonNullable<
Awaited<ReturnType<typeof listInvite>>
>;
export type ListInviteQueryError = ErrorType<RenderErrorResponseDTO>;
export type ListInviteQueryError = RenderErrorResponseDTO;
/**
* @summary List invites
@@ -306,7 +305,7 @@ export type ListInviteQueryError = ErrorType<RenderErrorResponseDTO>;
export function useListInvite<
TData = Awaited<ReturnType<typeof listInvite>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof listInvite>>, TError, TData>;
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
@@ -341,7 +340,7 @@ export const invalidateListInvite = async (
* @summary Create invite
*/
export const createInvite = (
typesPostableInviteDTO: BodyType<TypesPostableInviteDTO>,
typesPostableInviteDTO: TypesPostableInviteDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateInvite201>({
@@ -354,19 +353,19 @@ export const createInvite = (
};
export const getCreateInviteMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO> },
{ data: TypesPostableInviteDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO> },
{ data: TypesPostableInviteDTO },
TContext
> => {
const mutationKey = ['createInvite'];
@@ -380,7 +379,7 @@ export const getCreateInviteMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createInvite>>,
{ data: BodyType<TypesPostableInviteDTO> }
{ data: TypesPostableInviteDTO }
> = (props) => {
const { data } = props ?? {};
@@ -393,26 +392,26 @@ export const getCreateInviteMutationOptions = <
export type CreateInviteMutationResult = NonNullable<
Awaited<ReturnType<typeof createInvite>>
>;
export type CreateInviteMutationBody = BodyType<TypesPostableInviteDTO>;
export type CreateInviteMutationError = ErrorType<RenderErrorResponseDTO>;
export type CreateInviteMutationBody = TypesPostableInviteDTO;
export type CreateInviteMutationError = RenderErrorResponseDTO;
/**
* @summary Create invite
*/
export const useCreateInvite = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO> },
{ data: TypesPostableInviteDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO> },
{ data: TypesPostableInviteDTO },
TContext
> => {
const mutationOptions = getCreateInviteMutationOptions(options);
@@ -431,7 +430,7 @@ export const deleteInvite = ({ id }: DeleteInvitePathParameters) => {
};
export const getDeleteInviteMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -471,13 +470,13 @@ export type DeleteInviteMutationResult = NonNullable<
Awaited<ReturnType<typeof deleteInvite>>
>;
export type DeleteInviteMutationError = ErrorType<RenderErrorResponseDTO>;
export type DeleteInviteMutationError = RenderErrorResponseDTO;
/**
* @summary Delete invite
*/
export const useDeleteInvite = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -512,12 +511,12 @@ export const getInvite = (
};
export const getGetInviteQueryKey = ({ token }: GetInvitePathParameters) => {
return [`/api/v1/invite/${token}`] as const;
return ['getInvite'] as const;
};
export const getGetInviteQueryOptions = <
TData = Awaited<ReturnType<typeof getInvite>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ token }: GetInvitePathParameters,
options?: {
@@ -545,7 +544,7 @@ export const getGetInviteQueryOptions = <
export type GetInviteQueryResult = NonNullable<
Awaited<ReturnType<typeof getInvite>>
>;
export type GetInviteQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetInviteQueryError = RenderErrorResponseDTO;
/**
* @summary Get invite
@@ -553,7 +552,7 @@ export type GetInviteQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetInvite<
TData = Awaited<ReturnType<typeof getInvite>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ token }: GetInvitePathParameters,
options?: {
@@ -592,7 +591,7 @@ export const invalidateGetInvite = async (
* @summary Accept invite
*/
export const acceptInvite = (
typesPostableAcceptInviteDTO: BodyType<TypesPostableAcceptInviteDTO>,
typesPostableAcceptInviteDTO: TypesPostableAcceptInviteDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<AcceptInvite201>({
@@ -605,19 +604,19 @@ export const acceptInvite = (
};
export const getAcceptInviteMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof acceptInvite>>,
TError,
{ data: BodyType<TypesPostableAcceptInviteDTO> },
{ data: TypesPostableAcceptInviteDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof acceptInvite>>,
TError,
{ data: BodyType<TypesPostableAcceptInviteDTO> },
{ data: TypesPostableAcceptInviteDTO },
TContext
> => {
const mutationKey = ['acceptInvite'];
@@ -631,7 +630,7 @@ export const getAcceptInviteMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof acceptInvite>>,
{ data: BodyType<TypesPostableAcceptInviteDTO> }
{ data: TypesPostableAcceptInviteDTO }
> = (props) => {
const { data } = props ?? {};
@@ -644,26 +643,26 @@ export const getAcceptInviteMutationOptions = <
export type AcceptInviteMutationResult = NonNullable<
Awaited<ReturnType<typeof acceptInvite>>
>;
export type AcceptInviteMutationBody = BodyType<TypesPostableAcceptInviteDTO>;
export type AcceptInviteMutationError = ErrorType<RenderErrorResponseDTO>;
export type AcceptInviteMutationBody = TypesPostableAcceptInviteDTO;
export type AcceptInviteMutationError = RenderErrorResponseDTO;
/**
* @summary Accept invite
*/
export const useAcceptInvite = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof acceptInvite>>,
TError,
{ data: BodyType<TypesPostableAcceptInviteDTO> },
{ data: TypesPostableAcceptInviteDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof acceptInvite>>,
TError,
{ data: BodyType<TypesPostableAcceptInviteDTO> },
{ data: TypesPostableAcceptInviteDTO },
TContext
> => {
const mutationOptions = getAcceptInviteMutationOptions(options);
@@ -675,7 +674,7 @@ export const useAcceptInvite = <
* @summary Create bulk invite
*/
export const createBulkInvite = (
typesPostableInviteDTO: BodyType<TypesPostableInviteDTO[]>,
typesPostableInviteDTO: TypesPostableInviteDTO[],
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -688,19 +687,19 @@ export const createBulkInvite = (
};
export const getCreateBulkInviteMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createBulkInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO[]> },
{ data: TypesPostableInviteDTO[] },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createBulkInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO[]> },
{ data: TypesPostableInviteDTO[] },
TContext
> => {
const mutationKey = ['createBulkInvite'];
@@ -714,7 +713,7 @@ export const getCreateBulkInviteMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createBulkInvite>>,
{ data: BodyType<TypesPostableInviteDTO[]> }
{ data: TypesPostableInviteDTO[] }
> = (props) => {
const { data } = props ?? {};
@@ -727,26 +726,26 @@ export const getCreateBulkInviteMutationOptions = <
export type CreateBulkInviteMutationResult = NonNullable<
Awaited<ReturnType<typeof createBulkInvite>>
>;
export type CreateBulkInviteMutationBody = BodyType<TypesPostableInviteDTO[]>;
export type CreateBulkInviteMutationError = ErrorType<RenderErrorResponseDTO>;
export type CreateBulkInviteMutationBody = TypesPostableInviteDTO[];
export type CreateBulkInviteMutationError = RenderErrorResponseDTO;
/**
* @summary Create bulk invite
*/
export const useCreateBulkInvite = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createBulkInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO[]> },
{ data: TypesPostableInviteDTO[] },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createBulkInvite>>,
TError,
{ data: BodyType<TypesPostableInviteDTO[]> },
{ data: TypesPostableInviteDTO[] },
TContext
> => {
const mutationOptions = getCreateBulkInviteMutationOptions(options);
@@ -766,12 +765,12 @@ export const listAPIKeys = (signal?: AbortSignal) => {
};
export const getListAPIKeysQueryKey = () => {
return [`/api/v1/pats`] as const;
return ['listAPIKeys'] as const;
};
export const getListAPIKeysQueryOptions = <
TData = Awaited<ReturnType<typeof listAPIKeys>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listAPIKeys>>,
@@ -797,7 +796,7 @@ export const getListAPIKeysQueryOptions = <
export type ListAPIKeysQueryResult = NonNullable<
Awaited<ReturnType<typeof listAPIKeys>>
>;
export type ListAPIKeysQueryError = ErrorType<RenderErrorResponseDTO>;
export type ListAPIKeysQueryError = RenderErrorResponseDTO;
/**
* @summary List api keys
@@ -805,7 +804,7 @@ export type ListAPIKeysQueryError = ErrorType<RenderErrorResponseDTO>;
export function useListAPIKeys<
TData = Awaited<ReturnType<typeof listAPIKeys>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listAPIKeys>>,
@@ -844,7 +843,7 @@ export const invalidateListAPIKeys = async (
* @summary Create api key
*/
export const createAPIKey = (
typesPostableAPIKeyDTO: BodyType<TypesPostableAPIKeyDTO>,
typesPostableAPIKeyDTO: TypesPostableAPIKeyDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<CreateAPIKey201>({
@@ -857,19 +856,19 @@ export const createAPIKey = (
};
export const getCreateAPIKeyMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createAPIKey>>,
TError,
{ data: BodyType<TypesPostableAPIKeyDTO> },
{ data: TypesPostableAPIKeyDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createAPIKey>>,
TError,
{ data: BodyType<TypesPostableAPIKeyDTO> },
{ data: TypesPostableAPIKeyDTO },
TContext
> => {
const mutationKey = ['createAPIKey'];
@@ -883,7 +882,7 @@ export const getCreateAPIKeyMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createAPIKey>>,
{ data: BodyType<TypesPostableAPIKeyDTO> }
{ data: TypesPostableAPIKeyDTO }
> = (props) => {
const { data } = props ?? {};
@@ -896,26 +895,26 @@ export const getCreateAPIKeyMutationOptions = <
export type CreateAPIKeyMutationResult = NonNullable<
Awaited<ReturnType<typeof createAPIKey>>
>;
export type CreateAPIKeyMutationBody = BodyType<TypesPostableAPIKeyDTO>;
export type CreateAPIKeyMutationError = ErrorType<RenderErrorResponseDTO>;
export type CreateAPIKeyMutationBody = TypesPostableAPIKeyDTO;
export type CreateAPIKeyMutationError = RenderErrorResponseDTO;
/**
* @summary Create api key
*/
export const useCreateAPIKey = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createAPIKey>>,
TError,
{ data: BodyType<TypesPostableAPIKeyDTO> },
{ data: TypesPostableAPIKeyDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createAPIKey>>,
TError,
{ data: BodyType<TypesPostableAPIKeyDTO> },
{ data: TypesPostableAPIKeyDTO },
TContext
> => {
const mutationOptions = getCreateAPIKeyMutationOptions(options);
@@ -934,7 +933,7 @@ export const revokeAPIKey = ({ id }: RevokeAPIKeyPathParameters) => {
};
export const getRevokeAPIKeyMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -974,13 +973,13 @@ export type RevokeAPIKeyMutationResult = NonNullable<
Awaited<ReturnType<typeof revokeAPIKey>>
>;
export type RevokeAPIKeyMutationError = ErrorType<RenderErrorResponseDTO>;
export type RevokeAPIKeyMutationError = RenderErrorResponseDTO;
/**
* @summary Revoke api key
*/
export const useRevokeAPIKey = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -1005,7 +1004,7 @@ export const useRevokeAPIKey = <
*/
export const updateAPIKey = (
{ id }: UpdateAPIKeyPathParameters,
typesStorableAPIKeyDTO: BodyType<TypesStorableAPIKeyDTO>,
typesStorableAPIKeyDTO: TypesStorableAPIKeyDTO,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/pats/${id}`,
@@ -1016,25 +1015,19 @@ export const updateAPIKey = (
};
export const getUpdateAPIKeyMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateAPIKey>>,
TError,
{
pathParams: UpdateAPIKeyPathParameters;
data: BodyType<TypesStorableAPIKeyDTO>;
},
{ pathParams: UpdateAPIKeyPathParameters; data: TypesStorableAPIKeyDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof updateAPIKey>>,
TError,
{
pathParams: UpdateAPIKeyPathParameters;
data: BodyType<TypesStorableAPIKeyDTO>;
},
{ pathParams: UpdateAPIKeyPathParameters; data: TypesStorableAPIKeyDTO },
TContext
> => {
const mutationKey = ['updateAPIKey'];
@@ -1048,10 +1041,7 @@ export const getUpdateAPIKeyMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof updateAPIKey>>,
{
pathParams: UpdateAPIKeyPathParameters;
data: BodyType<TypesStorableAPIKeyDTO>;
}
{ pathParams: UpdateAPIKeyPathParameters; data: TypesStorableAPIKeyDTO }
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -1064,32 +1054,26 @@ export const getUpdateAPIKeyMutationOptions = <
export type UpdateAPIKeyMutationResult = NonNullable<
Awaited<ReturnType<typeof updateAPIKey>>
>;
export type UpdateAPIKeyMutationBody = BodyType<TypesStorableAPIKeyDTO>;
export type UpdateAPIKeyMutationError = ErrorType<RenderErrorResponseDTO>;
export type UpdateAPIKeyMutationBody = TypesStorableAPIKeyDTO;
export type UpdateAPIKeyMutationError = RenderErrorResponseDTO;
/**
* @summary Update api key
*/
export const useUpdateAPIKey = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateAPIKey>>,
TError,
{
pathParams: UpdateAPIKeyPathParameters;
data: BodyType<TypesStorableAPIKeyDTO>;
},
{ pathParams: UpdateAPIKeyPathParameters; data: TypesStorableAPIKeyDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof updateAPIKey>>,
TError,
{
pathParams: UpdateAPIKeyPathParameters;
data: BodyType<TypesStorableAPIKeyDTO>;
},
{ pathParams: UpdateAPIKeyPathParameters; data: TypesStorableAPIKeyDTO },
TContext
> => {
const mutationOptions = getUpdateAPIKeyMutationOptions(options);
@@ -1101,7 +1085,7 @@ export const useUpdateAPIKey = <
* @summary Reset password
*/
export const resetPassword = (
typesPostableResetPasswordDTO: BodyType<TypesPostableResetPasswordDTO>,
typesPostableResetPasswordDTO: TypesPostableResetPasswordDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -1114,19 +1098,19 @@ export const resetPassword = (
};
export const getResetPasswordMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof resetPassword>>,
TError,
{ data: BodyType<TypesPostableResetPasswordDTO> },
{ data: TypesPostableResetPasswordDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof resetPassword>>,
TError,
{ data: BodyType<TypesPostableResetPasswordDTO> },
{ data: TypesPostableResetPasswordDTO },
TContext
> => {
const mutationKey = ['resetPassword'];
@@ -1140,7 +1124,7 @@ export const getResetPasswordMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof resetPassword>>,
{ data: BodyType<TypesPostableResetPasswordDTO> }
{ data: TypesPostableResetPasswordDTO }
> = (props) => {
const { data } = props ?? {};
@@ -1153,26 +1137,26 @@ export const getResetPasswordMutationOptions = <
export type ResetPasswordMutationResult = NonNullable<
Awaited<ReturnType<typeof resetPassword>>
>;
export type ResetPasswordMutationBody = BodyType<TypesPostableResetPasswordDTO>;
export type ResetPasswordMutationError = ErrorType<RenderErrorResponseDTO>;
export type ResetPasswordMutationBody = TypesPostableResetPasswordDTO;
export type ResetPasswordMutationError = RenderErrorResponseDTO;
/**
* @summary Reset password
*/
export const useResetPassword = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof resetPassword>>,
TError,
{ data: BodyType<TypesPostableResetPasswordDTO> },
{ data: TypesPostableResetPasswordDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof resetPassword>>,
TError,
{ data: BodyType<TypesPostableResetPasswordDTO> },
{ data: TypesPostableResetPasswordDTO },
TContext
> => {
const mutationOptions = getResetPasswordMutationOptions(options);
@@ -1192,12 +1176,12 @@ export const listUsers = (signal?: AbortSignal) => {
};
export const getListUsersQueryKey = () => {
return [`/api/v1/user`] as const;
return ['listUsers'] as const;
};
export const getListUsersQueryOptions = <
TData = Awaited<ReturnType<typeof listUsers>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof listUsers>>, TError, TData>;
}) => {
@@ -1219,7 +1203,7 @@ export const getListUsersQueryOptions = <
export type ListUsersQueryResult = NonNullable<
Awaited<ReturnType<typeof listUsers>>
>;
export type ListUsersQueryError = ErrorType<RenderErrorResponseDTO>;
export type ListUsersQueryError = RenderErrorResponseDTO;
/**
* @summary List users
@@ -1227,7 +1211,7 @@ export type ListUsersQueryError = ErrorType<RenderErrorResponseDTO>;
export function useListUsers<
TData = Awaited<ReturnType<typeof listUsers>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof listUsers>>, TError, TData>;
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
@@ -1269,7 +1253,7 @@ export const deleteUser = ({ id }: DeleteUserPathParameters) => {
};
export const getDeleteUserMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -1309,13 +1293,13 @@ export type DeleteUserMutationResult = NonNullable<
Awaited<ReturnType<typeof deleteUser>>
>;
export type DeleteUserMutationError = ErrorType<RenderErrorResponseDTO>;
export type DeleteUserMutationError = RenderErrorResponseDTO;
/**
* @summary Delete user
*/
export const useDeleteUser = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -1350,12 +1334,12 @@ export const getUser = (
};
export const getGetUserQueryKey = ({ id }: GetUserPathParameters) => {
return [`/api/v1/user/${id}`] as const;
return ['getUser'] as const;
};
export const getGetUserQueryOptions = <
TData = Awaited<ReturnType<typeof getUser>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetUserPathParameters,
options?: {
@@ -1383,7 +1367,7 @@ export const getGetUserQueryOptions = <
export type GetUserQueryResult = NonNullable<
Awaited<ReturnType<typeof getUser>>
>;
export type GetUserQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetUserQueryError = RenderErrorResponseDTO;
/**
* @summary Get user
@@ -1391,7 +1375,7 @@ export type GetUserQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetUser<
TData = Awaited<ReturnType<typeof getUser>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetUserPathParameters,
options?: {
@@ -1431,7 +1415,7 @@ export const invalidateGetUser = async (
*/
export const updateUser = (
{ id }: UpdateUserPathParameters,
typesUserDTO: BodyType<TypesUserDTO>,
typesUserDTO: TypesUserDTO,
) => {
return GeneratedAPIInstance<UpdateUser200>({
url: `/api/v1/user/${id}`,
@@ -1442,19 +1426,19 @@ export const updateUser = (
};
export const getUpdateUserMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateUser>>,
TError,
{ pathParams: UpdateUserPathParameters; data: BodyType<TypesUserDTO> },
{ pathParams: UpdateUserPathParameters; data: TypesUserDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof updateUser>>,
TError,
{ pathParams: UpdateUserPathParameters; data: BodyType<TypesUserDTO> },
{ pathParams: UpdateUserPathParameters; data: TypesUserDTO },
TContext
> => {
const mutationKey = ['updateUser'];
@@ -1468,7 +1452,7 @@ export const getUpdateUserMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof updateUser>>,
{ pathParams: UpdateUserPathParameters; data: BodyType<TypesUserDTO> }
{ pathParams: UpdateUserPathParameters; data: TypesUserDTO }
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -1481,26 +1465,26 @@ export const getUpdateUserMutationOptions = <
export type UpdateUserMutationResult = NonNullable<
Awaited<ReturnType<typeof updateUser>>
>;
export type UpdateUserMutationBody = BodyType<TypesUserDTO>;
export type UpdateUserMutationError = ErrorType<RenderErrorResponseDTO>;
export type UpdateUserMutationBody = TypesUserDTO;
export type UpdateUserMutationError = RenderErrorResponseDTO;
/**
* @summary Update user
*/
export const useUpdateUser = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof updateUser>>,
TError,
{ pathParams: UpdateUserPathParameters; data: BodyType<TypesUserDTO> },
{ pathParams: UpdateUserPathParameters; data: TypesUserDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof updateUser>>,
TError,
{ pathParams: UpdateUserPathParameters; data: BodyType<TypesUserDTO> },
{ pathParams: UpdateUserPathParameters; data: TypesUserDTO },
TContext
> => {
const mutationOptions = getUpdateUserMutationOptions(options);
@@ -1520,12 +1504,12 @@ export const getMyUser = (signal?: AbortSignal) => {
};
export const getGetMyUserQueryKey = () => {
return [`/api/v1/user/me`] as const;
return ['getMyUser'] as const;
};
export const getGetMyUserQueryOptions = <
TData = Awaited<ReturnType<typeof getMyUser>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof getMyUser>>, TError, TData>;
}) => {
@@ -1547,7 +1531,7 @@ export const getGetMyUserQueryOptions = <
export type GetMyUserQueryResult = NonNullable<
Awaited<ReturnType<typeof getMyUser>>
>;
export type GetMyUserQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetMyUserQueryError = RenderErrorResponseDTO;
/**
* @summary Get my user
@@ -1555,7 +1539,7 @@ export type GetMyUserQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetMyUser<
TData = Awaited<ReturnType<typeof getMyUser>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof getMyUser>>, TError, TData>;
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
@@ -1590,7 +1574,7 @@ export const invalidateGetMyUser = async (
* @summary Forgot password
*/
export const forgotPassword = (
typesPostableForgotPasswordDTO: BodyType<TypesPostableForgotPasswordDTO>,
typesPostableForgotPasswordDTO: TypesPostableForgotPasswordDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<void>({
@@ -1603,19 +1587,19 @@ export const forgotPassword = (
};
export const getForgotPasswordMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof forgotPassword>>,
TError,
{ data: BodyType<TypesPostableForgotPasswordDTO> },
{ data: TypesPostableForgotPasswordDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof forgotPassword>>,
TError,
{ data: BodyType<TypesPostableForgotPasswordDTO> },
{ data: TypesPostableForgotPasswordDTO },
TContext
> => {
const mutationKey = ['forgotPassword'];
@@ -1629,7 +1613,7 @@ export const getForgotPasswordMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof forgotPassword>>,
{ data: BodyType<TypesPostableForgotPasswordDTO> }
{ data: TypesPostableForgotPasswordDTO }
> = (props) => {
const { data } = props ?? {};
@@ -1642,26 +1626,26 @@ export const getForgotPasswordMutationOptions = <
export type ForgotPasswordMutationResult = NonNullable<
Awaited<ReturnType<typeof forgotPassword>>
>;
export type ForgotPasswordMutationBody = BodyType<TypesPostableForgotPasswordDTO>;
export type ForgotPasswordMutationError = ErrorType<RenderErrorResponseDTO>;
export type ForgotPasswordMutationBody = TypesPostableForgotPasswordDTO;
export type ForgotPasswordMutationError = RenderErrorResponseDTO;
/**
* @summary Forgot password
*/
export const useForgotPassword = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof forgotPassword>>,
TError,
{ data: BodyType<TypesPostableForgotPasswordDTO> },
{ data: TypesPostableForgotPasswordDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof forgotPassword>>,
TError,
{ data: BodyType<TypesPostableForgotPasswordDTO> },
{ data: TypesPostableForgotPasswordDTO },
TContext
> => {
const mutationOptions = getForgotPasswordMutationOptions(options);

View File

@@ -17,8 +17,7 @@ import type {
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../index';
import type {
GetHosts200,
RenderErrorResponseDTO,
@@ -43,12 +42,12 @@ export const getHosts = (signal?: AbortSignal) => {
};
export const getGetHostsQueryKey = () => {
return [`/api/v2/zeus/hosts`] as const;
return ['getHosts'] as const;
};
export const getGetHostsQueryOptions = <
TData = Awaited<ReturnType<typeof getHosts>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof getHosts>>, TError, TData>;
}) => {
@@ -70,7 +69,7 @@ export const getGetHostsQueryOptions = <
export type GetHostsQueryResult = NonNullable<
Awaited<ReturnType<typeof getHosts>>
>;
export type GetHostsQueryError = ErrorType<RenderErrorResponseDTO>;
export type GetHostsQueryError = RenderErrorResponseDTO;
/**
* @summary Get host info from Zeus.
@@ -78,7 +77,7 @@ export type GetHostsQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetHosts<
TData = Awaited<ReturnType<typeof getHosts>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof getHosts>>, TError, TData>;
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
@@ -112,9 +111,7 @@ export const invalidateGetHosts = async (
* This endpoint saves the host of a deployment to zeus.
* @summary Put host in Zeus for a deployment.
*/
export const putHost = (
zeustypesPostableHostDTO: BodyType<ZeustypesPostableHostDTO>,
) => {
export const putHost = (zeustypesPostableHostDTO: ZeustypesPostableHostDTO) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/zeus/hosts`,
method: 'PUT',
@@ -124,19 +121,19 @@ export const putHost = (
};
export const getPutHostMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
{ data: ZeustypesPostableHostDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
{ data: ZeustypesPostableHostDTO },
TContext
> => {
const mutationKey = ['putHost'];
@@ -150,7 +147,7 @@ export const getPutHostMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof putHost>>,
{ data: BodyType<ZeustypesPostableHostDTO> }
{ data: ZeustypesPostableHostDTO }
> = (props) => {
const { data } = props ?? {};
@@ -163,26 +160,26 @@ export const getPutHostMutationOptions = <
export type PutHostMutationResult = NonNullable<
Awaited<ReturnType<typeof putHost>>
>;
export type PutHostMutationBody = BodyType<ZeustypesPostableHostDTO>;
export type PutHostMutationError = ErrorType<RenderErrorResponseDTO>;
export type PutHostMutationBody = ZeustypesPostableHostDTO;
export type PutHostMutationError = RenderErrorResponseDTO;
/**
* @summary Put host in Zeus for a deployment.
*/
export const usePutHost = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
{ data: ZeustypesPostableHostDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
{ data: ZeustypesPostableHostDTO },
TContext
> => {
const mutationOptions = getPutHostMutationOptions(options);
@@ -194,7 +191,7 @@ export const usePutHost = <
* @summary Put profile in Zeus for a deployment.
*/
export const putProfile = (
zeustypesPostableProfileDTO: BodyType<ZeustypesPostableProfileDTO>,
zeustypesPostableProfileDTO: ZeustypesPostableProfileDTO,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/zeus/profiles`,
@@ -205,19 +202,19 @@ export const putProfile = (
};
export const getPutProfileMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
{ data: ZeustypesPostableProfileDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
{ data: ZeustypesPostableProfileDTO },
TContext
> => {
const mutationKey = ['putProfile'];
@@ -231,7 +228,7 @@ export const getPutProfileMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof putProfile>>,
{ data: BodyType<ZeustypesPostableProfileDTO> }
{ data: ZeustypesPostableProfileDTO }
> = (props) => {
const { data } = props ?? {};
@@ -244,26 +241,26 @@ export const getPutProfileMutationOptions = <
export type PutProfileMutationResult = NonNullable<
Awaited<ReturnType<typeof putProfile>>
>;
export type PutProfileMutationBody = BodyType<ZeustypesPostableProfileDTO>;
export type PutProfileMutationError = ErrorType<RenderErrorResponseDTO>;
export type PutProfileMutationBody = ZeustypesPostableProfileDTO;
export type PutProfileMutationError = RenderErrorResponseDTO;
/**
* @summary Put profile in Zeus for a deployment.
*/
export const usePutProfile = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
{ data: ZeustypesPostableProfileDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
{ data: ZeustypesPostableProfileDTO },
TContext
> => {
const mutationOptions = getPutProfileMutationOptions(options);

View File

@@ -1,27 +0,0 @@
import {
interceptorRejected,
interceptorsRequestResponse,
interceptorsResponse,
} from 'api';
import axios, { AxiosError, AxiosRequestConfig } from 'axios';
import { ENVIRONMENT } from 'constants/env';
// generated API Instance
const generatedAPIAxiosInstance = axios.create({
baseURL: ENVIRONMENT.baseURL,
});
export const GeneratedAPIInstance = <T>(
config: AxiosRequestConfig,
): Promise<T> => {
return generatedAPIAxiosInstance({ ...config }).then(({ data }) => data);
};
generatedAPIAxiosInstance.interceptors.request.use(interceptorsRequestResponse);
generatedAPIAxiosInstance.interceptors.response.use(
interceptorsResponse,
interceptorRejected,
);
export type ErrorType<Error> = AxiosError<Error>;
export type BodyType<BodyData> = BodyData;

View File

@@ -28,7 +28,7 @@ const queryClient = new QueryClient({
},
});
export const interceptorsResponse = (
const interceptorsResponse = (
value: AxiosResponse<any>,
): Promise<AxiosResponse<any>> => {
if ((value.config as any)?.metadata) {
@@ -51,7 +51,7 @@ export const interceptorsResponse = (
return Promise.resolve(value);
};
export const interceptorsRequestResponse = (
const interceptorsRequestResponse = (
value: InternalAxiosRequestConfig,
): InternalAxiosRequestConfig => {
// Attach metadata safely (not sent with the request)
@@ -69,7 +69,7 @@ export const interceptorsRequestResponse = (
return value;
};
export const interceptorRejected = async (
const interceptorRejected = async (
value: AxiosResponse<any>,
): Promise<AxiosResponse<any>> => {
try {
@@ -203,6 +203,17 @@ LogEventAxiosInstance.interceptors.response.use(
LogEventAxiosInstance.interceptors.request.use(interceptorsRequestResponse);
//
// generated API Instance
export const GeneratedAPIInstance = axios.create({
baseURL: ENVIRONMENT.baseURL,
});
GeneratedAPIInstance.interceptors.request.use(interceptorsRequestResponse);
GeneratedAPIInstance.interceptors.response.use(
interceptorsResponse,
interceptorRejected,
);
AxiosAlertManagerInstance.interceptors.response.use(
interceptorsResponse,
interceptorRejected,

View File

@@ -0,0 +1,26 @@
import { ApiV2Instance as axios } from 'api';
import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
import { AxiosError } from 'axios';
import { ErrorResponseV2, ErrorV2Resp, SuccessResponseV2 } from 'types/api';
import { MetricMetadataResponse } from 'types/api/metricsExplorer/v2/getMetricMetadata';
export const getMetricMetadata = async (
metricName: string,
signal?: AbortSignal,
headers?: Record<string, string>,
): Promise<SuccessResponseV2<MetricMetadataResponse> | ErrorResponseV2> => {
try {
const encodedMetricName = encodeURIComponent(metricName);
const response = await axios.get(`/metrics/${encodedMetricName}/metadata`, {
signal,
headers,
});
return {
httpStatusCode: response.status,
data: response.data,
};
} catch (error) {
return ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
}
};

View File

@@ -86,13 +86,8 @@ function LogDetailInner({
const handleClickOutside = (e: MouseEvent): void => {
const target = e.target as HTMLElement;
// Don't close if clicking on drawer content, overlays, or portal elements
if (
target.closest('[data-log-detail-ignore="true"]') ||
target.closest('.cm-tooltip-autocomplete') ||
target.closest('.drawer-popover') ||
target.closest('.query-status-popover')
) {
// Don't close if clicking on explicitly ignored regions
if (target.closest('[data-log-detail-ignore="true"]')) {
return;
}
@@ -405,11 +400,7 @@ function LogDetailInner({
<div className="log-detail-drawer__content" data-log-detail-ignore="true">
<div className="log-detail-drawer__log">
<Divider type="vertical" className={cx('log-type-indicator', logType)} />
<Tooltip
title={removeEscapeCharacters(log?.body)}
placement="left"
mouseLeaveDelay={0}
>
<Tooltip title={removeEscapeCharacters(log?.body)} placement="left">
<div className="log-body" dangerouslySetInnerHTML={htmlBody} />
</Tooltip>
@@ -475,7 +466,6 @@ function LogDetailInner({
title="Show Filters"
placement="topLeft"
aria-label="Show Filters"
mouseLeaveDelay={0}
>
<Button
className="action-btn"
@@ -491,7 +481,6 @@ function LogDetailInner({
aria-label={
selectedView === VIEW_TYPES.JSON ? 'Copy JSON' : 'Copy Log Link'
}
mouseLeaveDelay={0}
>
<Button
className="action-btn"

View File

@@ -27,11 +27,7 @@ function AddToQueryHOC({
return (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
<div className={cx('addToQueryContainer', fontSize)} onClick={handleQueryAdd}>
<Popover
overlayClassName="drawer-popover"
placement="top"
content={popOverContent}
>
<Popover placement="top" content={popOverContent}>
{children}
</Popover>
</div>

View File

@@ -32,7 +32,6 @@ function CopyClipboardHOC({
<span onClick={onClick} role="presentation" tabIndex={-1}>
<Popover
placement="top"
overlayClassName="drawer-popover"
content={<span style={{ fontSize: '0.9rem' }}>{tooltipText}</span>}
>
{children}

View File

@@ -21,7 +21,7 @@ export function getDefaultCellStyle(isDarkMode?: boolean): CSSProperties {
export const defaultTableStyle: CSSProperties = {
minWidth: '40rem',
maxWidth: '90rem',
maxWidth: '60rem',
};
export const defaultListViewPanelStyle: CSSProperties = {

View File

@@ -11,6 +11,7 @@ import {
startCompletion,
} from '@codemirror/autocomplete';
import { javascript } from '@codemirror/lang-javascript';
import * as Sentry from '@sentry/react';
import { Color } from '@signozhq/design-tokens';
import { copilot } from '@uiw/codemirror-theme-copilot';
import { githubLight } from '@uiw/codemirror-theme-github';
@@ -563,7 +564,15 @@ function QuerySearch({
const lastPos = lastPosRef.current;
if (newPos.line !== lastPos.line || newPos.ch !== lastPos.ch) {
setCursorPos(newPos);
setCursorPos((lastPos) => {
if (newPos.ch !== lastPos.ch && newPos.ch === 0) {
Sentry.captureEvent({
message: `Cursor jumped to start of line from ${lastPos.ch} to ${newPos.ch}`,
level: 'warning',
});
}
return newPos;
});
lastPosRef.current = newPos;
if (doc) {
@@ -1319,10 +1328,7 @@ function QuerySearch({
)}
<div className="query-where-clause-editor-container">
<Tooltip
title={<div data-log-detail-ignore="true">{getTooltipContent()}</div>}
placement="left"
>
<Tooltip title={getTooltipContent()} placement="left">
<a
href="https://signoz.io/docs/userguide/search-syntax/"
target="_blank"

View File

@@ -40,7 +40,6 @@ function ValueGraph({
value,
rawValue,
thresholds,
yAxisUnit,
}: ValueGraphProps): JSX.Element {
const { t } = useTranslation(['valueGraph']);
const containerRef = useRef<HTMLDivElement>(null);
@@ -88,7 +87,7 @@ function ValueGraph({
const {
threshold,
isConflictingThresholds,
} = getBackgroundColorAndThresholdCheck(thresholds, rawValue, yAxisUnit);
} = getBackgroundColorAndThresholdCheck(thresholds, rawValue);
return (
<div
@@ -156,7 +155,6 @@ interface ValueGraphProps {
value: string;
rawValue: number;
thresholds: ThresholdProps[];
yAxisUnit?: string;
}
export default ValueGraph;

View File

@@ -1,10 +1,9 @@
import { evaluateThresholdWithConvertedValue } from 'container/GridTableComponent/utils';
import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';
function doesValueSatisfyThreshold(
function compareThreshold(
rawValue: number,
threshold: ThresholdProps,
yAxisUnit?: string,
): boolean {
if (
threshold.thresholdOperator === undefined ||
@@ -12,14 +11,31 @@ function doesValueSatisfyThreshold(
) {
return false;
}
switch (threshold.thresholdOperator) {
case '>':
return rawValue > threshold.thresholdValue;
case '>=':
return rawValue >= threshold.thresholdValue;
case '<':
return rawValue < threshold.thresholdValue;
case '<=':
return rawValue <= threshold.thresholdValue;
case '=':
return rawValue === threshold.thresholdValue;
default:
return false;
}
}
return evaluateThresholdWithConvertedValue(
rawValue,
threshold.thresholdValue,
threshold.thresholdOperator,
threshold.thresholdUnit,
yAxisUnit,
);
function extractNumbersFromString(inputString: string): number[] {
const regex = /[+-]?\d+(\.\d+)?/g;
const matches = inputString.match(regex);
if (matches) {
return matches.map(Number);
}
return [];
}
function getHighestPrecedenceThreshold(
@@ -44,32 +60,21 @@ function getHighestPrecedenceThreshold(
return highestPrecedenceThreshold;
}
function extractNumbersFromString(inputString: string): number[] {
const regex = /[+-]?\d+(\.\d+)?/g;
const matches = inputString.match(regex);
if (matches) {
return matches.map(Number);
}
return [];
}
export function getBackgroundColorAndThresholdCheck(
thresholds: ThresholdProps[],
rawValue: number,
yAxisUnit?: string,
): {
threshold: ThresholdProps;
isConflictingThresholds: boolean;
} {
const matchingThresholds = thresholds.filter((threshold) => {
const numbers = extractNumbersFromString(rawValue.toString());
if (numbers.length === 0) {
return false;
}
return doesValueSatisfyThreshold(numbers[0], threshold, yAxisUnit);
});
const matchingThresholds = thresholds.filter((threshold) =>
compareThreshold(
extractNumbersFromString(
getYAxisFormattedValue(rawValue.toString(), threshold.thresholdUnit || ''),
)[0],
threshold,
),
);
if (matchingThresholds.length === 0) {
return {

View File

@@ -22,8 +22,6 @@ function YAxisUnitSelector({
'data-testid': dataTestId,
source,
initialValue,
categoriesOverride,
containerClassName,
}: YAxisUnitSelectorProps): JSX.Element {
const universalUnit = mapMetricUnitToUniversalUnit(value);
@@ -68,14 +66,10 @@ function YAxisUnitSelector({
return aliases.some((alias) => alias.toLowerCase().includes(search));
};
const categoriesToRender = useMemo(() => {
return categoriesOverride || getYAxisCategories(source);
}, [categoriesOverride, source]);
const categories = getYAxisCategories(source);
return (
<div
className={classNames('y-axis-unit-selector-component', containerClassName)}
>
<div className="y-axis-unit-selector-component">
<Select
showSearch
value={universalUnit}
@@ -96,7 +90,7 @@ function YAxisUnitSelector({
data-testid={dataTestId}
allowClear
>
{categoriesToRender.map((category) => (
{categories.map((category) => (
<Select.OptGroup key={category.name} label={category.name}>
{category.units.map((unit) => (
<Select.Option key={unit.id} value={unit.id}>

View File

@@ -1,7 +1,6 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { YAxisCategoryNames } from '../constants';
import { UniversalYAxisUnit, YAxisSource } from '../types';
import { YAxisSource } from '../types';
import YAxisUnitSelector from '../YAxisUnitSelector';
describe('YAxisUnitSelector', () => {
@@ -124,34 +123,4 @@ describe('YAxisUnitSelector', () => {
const warningIcon = screen.queryByLabelText('warning');
expect(warningIcon).not.toBeInTheDocument();
});
it('uses categories override to render custom units', () => {
const customCategories = [
{
name: YAxisCategoryNames.Data,
units: [
{
id: UniversalYAxisUnit.BYTES,
name: 'Custom Bytes (B)',
},
],
},
];
render(
<YAxisUnitSelector
value=""
onChange={mockOnChange}
source={YAxisSource.ALERTS}
categoriesOverride={customCategories}
/>,
);
const select = screen.getByRole('combobox');
fireEvent.mouseDown(select);
expect(screen.getByText('Custom Bytes (B)')).toBeInTheDocument();
expect(screen.queryByText('Bytes (B)')).not.toBeInTheDocument();
});
});

View File

@@ -1,5 +1,4 @@
import { YAxisCategoryNames } from '../constants';
import { UniversalYAxisUnit, YAxisCategory } from '../types';
import { UniversalYAxisUnit } from '../types';
import {
getUniversalNameFromMetricUnit,
mapMetricUnitToUniversalUnit,
@@ -42,29 +41,29 @@ describe('YAxisUnitSelector utils', () => {
describe('mergeCategories', () => {
it('merges categories correctly', () => {
const categories1: YAxisCategory[] = [
const categories1 = [
{
name: YAxisCategoryNames.Data,
name: 'Data',
units: [
{ name: 'bytes', id: UniversalYAxisUnit.BYTES },
{ name: 'kilobytes', id: UniversalYAxisUnit.KILOBYTES },
],
},
];
const categories2: YAxisCategory[] = [
const categories2 = [
{
name: YAxisCategoryNames.Data,
name: 'Data',
units: [{ name: 'bits', id: UniversalYAxisUnit.BITS }],
},
{
name: YAxisCategoryNames.Time,
name: 'Time',
units: [{ name: 'seconds', id: UniversalYAxisUnit.SECONDS }],
},
];
const mergedCategories = mergeCategories(categories1, categories2);
expect(mergedCategories).toEqual([
{
name: YAxisCategoryNames.Data,
name: 'Data',
units: [
{ name: 'bytes', id: UniversalYAxisUnit.BYTES },
{ name: 'kilobytes', id: UniversalYAxisUnit.KILOBYTES },
@@ -72,7 +71,7 @@ describe('YAxisUnitSelector utils', () => {
],
},
{
name: YAxisCategoryNames.Time,
name: 'Time',
units: [{ name: 'seconds', id: UniversalYAxisUnit.SECONDS }],
},
]);

View File

@@ -1,36 +1,5 @@
import { UnitFamilyConfig, UniversalYAxisUnit, YAxisUnit } from './types';
export enum YAxisCategoryNames {
Time = 'Time',
Data = 'Data',
DataRate = 'Data Rate',
Count = 'Count',
Operations = 'Operations',
Percentage = 'Percentage',
Boolean = 'Boolean',
None = 'None',
HashRate = 'Hash Rate',
Miscellaneous = 'Miscellaneous',
Acceleration = 'Acceleration',
Angular = 'Angular',
Area = 'Area',
Flops = 'FLOPs',
Concentration = 'Concentration',
Currency = 'Currency',
Datetime = 'Datetime',
PowerElectrical = 'Power/Electrical',
Flow = 'Flow',
Force = 'Force',
Mass = 'Mass',
Length = 'Length',
Pressure = 'Pressure',
Radiation = 'Radiation',
RotationSpeed = 'Rotation Speed',
Temperature = 'Temperature',
Velocity = 'Velocity',
Volume = 'Volume',
}
// Mapping of universal y-axis units to their AWS, UCUM, and OpenMetrics equivalents (if available)
export const UniversalYAxisUnitMappings: Partial<
Record<UniversalYAxisUnit, Set<YAxisUnit> | null>

View File

@@ -1,11 +1,10 @@
import { Y_AXIS_UNIT_NAMES } from './constants';
import { YAxisCategoryNames } from './constants';
import { UniversalYAxisUnit, YAxisCategory } from './types';
// Base categories for the universal y-axis units
export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
{
name: YAxisCategoryNames.Time,
name: 'Time',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.SECONDS],
@@ -38,7 +37,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Data,
name: 'Data',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.BYTES],
@@ -155,7 +154,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.DataRate,
name: 'Data Rate',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.BYTES_SECOND],
@@ -296,7 +295,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Count,
name: 'Count',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.COUNT],
@@ -313,7 +312,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Operations,
name: 'Operations',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.OPS_SECOND],
@@ -354,7 +353,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Percentage,
name: 'Percentage',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.PERCENT],
@@ -367,7 +366,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Boolean,
name: 'Boolean',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.TRUE_FALSE],
@@ -383,7 +382,7 @@ export const BASE_Y_AXIS_CATEGORIES: YAxisCategory[] = [
export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
{
name: YAxisCategoryNames.Time,
name: 'Time',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.DURATION_MS],
@@ -420,7 +419,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.DataRate,
name: 'Data Rate',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.DATA_RATE_PACKETS_PER_SECOND],
@@ -429,7 +428,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Boolean,
name: 'Boolean',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.ON_OFF],
@@ -438,7 +437,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.None,
name: 'None',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.NONE],
@@ -447,7 +446,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.HashRate,
name: 'Hash Rate',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.HASH_RATE_HASHES_PER_SECOND],
@@ -480,7 +479,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Miscellaneous,
name: 'Miscellaneous',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.MISC_STRING],
@@ -521,7 +520,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Acceleration,
name: 'Acceleration',
units: [
{
name:
@@ -542,7 +541,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Angular,
name: 'Angular',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.ANGULAR_DEGREE],
@@ -567,7 +566,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Area,
name: 'Area',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.AREA_SQUARE_METERS],
@@ -584,7 +583,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Flops,
name: 'FLOPs',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.FLOPS_FLOPS],
@@ -621,7 +620,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Concentration,
name: 'Concentration',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.CONCENTRATION_PPM],
@@ -678,7 +677,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Currency,
name: 'Currency',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.CURRENCY_USD],
@@ -775,7 +774,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Datetime,
name: 'Datetime',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.DATETIME_ISO],
@@ -812,7 +811,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.PowerElectrical,
name: 'Power/Electrical',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.POWER_WATT],
@@ -969,7 +968,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Flow,
name: 'Flow',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.FLOW_GALLONS_PER_MINUTE],
@@ -1006,7 +1005,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Force,
name: 'Force',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.FORCE_NEWTON_METERS],
@@ -1027,7 +1026,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Mass,
name: 'Mass',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.MASS_MILLIGRAM],
@@ -1052,7 +1051,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Length,
name: 'Length',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.LENGTH_MILLIMETER],
@@ -1081,7 +1080,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Pressure,
name: 'Pressure',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.PRESSURE_MILLIBAR],
@@ -1118,7 +1117,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Radiation,
name: 'Radiation',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.RADIATION_BECQUEREL],
@@ -1175,7 +1174,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.RotationSpeed,
name: 'Rotation Speed',
units: [
{
name:
@@ -1201,7 +1200,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Temperature,
name: 'Temperature',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.TEMPERATURE_CELSIUS],
@@ -1218,7 +1217,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Velocity,
name: 'Velocity',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.VELOCITY_METERS_PER_SECOND],
@@ -1239,7 +1238,7 @@ export const ADDITIONAL_Y_AXIS_CATEGORIES: YAxisCategory[] = [
],
},
{
name: YAxisCategoryNames.Volume,
name: 'Volume',
units: [
{
name: Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.VOLUME_MILLILITER],

View File

@@ -1,5 +1,3 @@
import { YAxisCategoryNames } from './constants';
export interface YAxisUnitSelectorProps {
value: string | undefined;
onChange: (value: UniversalYAxisUnit) => void;
@@ -9,8 +7,6 @@ export interface YAxisUnitSelectorProps {
'data-testid'?: string;
source: YAxisSource;
initialValue?: string;
categoriesOverride?: YAxisCategory[];
containerClassName?: string;
}
export enum UniversalYAxisUnit {
@@ -673,7 +669,7 @@ export interface UnitFamilyConfig {
}
export interface YAxisCategory {
name: YAxisCategoryNames;
name: string;
units: {
name: string;
id: UniversalYAxisUnit;

View File

@@ -117,7 +117,7 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
const [showSlowApiWarning, setShowSlowApiWarning] = useState(false);
const [slowApiWarningShown, setSlowApiWarningShown] = useState(false);
const { currentVersion } = useSelector<AppState, AppReducer>(
const { latestVersion } = useSelector<AppState, AppReducer>(
(state) => state.app,
);
@@ -213,9 +213,9 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
},
{
queryFn: (): Promise<SuccessResponse<ChangelogSchema> | ErrorResponse> =>
getChangelogByVersion(currentVersion, changelogForTenant),
queryKey: ['getChangelogByVersion', currentVersion, changelogForTenant],
enabled: isLoggedIn && Boolean(currentVersion),
getChangelogByVersion(latestVersion, changelogForTenant),
queryKey: ['getChangelogByVersion', latestVersion, changelogForTenant],
enabled: isLoggedIn && Boolean(latestVersion),
},
]);
@@ -226,7 +226,7 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
!changelog &&
!getChangelogByVersionResponse.isLoading &&
isLoggedIn &&
Boolean(currentVersion)
Boolean(latestVersion)
) {
getChangelogByVersionResponse.refetch();
}
@@ -237,9 +237,9 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
let timer: ReturnType<typeof setTimeout>;
if (
isCloudUserVal &&
Boolean(currentVersion) &&
Boolean(latestVersion) &&
seenChangelogVersion != null &&
currentVersion !== seenChangelogVersion &&
latestVersion !== seenChangelogVersion &&
daysSinceAccountCreation > MIN_ACCOUNT_AGE_FOR_CHANGELOG && // Show to only users older than 2 weeks
!isWorkspaceAccessRestricted
) {
@@ -255,7 +255,7 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
isCloudUserVal,
currentVersion,
latestVersion,
seenChangelogVersion,
toggleChangelogModal,
isWorkspaceAccessRestricted,

View File

@@ -81,14 +81,14 @@ export default function CustomDomainSettings(): JSX.Element {
}, [hosts]);
useEffect(() => {
if (isFetchingHosts || !hostsData) {
if (isFetchingHosts) {
return;
}
if (hostsData.status === 'success') {
setHosts(hostsData.data.hosts ?? null);
if (hostsData?.data?.status === 'success') {
setHosts(hostsData?.data?.data?.hosts ?? null);
const activeCustomDomain = hostsData.data.hosts?.find(
const activeCustomDomain = hostsData?.data?.data?.hosts?.find(
(host) => !host.is_default,
);
@@ -99,13 +99,13 @@ export default function CustomDomainSettings(): JSX.Element {
}
}
if (hostsData.data.state !== 'HEALTHY' && isPollingEnabled) {
if (hostsData?.data?.data?.state !== 'HEALTHY' && isPollingEnabled) {
setTimeout(() => {
refetchHosts();
}, 3000);
}
if (hostsData.data.state === 'HEALTHY') {
if (hostsData?.data?.data?.state === 'HEALTHY') {
setIsPollingEnabled(false);
}
}, [hostsData, refetchHosts, isPollingEnabled, isFetchingHosts]);

View File

@@ -9,7 +9,6 @@ import {
import useVariablesFromUrl from 'hooks/dashboard/useVariablesFromUrl';
import { useDashboard } from 'providers/Dashboard/Dashboard';
import { initializeDefaultVariables } from 'providers/Dashboard/initializeDefaultVariables';
import { updateDashboardVariablesStore } from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStore';
import {
enqueueDescendantsOfVariable,
enqueueFetchOfAllVariables,
@@ -32,9 +31,6 @@ function DashboardVariableSelection(): JSX.Element | null {
const { updateUrlVariable, getUrlVariables } = useVariablesFromUrl();
const { dashboardVariables } = useDashboardVariables();
const dashboardId = useDashboardVariablesSelector(
(state) => state.dashboardId,
);
const sortedVariablesArray = useDashboardVariablesSelector(
(state) => state.sortedVariablesArray,
);
@@ -100,28 +96,6 @@ function DashboardVariableSelection(): JSX.Element | null {
updateUrlVariable(name || id, value);
}
// Synchronously update the external store with the new variable value so that
// child variables see the updated parent value when they refetch, rather than
// waiting for setSelectedDashboard → useEffect → updateDashboardVariablesStore.
const updatedVariables = { ...dashboardVariables };
if (updatedVariables[id]) {
updatedVariables[id] = {
...updatedVariables[id],
selectedValue: value,
allSelected,
haveCustomValuesSelected,
};
}
if (updatedVariables[name]) {
updatedVariables[name] = {
...updatedVariables[name],
selectedValue: value,
allSelected,
haveCustomValuesSelected,
};
}
updateDashboardVariablesStore({ dashboardId, variables: updatedVariables });
setSelectedDashboard((prev) => {
if (prev) {
const oldVariables = { ...prev?.data.variables };
@@ -156,12 +130,10 @@ function DashboardVariableSelection(): JSX.Element | null {
return prev;
});
// Cascade: enqueue query-type descendants for refetching.
// Safe to call synchronously now that the store already has the updated value.
// Cascade: enqueue query-type descendants for refetching
enqueueDescendantsOfVariable(name);
},
[
dashboardId,
dashboardVariables,
updateLocalStorageDashboardVariables,
updateUrlVariable,

View File

@@ -5,7 +5,7 @@ import dashboardVariablesQuery from 'api/dashboard/variables/dashboardVariablesQ
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useVariableFetchState } from 'hooks/dashboard/useVariableFetchState';
import sortValues from 'lib/dashboardVariables/sortVariableValues';
import { isArray, isEmpty } from 'lodash-es';
import { isArray, isEmpty, isString } from 'lodash-es';
import { AppState } from 'store/reducers';
import { VariableResponseProps } from 'types/api/dashboard/variables/query';
import { GlobalReducer } from 'types/reducer/globalTime';
@@ -54,7 +54,7 @@ function QueryVariableInput({
onChange,
onDropdownVisibleChange,
handleClear,
getDefaultValue,
applyDefaultIfNeeded,
} = useDashboardVariableSelectHelper({
variableData,
optionsData,
@@ -68,93 +68,81 @@ function QueryVariableInput({
try {
setErrorMessage(null);
// This is just a check given the previously undefined typed name prop. Not significant
// This will be changed when we change the schema
// TODO: @AshwinBhatkal Perses
if (!variableData.name) {
return;
}
// if the response is not an array, premature return
if (
!variablesRes?.variableValues ||
!Array.isArray(variablesRes?.variableValues)
variablesRes?.variableValues &&
Array.isArray(variablesRes?.variableValues)
) {
return;
}
const sortedNewOptions = sortValues(
variablesRes.variableValues,
variableData.sort,
);
const sortedOldOptions = sortValues(optionsData, variableData.sort);
// if options are the same as before, no need to update state or check for selected value validity
// ! selectedValue needs to be set in the first pass though, as options are initially empty array and we need to apply default if needed
// Expecatation is that when oldOptions are not empty, then there is always some selectedValue
if (areArraysEqual(sortedNewOptions, sortedOldOptions)) {
return;
}
setOptionsData(sortedNewOptions);
let isSelectedValueMissingInNewOptions = false;
// Check if currently selected value(s) are present in the new options list
if (isArray(variableData.selectedValue)) {
isSelectedValueMissingInNewOptions = variableData.selectedValue.some(
(val) => !sortedNewOptions.includes(val),
const newOptionsData = sortValues(
variablesRes?.variableValues,
variableData.sort,
);
} else if (
variableData.selectedValue &&
!sortedNewOptions.includes(variableData.selectedValue)
) {
isSelectedValueMissingInNewOptions = true;
}
// If multi-select with ALL option enabled, and ALL is currently selected, we want to maintain that state and select all new options
// This block does not depend on selected value because of ALL and also because we would only come here if options are different from the previous
if (
variableData.multiSelect &&
variableData.showALLOption &&
variableData.allSelected &&
isSelectedValueMissingInNewOptions
) {
onValueUpdate(variableData.name, variableData.id, sortedNewOptions, true);
const oldOptionsData = sortValues(optionsData, variableData.sort) as never;
// Update tempSelection to maintain ALL state when dropdown is open
if (tempSelection !== undefined) {
setTempSelection(sortedNewOptions.map((option) => option.toString()));
}
return;
}
if (!areArraysEqual(newOptionsData, oldOptionsData)) {
let valueNotInList = false;
const value = variableData.selectedValue;
let allSelected = false;
if (isArray(variableData.selectedValue)) {
variableData.selectedValue.forEach((val) => {
if (!newOptionsData.includes(val)) {
valueNotInList = true;
}
});
} else if (
isString(variableData.selectedValue) &&
!newOptionsData.includes(variableData.selectedValue)
) {
valueNotInList = true;
}
if (variableData.multiSelect) {
const { selectedValue } = variableData;
allSelected =
sortedNewOptions.length > 0 &&
Array.isArray(selectedValue) &&
sortedNewOptions.every((option) => selectedValue.includes(option));
}
if (variableData.name && (valueNotInList || variableData.allSelected)) {
if (
variableData.allSelected &&
variableData.multiSelect &&
variableData.showALLOption
) {
if (
variableData.name &&
variableData.id &&
!isEmpty(variableData.selectedValue)
) {
onValueUpdate(
variableData.name,
variableData.id,
newOptionsData,
true,
);
}
if (
variableData.name &&
variableData.id &&
!isEmpty(variableData.selectedValue)
) {
onValueUpdate(variableData.name, variableData.id, value, allSelected);
} else {
const defaultValue = getDefaultValue(sortedNewOptions);
if (defaultValue !== undefined) {
onValueUpdate(
variableData.name,
variableData.id,
defaultValue,
allSelected,
);
// Update tempSelection to maintain ALL state when dropdown is open
if (tempSelection !== undefined) {
setTempSelection(newOptionsData.map((option) => option.toString()));
}
} else {
const value = variableData.selectedValue;
let allSelected = false;
if (variableData.multiSelect) {
const { selectedValue } = variableData;
allSelected =
newOptionsData.length > 0 &&
Array.isArray(selectedValue) &&
newOptionsData.every((option) => selectedValue.includes(option));
}
if (
variableData.name &&
variableData.id &&
!isEmpty(variableData.selectedValue)
) {
onValueUpdate(variableData.name, variableData.id, value, allSelected);
}
}
}
setOptionsData(newOptionsData);
// Apply default if no value is selected (e.g., new variable, first load)
applyDefaultIfNeeded(newOptionsData);
}
}
} catch (e) {
@@ -167,7 +155,7 @@ function QueryVariableInput({
onValueUpdate,
tempSelection,
setTempSelection,
getDefaultValue,
applyDefaultIfNeeded,
],
);

View File

@@ -1,6 +1,5 @@
/* eslint-disable sonarjs/no-duplicate-string */
import { act, render } from '@testing-library/react';
import * as dashboardVariablesStoreModule from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStore';
import {
dashboardVariablesStore,
setDashboardVariablesStore,
@@ -11,7 +10,6 @@ import {
IDashboardVariablesStoreState,
} from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreTypes';
import {
enqueueDescendantsOfVariable,
enqueueFetchOfAllVariables,
initializeVariableFetchStore,
} from 'providers/Dashboard/store/variableFetchStore';
@@ -19,17 +17,6 @@ import { IDashboardVariable } from 'types/api/dashboard/getAll';
import DashboardVariableSelection from '../DashboardVariableSelection';
// Mutable container to capture the onValueUpdate callback from VariableItem
const mockVariableItemCallbacks: {
onValueUpdate?: (
name: string,
id: string,
value: IDashboardVariable['selectedValue'],
allSelected: boolean,
haveCustomValuesSelected?: boolean,
) => void;
} = {};
// Mock providers/Dashboard/Dashboard
const mockSetSelectedDashboard = jest.fn();
const mockUpdateLocalStorageDashboardVariables = jest.fn();
@@ -69,14 +56,10 @@ jest.mock('react-redux', () => ({
useSelector: jest.fn().mockReturnValue({ minTime: 1000, maxTime: 2000 }),
}));
// VariableItem mock captures the onValueUpdate prop for use in onValueUpdate tests
// Mock VariableItem to avoid rendering complexity
jest.mock('../VariableItem', () => ({
__esModule: true,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
default: (props: any): JSX.Element => {
mockVariableItemCallbacks.onValueUpdate = props.onValueUpdate;
return <div data-testid="variable-item" />;
},
default: (): JSX.Element => <div data-testid="variable-item" />,
}));
function createVariable(
@@ -217,162 +200,4 @@ describe('DashboardVariableSelection', () => {
expect(initializeVariableFetchStore).not.toHaveBeenCalled();
expect(enqueueFetchOfAllVariables).not.toHaveBeenCalled();
});
describe('onValueUpdate', () => {
let updateStoreSpy: jest.SpyInstance;
beforeEach(() => {
resetStore();
jest.clearAllMocks();
// Real implementation pass-through — we just want to observe calls
updateStoreSpy = jest.spyOn(
dashboardVariablesStoreModule,
'updateDashboardVariablesStore',
);
});
afterEach(() => {
updateStoreSpy.mockRestore();
});
it('updates dashboardVariablesStore synchronously before enqueueDescendantsOfVariable', () => {
setDashboardVariablesStore({
dashboardId: 'dash-1',
variables: {
env: createVariable({ name: 'env', id: 'env-id', order: 0 }),
},
});
render(<DashboardVariableSelection />);
const callOrder: string[] = [];
updateStoreSpy.mockImplementation(() => {
callOrder.push('updateDashboardVariablesStore');
});
(enqueueDescendantsOfVariable as jest.Mock).mockImplementation(() => {
callOrder.push('enqueueDescendantsOfVariable');
});
act(() => {
mockVariableItemCallbacks.onValueUpdate?.(
'env',
'env-id',
'production',
false,
);
});
expect(callOrder).toEqual([
'updateDashboardVariablesStore',
'enqueueDescendantsOfVariable',
]);
});
it('passes updated variable value to dashboardVariablesStore', () => {
setDashboardVariablesStore({
dashboardId: 'dash-1',
variables: {
env: createVariable({
name: 'env',
id: 'env-id',
order: 0,
selectedValue: 'staging',
}),
},
});
render(<DashboardVariableSelection />);
// Clear spy calls that happened during setup/render
updateStoreSpy.mockClear();
act(() => {
mockVariableItemCallbacks.onValueUpdate?.(
'env',
'env-id',
'production',
false,
);
});
expect(updateStoreSpy).toHaveBeenCalledWith(
expect.objectContaining({
dashboardId: 'dash-1',
variables: expect.objectContaining({
env: expect.objectContaining({
selectedValue: 'production',
allSelected: false,
}),
}),
}),
);
});
it('calls enqueueDescendantsOfVariable synchronously without a timer', () => {
jest.useFakeTimers();
setDashboardVariablesStore({
dashboardId: 'dash-1',
variables: {
env: createVariable({ name: 'env', id: 'env-id', order: 0 }),
},
});
render(<DashboardVariableSelection />);
act(() => {
mockVariableItemCallbacks.onValueUpdate?.(
'env',
'env-id',
'production',
false,
);
});
// Must be called immediately — no timer advancement needed
expect(enqueueDescendantsOfVariable).toHaveBeenCalledWith('env');
jest.useRealTimers();
});
it('propagates allSelected and haveCustomValuesSelected to the store', () => {
setDashboardVariablesStore({
dashboardId: 'dash-1',
variables: {
env: createVariable({
name: 'env',
id: 'env-id',
order: 0,
multiSelect: true,
showALLOption: true,
}),
},
});
render(<DashboardVariableSelection />);
updateStoreSpy.mockClear();
act(() => {
mockVariableItemCallbacks.onValueUpdate?.(
'env',
'env-id',
['production', 'staging'],
true,
false,
);
});
expect(updateStoreSpy).toHaveBeenCalledWith(
expect.objectContaining({
variables: expect.objectContaining({
env: expect.objectContaining({
selectedValue: ['production', 'staging'],
allSelected: true,
haveCustomValuesSelected: false,
}),
}),
}),
);
});
});
});

View File

@@ -1,275 +0,0 @@
/* eslint-disable sonarjs/no-duplicate-string */
import { QueryClient, QueryClientProvider } from 'react-query';
import { act, render, waitFor } from '@testing-library/react';
import dashboardVariablesQuery from 'api/dashboard/variables/dashboardVariablesQuery';
import { variableFetchStore } from 'providers/Dashboard/store/variableFetchStore';
import { IDashboardVariable } from 'types/api/dashboard/getAll';
import QueryVariableInput from '../QueryVariableInput';
jest.mock('api/dashboard/variables/dashboardVariablesQuery');
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: jest.fn().mockReturnValue({ minTime: 1000, maxTime: 2000 }),
}));
function createTestQueryClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: { retry: false, refetchOnWindowFocus: false },
},
});
}
function Wrapper({
children,
queryClient,
}: {
children: React.ReactNode;
queryClient: QueryClient;
}): JSX.Element {
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
}
function createVariable(
overrides: Partial<IDashboardVariable> = {},
): IDashboardVariable {
return {
id: 'env-id',
name: 'env',
description: '',
type: 'QUERY',
sort: 'DISABLED',
showALLOption: false,
multiSelect: false,
order: 0,
queryValue: 'SELECT env FROM table',
...overrides,
};
}
/** Put the named variable into 'loading' state so useQuery fires on mount */
function setVariableLoading(name: string): void {
variableFetchStore.update((draft) => {
draft.states[name] = 'loading';
draft.cycleIds[name] = (draft.cycleIds[name] || 0) + 1;
});
}
function resetFetchStore(): void {
variableFetchStore.set(() => ({
states: {},
lastUpdated: {},
cycleIds: {},
}));
}
describe('QueryVariableInput - getOptions logic', () => {
const mockOnValueUpdate = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
resetFetchStore();
});
afterEach(() => {
resetFetchStore();
});
it('applies default value (first option) when selectedValue is empty on first load', async () => {
(dashboardVariablesQuery as jest.Mock).mockResolvedValue({
statusCode: 200,
payload: { variableValues: ['production', 'staging', 'dev'] },
});
const variable = createVariable({ selectedValue: undefined });
setVariableLoading('env');
const queryClient = createTestQueryClient();
render(
<Wrapper queryClient={queryClient}>
<QueryVariableInput
variableData={variable}
existingVariables={{ 'env-id': variable }}
onValueUpdate={mockOnValueUpdate}
/>
</Wrapper>,
);
await waitFor(() => {
expect(mockOnValueUpdate).toHaveBeenCalledWith(
'env',
'env-id',
'production', // first option by default
false,
);
});
});
it('keeps existing selectedValue when it is present in new options', async () => {
(dashboardVariablesQuery as jest.Mock).mockResolvedValue({
statusCode: 200,
payload: { variableValues: ['production', 'staging'] },
});
const variable = createVariable({ selectedValue: 'staging' });
setVariableLoading('env');
const queryClient = createTestQueryClient();
render(
<Wrapper queryClient={queryClient}>
<QueryVariableInput
variableData={variable}
existingVariables={{ 'env-id': variable }}
onValueUpdate={mockOnValueUpdate}
/>
</Wrapper>,
);
await waitFor(() => {
expect(mockOnValueUpdate).toHaveBeenCalledWith(
'env',
'env-id',
'staging',
false,
);
});
});
it('selects all new options when allSelected=true and value is missing from new options', async () => {
(dashboardVariablesQuery as jest.Mock).mockResolvedValue({
statusCode: 200,
payload: { variableValues: ['production', 'staging'] },
});
const variable = createVariable({
selectedValue: ['old-env'],
allSelected: true,
multiSelect: true,
showALLOption: true,
});
setVariableLoading('env');
const queryClient = createTestQueryClient();
render(
<Wrapper queryClient={queryClient}>
<QueryVariableInput
variableData={variable}
existingVariables={{ 'env-id': variable }}
onValueUpdate={mockOnValueUpdate}
/>
</Wrapper>,
);
await waitFor(() => {
expect(mockOnValueUpdate).toHaveBeenCalledWith(
'env',
'env-id',
['production', 'staging'],
true,
);
});
});
it('does not call onValueUpdate a second time when options have not changed', async () => {
const mockQueryFn = jest.fn().mockResolvedValue({
statusCode: 200,
payload: { variableValues: ['production', 'staging'] },
});
(dashboardVariablesQuery as jest.Mock).mockImplementation(mockQueryFn);
const variable = createVariable({ selectedValue: 'production' });
setVariableLoading('env');
const queryClient = createTestQueryClient();
render(
<Wrapper queryClient={queryClient}>
<QueryVariableInput
variableData={variable}
existingVariables={{ 'env-id': variable }}
onValueUpdate={mockOnValueUpdate}
/>
</Wrapper>,
);
// Wait for first fetch and onValueUpdate call
await waitFor(() => {
expect(mockOnValueUpdate).toHaveBeenCalledTimes(1);
});
mockOnValueUpdate.mockClear();
// Trigger a second fetch cycle with the same API response
act(() => {
variableFetchStore.update((draft) => {
draft.states['env'] = 'revalidating';
draft.cycleIds['env'] = (draft.cycleIds['env'] || 0) + 1;
});
});
// Wait for second query to fire
await waitFor(() => {
expect(mockQueryFn).toHaveBeenCalledTimes(2);
});
// Options are unchanged, so onValueUpdate must not fire again
expect(mockOnValueUpdate).not.toHaveBeenCalled();
});
it('does not call onValueUpdate when API returns a non-array response', async () => {
(dashboardVariablesQuery as jest.Mock).mockResolvedValue({
statusCode: 200,
payload: { variableValues: null },
});
const variable = createVariable({ selectedValue: 'production' });
setVariableLoading('env');
const queryClient = createTestQueryClient();
render(
<Wrapper queryClient={queryClient}>
<QueryVariableInput
variableData={variable}
existingVariables={{ 'env-id': variable }}
onValueUpdate={mockOnValueUpdate}
/>
</Wrapper>,
);
await waitFor(() => {
expect(dashboardVariablesQuery).toHaveBeenCalled();
});
expect(mockOnValueUpdate).not.toHaveBeenCalled();
});
it('does not fire the query when variableData.name is empty', () => {
(dashboardVariablesQuery as jest.Mock).mockResolvedValue({
statusCode: 200,
payload: { variableValues: ['production'] },
});
// Variable with no name — useVariableFetchState will be called with ''
// and the query key will have an empty name, leaving it disabled
const variable = createVariable({ name: '' });
// Note: we do NOT put it in 'loading' state since name is empty
// (no variableFetchStore entry for '' means isVariableFetching=false)
const queryClient = createTestQueryClient();
render(
<Wrapper queryClient={queryClient}>
<QueryVariableInput
variableData={variable}
existingVariables={{ 'env-id': variable }}
onValueUpdate={mockOnValueUpdate}
/>
</Wrapper>,
);
expect(dashboardVariablesQuery).not.toHaveBeenCalled();
expect(mockOnValueUpdate).not.toHaveBeenCalled();
});
});

View File

@@ -46,9 +46,6 @@ interface UseDashboardVariableSelectHelperReturn {
applyDefaultIfNeeded: (
overrideOptions?: (string | number | boolean)[],
) => void;
getDefaultValue: (
overrideOptions?: (string | number | boolean)[],
) => string | string[] | undefined;
}
// eslint-disable-next-line sonarjs/cognitive-complexity
@@ -251,6 +248,5 @@ export function useDashboardVariableSelectHelper({
defaultValue,
onChange,
applyDefaultIfNeeded,
getDefaultValue,
};
}

View File

@@ -172,51 +172,23 @@ function ExplorerOptions({
const { user } = useAppContext();
const handleConditionalQueryModification = useCallback(
// eslint-disable-next-line sonarjs/cognitive-complexity
(defaultQuery: Query | null): string => {
const queryToUse = defaultQuery || query;
if (!queryToUse) {
throw new Error('No query provided');
}
if (
queryToUse?.builder?.queryData?.[0]?.aggregateOperator !==
StringOperators.NOOP &&
sourcepage !== DataSource.LOGS
StringOperators.NOOP
) {
return JSON.stringify(queryToUse);
}
// Convert NOOP to COUNT for alerts and strip orderBy for logs
// Modify aggregateOperator to count, as noop is not supported in alerts
const modifiedQuery = cloneDeep(queryToUse);
if (modifiedQuery && modifiedQuery.builder?.queryData) {
modifiedQuery.builder.queryData = modifiedQuery.builder.queryData.map(
(item) => {
const updatedItem = { ...item };
if (updatedItem.aggregateOperator === StringOperators.NOOP) {
updatedItem.aggregateOperator = StringOperators.COUNT;
}
modifiedQuery.builder.queryData[0].aggregateOperator = StringOperators.COUNT;
// Alerts do not support order by on logs explorer queries
if (sourcepage === DataSource.LOGS && panelType === PANEL_TYPES.LIST) {
updatedItem.orderBy = [];
}
return updatedItem;
},
);
}
try {
return JSON.stringify(modifiedQuery);
} catch (err) {
throw new Error(
'Failed to stringify modified query: ' +
(err instanceof Error ? err.message : String(err)),
);
}
return JSON.stringify(modifiedQuery);
},
[panelType, query, sourcepage],
[query],
);
const onCreateAlertsHandler = useCallback(
@@ -785,9 +757,9 @@ function ExplorerOptions({
);
}, [
disabled,
query,
isOneChartPerQuery,
onCreateAlertsHandler,
query,
splitedQueries,
]);

View File

@@ -1,4 +1,3 @@
import { useHistory } from 'react-router-dom';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { MOCK_QUERY } from 'container/QueryTable/Drilldown/__tests__/mockTableData';
import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
@@ -16,11 +15,6 @@ import { getExplorerToolBarVisibility } from '../utils';
// Mock dependencies
jest.mock('hooks/dashboard/useUpdateDashboard');
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: jest.fn(),
}));
jest.mock('../utils', () => ({
getExplorerToolBarVisibility: jest.fn(),
generateRGBAFromHex: jest.fn(() => 'rgba(0, 0, 0, 0.08)'),
@@ -35,7 +29,6 @@ const mockGetExplorerToolBarVisibility = jest.mocked(
);
const mockUseUpdateDashboard = jest.mocked(useUpdateDashboard);
const mockUseHistory = jest.mocked(useHistory);
// Mock data
const TEST_QUERY_ID = 'test-query-id';
@@ -110,6 +103,7 @@ describe('ExplorerOptionWrapper', () => {
beforeEach(() => {
jest.clearAllMocks();
mockGetExplorerToolBarVisibility.mockReturnValue(true);
// Mock useUpdateDashboard to return a mutation object
mockUseUpdateDashboard.mockReturnValue(({
mutate: jest.fn(),
@@ -123,28 +117,6 @@ describe('ExplorerOptionWrapper', () => {
} as unknown) as ReturnType<typeof useUpdateDashboard>);
});
it('should navigate to alert creation page when "Create an Alert" is clicked in logs-explorer', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockPush = jest.fn();
mockUseHistory.mockReturnValue(({
push: mockPush,
} as unknown) as ReturnType<typeof useHistory>);
renderExplorerOptionWrapper({ sourcepage: DataSource.LOGS });
const createAlertButton = screen.getByRole('button', {
name: 'Create an Alert',
});
await user.click(createAlertButton);
expect(mockPush).toHaveBeenCalledTimes(1);
const calledWith = mockPush.mock.calls[0][0] as string;
const [path, search = ''] = calledWith.split('?');
expect(path).toBe('/alerts/new');
const params = new URLSearchParams(search);
expect(params.has('compositeQuery')).toBe(true);
});
describe('onExport functionality', () => {
it('should call onExport when New Dashboard button is clicked in export modal', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });

View File

@@ -3,11 +3,13 @@ import { Button } from '@signozhq/button';
import { ArrowLeft, ArrowRight } from '@signozhq/icons';
import { Input } from '@signozhq/input';
import { Form, Select } from 'antd';
import { ErrorResponseHandlerForGeneratedAPIs } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
import { useForgotPassword } from 'api/generated/services/users';
import { AxiosError } from 'axios';
import AuthError from 'components/AuthError/AuthError';
import ROUTES from 'constants/routes';
import history from 'lib/history';
import { ErrorV2Resp } from 'types/api';
import APIError from 'types/api/error';
import { OrgSessionContext } from 'types/api/v2/sessions/context/get';
@@ -46,7 +48,7 @@ function ForgotPassword({
}
try {
ErrorResponseHandlerForGeneratedAPIs(mutationError);
ErrorResponseHandlerV2(mutationError as AxiosError<ErrorV2Resp>);
} catch (apiError) {
return apiError as APIError;
}

View File

@@ -49,7 +49,7 @@ function evaluateCondition(
* @param columnUnit - The current unit of the value.
* @returns A boolean indicating whether the value meets the threshold condition.
*/
export function evaluateThresholdWithConvertedValue(
function evaluateThresholdWithConvertedValue(
value: number,
thresholdValue: number,
thresholdOperator?: string,

View File

@@ -99,7 +99,6 @@ function GridValueComponent({
<ValueGraph
thresholds={thresholds || []}
rawValue={value}
yAxisUnit={yAxisUnit}
value={
yAxisUnit
? getYAxisFormattedValue(

View File

@@ -34,7 +34,7 @@ function DataSourceInfo({
useEffect(() => {
if (hostsData) {
const defaultHost = hostsData?.data.hosts?.find((h) => h.is_default);
const defaultHost = hostsData?.data?.data?.hosts?.find((h) => h.is_default);
if (defaultHost?.url) {
const url = defaultHost?.url?.split('://')[1] ?? '';
setUrl(url);

View File

@@ -335,14 +335,14 @@ function MultiIngestionSettings(): JSX.Element {
const isError = isSearching ? isSearchError : isGetError;
useEffect(() => {
setDataSource(ingestionKeys?.data.keys || []);
setTotalIngestionKeys(ingestionKeys?.data._pagination?.total || 0);
setDataSource(ingestionKeys?.data.data?.keys || []);
setTotalIngestionKeys(ingestionKeys?.data?.data?._pagination?.total || 0);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ingestionKeys?.data]);
}, [ingestionKeys?.data?.data]);
useEffect(() => {
if (isError && error) {
showErrorNotification(notifications, error);
if (isError) {
showErrorNotification(notifications, error as AxiosError);
}
}, [error, isError, notifications]);

View File

@@ -121,23 +121,9 @@ function BodyTitleRenderer({
return (
<TitleWrapper onClick={handleNodeClick}>
{typeof value !== 'object' && (
<span
onClick={(e): void => {
e.stopPropagation();
e.preventDefault();
}}
onMouseDown={(e): void => e.preventDefault()}
>
<Dropdown
menu={menu}
trigger={['click']}
dropdownRender={(originNode): React.ReactNode => (
<div data-log-detail-ignore="true">{originNode}</div>
)}
>
<SettingOutlined style={{ marginRight: 8 }} className="hover-reveal" />
</Dropdown>
</span>
<Dropdown menu={menu} trigger={['click']}>
<SettingOutlined style={{ marginRight: 8 }} className="hover-reveal" />
</Dropdown>
)}
{title.toString()}{' '}
{!parentIsArray && typeof value !== 'object' && (

View File

@@ -13,7 +13,7 @@ function FieldRenderer({ field }: FieldRendererProps): JSX.Element {
<span className="field-renderer-container">
{dataType && newField && logType ? (
<>
<Tooltip placement="left" title={newField} mouseLeaveDelay={0}>
<Tooltip placement="left" title={newField}>
<Typography.Text ellipsis className="label">
{newField}{' '}
</Typography.Text>

View File

@@ -46,7 +46,7 @@ function Overview({
handleChangeSelectedView,
}: Props): JSX.Element {
const [isWrapWord, setIsWrapWord] = useState<boolean>(true);
const [isSearchVisible, setIsSearchVisible] = useState<boolean>(true);
const [isSearchVisible, setIsSearchVisible] = useState<boolean>(false);
const [isAttributesExpanded, setIsAttributesExpanded] = useState<boolean>(
true,
);

View File

@@ -245,7 +245,7 @@ function TableView({
<Typography.Text>{renderedField}</Typography.Text>
{traceId && (
<Tooltip title="Inspect in Trace" mouseLeaveDelay={0}>
<Tooltip title="Inspect in Trace">
<Button
className="periscope-btn"
onClick={(

View File

@@ -1,34 +0,0 @@
import { Color } from '@signozhq/design-tokens';
import { getColorsForSeverityLabels, isRedLike } from '../utils';
describe('getColorsForSeverityLabels', () => {
it('should return slate for blank labels', () => {
expect(getColorsForSeverityLabels('', 0)).toBe(Color.BG_SLATE_300);
expect(getColorsForSeverityLabels(' ', 0)).toBe(Color.BG_SLATE_300);
});
it('should return correct colors for known severity variants', () => {
expect(getColorsForSeverityLabels('INFO', 0)).toBe(Color.BG_ROBIN_600);
expect(getColorsForSeverityLabels('ERROR', 0)).toBe(Color.BG_CHERRY_600);
expect(getColorsForSeverityLabels('WARN', 0)).toBe(Color.BG_AMBER_600);
expect(getColorsForSeverityLabels('DEBUG', 0)).toBe(Color.BG_AQUA_600);
expect(getColorsForSeverityLabels('TRACE', 0)).toBe(Color.BG_FOREST_600);
expect(getColorsForSeverityLabels('FATAL', 0)).toBe(Color.BG_SAKURA_600);
});
it('should return non-red colors for unrecognized labels at any index', () => {
for (let i = 0; i < 30; i++) {
const color = getColorsForSeverityLabels('4', i);
expect(isRedLike(color)).toBe(false);
}
});
it('should return non-red colors for numeric severity text', () => {
const numericLabels = ['1', '2', '4', '9', '13', '17', '21'];
numericLabels.forEach((label) => {
const color = getColorsForSeverityLabels(label, 0);
expect(isRedLike(color)).toBe(false);
});
});
});

View File

@@ -1,16 +1,7 @@
import { Color } from '@signozhq/design-tokens';
import { themeColors } from 'constants/theme';
import { colors } from 'lib/getRandomColor';
// Function to determine if a color is "red-like" based on its RGB values
export function isRedLike(hex: string): boolean {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return r > 180 && r > g * 1.4 && r > b * 1.4;
}
const SAFE_FALLBACK_COLORS = colors.filter((c) => !isRedLike(c));
const SEVERITY_VARIANT_COLORS: Record<string, string> = {
TRACE: Color.BG_FOREST_600,
Trace: Color.BG_FOREST_500,
@@ -76,13 +67,8 @@ export function getColorsForSeverityLabels(
label: string,
index: number,
): string {
const trimmed = label.trim();
if (!trimmed) {
return Color.BG_SLATE_300;
}
const variantColor = SEVERITY_VARIANT_COLORS[trimmed];
// Check if we have a direct mapping for this severity variant
const variantColor = SEVERITY_VARIANT_COLORS[label.trim()];
if (variantColor) {
return variantColor;
}
@@ -117,8 +103,5 @@ export function getColorsForSeverityLabels(
return Color.BG_SAKURA_500;
}
return (
SAFE_FALLBACK_COLORS[index % SAFE_FALLBACK_COLORS.length] ||
Color.BG_SLATE_400
);
return colors[index % colors.length] || themeColors.red;
}

View File

@@ -111,19 +111,23 @@ const InfinityTable = forwardRef<TableVirtuosoHandle, InfinityTableProps>(
);
const itemContent = useCallback(
(index: number, log: Record<string, unknown>): JSX.Element => (
<TableRow
tableColumns={tableColumns}
index={index}
log={log}
logs={tableViewProps.logs}
hasActions
fontSize={tableViewProps.fontSize}
onShowLogDetails={onSetActiveLog}
isActiveLog={activeLog?.id === log.id}
onClearActiveLog={onCloseActiveLog}
/>
),
(index: number, log: Record<string, unknown>): JSX.Element => {
return (
<div key={log.id as string}>
<TableRow
tableColumns={tableColumns}
index={index}
log={log}
logs={tableViewProps.logs}
hasActions
fontSize={tableViewProps.fontSize}
onShowLogDetails={onSetActiveLog}
isActiveLog={activeLog?.id === log.id}
onClearActiveLog={onCloseActiveLog}
/>
</div>
);
},
[
tableColumns,
onSetActiveLog,

View File

@@ -87,7 +87,7 @@ function Explorer(): JSX.Element {
const [yAxisUnit, setYAxisUnit] = useState<string | undefined>();
const unitsLength = useMemo(() => units.length, [units]);
const firstUnit = useMemo(() => units[0], [units]);
const firstUnit = useMemo(() => units?.[0], [units]);
useEffect(() => {
// Set the y axis unit to the first metric unit if
@@ -349,7 +349,7 @@ function Explorer(): JSX.Element {
isOneChartPerQuery={showOneChartPerQuery}
splitedQueries={splitedQueries}
/>
{isMetricDetailsOpen && selectedMetricName && (
{isMetricDetailsOpen && (
<MetricDetails
metricName={selectedMetricName}
isOpen={isMetricDetailsOpen}

View File

@@ -39,7 +39,10 @@ function RelatedMetricsCard({ metric }: RelatedMetricsCardProps): JSX.Element {
dataSource={DataSource.METRICS}
/>
)}
<DashboardsAndAlertsPopover metricName={metric.name} />
<DashboardsAndAlertsPopover
dashboards={metric.dashboards}
alerts={metric.alerts}
/>
</div>
);
}

View File

@@ -1,13 +1,8 @@
import { useMemo } from 'react';
import { useQueries, useQueryClient } from 'react-query';
import { useQueries } from 'react-query';
import { useSelector } from 'react-redux';
import { Color } from '@signozhq/design-tokens';
import { toast } from '@signozhq/sonner';
import { Button, Tooltip, Typography } from 'antd';
import {
invalidateGetMetricMetadata,
useUpdateMetricMetadata,
} from 'api/generated/services/metrics';
import { Tooltip, Typography } from 'antd';
import { isAxiosError } from 'axios';
import classNames from 'classnames';
import YAxisUnitSelector from 'components/YAxisUnitSelector';
@@ -28,10 +23,7 @@ import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
import { TimeSeriesProps } from './types';
import {
buildUpdateMetricYAxisUnitPayload,
splitQueryIntoOneChartPerQuery,
} from './utils';
import { splitQueryIntoOneChartPerQuery } from './utils';
function TimeSeries({
showOneChartPerQuery,
@@ -43,7 +35,6 @@ function TimeSeries({
yAxisUnit,
setYAxisUnit,
showYAxisUnitSelector,
metrics,
}: TimeSeriesProps): JSX.Element {
const { stagedQuery, currentQuery } = useQueryBuilder();
@@ -51,7 +42,6 @@ function TimeSeries({
AppState,
GlobalReducer
>((state) => state.globalTime);
const queryClient = useQueryClient();
const isValidToConvertToMs = useMemo(() => {
const isValid: boolean[] = [];
@@ -148,51 +138,54 @@ function TimeSeries({
setYAxisUnit(value);
};
// TODO: Enable once we have resolved all related metrics v2 api issues
// Show the save unit button if
// 1. There is only one metric
// 2. The metric has no saved unit
// 3. The user has selected a unit
const showSaveUnitButton = useMemo(
() =>
metricUnits.length === 1 &&
Boolean(metrics[0]) &&
!metricUnits[0] &&
yAxisUnit,
[metricUnits, metrics, yAxisUnit],
);
// const showSaveUnitButton = useMemo(
// () =>
// metricUnits.length === 1 &&
// Boolean(metrics?.[0]) &&
// !metricUnits[0] &&
// yAxisUnit,
// [metricUnits, metrics, yAxisUnit],
// );
const {
mutate: updateMetricMetadata,
isLoading: isUpdatingMetricMetadata,
} = useUpdateMetricMetadata();
// const {
// mutate: updateMetricMetadata,
// isLoading: isUpdatingMetricMetadata,
// } = useUpdateMetricMetadata();
const handleSaveUnit = (): void => {
if (metrics[0] && yAxisUnit) {
updateMetricMetadata(
{
pathParams: {
metricName: metricNames[0],
},
data: buildUpdateMetricYAxisUnitPayload(
metricNames[0],
metrics[0],
yAxisUnit,
),
},
{
onSuccess: () => {
toast.success('Unit saved successfully');
invalidateGetMetricMetadata(queryClient, {
metricName: metricNames[0],
});
},
onError: () => {
toast.error('Failed to save unit');
},
},
);
}
};
// const handleSaveUnit = (): void => {
// updateMetricMetadata(
// {
// metricName: metricNames[0],
// payload: {
// unit: yAxisUnit,
// description: metrics[0]?.description ?? '',
// metricType: metrics[0]?.type as MetricType,
// temporality: metrics[0]?.temporality,
// },
// },
// {
// onSuccess: () => {
// notifications.success({
// message: 'Unit saved successfully',
// });
// queryClient.invalidateQueries([
// REACT_QUERY_KEY.GET_METRIC_DETAILS,
// metricNames[0],
// ]);
// },
// onError: () => {
// notifications.error({
// message: 'Failed to save unit',
// });
// },
// },
// );
// };
return (
<>
@@ -205,7 +198,8 @@ function TimeSeries({
source={YAxisSource.EXPLORER}
data-testid="y-axis-unit-selector"
/>
{showSaveUnitButton && (
{/* TODO: Enable once we have resolved all related metrics v2 api issues */}
{/* {showSaveUnitButton && (
<div className="save-unit-container">
<Typography.Text>
Save the selected unit for this metric?
@@ -219,7 +213,7 @@ function TimeSeries({
<Typography.Paragraph>Yes</Typography.Paragraph>
</Button>
</div>
)}
)} */}
</>
)}
</div>

View File

@@ -3,10 +3,8 @@ import { Provider } from 'react-redux';
import { MemoryRouter } from 'react-router-dom';
import { useSearchParams } from 'react-router-dom-v5-compat';
import { render, screen } from '@testing-library/react';
import {
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import { Temporality } from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import * as useOptionsMenuHooks from 'container/OptionsMenu';
import * as useUpdateDashboardHooks from 'hooks/dashboard/useUpdateDashboard';
@@ -16,12 +14,12 @@ import { ErrorModalProvider } from 'providers/ErrorModalProvider';
import * as timezoneHooks from 'providers/Timezone';
import store from 'store';
import { LicenseEvent } from 'types/api/licensesV3/getActive';
import { MetricMetadata } from 'types/api/metricsExplorer/v2/getMetricMetadata';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { DataSource, QueryBuilderContextType } from 'types/common/queryBuilder';
import Explorer from '../Explorer';
import * as useGetMetricsHooks from '../utils';
import { MOCK_METRIC_METADATA } from './testUtils';
const mockSetSearchParams = jest.fn();
const queryClient = new QueryClient();
@@ -137,6 +135,14 @@ jest.spyOn(useQueryBuilderHooks, 'useQueryBuilder').mockReturnValue({
const Y_AXIS_UNIT_SELECTOR_TEST_ID = 'y-axis-unit-selector';
const mockMetric: MetricMetadata = {
type: MetricType.SUM,
description: 'metric1 description',
unit: 'metric1 unit',
temporality: Temporality.CUMULATIVE,
isMonotonic: true,
};
function renderExplorer(): void {
render(
<QueryClientProvider client={queryClient}>
@@ -184,7 +190,7 @@ describe('Explorer', () => {
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
metrics: [MOCK_METRIC_METADATA, MOCK_METRIC_METADATA],
metrics: [mockMetric, mockMetric],
});
renderExplorer();
@@ -201,7 +207,7 @@ describe('Explorer', () => {
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
metrics: [MOCK_METRIC_METADATA, MOCK_METRIC_METADATA],
metrics: [mockMetric, mockMetric],
});
renderExplorer();
@@ -214,7 +220,7 @@ describe('Explorer', () => {
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
metrics: [MOCK_METRIC_METADATA],
metrics: [mockMetric],
});
renderExplorer();
@@ -231,7 +237,7 @@ describe('Explorer', () => {
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
metrics: [MOCK_METRIC_METADATA, MOCK_METRIC_METADATA],
metrics: [mockMetric, mockMetric],
});
renderExplorer();
@@ -244,7 +250,7 @@ describe('Explorer', () => {
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
metrics: [MOCK_METRIC_METADATA, MOCK_METRIC_METADATA],
metrics: [mockMetric, mockMetric],
});
renderExplorer();
@@ -263,10 +269,10 @@ describe('Explorer', () => {
isError: false,
metrics: [
{
type: MetrictypesTypeDTO.sum,
type: MetricType.SUM,
description: 'metric1 description',
unit: '',
temporality: MetrictypesTemporalityDTO.cumulative,
temporality: Temporality.CUMULATIVE,
isMonotonic: true,
},
],
@@ -283,7 +289,7 @@ describe('Explorer', () => {
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
metrics: [MOCK_METRIC_METADATA],
metrics: [mockMetric],
});
renderExplorer();
@@ -318,7 +324,7 @@ describe('Explorer', () => {
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
metrics: [MOCK_METRIC_METADATA, MOCK_METRIC_METADATA],
metrics: [mockMetric, mockMetric],
});
renderExplorer();

View File

@@ -1,19 +1,29 @@
import { UseMutationResult } from 'react-query';
import { render, RenderResult, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import { Temporality } from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import { UpdateMetricMetadataResponse } from 'api/metricsExplorer/updateMetricMetadata';
import * as useUpdateMetricMetadataHooks from 'hooks/metricsExplorer/useUpdateMetricMetadata';
import { UseUpdateMetricMetadataProps } from 'hooks/metricsExplorer/useUpdateMetricMetadata';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { MetricMetadata } from 'types/api/metricsExplorer/v2/getMetricMetadata';
import TimeSeries from '../TimeSeries';
import { TimeSeriesProps } from '../types';
import { MOCK_METRIC_METADATA } from './testUtils';
const mockUpdateMetricMetadata = jest.fn();
const updateMetricMetadataSpy = jest.spyOn(
metricsExplorerHooks,
'useUpdateMetricMetadata',
);
type UseUpdateMetricMetadataReturnType = ReturnType<
typeof metricsExplorerHooks.useUpdateMetricMetadata
type MockUpdateMetricMetadata = UseMutationResult<
SuccessResponse<UpdateMetricMetadataResponse> | ErrorResponse,
Error,
UseUpdateMetricMetadataProps
>;
const mockUpdateMetricMetadata = jest.fn();
jest
.spyOn(useUpdateMetricMetadataHooks, 'useUpdateMetricMetadata')
.mockReturnValue(({
mutate: mockUpdateMetricMetadata,
isLoading: false,
} as Partial<MockUpdateMetricMetadata>) as MockUpdateMetricMetadata);
jest.mock('container/TimeSeriesView/TimeSeriesView', () => ({
__esModule: true,
@@ -50,6 +60,14 @@ jest.mock('react-redux', () => ({
}),
}));
const mockMetric: MetricMetadata = {
type: MetricType.SUM,
description: 'metric1 description',
unit: 'metric1 unit',
temporality: Temporality.CUMULATIVE,
isMonotonic: true,
};
const mockSetWarning = jest.fn();
const mockSetIsMetricDetailsOpen = jest.fn();
const mockSetYAxisUnit = jest.fn();
@@ -78,13 +96,6 @@ function renderTimeSeries(
}
describe('TimeSeries', () => {
beforeEach(() => {
updateMetricMetadataSpy.mockReturnValue(({
mutate: mockUpdateMetricMetadata,
isLoading: false,
} as Partial<UseUpdateMetricMetadataReturnType>) as UseUpdateMetricMetadataReturnType);
});
it('should render a warning icon when a metric has no unit among multiple metrics', () => {
const user = userEvent.setup();
const { container } = renderTimeSeries({
@@ -107,7 +118,7 @@ describe('TimeSeries', () => {
const { container } = renderTimeSeries({
metricUnits: ['', 'count'],
metricNames: ['metric1', 'metric2'],
metrics: [MOCK_METRIC_METADATA, MOCK_METRIC_METADATA],
metrics: [mockMetric, mockMetric],
yAxisUnit: 'seconds',
});
@@ -122,17 +133,18 @@ describe('TimeSeries', () => {
);
});
it('shows Save unit button when metric had no unit but one is selected', async () => {
// TODO: Unskip this test once the save unit button is implemented
// Tracking at - https://github.com/SigNoz/engineering-pod/issues/3495
it.skip('shows Save unit button when metric had no unit but one is selected', () => {
const { findByText, getByRole } = renderTimeSeries({
metricUnits: [undefined],
metricNames: ['metric1'],
metrics: [MOCK_METRIC_METADATA],
metrics: [mockMetric],
yAxisUnit: 'seconds',
showYAxisUnitSelector: true,
});
expect(
await findByText('Save the selected unit for this metric?'),
findByText('Save the selected unit for this metric?'),
).toBeInTheDocument();
const yesButton = getByRole('button', { name: 'Yes' });
@@ -140,25 +152,24 @@ describe('TimeSeries', () => {
expect(yesButton).toBeEnabled();
});
it('clicking on save unit button shoould upated metric metadata', async () => {
// TODO: Unskip this test once the save unit button is implemented
// Tracking at - https://github.com/SigNoz/engineering-pod/issues/3495
it.skip('clicking on save unit button shoould upated metric metadata', () => {
const user = userEvent.setup();
const { getByRole } = renderTimeSeries({
metricUnits: [''],
metricNames: ['metric1'],
metrics: [MOCK_METRIC_METADATA],
metrics: [mockMetric],
yAxisUnit: 'seconds',
showYAxisUnitSelector: true,
});
const yesButton = getByRole('button', { name: /Yes/i });
await user.click(yesButton);
user.click(yesButton);
expect(mockUpdateMetricMetadata).toHaveBeenCalledWith(
{
pathParams: {
metricName: 'metric1',
},
data: expect.objectContaining({ unit: 'seconds' }),
metricName: 'metric1',
payload: expect.objectContaining({ unit: 'seconds' }),
},
expect.objectContaining({
onSuccess: expect.any(Function),

View File

@@ -1,13 +0,0 @@
import {
MetricsexplorertypesMetricMetadataDTO,
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
export const MOCK_METRIC_METADATA: MetricsexplorertypesMetricMetadataDTO = {
type: MetrictypesTypeDTO.sum,
description: 'metric1 description',
unit: 'metric1 unit',
temporality: MetrictypesTemporalityDTO.cumulative,
isMonotonic: true,
};

View File

@@ -1,8 +1,14 @@
import { UseQueryResult } from 'react-query';
import { renderHook } from '@testing-library/react';
import { GetMetricMetadata200 } from 'api/generated/services/sigNoz.schemas';
import { Temporality } from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import { initialQueriesMap } from 'constants/queryBuilder';
import * as useGetMultipleMetricsHook from 'hooks/metricsExplorer/useGetMultipleMetrics';
import { SuccessResponseV2 } from 'types/api';
import {
MetricMetadata,
MetricMetadataResponse,
} from 'types/api/metricsExplorer/v2/getMetricMetadata';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import {
IBuilderFormula,
@@ -16,7 +22,6 @@ import {
splitQueryIntoOneChartPerQuery,
useGetMetrics,
} from '../utils';
import { MOCK_METRIC_METADATA } from './testUtils';
const MOCK_QUERY_DATA_1: IBuilderQuery = {
...initialQueriesMap[DataSource.METRICS].builder.queryData[0],
@@ -86,19 +91,32 @@ describe('splitQueryIntoOneChartPerQuery', () => {
});
});
const MOCK_METRIC_METADATA: MetricMetadata = {
description: 'Metric 1 description',
unit: 'unit1',
type: MetricType.GAUGE,
temporality: Temporality.DELTA,
isMonotonic: true,
};
describe('useGetMetrics', () => {
beforeEach(() => {
jest
.spyOn(useGetMultipleMetricsHook, 'useGetMultipleMetrics')
.mockReturnValue([
{
({
isLoading: false,
isError: false,
data: {
data: MOCK_METRIC_METADATA,
status: 'success',
httpStatusCode: 200,
data: {
status: 'success',
data: MOCK_METRIC_METADATA,
},
},
} as UseQueryResult<GetMetricMetadata200, Error>,
} as Partial<
UseQueryResult<SuccessResponseV2<MetricMetadataResponse>, Error>
>) as UseQueryResult<SuccessResponseV2<MetricMetadataResponse>, Error>,
]);
});
@@ -115,11 +133,12 @@ describe('useGetMetrics', () => {
jest
.spyOn(useGetMultipleMetricsHook, 'useGetMultipleMetrics')
.mockReturnValue([
{
({
isLoading: true,
isError: false,
data: undefined,
} as UseQueryResult<GetMetricMetadata200, Error>,
} as Partial<
UseQueryResult<SuccessResponseV2<MetricMetadataResponse>, Error>
>) as UseQueryResult<SuccessResponseV2<MetricMetadataResponse>, Error>,
]);
const { result } = renderHook(() => useGetMetrics(['metric1']));
expect(result.current.metrics).toHaveLength(1);

View File

@@ -1,9 +1,9 @@
import { Dispatch, SetStateAction } from 'react';
import { UseQueryResult } from 'react-query';
import { MetricsexplorertypesMetricMetadataDTO } from 'api/generated/services/sigNoz.schemas';
import { RelatedMetric } from 'api/metricsExplorer/getRelatedMetrics';
import { SuccessResponse, Warning } from 'types/api';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import { MetricMetadata } from 'types/api/metricsExplorer/v2/getMetricMetadata';
export enum ExplorerTabs {
TIME_SERIES = 'time-series',
@@ -18,7 +18,7 @@ export interface TimeSeriesProps {
isMetricUnitsError: boolean;
metricUnits: (string | undefined)[];
metricNames: string[];
metrics: (MetricsexplorertypesMetricMetadataDTO | undefined)[];
metrics: (MetricMetadata | undefined)[];
handleOpenMetricDetails: (metricName: string) => void;
yAxisUnit: string | undefined;
setYAxisUnit: (unit: string) => void;

View File

@@ -1,12 +1,9 @@
import { UpdateMetricMetadataMutationBody } from 'api/generated/services/metrics';
import { MetricsexplorertypesMetricMetadataDTO } from 'api/generated/services/sigNoz.schemas';
import { mapMetricUnitToUniversalUnit } from 'components/YAxisUnitSelector/utils';
import { useGetMultipleMetrics } from 'hooks/metricsExplorer/useGetMultipleMetrics';
import { MetricMetadata } from 'types/api/metricsExplorer/v2/getMetricMetadata';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { v4 as uuid } from 'uuid';
import { determineIsMonotonic } from '../MetricDetails/utils';
/**
* Split a query with multiple queryData to multiple distinct queries, each with a single queryData.
* @param query - The query to split
@@ -71,14 +68,16 @@ export function useGetMetrics(
): {
isLoading: boolean;
isError: boolean;
metrics: (MetricsexplorertypesMetricMetadataDTO | undefined)[];
metrics: (MetricMetadata | undefined)[];
} {
const metricsData = useGetMultipleMetrics(metricNames, {
enabled: metricNames.length > 0 && isEnabled,
});
return {
isLoading: metricsData.some((metric) => metric.isLoading),
metrics: metricsData.map((metric) => metric.data?.data),
metrics: metricsData
.map((metric) => metric.data?.data)
.map((data) => data?.data),
isError: metricsData.some((metric) => metric.isError),
};
}
@@ -90,24 +89,9 @@ export function useGetMetrics(
* @returns The units of the metrics, can be undefined if the metric has no unit
*/
export function getMetricUnits(
metrics: (MetricsexplorertypesMetricMetadataDTO | undefined)[],
metrics: (MetricMetadata | undefined)[],
): (string | undefined)[] {
return metrics
.map((metric) => metric?.unit)
.map((unit) => mapMetricUnitToUniversalUnit(unit) || undefined);
}
export function buildUpdateMetricYAxisUnitPayload(
metricName: string,
metric: MetricsexplorertypesMetricMetadataDTO,
yAxisUnit: string,
): UpdateMetricMetadataMutationBody {
return {
metricName,
type: metric.type,
description: metric.description,
unit: yAxisUnit || '',
temporality: metric.temporality,
isMonotonic: determineIsMonotonic(metric?.type, metric?.temporality),
};
}

View File

@@ -2,8 +2,8 @@
import { useMemo, useState } from 'react';
import { Card, Input, Select, Typography } from 'antd';
import logEvent from 'api/common/logEvent';
import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { InspectMetricsSeries } from 'api/metricsExplorer/getInspectMetricsDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import classNames from 'classnames';
import { initialQueriesMap } from 'constants/queryBuilder';
import { AggregatorFilter } from 'container/QueryBuilder/filters';
@@ -40,10 +40,8 @@ import {
* returns true if the feature flag is enabled, false otherwise
* Show the inspect button in metrics explorer if the feature flag is enabled
*/
export function isInspectEnabled(
metricType: MetrictypesTypeDTO | undefined,
): boolean {
return metricType === MetrictypesTypeDTO.gauge;
export function isInspectEnabled(metricType: MetricType | undefined): boolean {
return metricType === MetricType.GAUGE;
}
export function getAllTimestampsOfMetrics(

View File

@@ -1,17 +1,8 @@
import { useCallback, useMemo, useState } from 'react';
import { useCopyToClipboard } from 'react-use';
import {
Button,
Collapse,
Input,
Menu,
Popover,
Skeleton,
Typography,
} from 'antd';
import { Button, Collapse, Input, Menu, Popover, Typography } from 'antd';
import { ColumnsType } from 'antd/es/table';
import logEvent from 'api/common/logEvent';
import { useGetMetricAttributes } from 'api/generated/services/metrics';
import { ResizeTable } from 'components/ResizeTable';
import { DataType } from 'container/LogDetailedView/TableView';
import { useNotifications } from 'hooks/useNotifications';
@@ -21,33 +12,9 @@ import { PANEL_TYPES } from '../../../constants/queryBuilder';
import ROUTES from '../../../constants/routes';
import { useHandleExplorerTabChange } from '../../../hooks/useHandleExplorerTabChange';
import { MetricsExplorerEventKeys, MetricsExplorerEvents } from '../events';
import MetricDetailsErrorState from './MetricDetailsErrorState';
import {
AllAttributesEmptyTextProps,
AllAttributesProps,
AllAttributesValueProps,
} from './types';
import { AllAttributesProps, AllAttributesValueProps } from './types';
import { getMetricDetailsQuery } from './utils';
const ALL_ATTRIBUTES_KEY = 'all-attributes';
function AllAttributesEmptyText({
isErrorAttributes,
refetchAttributes,
}: AllAttributesEmptyTextProps): JSX.Element {
if (isErrorAttributes) {
return (
<div className="all-attributes-error-state">
<MetricDetailsErrorState
refetch={refetchAttributes}
errorMessage="Something went wrong while fetching attributes"
/>
</div>
);
}
return <Typography.Text>No attributes found</Typography.Text>;
}
export function AllAttributesValue({
filterKey,
filterValue,
@@ -143,23 +110,13 @@ export function AllAttributesValue({
function AllAttributes({
metricName,
attributes,
metricType,
}: AllAttributesProps): JSX.Element {
const [searchString, setSearchString] = useState('');
const [activeKey, setActiveKey] = useState<string[]>([ALL_ATTRIBUTES_KEY]);
const {
data: attributesData,
isLoading: isLoadingAttributes,
isError: isErrorAttributes,
refetch: refetchAttributes,
} = useGetMetricAttributes({
metricName,
});
const attributes = useMemo(() => attributesData?.data.attributes ?? [], [
attributesData,
]);
const [activeKey, setActiveKey] = useState<string | string[]>(
'all-attributes',
);
const { handleExplorerTabChange } = useHandleExplorerTabChange();
@@ -221,7 +178,7 @@ function AllAttributes({
attributes.filter(
(attribute) =>
attribute.key.toLowerCase().includes(searchString.toLowerCase()) ||
attribute.values?.some((value) =>
attribute.value.some((value) =>
value.toLowerCase().includes(searchString.toLowerCase()),
),
),
@@ -238,7 +195,7 @@ function AllAttributes({
},
value: {
key: attribute.key,
value: attribute.values,
value: attribute.value,
},
}))
: [],
@@ -313,7 +270,6 @@ function AllAttributes({
onClick={(e): void => {
e.stopPropagation();
}}
disabled={isLoadingAttributes || isErrorAttributes}
/>
</div>
),
@@ -321,49 +277,25 @@ function AllAttributes({
children: (
<ResizeTable
columns={columns}
loading={isLoadingAttributes}
tableLayout="fixed"
dataSource={tableData}
pagination={false}
showHeader={false}
className="metrics-accordion-content all-attributes-content"
scroll={{ y: 600 }}
locale={{
emptyText: (
<AllAttributesEmptyText
isErrorAttributes={isErrorAttributes}
refetchAttributes={refetchAttributes}
/>
),
}}
/>
),
},
],
[
searchString,
isLoadingAttributes,
isErrorAttributes,
columns,
tableData,
refetchAttributes,
],
[columns, tableData, searchString],
);
if (isLoadingAttributes) {
return (
<div className="all-attributes-skeleton-container">
<Skeleton active paragraph={{ rows: 8 }} />
</div>
);
}
return (
<Collapse
bordered
className="metrics-accordion"
className="metrics-accordion metrics-metadata-accordion"
activeKey={activeKey}
onChange={(keys): void => setActiveKey(keys as string[])}
onChange={(keys): void => setActiveKey(keys)}
items={items}
/>
);

View File

@@ -2,84 +2,36 @@ import { useMemo } from 'react';
import { generatePath } from 'react-router-dom';
import { Color } from '@signozhq/design-tokens';
import { Dropdown, Typography } from 'antd';
import { Skeleton } from 'antd/lib';
import {
useGetMetricAlerts,
useGetMetricDashboards,
} from 'api/generated/services/metrics';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import history from 'lib/history';
import { Bell, Grid } from 'lucide-react';
import { pluralize } from 'utils/pluralize';
import { DashboardsAndAlertsPopoverProps } from './types';
function DashboardsAndAlertsPopover({
metricName,
alerts,
dashboards,
}: DashboardsAndAlertsPopoverProps): JSX.Element | null {
const { safeNavigate } = useSafeNavigate();
const params = useUrlQuery();
const {
data: alertsData,
isLoading: isLoadingAlerts,
isError: isErrorAlerts,
} = useGetMetricAlerts(
{
metricName,
},
{
query: {
enabled: !!metricName,
},
},
);
const {
data: dashboardsData,
isLoading: isLoadingDashboards,
isError: isErrorDashboards,
} = useGetMetricDashboards(
{
metricName,
},
{
query: {
enabled: !!metricName,
},
},
);
const alerts = useMemo(() => {
return alertsData?.data.alerts ?? [];
}, [alertsData]);
const dashboards = useMemo(() => {
const currentDashboards = dashboardsData?.data.dashboards ?? [];
// Remove duplicate dashboards
return currentDashboards.filter(
(dashboard, index, self) =>
index === self.findIndex((t) => t.dashboardId === dashboard.dashboardId),
);
}, [dashboardsData]);
const alertsPopoverContent = useMemo(() => {
if (alerts && alerts.length > 0) {
return alerts.map((alert) => ({
key: alert.alertId,
key: alert.alert_id,
label: (
<Typography.Link
key={alert.alertId}
key={alert.alert_id}
onClick={(): void => {
params.set(QueryParams.ruleId, alert.alertId);
params.set(QueryParams.ruleId, alert.alert_id);
history.push(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`);
}}
className="dashboards-popover-content-item"
>
{alert.alertName || alert.alertId}
{alert.alert_name || alert.alert_id}
</Typography.Link>
),
}));
@@ -87,44 +39,41 @@ function DashboardsAndAlertsPopover({
return null;
}, [alerts, params]);
const uniqueDashboards = useMemo(
() =>
dashboards?.filter(
(item, index, self) =>
index === self.findIndex((t) => t.dashboard_id === item.dashboard_id),
),
[dashboards],
);
const dashboardsPopoverContent = useMemo(() => {
if (dashboards && dashboards.length > 0) {
return dashboards.map((dashboard) => ({
key: dashboard.dashboardId,
if (uniqueDashboards && uniqueDashboards.length > 0) {
return uniqueDashboards.map((dashboard) => ({
key: dashboard.dashboard_id,
label: (
<Typography.Link
key={dashboard.dashboardId}
key={dashboard.dashboard_id}
onClick={(): void => {
safeNavigate(
generatePath(ROUTES.DASHBOARD, {
dashboardId: dashboard.dashboardId,
dashboardId: dashboard.dashboard_id,
}),
);
}}
className="dashboards-popover-content-item"
>
{dashboard.dashboardName || dashboard.dashboardId}
{dashboard.dashboard_name || dashboard.dashboard_id}
</Typography.Link>
),
}));
}
return null;
}, [dashboards, safeNavigate]);
}, [uniqueDashboards, safeNavigate]);
if (isLoadingAlerts || isLoadingDashboards) {
return (
<div className="dashboards-and-alerts-popover-container">
<Skeleton title={false} paragraph={{ rows: 1 }} active />
</div>
);
}
// If there are no dashboards or alerts or both have errors, don't show the popover
const hidePopover =
(!dashboardsPopoverContent && !alertsPopoverContent) ||
(isErrorAlerts && isErrorDashboards);
if (hidePopover) {
return <div className="dashboards-and-alerts-popover-container" />;
if (!dashboardsPopoverContent && !alertsPopoverContent) {
return null;
}
return (
@@ -143,7 +92,8 @@ function DashboardsAndAlertsPopover({
>
<Grid size={12} color={Color.BG_SIENNA_500} />
<Typography.Text>
{pluralize(dashboards.length, 'dashboard')}
{uniqueDashboards?.length} dashboard
{uniqueDashboards?.length === 1 ? '' : 's'}
</Typography.Text>
</div>
</Dropdown>
@@ -162,7 +112,7 @@ function DashboardsAndAlertsPopover({
>
<Bell size={12} color={Color.BG_SAKURA_500} />
<Typography.Text>
{pluralize(alerts.length, 'alert rule')}
{alerts?.length} alert {alerts?.length === 1 ? 'rule' : 'rules'}
</Typography.Text>
</div>
</Dropdown>

View File

@@ -1,123 +0,0 @@
import { Color } from '@signozhq/design-tokens';
import { Button, Skeleton, Tooltip, Typography } from 'antd';
import { useGetMetricHighlights } from 'api/generated/services/metrics';
import { InfoIcon } from 'lucide-react';
import { formatNumberIntoHumanReadableFormat } from '../Summary/utils';
import { HighlightsProps } from './types';
import {
formatNumberToCompactFormat,
formatTimestampToReadableDate,
} from './utils';
function Highlights({ metricName }: HighlightsProps): JSX.Element {
const {
data: metricHighlightsData,
isLoading: isLoadingMetricHighlights,
isError: isErrorMetricHighlights,
refetch: refetchMetricHighlights,
} = useGetMetricHighlights(
{
metricName,
},
{
query: {
enabled: !!metricName,
},
},
);
const metricHighlights = metricHighlightsData?.data;
const timeSeriesActive = formatNumberToCompactFormat(
metricHighlights?.activeTimeSeries,
);
const timeSeriesTotal = formatNumberToCompactFormat(
metricHighlights?.totalTimeSeries,
);
const lastReceivedText = formatTimestampToReadableDate(
metricHighlights?.lastReceived,
);
if (isLoadingMetricHighlights) {
return (
<div
className="metric-details-content-grid"
data-testid="metric-highlights-loading-state"
>
<Skeleton title={false} paragraph={{ rows: 2 }} active />
</div>
);
}
if (isErrorMetricHighlights) {
return (
<div className="metric-details-content-grid">
<div
className="metric-highlights-error-state"
data-testid="metric-highlights-error-state"
>
<InfoIcon size={16} color={Color.BG_CHERRY_500} />
<Typography.Text>
Something went wrong while fetching metric highlights
</Typography.Text>
<Button
type="link"
size="large"
onClick={(): void => {
refetchMetricHighlights();
}}
>
Retry ?
</Button>
</div>
</div>
);
}
return (
<div className="metric-details-content-grid">
<div className="labels-row">
<Typography.Text type="secondary" className="metric-details-grid-label">
SAMPLES
</Typography.Text>
<Typography.Text type="secondary" className="metric-details-grid-label">
TIME SERIES
</Typography.Text>
<Typography.Text type="secondary" className="metric-details-grid-label">
LAST RECEIVED
</Typography.Text>
</div>
<div className="values-row">
<Typography.Text
className="metric-details-grid-value"
data-testid="metric-highlights-data-points"
>
<Tooltip title={metricHighlights?.dataPoints?.toLocaleString()}>
{formatNumberIntoHumanReadableFormat(metricHighlights?.dataPoints ?? 0)}
</Tooltip>
</Typography.Text>
<Typography.Text
className="metric-details-grid-value"
data-testid="metric-highlights-time-series-total"
>
<Tooltip
title="Active time series are those that have received data points in the last 1
hour."
placement="top"
>
<span>{`${timeSeriesTotal} total ⎯ ${timeSeriesActive} active`}</span>
</Tooltip>
</Typography.Text>
<Typography.Text
className="metric-details-grid-value"
data-testid="metric-highlights-last-received"
>
<Tooltip title={lastReceivedText}>{lastReceivedText}</Tooltip>
</Typography.Text>
</div>
</div>
);
}
export default Highlights;

View File

@@ -1,58 +1,45 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
import { Button, Collapse, Input, Select, Skeleton, Typography } from 'antd';
import { Button, Collapse, Input, Select, Typography } from 'antd';
import { ColumnsType } from 'antd/es/table';
import logEvent from 'api/common/logEvent';
import {
invalidateGetMetricMetadata,
invalidateListMetrics,
useUpdateMetricMetadata,
} from 'api/generated/services/metrics';
import {
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
RenderErrorResponseDTO,
} from 'api/generated/services/sigNoz.schemas';
import { AxiosError } from 'axios';
import { Temporality } from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import { UpdateMetricMetadataProps } from 'api/metricsExplorer/updateMetricMetadata';
import { ResizeTable } from 'components/ResizeTable';
import YAxisUnitSelector from 'components/YAxisUnitSelector';
import { YAxisSource } from 'components/YAxisUnitSelector/types';
import { getUniversalNameFromMetricUnit } from 'components/YAxisUnitSelector/utils';
import FieldRenderer from 'container/LogDetailedView/FieldRenderer';
import { DataType } from 'container/LogDetailedView/TableView';
import { useUpdateMetricMetadata } from 'hooks/metricsExplorer/useUpdateMetricMetadata';
import { useNotifications } from 'hooks/useNotifications';
import { Edit2, Save, X } from 'lucide-react';
import { MetricsExplorerEventKeys, MetricsExplorerEvents } from '../events';
import { MetricTypeViewRenderer } from '../Summary/utils';
import {
METRIC_METADATA_KEYS,
METRIC_METADATA_TEMPORALITY_OPTIONS,
METRIC_METADATA_TYPE_OPTIONS,
METRIC_METADATA_UPDATE_ERROR_MESSAGE,
} from './constants';
import MetricDetailsErrorState from './MetricDetailsErrorState';
import { MetadataProps, MetricMetadataFormState, TableFields } from './types';
import { transformUpdateMetricMetadataRequest } from './utils';
METRIC_TYPE_LABEL_MAP,
METRIC_TYPE_VALUES_MAP,
} from '../Summary/constants';
import { MetricTypeRenderer } from '../Summary/utils';
import { METRIC_METADATA_KEYS } from './constants';
import { MetadataProps } from './types';
import { determineIsMonotonic } from './utils';
function Metadata({
metricName,
metadata,
isErrorMetricMetadata,
isLoadingMetricMetadata,
refetchMetricMetadata,
refetchMetricDetails,
}: MetadataProps): JSX.Element {
const [isEditing, setIsEditing] = useState(false);
const [
metricMetadataState,
setMetricMetadataState,
] = useState<MetricMetadataFormState>({
type: MetrictypesTypeDTO.sum,
description: '',
temporality: MetrictypesTemporalityDTO.unspecified,
unit: '',
isMonotonic: false,
metricMetadata,
setMetricMetadata,
] = useState<UpdateMetricMetadataProps>({
metricType: metadata?.metric_type || MetricType.SUM,
description: metadata?.description || '',
temporality: metadata?.temporality,
unit: metadata?.unit,
});
const { notifications } = useNotifications();
const {
@@ -64,135 +51,110 @@ function Metadata({
);
const queryClient = useQueryClient();
// Initialize state from metadata api data
useEffect(() => {
if (metadata) {
setMetricMetadataState({
type: metadata.type,
description: metadata.description,
temporality: metadata.temporality,
unit: metadata.unit,
isMonotonic: metadata.isMonotonic,
});
}
}, [metadata]);
const tableData = useMemo(
() =>
metadata
? Object.keys(metadata).map((key) => ({
key,
value: {
value: metadata[key as keyof typeof metadata],
? Object.keys({
...metadata,
temporality: metadata?.temporality,
})
// Filter out monotonic as user input is not required
.filter((key) => key !== 'monotonic')
.map((key) => ({
key,
},
}))
value: {
value: metadata[key as keyof typeof metadata],
key,
},
}))
: [],
[metadata],
);
// Render un-editable field value
const renderUneditableField = useCallback(
(key: keyof MetricMetadataFormState, value: string) => {
if (isErrorMetricMetadata) {
return <FieldRenderer field="-" />;
}
if (key === TableFields.TYPE) {
return <MetricTypeViewRenderer type={value as MetrictypesTypeDTO} />;
}
if (key === TableFields.IS_MONOTONIC) {
return <FieldRenderer field={value ? 'Yes' : 'No'} />;
}
if (key === TableFields.Temporality) {
const temporality = METRIC_METADATA_TEMPORALITY_OPTIONS.find(
(option) => option.value === value,
);
return <FieldRenderer field={temporality?.label || '-'} />;
}
let fieldValue = value;
if (key === TableFields.UNIT) {
fieldValue = getUniversalNameFromMetricUnit(value);
}
return <FieldRenderer field={fieldValue || '-'} />;
},
[isErrorMetricMetadata],
);
const renderUneditableField = useCallback((key: string, value: string) => {
if (key === 'metric_type') {
return <MetricTypeRenderer type={value as MetricType} />;
}
let fieldValue = value;
if (key === 'unit') {
fieldValue = getUniversalNameFromMetricUnit(value);
}
return <FieldRenderer field={fieldValue || '-'} />;
}, []);
const renderColumnValue = useCallback(
(field: {
value: string;
key: keyof MetricMetadataFormState;
}): JSX.Element => {
(field: { value: string; key: string }): JSX.Element => {
if (!isEditing) {
return renderUneditableField(field.key, field.value);
}
// Don't allow editing of unit if it's already set
const metricUnitAlreadySet =
field.key === TableFields.UNIT && Boolean(metadata?.unit);
const metricUnitAlreadySet = field.key === 'unit' && Boolean(metadata?.unit);
if (metricUnitAlreadySet) {
return renderUneditableField(field.key, field.value);
}
// Monotonic is not editable
if (field.key === TableFields.IS_MONOTONIC) {
return renderUneditableField(field.key, field.value);
}
if (field.key === TableFields.TYPE) {
if (field.key === 'metric_type') {
return (
<Select
data-testid="metric-type-select"
options={METRIC_METADATA_TYPE_OPTIONS}
value={metricMetadataState.type}
options={Object.entries(METRIC_TYPE_VALUES_MAP).map(([key]) => ({
value: key,
label: METRIC_TYPE_LABEL_MAP[key as MetricType],
}))}
value={metricMetadata.metricType}
onChange={(value): void => {
setMetricMetadataState((prev) => ({
setMetricMetadata((prev) => ({
...prev,
type: value,
metricType: value as MetricType,
}));
}}
/>
);
}
if (field.key === TableFields.UNIT) {
if (field.key === 'unit') {
return (
<YAxisUnitSelector
value={metricMetadataState.unit}
value={metricMetadata.unit}
onChange={(value): void => {
setMetricMetadataState((prev) => ({ ...prev, unit: value }));
setMetricMetadata((prev) => ({ ...prev, unit: value }));
}}
data-testid="unit-select"
source={YAxisSource.EXPLORER}
/>
);
}
if (field.key === TableFields.Temporality) {
const temporalityValue =
metricMetadataState.temporality === MetrictypesTemporalityDTO.unspecified
? undefined
: metricMetadataState.temporality;
if (field.key === 'temporality') {
return (
<Select
data-testid="temporality-select"
options={METRIC_METADATA_TEMPORALITY_OPTIONS}
value={temporalityValue}
options={Object.values(Temporality).map((key) => ({
value: key,
label: key,
}))}
value={metricMetadata.temporality}
onChange={(value): void => {
setMetricMetadataState((prev) => ({
setMetricMetadata((prev) => ({
...prev,
temporality: value,
temporality: value as Temporality,
}));
}}
/>
);
}
if (field.key === TableFields.DESCRIPTION) {
if (field.key === 'description') {
return (
<Input
data-testid="description-input"
name={field.key}
defaultValue={metricMetadataState.description}
defaultValue={
metricMetadata[
field.key as Exclude<keyof UpdateMetricMetadataProps, 'isMonotonic'>
]
}
onChange={(e): void => {
setMetricMetadataState((prev) => ({
setMetricMetadata((prev) => ({
...prev,
[field.key]: e.target.value,
}));
@@ -202,7 +164,7 @@ function Metadata({
}
return <FieldRenderer field="-" />;
},
[isEditing, metadata?.unit, metricMetadataState, renderUneditableField],
[isEditing, metadata?.unit, metricMetadata, renderUneditableField],
);
const columns: ColumnsType<DataType> = useMemo(
@@ -239,61 +201,52 @@ function Metadata({
const handleSave = useCallback(() => {
updateMetricMetadata(
{
pathParams: {
metricName,
metricName,
payload: {
...metricMetadata,
isMonotonic: determineIsMonotonic(
metricMetadata.metricType,
metricMetadata.temporality,
),
},
data: transformUpdateMetricMetadataRequest(metricName, metricMetadataState),
},
{
onSuccess: (): void => {
logEvent(MetricsExplorerEvents.MetricMetadataUpdated, {
[MetricsExplorerEventKeys.MetricName]: metricName,
[MetricsExplorerEventKeys.Tab]: 'summary',
[MetricsExplorerEventKeys.Modal]: 'metric-details',
});
notifications.success({
message: 'Metadata updated successfully',
});
setIsEditing(false);
invalidateListMetrics(queryClient);
invalidateGetMetricMetadata(queryClient, {
metricName,
});
onSuccess: (response): void => {
if (response?.statusCode === 200) {
logEvent(MetricsExplorerEvents.MetricMetadataUpdated, {
[MetricsExplorerEventKeys.MetricName]: metricName,
[MetricsExplorerEventKeys.Tab]: 'summary',
[MetricsExplorerEventKeys.Modal]: 'metric-details',
});
notifications.success({
message: 'Metadata updated successfully',
});
refetchMetricDetails();
setIsEditing(false);
queryClient.invalidateQueries(['metricsList']);
} else {
notifications.error({
message:
'Failed to update metadata, please try again. If the issue persists, please contact support.',
});
}
},
onError: (error): void => {
const errorMessage = (error as AxiosError<RenderErrorResponseDTO>).response
?.data.error?.message;
onError: (): void =>
notifications.error({
message: errorMessage || METRIC_METADATA_UPDATE_ERROR_MESSAGE,
});
},
message:
'Failed to update metadata, please try again. If the issue persists, please contact support.',
}),
},
);
}, [
updateMetricMetadata,
metricName,
metricMetadataState,
metricMetadata,
notifications,
refetchMetricDetails,
queryClient,
]);
const cancelEdit = useCallback(
(e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
e.stopPropagation();
if (metadata) {
setMetricMetadataState({
type: metadata.type,
description: metadata.description,
unit: metadata.unit,
temporality: metadata.temporality,
isMonotonic: metadata.isMonotonic,
});
}
setIsEditing(false);
},
[metadata],
);
const actionButton = useMemo(() => {
if (isEditing) {
return (
@@ -301,7 +254,10 @@ function Metadata({
<Button
className="action-button"
type="text"
onClick={cancelEdit}
onClick={(e): void => {
e.stopPropagation();
setIsEditing(false);
}}
disabled={isUpdatingMetricsMetadata}
>
<X size={14} />
@@ -322,9 +278,6 @@ function Metadata({
</div>
);
}
if (isErrorMetricMetadata) {
return null;
}
return (
<div className="action-menu">
<Button
@@ -341,13 +294,7 @@ function Metadata({
</Button>
</div>
);
}, [
isEditing,
isErrorMetricMetadata,
isUpdatingMetricsMetadata,
cancelEdit,
handleSave,
]);
}, [handleSave, isEditing, isUpdatingMetricsMetadata]);
const items = useMemo(
() => [
@@ -359,14 +306,7 @@ function Metadata({
</div>
),
key: 'metric-metadata',
children: isErrorMetricMetadata ? (
<div className="metric-metadata-error-state">
<MetricDetailsErrorState
refetch={refetchMetricMetadata}
errorMessage="Something went wrong while fetching metric metadata"
/>
</div>
) : (
children: (
<ResizeTable
columns={columns}
tableLayout="fixed"
@@ -378,23 +318,9 @@ function Metadata({
),
},
],
[
actionButton,
columns,
isErrorMetricMetadata,
refetchMetricMetadata,
tableData,
],
[actionButton, columns, tableData],
);
if (isLoadingMetricMetadata) {
return (
<div className="metrics-metadata-skeleton-container">
<Skeleton active paragraph={{ rows: 8 }} />
</div>
);
}
return (
<Collapse
bordered

View File

@@ -38,12 +38,7 @@
flex-direction: column;
gap: 12px;
.metrics-metadata-error {
padding: 16px !important;
}
.metric-details-content-grid {
height: 50px;
.labels-row,
.values-row {
display: grid;
@@ -52,18 +47,6 @@
align-items: center;
}
.metric-highlights-error-state {
display: flex;
gap: 8px;
height: 100%;
width: 100%;
align-items: center;
.ant-btn {
padding: 2px 4px;
}
}
.labels-row {
margin-bottom: 8px;
@@ -89,7 +72,6 @@
.dashboards-and-alerts-popover-container {
display: flex;
gap: 16px;
height: 32px;
.dashboards-and-alerts-popover {
border-radius: 20px;
@@ -120,19 +102,7 @@
}
}
.metrics-metadata-skeleton-container {
height: 330px;
}
.all-attributes-skeleton-container {
height: 600px;
}
.metrics-accordion {
.all-attributes-error-state {
height: 300px;
}
.ant-table-body {
&::-webkit-scrollbar {
width: 2px;
@@ -178,6 +148,7 @@
.all-attributes-search-input {
width: 300px;
border: 1px solid var(--bg-slate-300);
}
}
@@ -190,7 +161,6 @@
.ant-typography:first-child {
font-family: 'Geist Mono';
color: var(--bg-robin-400);
background-color: transparent;
}
}
.all-attributes-contribution {
@@ -247,10 +217,6 @@
.ant-collapse-content-box {
padding: 0;
.metric-metadata-error-state {
height: 267px;
}
}
.ant-collapse-header {
@@ -271,7 +237,6 @@
}
.metric-metadata-value {
height: 67px;
background: rgba(22, 25, 34, 0.4);
overflow-x: scroll;
.field-renderer-container {
@@ -365,26 +330,18 @@
.metric-details-content {
.metrics-accordion {
.metrics-accordion-header {
.action-menu {
.action-button {
.ant-typography {
color: var(--bg-slate-400);
}
.action-button {
.ant-typography {
color: var(--bg-slate-400);
}
}
}
.metrics-accordion-content {
.metric-metadata-key {
.field-renderer-container {
.label {
color: var(--bg-slate-300);
}
}
.all-attributes-key {
.ant-typography:last-child {
color: var(--bg-vanilla-200);
color: var(--bg-slate-400);
background-color: var(--bg-robin-300);
}
}
@@ -438,13 +395,3 @@
}
}
}
.metric-details-error-state {
display: flex;
flex-direction: column;
gap: 8px;
align-items: center;
justify-content: center;
height: 100%;
width: 100%;
}

View File

@@ -1,8 +1,16 @@
import { useCallback, useEffect, useMemo } from 'react';
import { Color } from '@signozhq/design-tokens';
import { Button, Divider, Drawer, Typography } from 'antd';
import {
Button,
Divider,
Drawer,
Empty,
Skeleton,
Tooltip,
Typography,
} from 'antd';
import logEvent from 'api/common/logEvent';
import { useGetMetricMetadata } from 'api/generated/services/metrics';
import { useGetMetricDetails } from 'hooks/metricsExplorer/useGetMetricDetails';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { Compass, Crosshair, X } from 'lucide-react';
@@ -11,12 +19,16 @@ import ROUTES from '../../../constants/routes';
import { useHandleExplorerTabChange } from '../../../hooks/useHandleExplorerTabChange';
import { MetricsExplorerEventKeys, MetricsExplorerEvents } from '../events';
import { isInspectEnabled } from '../Inspect/utils';
import { formatNumberIntoHumanReadableFormat } from '../Summary/utils';
import AllAttributes from './AllAttributes';
import DashboardsAndAlertsPopover from './DashboardsAndAlertsPopover';
import Highlights from './Highlights';
import Metadata from './Metadata';
import { MetricDetailsProps } from './types';
import { getMetricDetailsQuery } from './utils';
import {
formatNumberToCompactFormat,
formatTimestampToReadableDate,
getMetricDetailsQuery,
} from './utils';
import './MetricDetails.styles.scss';
import '../Summary/Summary.styles.scss';
@@ -31,49 +43,55 @@ function MetricDetails({
const { handleExplorerTabChange } = useHandleExplorerTabChange();
const {
data: metricMetadataResponse,
isLoading: isLoadingMetricMetadata,
isError: isErrorMetricMetadata,
refetch: refetchMetricMetadata,
} = useGetMetricMetadata(
{
metricName,
},
{
query: {
enabled: !!metricName,
},
},
);
data,
isLoading,
isFetching,
error: metricDetailsError,
refetch: refetchMetricDetails,
} = useGetMetricDetails(metricName ?? '', {
enabled: !!metricName,
});
const metadata = useMemo(() => {
if (!metricMetadataResponse) {
const metric = data?.payload?.data;
const lastReceived = useMemo(() => {
if (!metric) {
return null;
}
const {
type,
description,
unit,
temporality,
isMonotonic,
} = metricMetadataResponse.data;
return formatTimestampToReadableDate(metric.lastReceived);
}, [metric]);
return {
type,
description,
unit,
temporality,
isMonotonic,
};
}, [metricMetadataResponse]);
const showInspectFeature = useMemo(
() => isInspectEnabled(metric?.metadata?.metric_type),
[metric],
);
const showInspectFeature = useMemo(() => isInspectEnabled(metadata?.type), [
metadata?.type,
]);
const isMetricDetailsLoading = isLoading || isFetching;
const timeSeries = useMemo(() => {
if (!metric) {
return null;
}
const timeSeriesActive = formatNumberToCompactFormat(metric.timeSeriesActive);
const timeSeriesTotal = formatNumberToCompactFormat(metric.timeSeriesTotal);
return (
<Tooltip
title="Active time series are those that have received data points in the last 1
hour."
placement="top"
>
<span>{`${timeSeriesTotal} total ⎯ ${timeSeriesActive} active`}</span>
</Tooltip>
);
}, [metric]);
const goToMetricsExplorerwithSelectedMetric = useCallback(() => {
if (metricName) {
const compositeQuery = getMetricDetailsQuery(metricName, metadata?.type);
const compositeQuery = getMetricDetailsQuery(
metricName,
metric?.metadata?.metric_type,
);
handleExplorerTabChange(
PANEL_TYPES.TIME_SERIES,
{
@@ -89,7 +107,9 @@ function MetricDetails({
[MetricsExplorerEventKeys.Modal]: 'metric-details',
});
}
}, [metricName, handleExplorerTabChange, metadata?.type]);
}, [metricName, handleExplorerTabChange, metric?.metadata?.metric_type]);
const isMetricDetailsError = metricDetailsError || !metric;
useEffect(() => {
logEvent(MetricsExplorerEvents.ModalOpened, {
@@ -97,9 +117,6 @@ function MetricDetails({
});
}, []);
const isActionButtonDisabled =
!metricName || isLoadingMetricMetadata || isErrorMetricMetadata;
return (
<Drawer
width="60%"
@@ -107,13 +124,13 @@ function MetricDetails({
<div className="metric-details-header">
<div className="metric-details-title">
<Divider type="vertical" />
<Typography.Text>{metricName}</Typography.Text>
<Typography.Text>{metric?.name}</Typography.Text>
</div>
<div className="metric-details-header-buttons">
<Button
onClick={goToMetricsExplorerwithSelectedMetric}
icon={<Compass size={16} />}
disabled={isActionButtonDisabled}
disabled={!metricName}
data-testid="open-in-explorer-button"
>
Open in Explorer
@@ -123,11 +140,10 @@ function MetricDetails({
<Button
className="inspect-metrics-button"
aria-label="Inspect Metric"
disabled={isActionButtonDisabled}
icon={<Crosshair size={18} />}
onClick={(): void => {
if (metricName) {
openInspectModal(metricName);
if (metric?.name) {
openInspectModal(metric.name);
}
}}
data-testid="inspect-metric-button"
@@ -147,18 +163,60 @@ function MetricDetails({
destroyOnClose
closeIcon={<X size={16} />}
>
<div className="metric-details-content">
<Highlights metricName={metricName} />
<DashboardsAndAlertsPopover metricName={metricName} />
<Metadata
metricName={metricName}
metadata={metadata}
isErrorMetricMetadata={isErrorMetricMetadata}
isLoadingMetricMetadata={isLoadingMetricMetadata}
refetchMetricMetadata={refetchMetricMetadata}
/>
<AllAttributes metricName={metricName} metricType={metadata?.type} />
</div>
{isMetricDetailsLoading && (
<div data-testid="metric-details-skeleton">
<Skeleton active />
</div>
)}
{isMetricDetailsError && !isMetricDetailsLoading && (
<Empty description="Error fetching metric details" />
)}
{!isMetricDetailsLoading && !isMetricDetailsError && (
<div className="metric-details-content">
<div className="metric-details-content-grid">
<div className="labels-row">
<Typography.Text type="secondary" className="metric-details-grid-label">
SAMPLES
</Typography.Text>
<Typography.Text type="secondary" className="metric-details-grid-label">
TIME SERIES
</Typography.Text>
<Typography.Text type="secondary" className="metric-details-grid-label">
LAST RECEIVED
</Typography.Text>
</div>
<div className="values-row">
<Typography.Text className="metric-details-grid-value">
<Tooltip title={metric?.samples.toLocaleString()}>
{formatNumberIntoHumanReadableFormat(metric?.samples)}
</Tooltip>
</Typography.Text>
<Typography.Text className="metric-details-grid-value">
<Tooltip title={timeSeries}>{timeSeries}</Tooltip>
</Typography.Text>
<Typography.Text className="metric-details-grid-value">
<Tooltip title={lastReceived}>{lastReceived}</Tooltip>
</Typography.Text>
</div>
</div>
<DashboardsAndAlertsPopover
dashboards={metric.dashboards}
alerts={metric.alerts}
/>
<Metadata
metricName={metric?.name}
metadata={metric.metadata}
refetchMetricDetails={refetchMetricDetails}
/>
{metric.attributes && (
<AllAttributes
metricName={metric?.name}
attributes={metric.attributes}
metricType={metric?.metadata?.metric_type}
/>
)}
</div>
)}
</Drawer>
);
}

View File

@@ -1,20 +0,0 @@
import { Color } from '@signozhq/design-tokens';
import { Button, Typography } from 'antd';
import { InfoIcon } from 'lucide-react';
import { MetricDetailsErrorStateProps } from './types';
function MetricDetailsErrorState({
refetch,
errorMessage,
}: MetricDetailsErrorStateProps): JSX.Element {
return (
<div className="metric-details-error-state">
<InfoIcon size={20} color={Color.BG_CHERRY_500} />
<Typography.Text>{errorMessage}</Typography.Text>
{refetch && <Button onClick={refetch}>Retry</Button>}
</div>
);
}
export default MetricDetailsErrorState;

View File

@@ -1,13 +1,11 @@
import * as reactUseHooks from 'react-use';
import { render, screen } from '@testing-library/react';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { fireEvent, render, screen } from '@testing-library/react';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import * as useHandleExplorerTabChange from 'hooks/useHandleExplorerTabChange';
import { userEvent } from 'tests/test-utils';
import { MetricDetailsAttribute } from '../../../../api/metricsExplorer/getMetricDetails';
import ROUTES from '../../../../constants/routes';
import AllAttributes, { AllAttributesValue } from '../AllAttributes';
import { getMockMetricAttributesData, MOCK_METRIC_NAME } from './testUtlls';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
@@ -22,28 +20,33 @@ jest
handleExplorerTabChange: mockHandleExplorerTabChange,
});
const mockMetricName = 'test-metric';
const mockMetricType = MetricType.GAUGE;
const mockAttributes: MetricDetailsAttribute[] = [
{
key: 'attribute1',
value: ['value1', 'value2'],
valueCount: 2,
},
{
key: 'attribute2',
value: ['value3'],
valueCount: 1,
},
];
const mockUseCopyToClipboard = jest.fn();
jest
.spyOn(reactUseHooks, 'useCopyToClipboard')
.mockReturnValue([{ value: 'value1' }, mockUseCopyToClipboard] as any);
const useGetMetricAttributesMock = jest.spyOn(
metricsExplorerHooks,
'useGetMetricAttributes',
);
describe('AllAttributes', () => {
beforeEach(() => {
useGetMetricAttributesMock.mockReturnValue({
...getMockMetricAttributesData(),
});
});
it('renders attributes section with title', () => {
render(
<AllAttributes
metricName={MOCK_METRIC_NAME}
metricType={MetrictypesTypeDTO.gauge}
metricName={mockMetricName}
attributes={mockAttributes}
metricType={mockMetricType}
/>,
);
@@ -53,8 +56,9 @@ describe('AllAttributes', () => {
it('renders all attribute keys and values', () => {
render(
<AllAttributes
metricName={MOCK_METRIC_NAME}
metricType={MetrictypesTypeDTO.gauge}
metricName={mockMetricName}
attributes={mockAttributes}
metricType={mockMetricType}
/>,
);
@@ -71,8 +75,9 @@ describe('AllAttributes', () => {
it('renders value counts correctly', () => {
render(
<AllAttributes
metricName={MOCK_METRIC_NAME}
metricType={MetrictypesTypeDTO.gauge}
metricName={mockMetricName}
attributes={mockAttributes}
metricType={mockMetricType}
/>,
);
@@ -81,44 +86,41 @@ describe('AllAttributes', () => {
});
it('handles empty attributes array', () => {
useGetMetricAttributesMock.mockReturnValue({
...getMockMetricAttributesData({
data: {
attributes: [],
totalKeys: 0,
},
}),
});
render(
<AllAttributes
metricName={MOCK_METRIC_NAME}
metricType={MetrictypesTypeDTO.gauge}
metricName={mockMetricName}
attributes={[]}
metricType={mockMetricType}
/>,
);
expect(screen.getByText('All Attributes')).toBeInTheDocument();
expect(screen.getByText('No attributes found')).toBeInTheDocument();
expect(screen.queryByText('No data')).toBeInTheDocument();
});
it('clicking on an attribute key opens the explorer with the attribute filter applied', async () => {
it('clicking on an attribute key opens the explorer with the attribute filter applied', () => {
render(
<AllAttributes
metricName={MOCK_METRIC_NAME}
metricType={MetrictypesTypeDTO.gauge}
metricName={mockMetricName}
attributes={mockAttributes}
metricType={mockMetricType}
/>,
);
await userEvent.click(screen.getByText('attribute1'));
fireEvent.click(screen.getByText('attribute1'));
expect(mockHandleExplorerTabChange).toHaveBeenCalled();
});
it('filters attributes based on search input', async () => {
it('filters attributes based on search input', () => {
render(
<AllAttributes
metricName={MOCK_METRIC_NAME}
metricType={MetrictypesTypeDTO.gauge}
metricName={mockMetricName}
attributes={mockAttributes}
metricType={mockMetricType}
/>,
);
await userEvent.type(screen.getByPlaceholderText('Search'), 'value1');
fireEvent.change(screen.getByPlaceholderText('Search'), {
target: { value: 'value1' },
});
expect(screen.getByText('attribute1')).toBeInTheDocument();
expect(screen.getByText('value1')).toBeInTheDocument();
@@ -142,7 +144,7 @@ describe('AllAttributesValue', () => {
expect(screen.getByText('value2')).toBeInTheDocument();
});
it('loads more attributes when show more button is clicked', async () => {
it('loads more attributes when show more button is clicked', () => {
render(
<AllAttributesValue
filterKey="attribute1"
@@ -153,7 +155,7 @@ describe('AllAttributesValue', () => {
/>,
);
expect(screen.queryByText('value6')).not.toBeInTheDocument();
await userEvent.click(screen.getByText('Show More'));
fireEvent.click(screen.getByText('Show More'));
expect(screen.getByText('value6')).toBeInTheDocument();
});
@@ -170,7 +172,7 @@ describe('AllAttributesValue', () => {
expect(screen.queryByText('Show More')).not.toBeInTheDocument();
});
it('copy button should copy the attribute value to the clipboard', async () => {
it('copy button should copy the attribute value to the clipboard', () => {
render(
<AllAttributesValue
filterKey="attribute1"
@@ -181,13 +183,13 @@ describe('AllAttributesValue', () => {
/>,
);
expect(screen.getByText('value1')).toBeInTheDocument();
await userEvent.click(screen.getByText('value1'));
fireEvent.click(screen.getByText('value1'));
expect(screen.getByText('Copy Attribute')).toBeInTheDocument();
await userEvent.click(screen.getByText('Copy Attribute'));
fireEvent.click(screen.getByText('Copy Attribute'));
expect(mockUseCopyToClipboard).toHaveBeenCalledWith('value1');
});
it('explorer button should go to metrics explore with the attribute filter applied', async () => {
it('explorer button should go to metrics explore with the attribute filter applied', () => {
render(
<AllAttributesValue
filterKey="attribute1"
@@ -198,10 +200,10 @@ describe('AllAttributesValue', () => {
/>,
);
expect(screen.getByText('value1')).toBeInTheDocument();
await userEvent.click(screen.getByText('value1'));
fireEvent.click(screen.getByText('value1'));
expect(screen.getByText('Open in Explorer')).toBeInTheDocument();
await userEvent.click(screen.getByText('Open in Explorer'));
fireEvent.click(screen.getByText('Open in Explorer'));
expect(mockGoToMetricsExploreWithAppliedAttribute).toHaveBeenCalledWith(
'attribute1',
'value1',

View File

@@ -1,18 +1,26 @@
import { render, screen } from '@testing-library/react';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import { fireEvent, render, screen } from '@testing-library/react';
import { QueryParams } from 'constants/query';
import { userEvent } from 'tests/test-utils';
import DashboardsAndAlertsPopover from '../DashboardsAndAlertsPopover';
import {
getMockAlertsData,
getMockDashboardsData,
MOCK_ALERT_1,
MOCK_ALERT_2,
MOCK_DASHBOARD_1,
MOCK_DASHBOARD_2,
MOCK_METRIC_NAME,
} from './testUtlls';
const mockAlert1 = {
alert_id: '1',
alert_name: 'Alert 1',
};
const mockAlert2 = {
alert_id: '2',
alert_name: 'Alert 2',
};
const mockDashboard1 = {
dashboard_id: '1',
dashboard_name: 'Dashboard 1',
};
const mockDashboard2 = {
dashboard_id: '2',
dashboard_name: 'Dashboard 2',
};
const mockAlerts = [mockAlert1, mockAlert2];
const mockDashboards = [mockDashboard1, mockDashboard2];
const mockSafeNavigate = jest.fn();
jest.mock('hooks/useSafeNavigate', () => ({
@@ -20,6 +28,7 @@ jest.mock('hooks/useSafeNavigate', () => ({
safeNavigate: mockSafeNavigate,
}),
}));
const mockSetQuery = jest.fn();
const mockUrlQuery = {
set: mockSetQuery,
@@ -30,156 +39,125 @@ jest.mock('hooks/useUrlQuery', () => ({
default: jest.fn(() => mockUrlQuery),
}));
const useGetMetricAlertsMock = jest.spyOn(
metricsExplorerHooks,
'useGetMetricAlerts',
);
const useGetMetricDashboardsMock = jest.spyOn(
metricsExplorerHooks,
'useGetMetricDashboards',
);
describe('DashboardsAndAlertsPopover', () => {
beforeEach(() => {
useGetMetricAlertsMock.mockReturnValue(getMockAlertsData());
useGetMetricDashboardsMock.mockReturnValue(getMockDashboardsData());
});
it('renders the popover correctly with multiple dashboards and alerts', () => {
render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);
render(
<DashboardsAndAlertsPopover
alerts={mockAlerts}
dashboards={mockDashboards}
/>,
);
expect(screen.getByText(`2 dashboards`)).toBeInTheDocument();
expect(screen.getByText(`2 alert rules`)).toBeInTheDocument();
expect(
screen.getByText(`${mockDashboards.length} dashboards`),
).toBeInTheDocument();
expect(
screen.getByText(`${mockAlerts.length} alert rules`),
).toBeInTheDocument();
});
it('renders null with no dashboards and alerts', () => {
useGetMetricAlertsMock.mockReturnValue(
getMockAlertsData({
data: {
alerts: [],
},
}),
);
useGetMetricDashboardsMock.mockReturnValue(
getMockDashboardsData({
data: {
dashboards: [],
},
}),
);
const { container } = render(
<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />,
<DashboardsAndAlertsPopover alerts={[]} dashboards={[]} />,
);
expect(
container.querySelector('dashboards-and-alerts-popover-container'),
).toBeNull();
expect(container).toBeEmptyDOMElement();
});
it('renders popover with single dashboard and alert', () => {
useGetMetricAlertsMock.mockReturnValue(
getMockAlertsData({
data: {
alerts: [MOCK_ALERT_1],
},
}),
render(
<DashboardsAndAlertsPopover
alerts={[mockAlert1]}
dashboards={[mockDashboard1]}
/>,
);
useGetMetricDashboardsMock.mockReturnValue(
getMockDashboardsData({
data: {
dashboards: [MOCK_DASHBOARD_1],
},
}),
);
render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);
expect(screen.getByText(`1 dashboard`)).toBeInTheDocument();
expect(screen.getByText(`1 alert rule`)).toBeInTheDocument();
});
it('renders popover with dashboard id if name is not available', async () => {
useGetMetricDashboardsMock.mockReturnValue(
getMockDashboardsData({
data: {
dashboards: [{ ...MOCK_DASHBOARD_1, dashboardName: '' }],
},
}),
it('renders popover with dashboard id if name is not available', () => {
render(
<DashboardsAndAlertsPopover
alerts={mockAlerts}
dashboards={[{ ...mockDashboard1, dashboard_name: undefined } as any]}
/>,
);
render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);
await userEvent.click(screen.getByText(`1 dashboard`));
expect(screen.getByText(MOCK_DASHBOARD_1.dashboardId)).toBeInTheDocument();
fireEvent.click(screen.getByText(`1 dashboard`));
expect(screen.getByText(mockDashboard1.dashboard_id)).toBeInTheDocument();
});
it('renders popover with alert id if name is not available', async () => {
useGetMetricAlertsMock.mockReturnValue(
getMockAlertsData({
data: {
alerts: [{ ...MOCK_ALERT_1, alertName: '' }],
},
}),
it('renders popover with alert id if name is not available', () => {
render(
<DashboardsAndAlertsPopover
alerts={[{ ...mockAlert1, alert_name: undefined } as any]}
dashboards={mockDashboards}
/>,
);
render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);
await userEvent.click(screen.getByText(`1 alert rule`));
expect(screen.getByText(MOCK_ALERT_1.alertId)).toBeInTheDocument();
fireEvent.click(screen.getByText(`1 alert rule`));
expect(screen.getByText(mockAlert1.alert_id)).toBeInTheDocument();
});
it('navigates to the dashboard when the dashboard is clicked', async () => {
render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);
it('navigates to the dashboard when the dashboard is clicked', () => {
render(
<DashboardsAndAlertsPopover
alerts={mockAlerts}
dashboards={mockDashboards}
/>,
);
// Click on 2 dashboards button
await userEvent.click(screen.getByText(`2 dashboards`));
fireEvent.click(screen.getByText(`${mockDashboards.length} dashboards`));
// Popover showing list of 2 dashboards should be visible
expect(screen.getByText(MOCK_DASHBOARD_1.dashboardName)).toBeInTheDocument();
expect(screen.getByText(MOCK_DASHBOARD_2.dashboardName)).toBeInTheDocument();
expect(screen.getByText(mockDashboard1.dashboard_name)).toBeInTheDocument();
expect(screen.getByText(mockDashboard2.dashboard_name)).toBeInTheDocument();
// Click on the first dashboard
await userEvent.click(screen.getByText(MOCK_DASHBOARD_1.dashboardName));
fireEvent.click(screen.getByText(mockDashboard1.dashboard_name));
// Should navigate to the dashboard
expect(mockSafeNavigate).toHaveBeenCalledWith(
`/dashboard/${MOCK_DASHBOARD_1.dashboardId}`,
`/dashboard/${mockDashboard1.dashboard_id}`,
);
});
it('navigates to the alert when the alert is clicked', async () => {
render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);
it('navigates to the alert when the alert is clicked', () => {
render(
<DashboardsAndAlertsPopover
alerts={mockAlerts}
dashboards={mockDashboards}
/>,
);
// Click on 2 alert rules button
await userEvent.click(screen.getByText(`2 alert rules`));
fireEvent.click(screen.getByText(`${mockAlerts.length} alert rules`));
// Popover showing list of 2 alert rules should be visible
expect(screen.getByText(MOCK_ALERT_1.alertName)).toBeInTheDocument();
expect(screen.getByText(MOCK_ALERT_2.alertName)).toBeInTheDocument();
expect(screen.getByText(mockAlert1.alert_name)).toBeInTheDocument();
expect(screen.getByText(mockAlert2.alert_name)).toBeInTheDocument();
// Click on the first alert rule
await userEvent.click(screen.getByText(MOCK_ALERT_1.alertName));
fireEvent.click(screen.getByText(mockAlert1.alert_name));
// Should navigate to the alert rule
expect(mockSetQuery).toHaveBeenCalledWith(
QueryParams.ruleId,
MOCK_ALERT_1.alertId,
mockAlert1.alert_id,
);
});
it('renders unique dashboards even when there are duplicates', async () => {
useGetMetricDashboardsMock.mockReturnValue(
getMockDashboardsData({
data: {
dashboards: [MOCK_DASHBOARD_1, MOCK_DASHBOARD_2, MOCK_DASHBOARD_1],
},
}),
it('renders unique dashboards even when there are duplicates', () => {
render(
<DashboardsAndAlertsPopover
alerts={mockAlerts}
dashboards={[...mockDashboards, mockDashboard1]}
/>,
);
expect(
screen.getByText(`${mockDashboards.length} dashboards`),
).toBeInTheDocument();
render(<DashboardsAndAlertsPopover metricName={MOCK_METRIC_NAME} />);
expect(screen.getByText('2 dashboards')).toBeInTheDocument();
await userEvent.click(screen.getByText('2 dashboards'));
expect(screen.getByText(MOCK_DASHBOARD_1.dashboardName)).toBeInTheDocument();
expect(screen.getByText(MOCK_DASHBOARD_2.dashboardName)).toBeInTheDocument();
fireEvent.click(screen.getByText(`${mockDashboards.length} dashboards`));
expect(screen.getByText(mockDashboard1.dashboard_name)).toBeInTheDocument();
expect(screen.getByText(mockDashboard2.dashboard_name)).toBeInTheDocument();
});
});

View File

@@ -1,67 +0,0 @@
import { render, screen } from '@testing-library/react';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import Highlights from '../Highlights';
import { formatTimestampToReadableDate } from '../utils';
import { getMockMetricHighlightsData, MOCK_METRIC_NAME } from './testUtlls';
const useGetMetricHighlightsMock = jest.spyOn(
metricsExplorerHooks,
'useGetMetricHighlights',
);
describe('Highlights', () => {
beforeEach(() => {
useGetMetricHighlightsMock.mockReturnValue(getMockMetricHighlightsData());
});
it('should render all highlights data correctly', () => {
render(<Highlights metricName={MOCK_METRIC_NAME} />);
const dataPoints = screen.getByTestId('metric-highlights-data-points');
const timeSeriesTotal = screen.getByTestId(
'metric-highlights-time-series-total',
);
const lastReceived = screen.getByTestId('metric-highlights-last-received');
expect(dataPoints.textContent).toBe('1M+');
expect(timeSeriesTotal.textContent).toBe('1M total ⎯ 1M active');
expect(lastReceived.textContent).toBe(
formatTimestampToReadableDate('2026-01-24T00:00:00Z'),
);
});
it('should render error state correctly', () => {
useGetMetricHighlightsMock.mockReturnValue(
getMockMetricHighlightsData(
{},
{
isError: true,
},
),
);
render(<Highlights metricName={MOCK_METRIC_NAME} />);
expect(
screen.getByTestId('metric-highlights-error-state'),
).toBeInTheDocument();
});
it('should render loading state when data is loading', () => {
useGetMetricHighlightsMock.mockReturnValue(
getMockMetricHighlightsData(
{},
{
isLoading: true,
},
),
);
render(<Highlights metricName={MOCK_METRIC_NAME} />);
expect(
screen.getByTestId('metric-highlights-loading-state'),
).toBeInTheDocument();
});
});

View File

@@ -1,24 +1,16 @@
/* eslint-disable sonarjs/no-duplicate-string */
import { render, screen } from '@testing-library/react';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import {
GetMetricMetadata200,
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import { fireEvent, render, screen } from '@testing-library/react';
import { Temporality } from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import {
UniversalYAxisUnit,
YAxisUnitSelectorProps,
} from 'components/YAxisUnitSelector/types';
import * as useUpdateMetricMetadataHooks from 'hooks/metricsExplorer/useUpdateMetricMetadata';
import * as useNotificationsHooks from 'hooks/useNotifications';
import { userEvent } from 'tests/test-utils';
import { SelectOption } from 'types/common/select';
import Metadata from '../Metadata';
import { MetricMetadata } from '../types';
import { transformMetricMetadata } from '../utils';
import { getMockMetricMetadataData, MOCK_METRIC_NAME } from './testUtlls';
// Mock antd select for testing
jest.mock('antd', () => ({
@@ -80,18 +72,13 @@ jest.mock('react-query', () => ({
}),
}));
const mockUseUpdateMetricMetadataHook = jest.spyOn(
metricsExplorerHooks,
'useUpdateMetricMetadata',
);
type UseUpdateMetricMetadataResult = ReturnType<
typeof metricsExplorerHooks.useUpdateMetricMetadata
>;
const mockUseUpdateMetricMetadata = jest.fn();
const mockMetricMetadata = transformMetricMetadata(
getMockMetricMetadataData().data as GetMetricMetadata200,
) as MetricMetadata;
jest
.spyOn(useUpdateMetricMetadataHooks, 'useUpdateMetricMetadata')
.mockReturnValue({
mutate: mockUseUpdateMetricMetadata,
isLoading: false,
} as any);
const mockErrorNotification = jest.fn();
const mockSuccessNotification = jest.fn();
@@ -102,50 +89,47 @@ jest.spyOn(useNotificationsHooks, 'useNotifications').mockReturnValue({
},
} as any);
const mockRefetchMetricMetadata = jest.fn();
const mockMetricName = 'test_metric';
const mockMetricMetadata = {
metric_type: MetricType.GAUGE,
description: 'test_description',
unit: 'test_unit',
temporality: Temporality.DELTA,
};
const mockRefetchMetricDetails = jest.fn();
describe('Metadata', () => {
beforeEach(() => {
mockUseUpdateMetricMetadataHook.mockReturnValue(({
mutate: mockUseUpdateMetricMetadata,
} as Partial<UseUpdateMetricMetadataResult>) as UseUpdateMetricMetadataResult);
});
it('should render the metadata properly', () => {
render(
<Metadata
metricName={MOCK_METRIC_NAME}
metricName={mockMetricName}
metadata={mockMetricMetadata}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
refetchMetricMetadata={mockRefetchMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
/>,
);
expect(screen.getByText('Metric Type')).toBeInTheDocument();
expect(screen.getByText('Gauge')).toBeInTheDocument();
expect(screen.getByText(mockMetricMetadata.metric_type)).toBeInTheDocument();
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText(mockMetricMetadata.description)).toBeInTheDocument();
expect(screen.getByText('Unit')).toBeInTheDocument();
expect(screen.getByText(mockMetricMetadata.unit)).toBeInTheDocument();
expect(screen.getByText('Temporality')).toBeInTheDocument();
expect(screen.getByText('Delta')).toBeInTheDocument();
expect(screen.getByText(mockMetricMetadata.temporality)).toBeInTheDocument();
});
it('editing the metadata should show the form inputs', async () => {
it('editing the metadata should show the form inputs', () => {
render(
<Metadata
metricName={MOCK_METRIC_NAME}
metricName={mockMetricName}
metadata={mockMetricMetadata}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
refetchMetricMetadata={mockRefetchMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
/>,
);
const editButton = screen.getByText('Edit');
expect(editButton).toBeInTheDocument();
await userEvent.click(editButton);
fireEvent.click(editButton);
expect(screen.getByTestId('metric-type-select')).toBeInTheDocument();
expect(screen.getByTestId('temporality-select')).toBeInTheDocument();
@@ -155,53 +139,57 @@ describe('Metadata', () => {
it('should update the metadata when the form is submitted', async () => {
render(
<Metadata
metricName={MOCK_METRIC_NAME}
metricName={mockMetricName}
metadata={{
...mockMetricMetadata,
unit: '',
}}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
refetchMetricMetadata={mockRefetchMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
/>,
);
const editButton = screen.getByText('Edit');
expect(editButton).toBeInTheDocument();
await userEvent.click(editButton);
fireEvent.click(editButton);
const metricDescriptionInput = screen.getByTestId('description-input');
expect(metricDescriptionInput).toBeInTheDocument();
await userEvent.clear(metricDescriptionInput);
await userEvent.type(metricDescriptionInput, 'Updated description');
fireEvent.change(metricDescriptionInput, {
target: { value: 'Updated description' },
});
const metricTypeSelect = screen.getByTestId('metric-type-select');
expect(metricTypeSelect).toBeInTheDocument();
await userEvent.selectOptions(metricTypeSelect, MetrictypesTypeDTO.sum);
fireEvent.change(metricTypeSelect, {
target: { value: MetricType.SUM },
});
const temporalitySelect = screen.getByTestId('temporality-select');
expect(temporalitySelect).toBeInTheDocument();
await userEvent.selectOptions(temporalitySelect, Temporality.CUMULATIVE);
fireEvent.change(temporalitySelect, {
target: { value: Temporality.CUMULATIVE },
});
const unitSelect = screen.getByTestId('unit-select');
expect(unitSelect).toBeInTheDocument();
await userEvent.selectOptions(unitSelect, 'By');
fireEvent.change(unitSelect, {
target: { value: 'By' },
});
const saveButton = screen.getByText('Save');
expect(saveButton).toBeInTheDocument();
await userEvent.click(saveButton);
fireEvent.click(saveButton);
expect(mockUseUpdateMetricMetadata).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
type: MetrictypesTypeDTO.sum,
temporality: MetrictypesTemporalityDTO.cumulative,
metricName: mockMetricName,
payload: expect.objectContaining({
description: 'Updated description',
metricType: MetricType.SUM,
temporality: Temporality.CUMULATIVE,
unit: 'By',
isMonotonic: true,
}),
pathParams: {
metricName: MOCK_METRIC_NAME,
},
}),
expect.objectContaining({
onSuccess: expect.any(Function),
@@ -213,56 +201,56 @@ describe('Metadata', () => {
it('should show success notification when metadata is updated successfully', async () => {
render(
<Metadata
metricName={MOCK_METRIC_NAME}
metricName={mockMetricName}
metadata={mockMetricMetadata}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
refetchMetricMetadata={mockRefetchMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
/>,
);
const editButton = screen.getByText('Edit');
await userEvent.click(editButton);
fireEvent.click(editButton);
const metricDescriptionInput = screen.getByTestId('description-input');
await userEvent.clear(metricDescriptionInput);
await userEvent.type(metricDescriptionInput, 'Updated description');
fireEvent.change(metricDescriptionInput, {
target: { value: 'Updated description' },
});
const saveButton = screen.getByText('Save');
await userEvent.click(saveButton);
fireEvent.click(saveButton);
const onSuccessCallback =
mockUseUpdateMetricMetadata.mock.calls[0][1].onSuccess;
onSuccessCallback({ status: 200 });
onSuccessCallback({ statusCode: 200 });
expect(mockSuccessNotification).toHaveBeenCalledWith({
message: 'Metadata updated successfully',
});
expect(mockRefetchMetricDetails).toHaveBeenCalled();
});
it('should show error notification when metadata update fails with non-200 response', async () => {
render(
<Metadata
metricName={MOCK_METRIC_NAME}
metricName={mockMetricName}
metadata={mockMetricMetadata}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
refetchMetricMetadata={mockRefetchMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
/>,
);
const editButton = screen.getByText('Edit');
await userEvent.click(editButton);
fireEvent.click(editButton);
const metricDescriptionInput = screen.getByTestId('description-input');
await userEvent.clear(metricDescriptionInput);
await userEvent.type(metricDescriptionInput, 'Updated description');
fireEvent.change(metricDescriptionInput, {
target: { value: 'Updated description' },
});
const saveButton = screen.getByText('Save');
await userEvent.click(saveButton);
fireEvent.click(saveButton);
const onErrorCallback = mockUseUpdateMetricMetadata.mock.calls[0][1].onError;
onErrorCallback({ status: 500 });
const onSuccessCallback =
mockUseUpdateMetricMetadata.mock.calls[0][1].onSuccess;
onSuccessCallback({ statusCode: 500 });
expect(mockErrorNotification).toHaveBeenCalledWith({
message:
@@ -273,23 +261,22 @@ describe('Metadata', () => {
it('should show error notification when metadata update fails', async () => {
render(
<Metadata
metricName={MOCK_METRIC_NAME}
metricName={mockMetricName}
metadata={mockMetricMetadata}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
refetchMetricMetadata={mockRefetchMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
/>,
);
const editButton = screen.getByText('Edit');
await userEvent.click(editButton);
fireEvent.click(editButton);
const metricDescriptionInput = screen.getByTestId('description-input');
await userEvent.clear(metricDescriptionInput);
await userEvent.type(metricDescriptionInput, 'Updated description');
fireEvent.change(metricDescriptionInput, {
target: { value: 'Updated description' },
});
const saveButton = screen.getByText('Save');
await userEvent.click(saveButton);
fireEvent.click(saveButton);
const onErrorCallback = mockUseUpdateMetricMetadata.mock.calls[0][1].onError;
@@ -302,43 +289,39 @@ describe('Metadata', () => {
});
});
it('cancel button should cancel the edit mode', async () => {
it('cancel button should cancel the edit mode', () => {
render(
<Metadata
metricName={MOCK_METRIC_NAME}
metricName={mockMetricName}
metadata={mockMetricMetadata}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
refetchMetricMetadata={mockRefetchMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
/>,
);
const editButton = screen.getByText('Edit');
expect(editButton).toBeInTheDocument();
await userEvent.click(editButton);
fireEvent.click(editButton);
const cancelButton = screen.getByText('Cancel');
expect(cancelButton).toBeInTheDocument();
await userEvent.click(cancelButton);
fireEvent.click(cancelButton);
const editButton2 = screen.getByText('Edit');
expect(editButton2).toBeInTheDocument();
});
it('should not allow editing of unit if it is already set', async () => {
it('should not allow editing of unit if it is already set', () => {
render(
<Metadata
metricName={MOCK_METRIC_NAME}
metricName={mockMetricName}
metadata={mockMetricMetadata}
isErrorMetricMetadata={false}
isLoadingMetricMetadata={false}
refetchMetricMetadata={mockRefetchMetricMetadata}
refetchMetricDetails={mockRefetchMetricDetails}
/>,
);
const editButton = screen.getByText('Edit');
expect(editButton).toBeInTheDocument();
await userEvent.click(editButton);
fireEvent.click(editButton);
const unitSelect = screen.queryByTestId('unit-select');
expect(unitSelect).not.toBeInTheDocument();

View File

@@ -1,16 +1,68 @@
import { render, screen } from '@testing-library/react';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import { fireEvent, render, screen } from '@testing-library/react';
import { MetricDetails as MetricDetailsType } from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import { getUniversalNameFromMetricUnit } from 'components/YAxisUnitSelector/utils';
import ROUTES from 'constants/routes';
import * as useGetMetricDetails from 'hooks/metricsExplorer/useGetMetricDetails';
import * as useUpdateMetricMetadata from 'hooks/metricsExplorer/useUpdateMetricMetadata';
import * as useHandleExplorerTabChange from 'hooks/useHandleExplorerTabChange';
import { userEvent } from 'tests/test-utils';
import MetricDetails from '../MetricDetails';
import { getMockMetricMetadataData } from './testUtlls';
const mockMetricName = 'test-metric';
const mockMetricDescription = 'description for a test metric';
const mockMetricData: MetricDetailsType = {
name: mockMetricName,
description: mockMetricDescription,
unit: 'count',
attributes: [
{
key: 'test-attribute',
value: ['test-value'],
valueCount: 1,
},
],
alerts: [],
dashboards: [],
metadata: {
metric_type: MetricType.SUM,
description: mockMetricDescription,
unit: 'count',
},
type: '',
timeseries: 0,
samples: 0,
timeSeriesTotal: 0,
timeSeriesActive: 0,
lastReceived: '',
};
const mockOpenInspectModal = jest.fn();
const mockOnClose = jest.fn();
const mockUseGetMetricDetailsData = {
data: {
payload: {
data: mockMetricData,
},
},
isLoading: false,
isFetching: false,
isError: false,
error: null,
refetch: jest.fn(),
};
jest
.spyOn(useGetMetricDetails, 'useGetMetricDetails')
.mockReturnValue(mockUseGetMetricDetailsData as any);
jest.spyOn(useUpdateMetricMetadata, 'useUpdateMetricMetadata').mockReturnValue({
mutate: jest.fn(),
isLoading: false,
isError: false,
error: null,
} as any);
const mockHandleExplorerTabChange = jest.fn();
jest
.spyOn(useHandleExplorerTabChange, 'useHandleExplorerTabChange')
@@ -36,50 +88,7 @@ jest.mock('react-query', () => ({
}),
}));
jest.mock(
'container/MetricsExplorer/MetricDetails/AllAttributes',
() =>
function MockAllAttributes(): JSX.Element {
return <div data-testid="all-attributes">All Attributes</div>;
},
);
jest.mock(
'container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover',
() =>
function MockDashboardsAndAlertsPopover(): JSX.Element {
return (
<div data-testid="dashboards-and-alerts-popover">
Dashboards and Alerts Popover
</div>
);
},
);
jest.mock(
'container/MetricsExplorer/MetricDetails/Highlights',
() =>
function MockHighlights(): JSX.Element {
return <div data-testid="highlights">Highlights</div>;
},
);
jest.mock(
'container/MetricsExplorer/MetricDetails/Metadata',
() =>
function MockMetadata(): JSX.Element {
return <div data-testid="metadata">Metadata</div>;
},
);
const useGetMetricMetadataMock = jest.spyOn(
metricsExplorerHooks,
'useGetMetricMetadata',
);
describe('MetricDetails', () => {
beforeEach(() => {
useGetMetricMetadataMock.mockReturnValue(getMockMetricMetadataData());
});
it('renders metric details correctly', () => {
render(
<MetricDetails
@@ -92,15 +101,27 @@ describe('MetricDetails', () => {
);
expect(screen.getByText(mockMetricName)).toBeInTheDocument();
expect(screen.getByTestId('all-attributes')).toBeInTheDocument();
expect(screen.getByText(mockMetricDescription)).toBeInTheDocument();
expect(
screen.getByTestId('dashboards-and-alerts-popover'),
screen.getByText(getUniversalNameFromMetricUnit(mockMetricData.unit)),
).toBeInTheDocument();
expect(screen.getByTestId('highlights')).toBeInTheDocument();
expect(screen.getByTestId('metadata')).toBeInTheDocument();
});
it('renders the "open in explorer" and "inspect" buttons', async () => {
it('renders the "open in explorer" and "inspect" buttons', () => {
jest.spyOn(useGetMetricDetails, 'useGetMetricDetails').mockReturnValueOnce({
...mockUseGetMetricDetailsData,
data: {
payload: {
data: {
...mockMetricData,
metadata: {
...mockMetricData.metadata,
metric_type: MetricType.GAUGE,
},
},
},
},
} as any);
render(
<MetricDetails
onClose={mockOnClose}
@@ -114,10 +135,93 @@ describe('MetricDetails', () => {
expect(screen.getByTestId('open-in-explorer-button')).toBeInTheDocument();
expect(screen.getByTestId('inspect-metric-button')).toBeInTheDocument();
await userEvent.click(screen.getByTestId('open-in-explorer-button'));
fireEvent.click(screen.getByTestId('open-in-explorer-button'));
expect(mockHandleExplorerTabChange).toHaveBeenCalled();
await userEvent.click(screen.getByTestId('inspect-metric-button'));
fireEvent.click(screen.getByTestId('inspect-metric-button'));
expect(mockOpenInspectModal).toHaveBeenCalled();
});
it('should render error state when metric details are not found', () => {
jest.spyOn(useGetMetricDetails, 'useGetMetricDetails').mockReturnValue({
...mockUseGetMetricDetailsData,
isError: true,
error: {
message: 'Error fetching metric details',
},
} as any);
render(
<MetricDetails
onClose={mockOnClose}
isOpen
metricName={mockMetricName}
isModalTimeSelection
openInspectModal={mockOpenInspectModal}
/>,
);
expect(screen.getByText('Error fetching metric details')).toBeInTheDocument();
});
it('should render loading state when metric details are loading', () => {
jest.spyOn(useGetMetricDetails, 'useGetMetricDetails').mockReturnValue({
...mockUseGetMetricDetailsData,
isLoading: true,
} as any);
render(
<MetricDetails
onClose={mockOnClose}
isOpen
metricName={mockMetricName}
isModalTimeSelection
openInspectModal={mockOpenInspectModal}
/>,
);
expect(screen.getByTestId('metric-details-skeleton')).toBeInTheDocument();
});
it('should render all attributes section', () => {
jest
.spyOn(useGetMetricDetails, 'useGetMetricDetails')
.mockReturnValue(mockUseGetMetricDetailsData as any);
render(
<MetricDetails
onClose={mockOnClose}
isOpen
metricName={mockMetricName}
isModalTimeSelection
openInspectModal={mockOpenInspectModal}
/>,
);
expect(screen.getByText('All Attributes')).toBeInTheDocument();
});
it('should not render all attributes section when relevant data is not present', () => {
jest.spyOn(useGetMetricDetails, 'useGetMetricDetails').mockReturnValue({
...mockUseGetMetricDetailsData,
data: {
payload: {
data: {
...mockMetricData,
attributes: null,
},
},
},
} as any);
render(
<MetricDetails
onClose={mockOnClose}
isOpen
metricName={mockMetricName}
isModalTimeSelection
openInspectModal={mockOpenInspectModal}
/>,
);
expect(screen.queryByText('All Attributes')).not.toBeInTheDocument();
});
});

View File

@@ -1,168 +0,0 @@
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import {
GetMetricAlerts200,
GetMetricAttributes200,
GetMetricDashboards200,
GetMetricHighlights200,
GetMetricMetadata200,
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
export const MOCK_METRIC_NAME = 'test-metric';
export function getMockMetricHighlightsData(
overrides?: Partial<GetMetricHighlights200>,
{
isLoading = false,
isError = false,
}: {
isLoading?: boolean;
isError?: boolean;
} = {},
): ReturnType<typeof metricsExplorerHooks.useGetMetricHighlights> {
return {
data: {
data: {
dataPoints: 1000000,
lastReceived: '2026-01-24T00:00:00Z',
totalTimeSeries: 1000000,
activeTimeSeries: 1000000,
},
status: 'success',
...overrides,
},
isLoading,
isError,
} as ReturnType<typeof metricsExplorerHooks.useGetMetricHighlights>;
}
export const MOCK_DASHBOARD_1 = {
dashboardName: 'Dashboard 1',
dashboardId: '1',
widgetId: '1',
widgetName: 'Widget 1',
};
export const MOCK_DASHBOARD_2 = {
dashboardName: 'Dashboard 2',
dashboardId: '2',
widgetId: '2',
widgetName: 'Widget 2',
};
export const MOCK_ALERT_1 = {
alertName: 'Alert 1',
alertId: '1',
};
export const MOCK_ALERT_2 = {
alertName: 'Alert 2',
alertId: '2',
};
export function getMockDashboardsData(
overrides?: Partial<GetMetricDashboards200>,
{
isLoading = false,
isError = false,
}: {
isLoading?: boolean;
isError?: boolean;
} = {},
): ReturnType<typeof metricsExplorerHooks.useGetMetricDashboards> {
return {
data: {
data: {
dashboards: [MOCK_DASHBOARD_1, MOCK_DASHBOARD_2],
},
status: 'success',
...overrides,
},
isLoading,
isError,
} as ReturnType<typeof metricsExplorerHooks.useGetMetricDashboards>;
}
export function getMockAlertsData(
overrides?: Partial<GetMetricAlerts200>,
{
isLoading = false,
isError = false,
}: {
isLoading?: boolean;
isError?: boolean;
} = {},
): ReturnType<typeof metricsExplorerHooks.useGetMetricAlerts> {
return {
data: {
data: {
alerts: [MOCK_ALERT_1, MOCK_ALERT_2],
},
status: 'success',
...overrides,
},
isLoading,
isError,
} as ReturnType<typeof metricsExplorerHooks.useGetMetricAlerts>;
}
export function getMockMetricAttributesData(
overrides?: Partial<GetMetricAttributes200>,
{
isLoading = false,
isError = false,
}: {
isLoading?: boolean;
isError?: boolean;
} = {},
): ReturnType<typeof metricsExplorerHooks.useGetMetricAttributes> {
return {
data: {
data: {
attributes: [
{
key: 'attribute1',
values: ['value1', 'value2'],
valueCount: 2,
},
{
key: 'attribute2',
values: ['value3'],
valueCount: 1,
},
],
totalKeys: 2,
},
status: 'success',
...overrides,
},
isLoading,
isError,
} as ReturnType<typeof metricsExplorerHooks.useGetMetricAttributes>;
}
export function getMockMetricMetadataData(
overrides?: Partial<GetMetricMetadata200>,
{
isLoading = false,
isError = false,
}: {
isLoading?: boolean;
isError?: boolean;
} = {},
): ReturnType<typeof metricsExplorerHooks.useGetMetricMetadata> {
return {
data: {
data: {
description: 'test_description',
type: MetrictypesTypeDTO.gauge,
unit: 'test_unit',
temporality: MetrictypesTemporalityDTO.delta,
isMonotonic: false,
},
status: 'success',
...overrides,
},
isLoading,
isError,
} as ReturnType<typeof metricsExplorerHooks.useGetMetricMetadata>;
}

View File

@@ -1,7 +1,5 @@
import {
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import { Temporality } from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import {
determineIsMonotonic,
@@ -12,48 +10,35 @@ import {
describe('MetricDetails utils', () => {
describe('determineIsMonotonic', () => {
it('should return true for histogram metrics', () => {
expect(determineIsMonotonic(MetrictypesTypeDTO.histogram)).toBe(true);
expect(determineIsMonotonic(MetricType.HISTOGRAM)).toBe(true);
});
it('should return true for exponential histogram metrics', () => {
expect(determineIsMonotonic(MetrictypesTypeDTO.exponentialhistogram)).toBe(
expect(determineIsMonotonic(MetricType.EXPONENTIAL_HISTOGRAM)).toBe(true);
});
it('should return false for gauge metrics', () => {
expect(determineIsMonotonic(MetricType.GAUGE)).toBe(false);
});
it('should return false for summary metrics', () => {
expect(determineIsMonotonic(MetricType.SUMMARY)).toBe(false);
});
it('should return true for sum metrics with cumulative temporality', () => {
expect(determineIsMonotonic(MetricType.SUM, Temporality.CUMULATIVE)).toBe(
true,
);
});
it('should return false for gauge metrics', () => {
expect(determineIsMonotonic(MetrictypesTypeDTO.gauge)).toBe(false);
});
it('should return false for summary metrics', () => {
expect(determineIsMonotonic(MetrictypesTypeDTO.summary)).toBe(false);
});
it('should return true for sum metrics with cumulative temporality', () => {
expect(
determineIsMonotonic(
MetrictypesTypeDTO.sum,
MetrictypesTemporalityDTO.cumulative,
),
).toBe(true);
});
it('should return false for sum metrics with delta temporality', () => {
expect(
determineIsMonotonic(
MetrictypesTypeDTO.sum,
MetrictypesTemporalityDTO.delta,
),
).toBe(false);
expect(determineIsMonotonic(MetricType.SUM, Temporality.DELTA)).toBe(false);
});
it('should return false by default', () => {
expect(
determineIsMonotonic(
'' as MetrictypesTypeDTO,
'' as MetrictypesTemporalityDTO,
),
).toBe(false);
expect(determineIsMonotonic('' as MetricType, '' as Temporality)).toBe(
false,
);
});
});
@@ -130,16 +115,13 @@ describe('MetricDetails utils', () => {
const API_GATEWAY = 'api-gateway';
it('should create correct query for SUM metric type', () => {
const query = getMetricDetailsQuery(
TEST_METRIC_NAME,
MetrictypesTypeDTO.sum,
);
const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.SUM);
expect(query.builder.queryData[0]?.aggregateAttribute?.key).toBe(
TEST_METRIC_NAME,
);
expect(query.builder.queryData[0]?.aggregateAttribute?.type).toBe(
MetrictypesTypeDTO.sum,
MetricType.SUM,
);
expect(query.builder.queryData[0]?.aggregateOperator).toBe('rate');
expect(query.builder.queryData[0]?.timeAggregation).toBe('rate');
@@ -147,16 +129,13 @@ describe('MetricDetails utils', () => {
});
it('should create correct query for GAUGE metric type', () => {
const query = getMetricDetailsQuery(
TEST_METRIC_NAME,
MetrictypesTypeDTO.gauge,
);
const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.GAUGE);
expect(query.builder.queryData[0]?.aggregateAttribute?.key).toBe(
TEST_METRIC_NAME,
);
expect(query.builder.queryData[0]?.aggregateAttribute?.type).toBe(
MetrictypesTypeDTO.gauge,
MetricType.GAUGE,
);
expect(query.builder.queryData[0]?.aggregateOperator).toBe('avg');
expect(query.builder.queryData[0]?.timeAggregation).toBe('avg');
@@ -164,16 +143,13 @@ describe('MetricDetails utils', () => {
});
it('should create correct query for SUMMARY metric type', () => {
const query = getMetricDetailsQuery(
TEST_METRIC_NAME,
MetrictypesTypeDTO.summary,
);
const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.SUMMARY);
expect(query.builder.queryData[0]?.aggregateAttribute?.key).toBe(
TEST_METRIC_NAME,
);
expect(query.builder.queryData[0]?.aggregateAttribute?.type).toBe(
MetrictypesTypeDTO.summary,
MetricType.SUMMARY,
);
expect(query.builder.queryData[0]?.aggregateOperator).toBe('noop');
expect(query.builder.queryData[0]?.timeAggregation).toBe('noop');
@@ -181,16 +157,13 @@ describe('MetricDetails utils', () => {
});
it('should create correct query for HISTOGRAM metric type', () => {
const query = getMetricDetailsQuery(
TEST_METRIC_NAME,
MetrictypesTypeDTO.histogram,
);
const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.HISTOGRAM);
expect(query.builder.queryData[0]?.aggregateAttribute?.key).toBe(
TEST_METRIC_NAME,
);
expect(query.builder.queryData[0]?.aggregateAttribute?.type).toBe(
MetrictypesTypeDTO.histogram,
MetricType.HISTOGRAM,
);
expect(query.builder.queryData[0]?.aggregateOperator).toBe('noop');
expect(query.builder.queryData[0]?.timeAggregation).toBe('noop');
@@ -200,14 +173,14 @@ describe('MetricDetails utils', () => {
it('should create correct query for EXPONENTIAL_HISTOGRAM metric type', () => {
const query = getMetricDetailsQuery(
TEST_METRIC_NAME,
MetrictypesTypeDTO.exponentialhistogram,
MetricType.EXPONENTIAL_HISTOGRAM,
);
expect(query.builder.queryData[0]?.aggregateAttribute?.key).toBe(
TEST_METRIC_NAME,
);
expect(query.builder.queryData[0]?.aggregateAttribute?.type).toBe(
MetrictypesTypeDTO.exponentialhistogram,
MetricType.EXPONENTIAL_HISTOGRAM,
);
expect(query.builder.queryData[0]?.aggregateOperator).toBe('noop');
expect(query.builder.queryData[0]?.timeAggregation).toBe('noop');
@@ -230,7 +203,7 @@ describe('MetricDetails utils', () => {
const filter = { key: 'service', value: API_GATEWAY };
const query = getMetricDetailsQuery(
TEST_METRIC_NAME,
MetrictypesTypeDTO.sum,
MetricType.SUM,
filter,
);
@@ -248,7 +221,7 @@ describe('MetricDetails utils', () => {
const groupBy = 'service';
const query = getMetricDetailsQuery(
TEST_METRIC_NAME,
MetrictypesTypeDTO.sum,
MetricType.SUM,
undefined,
groupBy,
);
@@ -263,7 +236,7 @@ describe('MetricDetails utils', () => {
const groupBy = 'endpoint';
const query = getMetricDetailsQuery(
TEST_METRIC_NAME,
MetrictypesTypeDTO.sum,
MetricType.SUM,
filter,
groupBy,
);
@@ -277,10 +250,7 @@ describe('MetricDetails utils', () => {
});
it('should not include filters or groupBy when not provided', () => {
const query = getMetricDetailsQuery(
TEST_METRIC_NAME,
MetrictypesTypeDTO.sum,
);
const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.SUM);
expect(query.builder.queryData[0]?.filters?.items).toHaveLength(0);
expect(query.builder.queryData[0]?.groupBy).toHaveLength(0);

View File

@@ -1,55 +1,6 @@
import {
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
export const METRIC_METADATA_KEYS = {
description: 'Description',
unit: 'Unit',
type: 'Metric Type',
metric_type: 'Metric Type',
temporality: 'Temporality',
isMonotonic: 'Monotonic',
};
export const METRIC_METADATA_TEMPORALITY_OPTIONS: Array<{
value: MetrictypesTemporalityDTO;
label: string;
}> = [
{
value: MetrictypesTemporalityDTO.delta,
label: 'Delta',
},
{
value: MetrictypesTemporalityDTO.cumulative,
label: 'Cumulative',
},
];
export const METRIC_METADATA_TYPE_OPTIONS: Array<{
value: MetrictypesTypeDTO;
label: string;
}> = [
{
value: MetrictypesTypeDTO.sum,
label: 'Sum',
},
{
value: MetrictypesTypeDTO.gauge,
label: 'Gauge',
},
{
value: MetrictypesTypeDTO.histogram,
label: 'Histogram',
},
{
value: MetrictypesTypeDTO.summary,
label: 'Summary',
},
{
value: MetrictypesTypeDTO.exponentialhistogram,
label: 'Exponential Histogram',
},
];
export const METRIC_METADATA_UPDATE_ERROR_MESSAGE =
'Failed to update metadata, please try again. If the issue persists, please contact support.';

View File

@@ -1,39 +1,34 @@
import {
MetricsexplorertypesMetricAlertDTO,
MetricsexplorertypesMetricAttributeDTO,
MetricsexplorertypesMetricDashboardDTO,
MetricsexplorertypesMetricHighlightsResponseDTO,
MetricsexplorertypesMetricMetadataDTO,
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
MetricDetails,
MetricDetailsAlert,
MetricDetailsAttribute,
MetricDetailsDashboard,
} from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
export interface MetricDetailsProps {
onClose: () => void;
isOpen: boolean;
metricName: string;
metricName: string | null;
isModalTimeSelection: boolean;
openInspectModal?: (metricName: string) => void;
}
export interface HighlightsProps {
metricName: string;
}
export interface DashboardsAndAlertsPopoverProps {
metricName: string;
dashboards: MetricDetailsDashboard[] | null;
alerts: MetricDetailsAlert[] | null;
}
export interface MetadataProps {
metricName: string;
metadata: MetricMetadata | null;
isErrorMetricMetadata: boolean;
isLoadingMetricMetadata: boolean;
refetchMetricMetadata: () => void;
metadata: MetricDetails['metadata'] | undefined;
refetchMetricDetails: () => void;
}
export interface AllAttributesProps {
attributes: MetricDetailsAttribute[];
metricName: string;
metricType: MetrictypesTypeDTO | undefined;
metricType: MetricType | undefined;
}
export interface AllAttributesValueProps {
@@ -41,38 +36,3 @@ export interface AllAttributesValueProps {
filterValue: string[];
goToMetricsExploreWithAppliedAttribute: (key: string, value: string) => void;
}
export interface AllAttributesEmptyTextProps {
isErrorAttributes: boolean;
refetchAttributes: () => void;
}
export type MetricHighlight = MetricsexplorertypesMetricHighlightsResponseDTO;
export type MetricAlert = MetricsexplorertypesMetricAlertDTO;
export type MetricDashboard = MetricsexplorertypesMetricDashboardDTO;
export type MetricMetadata = MetricsexplorertypesMetricMetadataDTO;
export interface MetricMetadataFormState {
type: MetrictypesTypeDTO;
description: string;
temporality?: MetrictypesTemporalityDTO;
unit: string;
isMonotonic: boolean;
}
export type MetricAttribute = MetricsexplorertypesMetricAttributeDTO;
export enum TableFields {
DESCRIPTION = 'description',
UNIT = 'unit',
TYPE = 'type',
Temporality = 'temporality',
IS_MONOTONIC = 'isMonotonic',
}
export interface MetricDetailsErrorStateProps {
refetch?: () => void;
errorMessage: string;
}

View File

@@ -1,23 +1,12 @@
import { UpdateMetricMetadataMutationBody } from 'api/generated/services/metrics';
import {
GetMetricMetadata200,
MetrictypesTemporalityDTO,
MetrictypesTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import { Temporality } from 'api/metricsExplorer/getMetricDetails';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import { SpaceAggregation, TimeAggregation } from 'api/v5/v5';
import { initialQueriesMap } from 'constants/queryBuilder';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { MetricMetadata, MetricMetadataFormState } from './types';
export function formatTimestampToReadableDate(
timestamp: number | string | undefined,
): string {
if (!timestamp) {
return '-';
}
export function formatTimestampToReadableDate(timestamp: string): string {
const date = new Date(timestamp);
const now = new Date();
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
@@ -50,10 +39,7 @@ export function formatTimestampToReadableDate(
return date.toLocaleDateString();
}
export function formatNumberToCompactFormat(num: number | undefined): string {
if (!num) {
return '-';
}
export function formatNumberToCompactFormat(num: number): string {
return new Intl.NumberFormat('en-US', {
notation: 'compact',
maximumFractionDigits: 1,
@@ -61,30 +47,27 @@ export function formatNumberToCompactFormat(num: number | undefined): string {
}
export function determineIsMonotonic(
metricType: MetrictypesTypeDTO,
temporality?: MetrictypesTemporalityDTO,
metricType: MetricType,
temporality?: Temporality,
): boolean {
if (
metricType === MetrictypesTypeDTO.histogram ||
metricType === MetrictypesTypeDTO.exponentialhistogram
metricType === MetricType.HISTOGRAM ||
metricType === MetricType.EXPONENTIAL_HISTOGRAM
) {
return true;
}
if (
metricType === MetrictypesTypeDTO.gauge ||
metricType === MetrictypesTypeDTO.summary
) {
if (metricType === MetricType.GAUGE || metricType === MetricType.SUMMARY) {
return false;
}
if (metricType === MetrictypesTypeDTO.sum) {
return temporality === MetrictypesTemporalityDTO.cumulative;
if (metricType === MetricType.SUM) {
return temporality === Temporality.CUMULATIVE;
}
return false;
}
export function getMetricDetailsQuery(
metricName: string,
metricType: MetrictypesTypeDTO | undefined,
metricType: MetricType | undefined,
filter?: { key: string; value: string },
groupBy?: string,
): Query {
@@ -92,23 +75,23 @@ export function getMetricDetailsQuery(
let spaceAggregation;
let aggregateOperator;
switch (metricType) {
case MetrictypesTypeDTO.sum:
case MetricType.SUM:
timeAggregation = 'rate';
spaceAggregation = 'sum';
aggregateOperator = 'rate';
break;
case MetrictypesTypeDTO.gauge:
case MetricType.GAUGE:
timeAggregation = 'avg';
spaceAggregation = 'avg';
aggregateOperator = 'avg';
break;
case MetrictypesTypeDTO.summary:
case MetricType.SUMMARY:
timeAggregation = 'noop';
spaceAggregation = 'sum';
aggregateOperator = 'noop';
break;
case MetrictypesTypeDTO.histogram:
case MetrictypesTypeDTO.exponentialhistogram:
case MetricType.HISTOGRAM:
case MetricType.EXPONENTIAL_HISTOGRAM:
timeAggregation = 'noop';
spaceAggregation = 'p90';
aggregateOperator = 'noop';
@@ -177,38 +160,3 @@ export function getMetricDetailsQuery(
},
};
}
export function transformMetricMetadata(
apiData: GetMetricMetadata200 | undefined,
): MetricMetadata | null {
if (!apiData || !apiData.data) {
return null;
}
const { type, description, unit, temporality, isMonotonic } = apiData.data;
return {
type,
description,
unit,
temporality,
isMonotonic,
};
}
export function transformUpdateMetricMetadataRequest(
metricName: string,
metricMetadata: MetricMetadataFormState,
): UpdateMetricMetadataMutationBody {
return {
metricName: metricName,
type: metricMetadata.type,
description: metricMetadata.description,
unit: metricMetadata.unit,
temporality:
metricMetadata.temporality ?? MetrictypesTemporalityDTO.unspecified,
isMonotonic: determineIsMonotonic(
metricMetadata.type,
metricMetadata.temporality,
),
};
}

View File

@@ -5,7 +5,6 @@ import { useSearchParams } from 'react-router-dom-v5-compat';
import * as Sentry from '@sentry/react';
import logEvent from 'api/common/logEvent';
import { initialQueriesMap } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { usePageSize } from 'container/InfraMonitoringK8s/utils';
import NoLogs from 'container/NoLogs/NoLogs';
import { useGetMetricsList } from 'hooks/metricsExplorer/useGetMetricsList';
@@ -129,7 +128,7 @@ function Summary(): JSX.Element {
} = useGetMetricsList(metricsListQuery, {
enabled: !!metricsListQuery && !isInspectModalOpen,
queryKey: [
REACT_QUERY_KEY.GET_METRICS_LIST,
'metricsList',
queryFiltersWithoutId,
orderBy,
pageSize,
@@ -324,7 +323,7 @@ function Summary(): JSX.Element {
</>
)}
</div>
{isMetricDetailsOpen && selectedMetricName && (
{isMetricDetailsOpen && (
<MetricDetails
isOpen={isMetricDetailsOpen}
onClose={closeMetricDetails}

View File

@@ -1,4 +1,3 @@
import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { MetricType } from 'api/metricsExplorer/getMetricsList';
import { TreemapViewType } from './types';
@@ -26,16 +25,7 @@ export const METRIC_TYPE_LABEL_MAP = {
[MetricType.EXPONENTIAL_HISTOGRAM]: 'Exp. Histogram',
};
export const METRIC_TYPE_VIEW_LABEL_MAP: Record<MetrictypesTypeDTO, string> = {
[MetrictypesTypeDTO.sum]: 'Sum',
[MetrictypesTypeDTO.gauge]: 'Gauge',
[MetrictypesTypeDTO.histogram]: 'Histogram',
[MetrictypesTypeDTO.summary]: 'Summary',
[MetrictypesTypeDTO.exponentialhistogram]: 'Exp. Histogram',
};
// TODO(@amlannandy): To remove this once API migration is complete
export const METRIC_TYPE_VALUES_MAP: Record<MetricType, string> = {
export const METRIC_TYPE_VALUES_MAP = {
[MetricType.SUM]: 'Sum',
[MetricType.GAUGE]: 'Gauge',
[MetricType.HISTOGRAM]: 'Histogram',
@@ -43,14 +33,6 @@ export const METRIC_TYPE_VALUES_MAP: Record<MetricType, string> = {
[MetricType.EXPONENTIAL_HISTOGRAM]: 'ExponentialHistogram',
};
export const METRIC_TYPE_VIEW_VALUES_MAP: Record<MetrictypesTypeDTO, string> = {
[MetrictypesTypeDTO.sum]: 'Sum',
[MetrictypesTypeDTO.gauge]: 'Gauge',
[MetrictypesTypeDTO.histogram]: 'Histogram',
[MetrictypesTypeDTO.summary]: 'Summary',
[MetrictypesTypeDTO.exponentialhistogram]: 'ExponentialHistogram',
};
export const IS_METRIC_DETAILS_OPEN_KEY = 'isMetricDetailsOpen';
export const IS_INSPECT_MODAL_OPEN_KEY = 'isInspectModalOpen';
export const SELECTED_METRIC_NAME_KEY = 'selectedMetricName';

View File

@@ -2,7 +2,6 @@ import { useMemo } from 'react';
import { Color } from '@signozhq/design-tokens';
import { Tooltip, Typography } from 'antd';
import { ColumnType } from 'antd/es/table';
import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';
import {
MetricsListItemData,
MetricsListPayload,
@@ -22,7 +21,7 @@ import {
} from 'lucide-react';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { METRIC_TYPE_LABEL_MAP, METRIC_TYPE_VIEW_LABEL_MAP } from './constants';
import { METRIC_TYPE_LABEL_MAP } from './constants';
import MetricNameSearch from './MetricNameSearch';
import MetricTypeSearch from './MetricTypeSearch';
import { MetricsListItemRowData, TreemapTile, TreemapViewType } from './types';
@@ -144,66 +143,6 @@ export function MetricTypeRenderer({
);
}
export function MetricTypeViewRenderer({
type,
}: {
type: MetrictypesTypeDTO;
}): JSX.Element {
const [icon, color] = useMemo(() => {
switch (type) {
case MetrictypesTypeDTO.sum:
return [
<Diff key={type} size={12} color={Color.BG_ROBIN_500} />,
Color.BG_ROBIN_500,
];
case MetrictypesTypeDTO.gauge:
return [
<Gauge key={type} size={12} color={Color.BG_SAKURA_500} />,
Color.BG_SAKURA_500,
];
case MetrictypesTypeDTO.histogram:
return [
<BarChart2 key={type} size={12} color={Color.BG_SIENNA_500} />,
Color.BG_SIENNA_500,
];
case MetrictypesTypeDTO.summary:
return [
<BarChartHorizontal key={type} size={12} color={Color.BG_FOREST_500} />,
Color.BG_FOREST_500,
];
case MetrictypesTypeDTO.exponentialhistogram:
return [
<BarChart key={type} size={12} color={Color.BG_AQUA_500} />,
Color.BG_AQUA_500,
];
default:
return [null, ''];
}
}, [type]);
const metricTypeRendererStyle = useMemo(
() => ({
backgroundColor: `${color}33`,
border: `1px solid ${color}`,
color,
}),
[color],
);
const metricTypeRendererTextStyle = useMemo(() => ({ color, fontSize: 12 }), [
color,
]);
return (
<div className="metric-type-renderer" style={metricTypeRendererStyle}>
{icon}
<Typography.Text style={metricTypeRendererTextStyle}>
{METRIC_TYPE_VIEW_LABEL_MAP[type]}
</Typography.Text>
</div>
);
}
function ValidateRowValueWrapper({
value,
children,
@@ -221,9 +160,6 @@ export const formatNumberIntoHumanReadableFormat = (
num: number,
addPlusSign = true,
): string => {
if (!num) {
return '-';
}
function format(num: number, divisor: number, suffix: string): string {
const value = num / divisor;
return value % 1 === 0

Some files were not shown because too many files have changed in this diff Show More