Compare commits

..

2 Commits

Author SHA1 Message Date
Nikhil Soni
0160a526fa fix: switch to new derived attributes for ip filtering 2026-02-19 20:11:52 +05:30
Nikhil Soni
deeb690621 fix: add missing filtering for ip address for scalar data
In domain listing api for external api monitoring,
we have option to filter out the IP address but
it only handles timeseries and raw type data while
domain list handler returns scalar data.
2026-02-19 20:11:52 +05:30
179 changed files with 3347 additions and 8445 deletions

View File

@@ -48,15 +48,14 @@ jobs:
- role
- ttl
- alerts
- ingestionkeys
sqlstore-provider:
- postgres
- sqlite
clickhouse-version:
- 25.5.6
- 25.10.5
- 25.10.1
schema-migrator-version:
- v0.142.0
- v0.129.7
postgres-version:
- 15
if: |

View File

@@ -85,9 +85,6 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
func(_ licensing.Licensing) factory.ProviderFactory[gateway.Gateway, gateway.Config] {
return noopgateway.NewProviderFactory()
},
func(ps factory.ProviderSettings, q querier.Querier, a analytics.Analytics) querier.Handler {
return querier.NewHandler(ps, q, a)
},
)
if err != nil {
logger.ErrorContext(ctx, "failed to create signoz", "error", err)

View File

@@ -9,7 +9,6 @@ import (
"github.com/SigNoz/signoz/ee/authn/callbackauthn/oidccallbackauthn"
"github.com/SigNoz/signoz/ee/authn/callbackauthn/samlcallbackauthn"
"github.com/SigNoz/signoz/ee/authz/openfgaauthz"
eequerier "github.com/SigNoz/signoz/ee/querier"
"github.com/SigNoz/signoz/ee/authz/openfgaschema"
"github.com/SigNoz/signoz/ee/gateway/httpgateway"
enterpriselicensing "github.com/SigNoz/signoz/ee/licensing"
@@ -125,10 +124,6 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
func(licensing licensing.Licensing) factory.ProviderFactory[gateway.Gateway, gateway.Config] {
return httpgateway.NewProviderFactory(licensing)
},
func(ps factory.ProviderSettings, q querier.Querier, a analytics.Analytics) querier.Handler {
communityHandler := querier.NewHandler(ps, q, a)
return eequerier.NewHandler(ps, q, communityHandler)
},
)
if err != nil {

File diff suppressed because it is too large Load Diff

View File

@@ -155,7 +155,6 @@ The `handler.New` function ties the HTTP handler to OpenAPI metadata via `OpenAP
- **Request / RequestContentType**:
- `Request` is a Go type that describes the request body or form.
- `RequestContentType` is usually `"application/json"` or `"application/x-www-form-urlencoded"` (for callbacks like SAML).
- **RequestExamples**: An array of `handler.OpenAPIExample` that provide concrete request payloads in the generated spec. See [Adding request examples](#adding-request-examples) below.
- **Response / ResponseContentType**:
- `Response` is the Go type for the successful response payload.
- `ResponseContentType` is usually `"application/json"`; use `""` for responses without a body.
@@ -173,170 +172,8 @@ See existing examples in:
- `addUserRoutes` (for typical JSON request/response)
- `addSessionRoutes` (for form-encoded and redirect flows)
## OpenAPI schema details for request/response types
The OpenAPI spec is generated from the Go types you pass as `Request` and `Response` in `OpenAPIDef`. The following struct tags and interfaces control how those types appear in the generated schema.
### Adding request examples
Use the `RequestExamples` field in `OpenAPIDef` to provide concrete request payloads. Each example is a `handler.OpenAPIExample`:
```go
type OpenAPIExample struct {
Name string // unique key for the example (e.g. "traces_time_series")
Summary string // short description shown in docs (e.g. "Time series: count spans grouped by service")
Description string // optional longer description
Value any // the example payload, typically map[string]any
}
```
For reference, see `pkg/apiserver/signozapiserver/querier.go` which defines examples inline for the `/api/v5/query_range` endpoint:
```go
if err := router.Handle("/api/v5/query_range", handler.New(provider.authZ.ViewAccess(provider.querierHandler.QueryRange), handler.OpenAPIDef{
ID: "QueryRangeV5",
Tags: []string{"querier"},
Summary: "Query range",
Description: "Execute a composite query over a time range.",
Request: new(qbtypes.QueryRangeRequest),
RequestContentType: "application/json",
RequestExamples: []handler.OpenAPIExample{
{
Name: "traces_time_series",
Summary: "Time series: count spans grouped by service",
Value: map[string]any{
"schemaVersion": "v1",
"start": 1640995200000,
"end": 1640998800000,
"requestType": "time_series",
"compositeQuery": map[string]any{
"queries": []any{
map[string]any{
"type": "builder_query",
"spec": map[string]any{
"name": "A",
"signal": "traces",
// ...
},
},
},
},
},
},
// ... more examples
},
// ...
})).Methods(http.MethodPost).GetError(); err != nil {
return err
}
```
### `required` tag
Use `required:"true"` on struct fields where the property is expected to be **present** in the JSON payload. This is different from the zero value, a field can have its zero value (e.g. `0`, `""`, `false`) and still be required. The `required` tag means the key itself must exist in the JSON object.
```go
type ListItem struct {
...
}
type ListResponse struct {
List []ListItem `json:"list" required:"true" nullable:"true"`
Total uint64 `json:"total" required:"true"`
}
```
In this example, a response like `{"list": null, "total": 0}` is valid. Both keys are present (satisfying `required`), `total` has its zero value, and `list` is null (allowed by `nullable`). But `{"total": 0}` would violate the schema because the `list` key is missing.
### `nullable` tag
Use `nullable:"true"` on struct fields that can be `null` in the JSON payload. This is especially important for **slice and map fields** because in Go, the zero value for these types is `nil`, which serializes to `null` in JSON (not `[]` or `{}`).
Be explicit about the distinction:
- **Nullable list** (`nullable:"true"`): the field can be `null`. Use this when the Go code may return `nil` for the slice.
- **Non-nullable list** (no `nullable` tag): the field is always an array, never `null`. Ensure the Go code initializes it to an empty slice (e.g. `make([]T, 0)`) before serializing.
```go
// Non-nullable: Go code must ensure this is always an initialized slice.
type NonNullableExample struct {
Items []Item `json:"items" required:"true"`
}
```
When defining your types, ask yourself: "Can this field be `null` in the JSON response, or is it always an array/object?" If the Go code ever returns a `nil` slice or map, mark it `nullable:"true"`.
### `Enum()` method
For types that have a fixed set of acceptable values, implement the `Enum() []any` method. This generates an `enum` constraint in the JSON schema so the OpenAPI spec accurately restricts the values.
```go
type Signal struct {
valuer.String
}
var (
SignalTraces = Signal{valuer.NewString("traces")}
SignalLogs = Signal{valuer.NewString("logs")}
SignalMetrics = Signal{valuer.NewString("metrics")}
)
func (Signal) Enum() []any {
return []any{
SignalTraces,
SignalLogs,
SignalMetrics,
}
}
```
This produces the following in the generated OpenAPI spec:
```yaml
Signal:
enum:
- traces
- logs
- metrics
type: string
```
Every type with a known set of values **must** implement `Enum()`. Without it, the JSON schema will only show the base type (e.g. `string`) with no value constraints.
### `JSONSchema()` method (custom schema)
For types that need a completely custom JSON schema (for example, a field that accepts either a string or a number), implement the `jsonschema.Exposer` interface:
```go
var _ jsonschema.Exposer = Step{}
func (Step) JSONSchema() (jsonschema.Schema, error) {
s := jsonschema.Schema{}
s.WithDescription("Step interval. Accepts a duration string or seconds.")
strSchema := jsonschema.Schema{}
strSchema.WithType(jsonschema.String.Type())
strSchema.WithExamples("60s", "5m", "1h")
numSchema := jsonschema.Schema{}
numSchema.WithType(jsonschema.Number.Type())
numSchema.WithExamples(60, 300, 3600)
s.OneOf = []jsonschema.SchemaOrBool{
strSchema.ToSchemaOrBool(),
numSchema.ToSchemaOrBool(),
}
return s, nil
}
```
## What should I remember?
- **Keep handlers thin**: focus on HTTP concerns and delegate logic to modules/services.
- **Always register routes through `signozapiserver`** using `handler.New` and a complete `OpenAPIDef`.
- **Choose accurate request/response types** from the `types` packages so OpenAPI schemas are correct.
- **Add `required:"true"`** on fields where the key must be present in the JSON (this is about key presence, not about the zero value).
- **Add `nullable:"true"`** on fields that can be `null`. Pay special attention to slices and maps -- in Go these default to `nil` which serializes to `null`. If the field should always be an array, initialize it and do not mark it nullable.
- **Implement `Enum()`** on every type that has a fixed set of acceptable values so the JSON schema generates proper `enum` constraints.
- **Add request examples** via `RequestExamples` in `OpenAPIDef` for any non-trivial endpoint. See `pkg/apiserver/signozapiserver/querier.go` for reference.

View File

@@ -62,6 +62,10 @@ func (provider *provider) Stop(ctx context.Context) error {
return provider.openfgaServer.Stop(ctx)
}
func (provider *provider) Check(ctx context.Context, tuple *openfgav1.TupleKey) error {
return provider.openfgaServer.Check(ctx, tuple)
}
func (provider *provider) CheckWithTupleCreation(ctx context.Context, claims authtypes.Claims, orgID valuer.UUID, relation authtypes.Relation, typeable authtypes.Typeable, selectors []authtypes.Selector, roleSelectors []authtypes.Selector) error {
return provider.openfgaServer.CheckWithTupleCreation(ctx, claims, orgID, relation, typeable, selectors, roleSelectors)
}
@@ -70,8 +74,8 @@ func (provider *provider) CheckWithTupleCreationWithoutClaims(ctx context.Contex
return provider.openfgaServer.CheckWithTupleCreationWithoutClaims(ctx, orgID, relation, typeable, selectors, roleSelectors)
}
func (provider *provider) BatchCheck(ctx context.Context, tupleReq map[string]*openfgav1.TupleKey) (map[string]*authtypes.TupleKeyAuthorization, error) {
return provider.openfgaServer.BatchCheck(ctx, tupleReq)
func (provider *provider) BatchCheck(ctx context.Context, tuples []*openfgav1.TupleKey) error {
return provider.openfgaServer.BatchCheck(ctx, tuples)
}
func (provider *provider) ListObjects(ctx context.Context, subject string, relation authtypes.Relation, typeable authtypes.Typeable) ([]*authtypes.Object, error) {
@@ -171,6 +175,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 {
@@ -181,11 +187,6 @@ func (provider *provider) GetResources(_ context.Context) []*authtypes.Resource
}
func (provider *provider) GetObjects(ctx context.Context, orgID valuer.UUID, id valuer.UUID, relation authtypes.Relation) ([]*authtypes.Object, error) {
_, err := provider.licensing.GetActive(ctx, orgID)
if err != nil {
return nil, errors.New(errors.TypeLicenseUnavailable, errors.CodeLicenseUnavailable, "a valid license is not available").WithAdditional("this feature requires a valid license").WithAdditional(err.Error())
}
storableRole, err := provider.store.Get(ctx, orgID, id)
if err != nil {
return nil, err
@@ -197,7 +198,7 @@ func (provider *provider) GetObjects(ctx context.Context, orgID valuer.UUID, id
resourceObjects, err := provider.
ListObjects(
ctx,
authtypes.MustNewSubject(authtypes.TypeableRole, storableRole.Name, orgID, &authtypes.RelationAssignee),
authtypes.MustNewSubject(authtypes.TypeableRole, storableRole.ID.String(), orgID, &authtypes.RelationAssignee),
relation,
authtypes.MustNewTypeableFromType(resource.Type, resource.Name),
)
@@ -257,7 +258,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

@@ -2,10 +2,8 @@ package openfgaserver
import (
"context"
"strconv"
"github.com/SigNoz/signoz/pkg/authz"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/valuer"
openfgav1 "github.com/openfga/api/proto/openfga/v1"
@@ -30,34 +28,27 @@ func (server *Server) Stop(ctx context.Context) error {
return server.pkgAuthzService.Stop(ctx)
}
func (server *Server) Check(ctx context.Context, tuple *openfgav1.TupleKey) error {
return server.pkgAuthzService.Check(ctx, tuple)
}
func (server *Server) CheckWithTupleCreation(ctx context.Context, claims authtypes.Claims, orgID valuer.UUID, relation authtypes.Relation, typeable authtypes.Typeable, selectors []authtypes.Selector, _ []authtypes.Selector) error {
subject, err := authtypes.NewSubject(authtypes.TypeableUser, claims.UserID, orgID, nil)
if err != nil {
return err
}
tupleSlice, err := typeable.Tuples(subject, relation, selectors, orgID)
tuples, err := typeable.Tuples(subject, relation, selectors, orgID)
if err != nil {
return err
}
tuples := make(map[string]*openfgav1.TupleKey, len(tupleSlice))
for idx, tuple := range tupleSlice {
tuples[strconv.Itoa(idx)] = tuple
}
response, err := server.BatchCheck(ctx, tuples)
err = server.BatchCheck(ctx, tuples)
if err != nil {
return err
}
for _, resp := range response {
if resp.Authorized {
return nil
}
}
return errors.Newf(errors.TypeForbidden, authtypes.ErrCodeAuthZForbidden, "subjects are not authorized for requested access")
return nil
}
func (server *Server) CheckWithTupleCreationWithoutClaims(ctx context.Context, orgID valuer.UUID, relation authtypes.Relation, typeable authtypes.Typeable, selectors []authtypes.Selector, _ []authtypes.Selector) error {
@@ -66,32 +57,21 @@ func (server *Server) CheckWithTupleCreationWithoutClaims(ctx context.Context, o
return err
}
tupleSlice, err := typeable.Tuples(subject, relation, selectors, orgID)
tuples, err := typeable.Tuples(subject, relation, selectors, orgID)
if err != nil {
return err
}
tuples := make(map[string]*openfgav1.TupleKey, len(tupleSlice))
for idx, tuple := range tupleSlice {
tuples[strconv.Itoa(idx)] = tuple
}
response, err := server.BatchCheck(ctx, tuples)
err = server.BatchCheck(ctx, tuples)
if err != nil {
return err
}
for _, resp := range response {
if resp.Authorized {
return nil
}
}
return errors.Newf(errors.TypeForbidden, authtypes.ErrCodeAuthZForbidden, "subjects are not authorized for requested access")
return nil
}
func (server *Server) BatchCheck(ctx context.Context, tupleReq map[string]*openfgav1.TupleKey) (map[string]*authtypes.TupleKeyAuthorization, error) {
return server.pkgAuthzService.BatchCheck(ctx, tupleReq)
func (server *Server) BatchCheck(ctx context.Context, tuples []*openfgav1.TupleKey) error {
return server.pkgAuthzService.BatchCheck(ctx, tuples)
}
func (server *Server) ListObjects(ctx context.Context, subject string, relation authtypes.Relation, typeable authtypes.Typeable) ([]*authtypes.Object, error) {

View File

@@ -220,7 +220,6 @@ func (module *module) MustGetManagedRoleTransactions() map[string][]*authtypes.T
return map[string][]*authtypes.Transaction{
roletypes.SigNozAnonymousRoleName: {
{
ID: valuer.GenerateUUID(),
Relation: authtypes.RelationRead,
Object: *authtypes.MustNewObject(
authtypes.Resource{

View File

@@ -1,178 +0,0 @@
package querier
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"runtime/debug"
anomalyV2 "github.com/SigNoz/signoz/ee/anomaly"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/http/render"
"github.com/SigNoz/signoz/pkg/querier"
"github.com/SigNoz/signoz/pkg/types/authtypes"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/valuer"
)
type handler struct {
set factory.ProviderSettings
querier querier.Querier
community querier.Handler
}
func NewHandler(set factory.ProviderSettings, querier querier.Querier, community querier.Handler) querier.Handler {
return &handler{
set: set,
querier: querier,
community: community,
}
}
func (h *handler) QueryRange(rw http.ResponseWriter, req *http.Request) {
bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to read request body: %v", err))
return
}
req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
ctx := req.Context()
claims, err := authtypes.ClaimsFromContext(ctx)
if err != nil {
render.Error(rw, err)
return
}
var queryRangeRequest qbtypes.QueryRangeRequest
if err := json.NewDecoder(req.Body).Decode(&queryRangeRequest); err != nil {
render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to decode request body: %v", err))
return
}
defer func() {
if r := recover(); r != nil {
stackTrace := string(debug.Stack())
queryJSON, _ := json.Marshal(queryRangeRequest)
h.set.Logger.ErrorContext(ctx, "panic in QueryRange",
"error", r,
"user", claims.UserID,
"payload", string(queryJSON),
"stacktrace", stackTrace,
)
render.Error(rw, errors.NewInternalf(
errors.CodeInternal,
"Something went wrong on our end. It's not you, it's us. Our team is notified about it. Reach out to support if issue persists.",
))
}
}()
if err := queryRangeRequest.Validate(); err != nil {
render.Error(rw, err)
return
}
orgID, err := valuer.NewUUID(claims.OrgID)
if err != nil {
render.Error(rw, err)
return
}
if anomalyQuery, ok := queryRangeRequest.IsAnomalyRequest(); ok {
anomalies, err := h.handleAnomalyQuery(ctx, orgID, anomalyQuery, queryRangeRequest)
if err != nil {
render.Error(rw, errors.NewInternalf(errors.CodeInternal, "failed to get anomalies: %v", err))
return
}
results := []any{}
for _, item := range anomalies.Results {
results = append(results, item)
}
// Build step intervals from the anomaly query
stepIntervals := make(map[string]uint64)
if anomalyQuery.StepInterval.Duration > 0 {
stepIntervals[anomalyQuery.Name] = uint64(anomalyQuery.StepInterval.Duration.Seconds())
}
finalResp := &qbtypes.QueryRangeResponse{
Type: queryRangeRequest.RequestType,
Data: qbtypes.QueryData{
Results: results,
},
Meta: qbtypes.ExecStats{
StepIntervals: stepIntervals,
},
}
render.Success(rw, http.StatusOK, finalResp)
return
}
// regular query range request, delegate to community handler
req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
h.community.QueryRange(rw, req)
}
func (h *handler) QueryRawStream(rw http.ResponseWriter, req *http.Request) {
h.community.QueryRawStream(rw, req)
}
func (h *handler) ReplaceVariables(rw http.ResponseWriter, req *http.Request) {
h.community.ReplaceVariables(rw, req)
}
func extractSeasonality(anomalyQuery *qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]) anomalyV2.Seasonality {
for _, fn := range anomalyQuery.Functions {
if fn.Name == qbtypes.FunctionNameAnomaly {
for _, arg := range fn.Args {
if arg.Name == "seasonality" {
if seasonalityStr, ok := arg.Value.(string); ok {
switch seasonalityStr {
case "weekly":
return anomalyV2.SeasonalityWeekly
case "hourly":
return anomalyV2.SeasonalityHourly
}
}
}
}
}
}
return anomalyV2.SeasonalityDaily // default
}
func (h *handler) createAnomalyProvider(seasonality anomalyV2.Seasonality) anomalyV2.Provider {
switch seasonality {
case anomalyV2.SeasonalityWeekly:
return anomalyV2.NewWeeklyProvider(
anomalyV2.WithQuerier[*anomalyV2.WeeklyProvider](h.querier),
anomalyV2.WithLogger[*anomalyV2.WeeklyProvider](h.set.Logger),
)
case anomalyV2.SeasonalityHourly:
return anomalyV2.NewHourlyProvider(
anomalyV2.WithQuerier[*anomalyV2.HourlyProvider](h.querier),
anomalyV2.WithLogger[*anomalyV2.HourlyProvider](h.set.Logger),
)
default:
return anomalyV2.NewDailyProvider(
anomalyV2.WithQuerier[*anomalyV2.DailyProvider](h.querier),
anomalyV2.WithLogger[*anomalyV2.DailyProvider](h.set.Logger),
)
}
}
func (h *handler) handleAnomalyQuery(ctx context.Context, orgID valuer.UUID, anomalyQuery *qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation], queryRangeRequest qbtypes.QueryRangeRequest) (*anomalyV2.AnomaliesResponse, error) {
seasonality := extractSeasonality(anomalyQuery)
provider := h.createAnomalyProvider(seasonality)
return provider.GetAnomalies(ctx, orgID, &anomalyV2.AnomaliesRequest{Params: queryRangeRequest})
}

View File

@@ -2,13 +2,17 @@ package api
import (
"net/http"
"net/http/httputil"
"time"
"github.com/SigNoz/signoz/ee/licensing/httplicensing"
"github.com/SigNoz/signoz/ee/query-service/integrations/gateway"
"github.com/SigNoz/signoz/ee/query-service/usage"
"github.com/SigNoz/signoz/pkg/alertmanager"
"github.com/SigNoz/signoz/pkg/global"
"github.com/SigNoz/signoz/pkg/http/handler"
"github.com/SigNoz/signoz/pkg/http/middleware"
querierAPI "github.com/SigNoz/signoz/pkg/querier"
baseapp "github.com/SigNoz/signoz/pkg/query-service/app"
"github.com/SigNoz/signoz/pkg/query-service/app/cloudintegrations"
"github.com/SigNoz/signoz/pkg/query-service/app/integrations"
@@ -29,6 +33,7 @@ type APIHandlerOptions struct {
IntegrationsController *integrations.Controller
CloudIntegrationsController *cloudintegrations.Controller
LogsParsingPipelineController *logparsingpipeline.LogParsingPipelineController
Gateway *httputil.ReverseProxy
GatewayUrl string
// Querier Influx Interval
FluxInterval time.Duration
@@ -52,6 +57,7 @@ func NewAPIHandler(opts APIHandlerOptions, signoz *signoz.SigNoz, config signoz.
AlertmanagerAPI: alertmanager.NewAPI(signoz.Alertmanager),
LicensingAPI: httplicensing.NewLicensingAPI(signoz.Licensing),
Signoz: signoz,
QuerierAPI: querierAPI.NewAPI(signoz.Instrumentation.ToProviderSettings(), signoz.Querier, signoz.Analytics),
QueryParserAPI: queryparser.NewAPI(signoz.Instrumentation.ToProviderSettings(), signoz.QueryParser),
}, config)
@@ -74,6 +80,10 @@ func (ah *APIHandler) UM() *usage.Manager {
return ah.opts.UsageManager
}
func (ah *APIHandler) Gateway() *httputil.ReverseProxy {
return ah.opts.Gateway
}
// RegisterRoutes registers routes for this handler on the given router
func (ah *APIHandler) RegisterRoutes(router *mux.Router, am *middleware.AuthZ) {
// note: add ee override methods first
@@ -96,6 +106,17 @@ func (ah *APIHandler) RegisterRoutes(router *mux.Router, am *middleware.AuthZ) {
// v4
router.HandleFunc("/api/v4/query_range", am.ViewAccess(ah.queryRangeV4)).Methods(http.MethodPost)
// v5
router.Handle("/api/v5/query_range", handler.New(
am.ViewAccess(ah.queryRangeV5),
querierAPI.QueryRangeV5OpenAPIDef,
)).Methods(http.MethodPost)
router.HandleFunc("/api/v5/substitute_vars", am.ViewAccess(ah.QuerierAPI.ReplaceVariables)).Methods(http.MethodPost)
// Gateway
router.PathPrefix(gateway.RoutePrefix).HandlerFunc(am.EditAccess(ah.ServeGatewayHTTP))
ah.APIHandler.RegisterRoutes(router, am)
}

View File

@@ -0,0 +1,58 @@
package api
import (
"net/http"
"strings"
"github.com/SigNoz/signoz/ee/query-service/integrations/gateway"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/http/render"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
func (ah *APIHandler) ServeGatewayHTTP(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
claims, err := authtypes.ClaimsFromContext(ctx)
if err != nil {
render.Error(rw, err)
return
}
orgID, err := valuer.NewUUID(claims.OrgID)
if err != nil {
render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "orgId is invalid"))
return
}
validPath := false
for _, allowedPrefix := range gateway.AllowedPrefix {
if strings.HasPrefix(req.URL.Path, gateway.RoutePrefix+allowedPrefix) {
validPath = true
break
}
}
if !validPath {
rw.WriteHeader(http.StatusNotFound)
return
}
license, err := ah.Signoz.Licensing.GetActive(ctx, orgID)
if err != nil {
render.Error(rw, err)
return
}
//Create headers
var licenseKey string
if license != nil {
licenseKey = license.Key
}
req.Header.Set("X-Signoz-Cloud-Api-Key", licenseKey)
req.Header.Set("X-Consumer-Username", "lid:00000000-0000-0000-0000-000000000000")
req.Header.Set("X-Consumer-Groups", "ns:default")
ah.Gateway().ServeHTTP(rw, req)
}

View File

@@ -2,11 +2,16 @@ package api
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"runtime/debug"
anomalyV2 "github.com/SigNoz/signoz/ee/anomaly"
"github.com/SigNoz/signoz/ee/query-service/anomaly"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/http/render"
baseapp "github.com/SigNoz/signoz/pkg/query-service/app"
"github.com/SigNoz/signoz/pkg/query-service/app/queryBuilder"
@@ -15,6 +20,8 @@ import (
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/valuer"
"go.uber.org/zap"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
)
func (aH *APIHandler) queryRangeV4(w http.ResponseWriter, r *http.Request) {
@@ -137,3 +144,140 @@ func (aH *APIHandler) queryRangeV4(w http.ResponseWriter, r *http.Request) {
}
}
func extractSeasonality(anomalyQuery *qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]) anomalyV2.Seasonality {
for _, fn := range anomalyQuery.Functions {
if fn.Name == qbtypes.FunctionNameAnomaly {
for _, arg := range fn.Args {
if arg.Name == "seasonality" {
if seasonalityStr, ok := arg.Value.(string); ok {
switch seasonalityStr {
case "weekly":
return anomalyV2.SeasonalityWeekly
case "hourly":
return anomalyV2.SeasonalityHourly
}
}
}
}
}
}
return anomalyV2.SeasonalityDaily // default
}
func createAnomalyProvider(aH *APIHandler, seasonality anomalyV2.Seasonality) anomalyV2.Provider {
switch seasonality {
case anomalyV2.SeasonalityWeekly:
return anomalyV2.NewWeeklyProvider(
anomalyV2.WithQuerier[*anomalyV2.WeeklyProvider](aH.Signoz.Querier),
anomalyV2.WithLogger[*anomalyV2.WeeklyProvider](aH.Signoz.Instrumentation.Logger()),
)
case anomalyV2.SeasonalityHourly:
return anomalyV2.NewHourlyProvider(
anomalyV2.WithQuerier[*anomalyV2.HourlyProvider](aH.Signoz.Querier),
anomalyV2.WithLogger[*anomalyV2.HourlyProvider](aH.Signoz.Instrumentation.Logger()),
)
default:
return anomalyV2.NewDailyProvider(
anomalyV2.WithQuerier[*anomalyV2.DailyProvider](aH.Signoz.Querier),
anomalyV2.WithLogger[*anomalyV2.DailyProvider](aH.Signoz.Instrumentation.Logger()),
)
}
}
func (aH *APIHandler) handleAnomalyQuery(ctx context.Context, orgID valuer.UUID, anomalyQuery *qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation], queryRangeRequest qbtypes.QueryRangeRequest) (*anomalyV2.AnomaliesResponse, error) {
seasonality := extractSeasonality(anomalyQuery)
provider := createAnomalyProvider(aH, seasonality)
return provider.GetAnomalies(ctx, orgID, &anomalyV2.AnomaliesRequest{Params: queryRangeRequest})
}
func (aH *APIHandler) queryRangeV5(rw http.ResponseWriter, req *http.Request) {
bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to read request body: %v", err))
return
}
req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
ctx := req.Context()
claims, err := authtypes.ClaimsFromContext(ctx)
if err != nil {
render.Error(rw, err)
return
}
var queryRangeRequest qbtypes.QueryRangeRequest
if err := json.NewDecoder(req.Body).Decode(&queryRangeRequest); err != nil {
render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "failed to decode request body: %v", err))
return
}
defer func() {
if r := recover(); r != nil {
stackTrace := string(debug.Stack())
queryJSON, _ := json.Marshal(queryRangeRequest)
aH.Signoz.Instrumentation.Logger().ErrorContext(ctx, "panic in QueryRange",
"error", r,
"user", claims.UserID,
"payload", string(queryJSON),
"stacktrace", stackTrace,
)
render.Error(rw, errors.NewInternalf(
errors.CodeInternal,
"Something went wrong on our end. It's not you, it's us. Our team is notified about it. Reach out to support if issue persists.",
))
}
}()
if err := queryRangeRequest.Validate(); err != nil {
render.Error(rw, err)
return
}
orgID, err := valuer.NewUUID(claims.OrgID)
if err != nil {
render.Error(rw, err)
return
}
if anomalyQuery, ok := queryRangeRequest.IsAnomalyRequest(); ok {
anomalies, err := aH.handleAnomalyQuery(ctx, orgID, anomalyQuery, queryRangeRequest)
if err != nil {
render.Error(rw, errors.NewInternalf(errors.CodeInternal, "failed to get anomalies: %v", err))
return
}
results := []any{}
for _, item := range anomalies.Results {
results = append(results, item)
}
// Build step intervals from the anomaly query
stepIntervals := make(map[string]uint64)
if anomalyQuery.StepInterval.Duration > 0 {
stepIntervals[anomalyQuery.Name] = uint64(anomalyQuery.StepInterval.Duration.Seconds())
}
finalResp := &qbtypes.QueryRangeResponse{
Type: queryRangeRequest.RequestType,
Data: qbtypes.QueryData{
Results: results,
},
Meta: qbtypes.ExecStats{
StepIntervals: stepIntervals,
},
}
render.Success(rw, http.StatusOK, finalResp)
return
} else {
// regular query range request, let the querier handle it
req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
aH.QuerierAPI.QueryRange(rw, req)
}
}

View File

@@ -19,6 +19,7 @@ import (
"github.com/gorilla/handlers"
"github.com/SigNoz/signoz/ee/query-service/app/api"
"github.com/SigNoz/signoz/ee/query-service/integrations/gateway"
"github.com/SigNoz/signoz/ee/query-service/rules"
"github.com/SigNoz/signoz/ee/query-service/usage"
"github.com/SigNoz/signoz/pkg/alertmanager"
@@ -71,6 +72,11 @@ type Server struct {
// NewServer creates and initializes Server
func NewServer(config signoz.Config, signoz *signoz.SigNoz) (*Server, error) {
gatewayProxy, err := gateway.NewProxy(config.Gateway.URL.String(), gateway.RoutePrefix)
if err != nil {
return nil, err
}
cacheForTraceDetail, err := memorycache.New(context.TODO(), signoz.Instrumentation.ToProviderSettings(), cache.Config{
Provider: "memory",
Memory: cache.Memory{
@@ -164,6 +170,7 @@ func NewServer(config signoz.Config, signoz *signoz.SigNoz) (*Server, error) {
CloudIntegrationsController: cloudIntegrationsController,
LogsParsingPipelineController: logParsingPipelineController,
FluxInterval: config.Querier.FluxInterval,
Gateway: gatewayProxy,
GatewayUrl: config.Gateway.URL.String(),
GlobalConfig: config.Global,
}
@@ -233,6 +240,7 @@ func (s *Server) createPublicServer(apiHandler *api.APIHandler, web web.Web) (*h
apiHandler.RegisterQueryRangeV3Routes(r, am)
apiHandler.RegisterInfraMetricsRoutes(r, am)
apiHandler.RegisterQueryRangeV4Routes(r, am)
apiHandler.RegisterQueryRangeV5Routes(r, am)
apiHandler.RegisterWebSocketPaths(r, am)
apiHandler.RegisterMessagingQueuesRoutes(r, am)
apiHandler.RegisterThirdPartyApiRoutes(r, am)

View File

@@ -0,0 +1,9 @@
package gateway
import (
"net/http/httputil"
)
func NewNoopProxy() (*httputil.ReverseProxy, error) {
return &httputil.ReverseProxy{}, nil
}

View File

@@ -0,0 +1,66 @@
package gateway
import (
"net/http"
"net/http/httputil"
"net/url"
"path"
"strings"
)
var (
RoutePrefix string = "/api/gateway"
AllowedPrefix []string = []string{"/v1/workspaces/me", "/v2/profiles/me", "/v2/deployments/me"}
)
type proxy struct {
url *url.URL
stripPath string
}
func NewProxy(u string, stripPath string) (*httputil.ReverseProxy, error) {
url, err := url.Parse(u)
if err != nil {
return nil, err
}
proxy := &proxy{url: url, stripPath: stripPath}
return &httputil.ReverseProxy{
Rewrite: proxy.rewrite,
ModifyResponse: proxy.modifyResponse,
ErrorHandler: proxy.errorHandler,
}, nil
}
func (p *proxy) rewrite(pr *httputil.ProxyRequest) {
pr.SetURL(p.url)
pr.SetXForwarded()
pr.Out.URL.Path = cleanPath(strings.ReplaceAll(pr.Out.URL.Path, p.stripPath, ""))
}
func (p *proxy) modifyResponse(res *http.Response) error {
return nil
}
func (p *proxy) errorHandler(rw http.ResponseWriter, req *http.Request, err error) {
rw.WriteHeader(http.StatusBadGateway)
}
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
if p[len(p)-1] == '/' && np != "/" {
if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
np = p
} else {
np += "/"
}
}
return np
}

View File

@@ -0,0 +1,61 @@
package gateway
import (
"context"
"net/http"
"net/http/httputil"
"net/url"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestProxyRewrite(t *testing.T) {
testCases := []struct {
name string
url *url.URL
stripPath string
in *url.URL
expected *url.URL
}{
{
name: "SamePathAdded",
url: &url.URL{Scheme: "http", Host: "backend", Path: "/path1"},
stripPath: "/strip",
in: &url.URL{Scheme: "http", Host: "localhost", Path: "/strip/path1"},
expected: &url.URL{Scheme: "http", Host: "backend", Path: "/path1/path1"},
},
{
name: "NoStripPathInput",
url: &url.URL{Scheme: "http", Host: "backend"},
stripPath: "",
in: &url.URL{Scheme: "http", Host: "localhost", Path: "/strip/path1"},
expected: &url.URL{Scheme: "http", Host: "backend", Path: "/strip/path1"},
},
{
name: "NoStripPathPresentInReq",
url: &url.URL{Scheme: "http", Host: "backend"},
stripPath: "/not-found",
in: &url.URL{Scheme: "http", Host: "localhost", Path: "/strip/path1"},
expected: &url.URL{Scheme: "http", Host: "backend", Path: "/strip/path1"},
},
}
for _, tc := range testCases {
proxy, err := NewProxy(tc.url.String(), tc.stripPath)
require.NoError(t, err)
inReq, err := http.NewRequest(http.MethodGet, tc.in.String(), nil)
require.NoError(t, err)
proxyReq := &httputil.ProxyRequest{
In: inReq,
Out: inReq.Clone(context.Background()),
}
proxy.Rewrite(proxyReq)
assert.Equal(t, tc.expected.Host, proxyReq.Out.URL.Host)
assert.Equal(t, tc.expected.Scheme, proxyReq.Out.URL.Scheme)
assert.Equal(t, tc.expected.Path, proxyReq.Out.URL.Path)
assert.Equal(t, tc.expected.Query(), proxyReq.Out.URL.Query())
}
}

View File

@@ -3,7 +3,6 @@ package httpzeus
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/url"
@@ -11,7 +10,6 @@ import (
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/http/client"
"github.com/SigNoz/signoz/pkg/types/zeustypes"
"github.com/SigNoz/signoz/pkg/zeus"
"github.com/tidwall/gjson"
)
@@ -121,13 +119,8 @@ func (provider *Provider) PutMeters(ctx context.Context, key string, data []byte
return err
}
func (provider *Provider) PutProfile(ctx context.Context, key string, profile *zeustypes.PostableProfile) error {
body, err := json.Marshal(profile)
if err != nil {
return err
}
_, err = provider.do(
func (provider *Provider) PutProfile(ctx context.Context, key string, body []byte) error {
_, err := provider.do(
ctx,
provider.config.URL.JoinPath("/v2/profiles/me"),
http.MethodPut,
@@ -138,15 +131,10 @@ func (provider *Provider) PutProfile(ctx context.Context, key string, profile *z
return err
}
func (provider *Provider) PutHost(ctx context.Context, key string, host *zeustypes.PostableHost) error {
body, err := json.Marshal(host)
if err != nil {
return err
}
_, err = provider.do(
func (provider *Provider) PutHost(ctx context.Context, key string, body []byte) error {
_, err := provider.do(
ctx,
provider.config.URL.JoinPath("/v2/deployments/me/host"),
provider.config.URL.JoinPath("/v2/deployments/me/hosts"),
http.MethodPut,
key,
body,
@@ -181,28 +169,21 @@ func (provider *Provider) do(ctx context.Context, url *url.URL, method string, k
return body, nil
}
errorMessage := gjson.GetBytes(body, "error").String()
if errorMessage == "" {
errorMessage = "an unknown error occurred"
}
return nil, provider.errFromStatusCode(response.StatusCode, errorMessage)
return nil, provider.errFromStatusCode(response.StatusCode)
}
// This can be taken down to the client package
func (provider *Provider) errFromStatusCode(statusCode int, errorMessage string) error {
func (provider *Provider) errFromStatusCode(statusCode int) error {
switch statusCode {
case http.StatusBadRequest:
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, errorMessage)
return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "bad request")
case http.StatusUnauthorized:
return errors.New(errors.TypeUnauthenticated, errors.CodeUnauthenticated, errorMessage)
return errors.Newf(errors.TypeUnauthenticated, errors.CodeUnauthenticated, "unauthenticated")
case http.StatusForbidden:
return errors.New(errors.TypeForbidden, errors.CodeForbidden, errorMessage)
return errors.Newf(errors.TypeForbidden, errors.CodeForbidden, "forbidden")
case http.StatusNotFound:
return errors.New(errors.TypeNotFound, errors.CodeNotFound, errorMessage)
case http.StatusConflict:
return errors.New(errors.TypeAlreadyExists, errors.CodeAlreadyExists, errorMessage)
return errors.Newf(errors.TypeNotFound, errors.CodeNotFound, "not found")
}
return errors.New(errors.TypeInternal, errors.CodeInternal, errorMessage)
return errors.Newf(errors.TypeInternal, errors.CodeInternal, "internal")
}

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

@@ -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

@@ -0,0 +1,29 @@
import { GatewayApiV1Instance } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
import {
CreateIngestionKeyProps,
IngestionKeyProps,
} from 'types/api/ingestionKeys/types';
const createIngestionKey = async (
props: CreateIngestionKeyProps,
): Promise<SuccessResponse<IngestionKeyProps> | ErrorResponse> => {
try {
const response = await GatewayApiV1Instance.post('/workspaces/me/keys', {
...props,
});
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};
export default createIngestionKey;

View File

@@ -0,0 +1,26 @@
import { GatewayApiV1Instance } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { AllIngestionKeyProps } from 'types/api/ingestionKeys/types';
const deleteIngestionKey = async (
id: string,
): Promise<SuccessResponse<AllIngestionKeyProps> | ErrorResponse> => {
try {
const response = await GatewayApiV1Instance.delete(
`/workspaces/me/keys/${id}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};
export default deleteIngestionKey;

View File

@@ -0,0 +1,21 @@
import { GatewayApiV1Instance } from 'api';
import { AxiosResponse } from 'axios';
import {
AllIngestionKeyProps,
GetIngestionKeyProps,
} from 'types/api/ingestionKeys/types';
export const getAllIngestionKeys = (
props: GetIngestionKeyProps,
): Promise<AxiosResponse<AllIngestionKeyProps>> => {
// eslint-disable-next-line @typescript-eslint/naming-convention
const { search, per_page, page } = props;
const BASE_URL = '/workspaces/me/keys';
const URL_QUERY_PARAMS =
search && search.length > 0
? `/search?name=${search}&page=1&per_page=100`
: `?page=${page}&per_page=${per_page}`;
return GatewayApiV1Instance.get(`${BASE_URL}${URL_QUERY_PARAMS}`);
};

View File

@@ -0,0 +1,65 @@
/* eslint-disable @typescript-eslint/no-throw-literal */
import { GatewayApiV1Instance } from 'api';
import axios from 'axios';
import {
AddLimitProps,
LimitSuccessProps,
} from 'types/api/ingestionKeys/limits/types';
interface SuccessResponse<T> {
statusCode: number;
error: null;
message: string;
payload: T;
}
interface ErrorResponse {
statusCode: number;
error: string;
message: string;
payload: null;
}
const createLimitForIngestionKey = async (
props: AddLimitProps,
): Promise<SuccessResponse<LimitSuccessProps> | ErrorResponse> => {
try {
const response = await GatewayApiV1Instance.post(
`/workspaces/me/keys/${props.keyID}/limits`,
{
...props,
},
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data.data,
};
} catch (error) {
if (axios.isAxiosError(error)) {
// Axios error
const errResponse: ErrorResponse = {
statusCode: error.response?.status || 500,
error: error.response?.data?.error,
message: error.response?.data?.status || 'An error occurred',
payload: null,
};
throw errResponse;
} else {
// Non-Axios error
const errResponse: ErrorResponse = {
statusCode: 500,
error: 'Unknown error',
message: 'An unknown error occurred',
payload: null,
};
throw errResponse;
}
}
};
export default createLimitForIngestionKey;

View File

@@ -0,0 +1,26 @@
import { GatewayApiV1Instance } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { AllIngestionKeyProps } from 'types/api/ingestionKeys/types';
const deleteLimitsForIngestionKey = async (
id: string,
): Promise<SuccessResponse<AllIngestionKeyProps> | ErrorResponse> => {
try {
const response = await GatewayApiV1Instance.delete(
`/workspaces/me/limits/${id}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};
export default deleteLimitsForIngestionKey;

View File

@@ -0,0 +1,65 @@
/* eslint-disable @typescript-eslint/no-throw-literal */
import { GatewayApiV1Instance } from 'api';
import axios from 'axios';
import {
LimitSuccessProps,
UpdateLimitProps,
} from 'types/api/ingestionKeys/limits/types';
interface SuccessResponse<T> {
statusCode: number;
error: null;
message: string;
payload: T;
}
interface ErrorResponse {
statusCode: number;
error: string;
message: string;
payload: null;
}
const updateLimitForIngestionKey = async (
props: UpdateLimitProps,
): Promise<SuccessResponse<LimitSuccessProps> | ErrorResponse> => {
try {
const response = await GatewayApiV1Instance.patch(
`/workspaces/me/limits/${props.limitID}`,
{
config: props.config,
},
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data.data,
};
} catch (error) {
if (axios.isAxiosError(error)) {
// Axios error
const errResponse: ErrorResponse = {
statusCode: error.response?.status || 500,
error: error.response?.data?.error,
message: error.response?.data?.status || 'An error occurred',
payload: null,
};
throw errResponse;
} else {
// Non-Axios error
const errResponse: ErrorResponse = {
statusCode: 500,
error: 'Unknown error',
message: 'An unknown error occurred',
payload: null,
};
throw errResponse;
}
}
};
export default updateLimitForIngestionKey;

View File

@@ -0,0 +1,32 @@
import { GatewayApiV1Instance } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError } from 'axios';
import { ErrorResponse, SuccessResponse } from 'types/api';
import {
IngestionKeysPayloadProps,
UpdateIngestionKeyProps,
} from 'types/api/ingestionKeys/types';
const updateIngestionKey = async (
props: UpdateIngestionKeyProps,
): Promise<SuccessResponse<IngestionKeysPayloadProps> | ErrorResponse> => {
try {
const response = await GatewayApiV1Instance.patch(
`/workspaces/me/keys/${props.id}`,
{
...props.data,
},
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};
export default updateIngestionKey;

View File

@@ -4,6 +4,8 @@ export const apiV2 = '/api/v2/';
export const apiV3 = '/api/v3/';
export const apiV4 = '/api/v4/';
export const apiV5 = '/api/v5/';
export const gatewayApiV1 = '/api/gateway/v1/';
export const gatewayApiV2 = '/api/gateway/v2/';
export const apiAlertManager = '/api/alertmanager/';
export default apiV1;

View File

@@ -0,0 +1,7 @@
import { GatewayApiV2Instance as axios } from 'api';
import { AxiosResponse } from 'axios';
import { DeploymentsDataProps } from 'types/api/customDomain/types';
export const getDeploymentsData = (): Promise<
AxiosResponse<DeploymentsDataProps>
> => axios.get(`/deployments/me`);

View File

@@ -0,0 +1,16 @@
import { GatewayApiV2Instance as axios } from 'api';
import { AxiosError } from 'axios';
import { SuccessResponse } from 'types/api';
import {
PayloadProps,
UpdateCustomDomainProps,
} from 'types/api/customDomain/types';
const updateSubDomainAPI = async (
props: UpdateCustomDomainProps,
): Promise<SuccessResponse<PayloadProps> | AxiosError> =>
axios.put(`/deployments/me/host`, {
...props.data,
});
export default updateSubDomainAPI;

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

@@ -1,200 +0,0 @@
/**
* ! Do not edit manually
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'yarn generate:api'
* SigNoz
*/
import type {
InvalidateOptions,
MutationFunction,
QueryClient,
QueryFunction,
QueryKey,
UseMutationOptions,
UseMutationResult,
UseQueryOptions,
UseQueryResult,
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import type {
AuthtypesTransactionDTO,
AuthzCheck200,
AuthzResources200,
RenderErrorResponseDTO,
} from '../sigNoz.schemas';
type AwaitedInput<T> = PromiseLike<T> | T;
type Awaited<O> = O extends AwaitedInput<infer T> ? T : never;
/**
* Checks if the authenticated user has permissions for given transactions
* @summary Check permissions
*/
export const authzCheck = (
authtypesTransactionDTO: BodyType<AuthtypesTransactionDTO[]>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<AuthzCheck200>({
url: `/api/v1/authz/check`,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: authtypesTransactionDTO,
signal,
});
};
export const getAuthzCheckMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
TContext
> => {
const mutationKey = ['authzCheck'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof authzCheck>>,
{ data: BodyType<AuthtypesTransactionDTO[]> }
> = (props) => {
const { data } = props ?? {};
return authzCheck(data);
};
return { mutationFn, ...mutationOptions };
};
export type AuthzCheckMutationResult = NonNullable<
Awaited<ReturnType<typeof authzCheck>>
>;
export type AuthzCheckMutationBody = BodyType<AuthtypesTransactionDTO[]>;
export type AuthzCheckMutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Check permissions
*/
export const useAuthzCheck = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<AuthtypesTransactionDTO[]> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof authzCheck>>,
TError,
{ data: BodyType<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
> => {
@@ -682,7 +678,7 @@ export const useUpdateIngestionKeyLimit = <
* @summary Search ingestion keys for workspace
*/
export const searchIngestionKeys = (
params: SearchIngestionKeysParams,
params?: SearchIngestionKeysParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<SearchIngestionKeys200>({
@@ -696,17 +692,14 @@ 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,
params?: SearchIngestionKeysParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof searchIngestionKeys>>,
@@ -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,9 +735,9 @@ export type SearchIngestionKeysQueryError = ErrorType<RenderErrorResponseDTO>;
export function useSearchIngestionKeys<
TData = Awaited<ReturnType<typeof searchIngestionKeys>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
params: SearchIngestionKeysParams,
params?: SearchIngestionKeysParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof searchIngestionKeys>>,
@@ -769,7 +762,7 @@ export function useSearchIngestionKeys<
*/
export const invalidateSearchIngestionKeys = async (
queryClient: QueryClient,
params: SearchIngestionKeysParams,
params?: SearchIngestionKeysParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(

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

@@ -1,192 +0,0 @@
/**
* ! Do not edit manually
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'yarn generate:api'
* SigNoz
*/
import type {
MutationFunction,
UseMutationOptions,
UseMutationResult,
} from 'react-query';
import { useMutation } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import type {
Querybuildertypesv5QueryRangeRequestDTO,
QueryRangeV5200,
RenderErrorResponseDTO,
ReplaceVariables200,
} from '../sigNoz.schemas';
type AwaitedInput<T> = PromiseLike<T> | T;
type Awaited<O> = O extends AwaitedInput<infer T> ? T : never;
/**
* Execute a composite query over a time range. Supports builder queries (traces, logs, metrics), formulas, trace operators, PromQL, and ClickHouse SQL.
* @summary Query range
*/
export const queryRangeV5 = (
querybuildertypesv5QueryRangeRequestDTO: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<QueryRangeV5200>({
url: `/api/v5/query_range`,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: querybuildertypesv5QueryRangeRequestDTO,
signal,
});
};
export const getQueryRangeV5MutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
> => {
const mutationKey = ['queryRangeV5'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof queryRangeV5>>,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> }
> = (props) => {
const { data } = props ?? {};
return queryRangeV5(data);
};
return { mutationFn, ...mutationOptions };
};
export type QueryRangeV5MutationResult = NonNullable<
Awaited<ReturnType<typeof queryRangeV5>>
>;
export type QueryRangeV5MutationBody = BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
export type QueryRangeV5MutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Query range
*/
export const useQueryRangeV5 = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
> => {
const mutationOptions = getQueryRangeV5MutationOptions(options);
return useMutation(mutationOptions);
};
/**
* Replace variables in a query
* @summary Replace variables
*/
export const replaceVariables = (
querybuildertypesv5QueryRangeRequestDTO: BodyType<Querybuildertypesv5QueryRangeRequestDTO>,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ReplaceVariables200>({
url: `/api/v5/substitute_vars`,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: querybuildertypesv5QueryRangeRequestDTO,
signal,
});
};
export const getReplaceVariablesMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
> => {
const mutationKey = ['replaceVariables'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof replaceVariables>>,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> }
> = (props) => {
const { data } = props ?? {};
return replaceVariables(data);
};
return { mutationFn, ...mutationOptions };
};
export type ReplaceVariablesMutationResult = NonNullable<
Awaited<ReturnType<typeof replaceVariables>>
>;
export type ReplaceVariablesMutationBody = BodyType<Querybuildertypesv5QueryRangeRequestDTO>;
export type ReplaceVariablesMutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Replace variables
*/
export const useReplaceVariables = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof replaceVariables>>,
TError,
{ data: BodyType<Querybuildertypesv5QueryRangeRequestDTO> },
TContext
> => {
const mutationOptions = getReplaceVariablesMutationOptions(options);
return useMutation(mutationOptions);
};

View File

@@ -0,0 +1,107 @@
/**
* ! Do not edit manually
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'yarn generate:api'
* SigNoz
*/
import type {
MutationFunction,
UseMutationOptions,
UseMutationResult,
} from 'react-query';
import { useMutation } from 'react-query';
import { GeneratedAPIInstance } from '../../../index';
import type {
Querybuildertypesv5QueryRangeRequestDTO,
QueryRangeV5200,
RenderErrorResponseDTO,
} from '../sigNoz.schemas';
type AwaitedInput<T> = PromiseLike<T> | T;
type Awaited<O> = O extends AwaitedInput<infer T> ? T : never;
/**
* Execute a composite query over a time range. Supports builder queries (traces, logs, metrics), formulas, trace operators, PromQL, and ClickHouse SQL.
* @summary Query range
*/
export const queryRangeV5 = (
querybuildertypesv5QueryRangeRequestDTO: Querybuildertypesv5QueryRangeRequestDTO,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<QueryRangeV5200>({
url: `/api/v5/query_range`,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: querybuildertypesv5QueryRangeRequestDTO,
signal,
});
};
export const getQueryRangeV5MutationOptions = <
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
> => {
const mutationKey = ['queryRangeV5'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof queryRangeV5>>,
{ data: Querybuildertypesv5QueryRangeRequestDTO }
> = (props) => {
const { data } = props ?? {};
return queryRangeV5(data);
};
return { mutationFn, ...mutationOptions };
};
export type QueryRangeV5MutationResult = NonNullable<
Awaited<ReturnType<typeof queryRangeV5>>
>;
export type QueryRangeV5MutationBody = Querybuildertypesv5QueryRangeRequestDTO;
export type QueryRangeV5MutationError = RenderErrorResponseDTO;
/**
* @summary Query range
*/
export const useQueryRangeV5 = <
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof queryRangeV5>>,
TError,
{ data: Querybuildertypesv5QueryRangeRequestDTO },
TContext
> => {
const mutationOptions = getQueryRangeV5MutationOptions(options);
return useMutation(mutationOptions);
};

View File

@@ -17,22 +17,15 @@ 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,
GetRole200,
GetRolePathParameters,
ListRoles200,
PatchObjectsPathParameters,
PatchRolePathParameters,
RenderErrorResponseDTO,
RoletypesPatchableRoleDTO,
RoletypesPostableRoleDTO,
} from '../sigNoz.schemas';
type AwaitedInput<T> = PromiseLike<T> | T;
@@ -52,12 +45,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 +72,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 +80,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 } {
@@ -121,33 +114,28 @@ export const invalidateListRoles = async (
* This endpoint creates a role
* @summary Create role
*/
export const createRole = (
roletypesPostableRoleDTO: BodyType<RoletypesPostableRoleDTO>,
signal?: AbortSignal,
) => {
export const createRole = (signal?: AbortSignal) => {
return GeneratedAPIInstance<CreateRole201>({
url: `/api/v1/roles`,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: roletypesPostableRoleDTO,
signal,
});
};
export const getCreateRoleMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<RoletypesPostableRoleDTO> },
void,
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<RoletypesPostableRoleDTO> },
void,
TContext
> => {
const mutationKey = ['createRole'];
@@ -161,11 +149,9 @@ export const getCreateRoleMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof createRole>>,
{ data: BodyType<RoletypesPostableRoleDTO> }
> = (props) => {
const { data } = props ?? {};
return createRole(data);
void
> = () => {
return createRole();
};
return { mutationFn, ...mutationOptions };
@@ -174,26 +160,26 @@ export const getCreateRoleMutationOptions = <
export type CreateRoleMutationResult = NonNullable<
Awaited<ReturnType<typeof createRole>>
>;
export type CreateRoleMutationBody = BodyType<RoletypesPostableRoleDTO>;
export type CreateRoleMutationError = ErrorType<RenderErrorResponseDTO>;
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> },
void,
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof createRole>>,
TError,
{ data: BodyType<RoletypesPostableRoleDTO> },
void,
TContext
> => {
const mutationOptions = getCreateRoleMutationOptions(options);
@@ -212,7 +198,7 @@ export const deleteRole = ({ id }: DeleteRolePathParameters) => {
};
export const getDeleteRoleMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TError = RenderErrorResponseDTO,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
@@ -252,13 +238,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 +279,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 +312,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 +320,7 @@ export type GetRoleQueryError = ErrorType<RenderErrorResponseDTO>;
export function useGetRole<
TData = Awaited<ReturnType<typeof getRole>>,
TError = ErrorType<RenderErrorResponseDTO>
TError = RenderErrorResponseDTO
>(
{ id }: GetRolePathParameters,
options?: {
@@ -372,38 +358,27 @@ export const invalidateGetRole = async (
* This endpoint patches a role
* @summary Patch role
*/
export const patchRole = (
{ id }: PatchRolePathParameters,
roletypesPatchableRoleDTO: BodyType<RoletypesPatchableRoleDTO>,
) => {
export const patchRole = ({ id }: PatchRolePathParameters) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/roles/${id}`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: roletypesPatchableRoleDTO,
});
};
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 },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof patchRole>>,
TError,
{
pathParams: PatchRolePathParameters;
data: BodyType<RoletypesPatchableRoleDTO>;
},
{ pathParams: PatchRolePathParameters },
TContext
> => {
const mutationKey = ['patchRole'];
@@ -417,14 +392,11 @@ export const getPatchRoleMutationOptions = <
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof patchRole>>,
{
pathParams: PatchRolePathParameters;
data: BodyType<RoletypesPatchableRoleDTO>;
}
{ pathParams: PatchRolePathParameters }
> = (props) => {
const { pathParams, data } = props ?? {};
const { pathParams } = props ?? {};
return patchRole(pathParams, data);
return patchRole(pathParams);
};
return { mutationFn, ...mutationOptions };
@@ -433,235 +405,29 @@ export const getPatchRoleMutationOptions = <
export type PatchRoleMutationResult = NonNullable<
Awaited<ReturnType<typeof patchRole>>
>;
export type PatchRoleMutationBody = BodyType<RoletypesPatchableRoleDTO>;
export type PatchRoleMutationError = ErrorType<RenderErrorResponseDTO>;
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 },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof patchRole>>,
TError,
{
pathParams: PatchRolePathParameters;
data: BodyType<RoletypesPatchableRoleDTO>;
},
{ pathParams: PatchRolePathParameters },
TContext
> => {
const mutationOptions = getPatchRoleMutationOptions(options);
return useMutation(mutationOptions);
};
/**
* Gets all objects connected to the specified role via a given relation type
* @summary Get objects for a role by relation
*/
export const getObjects = (
{ id, relation }: GetObjectsPathParameters,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<GetObjects200>({
url: `/api/v1/roles/${id}/relation/${relation}/objects`,
method: 'GET',
signal,
});
};
export const getGetObjectsQueryKey = ({
id,
relation,
}: GetObjectsPathParameters) => {
return [`/api/v1/roles/${id}/relation/${relation}/objects`] as const;
};
export const getGetObjectsQueryOptions = <
TData = Awaited<ReturnType<typeof getObjects>>,
TError = ErrorType<RenderErrorResponseDTO>
>(
{ id, relation }: GetObjectsPathParameters,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getObjects>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getGetObjectsQueryKey({ id, relation });
const queryFn: QueryFunction<Awaited<ReturnType<typeof getObjects>>> = ({
signal,
}) => getObjects({ id, relation }, signal);
return {
queryKey,
queryFn,
enabled: !!(id && relation),
...queryOptions,
} as UseQueryOptions<Awaited<ReturnType<typeof getObjects>>, TError, TData> & {
queryKey: QueryKey;
};
};
export type GetObjectsQueryResult = NonNullable<
Awaited<ReturnType<typeof getObjects>>
>;
export type GetObjectsQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Get objects for a role by relation
*/
export function useGetObjects<
TData = Awaited<ReturnType<typeof getObjects>>,
TError = ErrorType<RenderErrorResponseDTO>
>(
{ id, relation }: GetObjectsPathParameters,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof getObjects>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getGetObjectsQueryOptions({ id, relation }, options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
}
/**
* @summary Get objects for a role by relation
*/
export const invalidateGetObjects = async (
queryClient: QueryClient,
{ id, relation }: GetObjectsPathParameters,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getGetObjectsQueryKey({ id, relation }) },
options,
);
return queryClient;
};
/**
* Patches the objects connected to the specified role via a given relation type
* @summary Patch objects for a role by relation
*/
export const patchObjects = (
{ id, relation }: PatchObjectsPathParameters,
authtypesPatchableObjectsDTO: BodyType<AuthtypesPatchableObjectsDTO>,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/roles/${id}/relation/${relation}/objects`,
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
data: authtypesPatchableObjectsDTO,
});
};
export const getPatchObjectsMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof patchObjects>>,
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<AuthtypesPatchableObjectsDTO>;
},
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof patchObjects>>,
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<AuthtypesPatchableObjectsDTO>;
},
TContext
> => {
const mutationKey = ['patchObjects'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof patchObjects>>,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<AuthtypesPatchableObjectsDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
return patchObjects(pathParams, data);
};
return { mutationFn, ...mutationOptions };
};
export type PatchObjectsMutationResult = NonNullable<
Awaited<ReturnType<typeof patchObjects>>
>;
export type PatchObjectsMutationBody = BodyType<AuthtypesPatchableObjectsDTO>;
export type PatchObjectsMutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Patch objects for a role by relation
*/
export const usePatchObjects = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof patchObjects>>,
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<AuthtypesPatchableObjectsDTO>;
},
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof patchObjects>>,
TError,
{
pathParams: PatchObjectsPathParameters;
data: BodyType<AuthtypesPatchableObjectsDTO>;
},
TContext
> => {
const mutationOptions = getPatchObjectsMutationOptions(options);
return useMutation(mutationOptions);
};

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);

File diff suppressed because it is too large Load Diff

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

@@ -1,272 +0,0 @@
/**
* ! Do not edit manually
* * The file has been auto-generated using Orval for SigNoz
* * regenerate with 'yarn generate:api'
* SigNoz
*/
import type {
InvalidateOptions,
MutationFunction,
QueryClient,
QueryFunction,
QueryKey,
UseMutationOptions,
UseMutationResult,
UseQueryOptions,
UseQueryResult,
} from 'react-query';
import { useMutation, useQuery } from 'react-query';
import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import type {
GetHosts200,
RenderErrorResponseDTO,
ZeustypesPostableHostDTO,
ZeustypesPostableProfileDTO,
} from '../sigNoz.schemas';
type AwaitedInput<T> = PromiseLike<T> | T;
type Awaited<O> = O extends AwaitedInput<infer T> ? T : never;
/**
* This endpoint gets the host info from zeus.
* @summary Get host info from Zeus.
*/
export const getHosts = (signal?: AbortSignal) => {
return GeneratedAPIInstance<GetHosts200>({
url: `/api/v2/zeus/hosts`,
method: 'GET',
signal,
});
};
export const getGetHostsQueryKey = () => {
return [`/api/v2/zeus/hosts`] as const;
};
export const getGetHostsQueryOptions = <
TData = Awaited<ReturnType<typeof getHosts>>,
TError = ErrorType<RenderErrorResponseDTO>
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof getHosts>>, TError, TData>;
}) => {
const { query: queryOptions } = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetHostsQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof getHosts>>> = ({
signal,
}) => getHosts(signal);
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
Awaited<ReturnType<typeof getHosts>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type GetHostsQueryResult = NonNullable<
Awaited<ReturnType<typeof getHosts>>
>;
export type GetHostsQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Get host info from Zeus.
*/
export function useGetHosts<
TData = Awaited<ReturnType<typeof getHosts>>,
TError = ErrorType<RenderErrorResponseDTO>
>(options?: {
query?: UseQueryOptions<Awaited<ReturnType<typeof getHosts>>, TError, TData>;
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getGetHostsQueryOptions(options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
query.queryKey = queryOptions.queryKey;
return query;
}
/**
* @summary Get host info from Zeus.
*/
export const invalidateGetHosts = async (
queryClient: QueryClient,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getGetHostsQueryKey() },
options,
);
return queryClient;
};
/**
* This endpoint saves the host of a deployment to zeus.
* @summary Put host in Zeus for a deployment.
*/
export const putHost = (
zeustypesPostableHostDTO: BodyType<ZeustypesPostableHostDTO>,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/zeus/hosts`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: zeustypesPostableHostDTO,
});
};
export const getPutHostMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
TContext
> => {
const mutationKey = ['putHost'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof putHost>>,
{ data: BodyType<ZeustypesPostableHostDTO> }
> = (props) => {
const { data } = props ?? {};
return putHost(data);
};
return { mutationFn, ...mutationOptions };
};
export type PutHostMutationResult = NonNullable<
Awaited<ReturnType<typeof putHost>>
>;
export type PutHostMutationBody = BodyType<ZeustypesPostableHostDTO>;
export type PutHostMutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Put host in Zeus for a deployment.
*/
export const usePutHost = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof putHost>>,
TError,
{ data: BodyType<ZeustypesPostableHostDTO> },
TContext
> => {
const mutationOptions = getPutHostMutationOptions(options);
return useMutation(mutationOptions);
};
/**
* This endpoint saves the profile of a deployment to zeus.
* @summary Put profile in Zeus for a deployment.
*/
export const putProfile = (
zeustypesPostableProfileDTO: BodyType<ZeustypesPostableProfileDTO>,
) => {
return GeneratedAPIInstance<void>({
url: `/api/v2/zeus/profiles`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
data: zeustypesPostableProfileDTO,
});
};
export const getPutProfileMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
TContext
>;
}): UseMutationOptions<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
TContext
> => {
const mutationKey = ['putProfile'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
options.mutation.mutationKey
? options
: { ...options, mutation: { ...options.mutation, mutationKey } }
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
Awaited<ReturnType<typeof putProfile>>,
{ data: BodyType<ZeustypesPostableProfileDTO> }
> = (props) => {
const { data } = props ?? {};
return putProfile(data);
};
return { mutationFn, ...mutationOptions };
};
export type PutProfileMutationResult = NonNullable<
Awaited<ReturnType<typeof putProfile>>
>;
export type PutProfileMutationBody = BodyType<ZeustypesPostableProfileDTO>;
export type PutProfileMutationError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Put profile in Zeus for a deployment.
*/
export const usePutProfile = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
TContext
>;
}): UseMutationResult<
Awaited<ReturnType<typeof putProfile>>,
TError,
{ data: BodyType<ZeustypesPostableProfileDTO> },
TContext
> => {
const mutationOptions = getPutProfileMutationOptions(options);
return useMutation(mutationOptions);
};

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

@@ -15,7 +15,15 @@ import { Events } from 'constants/events';
import { LOCALSTORAGE } from 'constants/localStorage';
import { eventEmitter } from 'utils/getEventEmitter';
import apiV1, { apiAlertManager, apiV2, apiV3, apiV4, apiV5 } from './apiV1';
import apiV1, {
apiAlertManager,
apiV2,
apiV3,
apiV4,
apiV5,
gatewayApiV1,
gatewayApiV2,
} from './apiV1';
import { Logout } from './utils';
const RESPONSE_TIMEOUT_THRESHOLD = 5000; // 5 seconds
@@ -28,7 +36,7 @@ const queryClient = new QueryClient({
},
});
export const interceptorsResponse = (
const interceptorsResponse = (
value: AxiosResponse<any>,
): Promise<AxiosResponse<any>> => {
if ((value.config as any)?.metadata) {
@@ -51,7 +59,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 +77,7 @@ export const interceptorsRequestResponse = (
return value;
};
export const interceptorRejected = async (
const interceptorRejected = async (
value: AxiosResponse<any>,
): Promise<AxiosResponse<any>> => {
try {
@@ -203,6 +211,43 @@ LogEventAxiosInstance.interceptors.response.use(
LogEventAxiosInstance.interceptors.request.use(interceptorsRequestResponse);
//
// gateway Api V1
export const GatewayApiV1Instance = axios.create({
baseURL: `${ENVIRONMENT.baseURL}${gatewayApiV1}`,
});
GatewayApiV1Instance.interceptors.response.use(
interceptorsResponse,
interceptorRejected,
);
GatewayApiV1Instance.interceptors.request.use(interceptorsRequestResponse);
//
// gateway Api V2
export const GatewayApiV2Instance = axios.create({
baseURL: `${ENVIRONMENT.baseURL}${gatewayApiV2}`,
});
// generated API Instance
export const GeneratedAPIInstance = axios.create({
baseURL: ENVIRONMENT.baseURL,
});
GeneratedAPIInstance.interceptors.request.use(interceptorsRequestResponse);
GeneratedAPIInstance.interceptors.response.use(
interceptorsResponse,
interceptorRejected,
);
GatewayApiV2Instance.interceptors.response.use(
interceptorsResponse,
interceptorRejected,
);
GatewayApiV2Instance.interceptors.request.use(interceptorsRequestResponse);
//
AxiosAlertManagerInstance.interceptors.response.use(
interceptorsResponse,
interceptorRejected,

View File

@@ -0,0 +1,20 @@
import { GatewayApiV2Instance } from 'api';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { UpdateProfileProps } from 'types/api/onboarding/types';
const updateProfile = async (
props: UpdateProfileProps,
): Promise<SuccessResponse<UpdateProfileProps> | ErrorResponse> => {
const response = await GatewayApiV2Instance.put('/profiles/me', {
...props,
});
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data.data,
};
};
export default updateProfile;

View File

@@ -42,7 +42,6 @@
display: flex;
flex-direction: column;
padding: 16px;
padding-bottom: 0;
}
.title {
@@ -191,7 +190,7 @@
padding: 0px;
}
.log-detail-drawer__footer-hint {
position: sticky;
position: absolute;
bottom: 0;
left: 0;
right: 0;
@@ -367,7 +366,7 @@
}
.log-detail-drawer__footer-hint {
position: sticky;
position: absolute;
bottom: 0;
left: 0;
right: 0;

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;
@@ -671,7 +669,7 @@ export interface UnitFamilyConfig {
}
export interface YAxisCategory {
name: YAxisCategoryNames;
name: string;
units: {
name: string;
id: UniversalYAxisUnit;

View File

@@ -202,7 +202,7 @@ function AllEndPoints({
const onRowClick = useCallback(
(props: any): void => {
setSelectedEndPointName(props[SPAN_ATTRIBUTES.HTTP_URL] as string);
setSelectedEndPointName(props[SPAN_ATTRIBUTES.URL_PATH] as string);
setSelectedView(VIEWS.ENDPOINT_STATS);
const initialItems = [
...(filters?.items || []),
@@ -213,7 +213,7 @@ function AllEndPoints({
op: 'AND',
});
setParams({
selectedEndPointName: props[SPAN_ATTRIBUTES.HTTP_URL] as string,
selectedEndPointName: props[SPAN_ATTRIBUTES.URL_PATH] as string,
selectedView: VIEWS.ENDPOINT_STATS,
endPointDetailsLocalFilters: {
items: initialItems,

View File

@@ -33,7 +33,7 @@ import { SPAN_ATTRIBUTES } from './constants';
const httpUrlKey = {
dataType: DataTypes.String,
key: SPAN_ATTRIBUTES.HTTP_URL,
key: SPAN_ATTRIBUTES.URL_PATH,
type: 'tag',
};
@@ -93,7 +93,7 @@ function EndPointDetails({
return currentFilters; // No change needed, prevents loop
}
// Rebuild filters: Keep non-http_url filters and add/update http_url filter based on prop
// Rebuild filters: Keep non-http.url filters and add/update http.url filter based on prop
const otherFilters = currentFilters?.items?.filter(
(item) => item.key?.key !== httpUrlKey.key,
);
@@ -125,7 +125,7 @@ function EndPointDetails({
(newFilters: IBuilderQuery['filters']): void => {
// 1. Update local filters state immediately
setFilters(newFilters);
// Filter out http_url filter before saving to params
// Filter out http.url filter before saving to params
const filteredNewFilters = {
op: 'AND',
items:
@@ -299,6 +299,7 @@ function EndPointDetails({
endPointStatusCodeLatencyBarChartsDataQuery
}
domainName={domainName}
endPointName={endPointName}
filters={filters}
timeRange={timeRange}
onDragSelect={onDragSelect}

View File

@@ -56,15 +56,15 @@ function TopErrors({
{
items: endPointName
? [
// Remove any existing http_url filters from initialFilters to avoid duplicates
// Remove any existing http.url filters from initialFilters to avoid duplicates
...(initialFilters?.items?.filter(
(item) => item.key?.key !== SPAN_ATTRIBUTES.HTTP_URL,
(item) => item.key?.key !== SPAN_ATTRIBUTES.URL_PATH,
) || []),
{
id: '92b8a1c1',
key: {
dataType: DataTypes.String,
key: SPAN_ATTRIBUTES.HTTP_URL,
key: SPAN_ATTRIBUTES.URL_PATH,
type: 'tag',
},
op: '=',

View File

@@ -9,7 +9,6 @@ import { ENTITY_VERSION_V5 } from 'constants/app';
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { SPAN_ATTRIBUTES } from '../constants';
import DomainMetrics from './DomainMetrics';
// Mock the API call
@@ -127,9 +126,11 @@ describe('DomainMetrics - V5 Query Payload Tests', () => {
'count()',
);
// Verify exact domain filter expression structure
expect(queryA.filter.expression).toContain("http_host = '0.0.0.0'");
expect(queryA.filter.expression).toContain(
`${SPAN_ATTRIBUTES.HTTP_URL} EXISTS`,
"(net.peer.name = '0.0.0.0' OR server.address = '0.0.0.0')",
);
expect(queryA.filter.expression).toContain(
'url.full EXISTS OR http.url EXISTS',
);
// Verify Query B - p99 latency
@@ -141,13 +142,17 @@ describe('DomainMetrics - V5 Query Payload Tests', () => {
'p99(duration_nano)',
);
// Verify exact domain filter expression structure
expect(queryB.filter.expression).toContain("http_host = '0.0.0.0'");
expect(queryB.filter.expression).toContain(
"(net.peer.name = '0.0.0.0' OR server.address = '0.0.0.0')",
);
// Verify Query C - error count (disabled)
const queryC = queryData.find((q: any) => q.queryName === 'C');
expect(queryC).toBeDefined();
expect(queryC.disabled).toBe(true);
expect(queryC.filter.expression).toContain("http_host = '0.0.0.0'");
expect(queryC.filter.expression).toContain(
"(net.peer.name = '0.0.0.0' OR server.address = '0.0.0.0')",
);
expect(queryC.aggregations?.[0]).toBeDefined();
expect((queryC.aggregations?.[0] as TraceAggregation)?.expression).toBe(
'count()',
@@ -164,7 +169,9 @@ describe('DomainMetrics - V5 Query Payload Tests', () => {
'max(timestamp)',
);
// Verify exact domain filter expression structure
expect(queryD.filter.expression).toContain("http_host = '0.0.0.0'");
expect(queryD.filter.expression).toContain(
"(net.peer.name = '0.0.0.0' OR server.address = '0.0.0.0')",
);
// Verify Formula F1 - error rate calculation
const formulas = payload.query.builder.queryFormulas;

View File

@@ -153,7 +153,7 @@ describe('EndPointMetrics - V5 Query Payload Tests', () => {
// Verify exact domain filter expression structure
if (queryA.filter) {
expect(queryA.filter.expression).toContain(
`http_host = 'api.example.com'`,
"(net.peer.name = 'api.example.com' OR server.address = 'api.example.com')",
);
expect(queryA.filter.expression).toContain("kind_string = 'Client'");
}
@@ -171,7 +171,7 @@ describe('EndPointMetrics - V5 Query Payload Tests', () => {
// Verify exact domain filter expression structure
if (queryB.filter) {
expect(queryB.filter.expression).toContain(
`http_host = 'api.example.com'`,
"(net.peer.name = 'api.example.com' OR server.address = 'api.example.com')",
);
expect(queryB.filter.expression).toContain("kind_string = 'Client'");
}
@@ -185,7 +185,7 @@ describe('EndPointMetrics - V5 Query Payload Tests', () => {
expect(queryC.aggregateOperator).toBe('count');
if (queryC.filter) {
expect(queryC.filter.expression).toContain(
`http_host = 'api.example.com'`,
"(net.peer.name = 'api.example.com' OR server.address = 'api.example.com')",
);
expect(queryC.filter.expression).toContain("kind_string = 'Client'");
expect(queryC.filter.expression).toContain('has_error = true');
@@ -204,7 +204,7 @@ describe('EndPointMetrics - V5 Query Payload Tests', () => {
// Verify exact domain filter expression structure
if (queryD.filter) {
expect(queryD.filter.expression).toContain(
`http_host = 'api.example.com'`,
"(net.peer.name = 'api.example.com' OR server.address = 'api.example.com')",
);
expect(queryD.filter.expression).toContain("kind_string = 'Client'");
}
@@ -221,7 +221,7 @@ describe('EndPointMetrics - V5 Query Payload Tests', () => {
}
if (queryE.filter) {
expect(queryE.filter.expression).toContain(
`http_host = 'api.example.com'`,
"(net.peer.name = 'api.example.com' OR server.address = 'api.example.com')",
);
expect(queryE.filter.expression).toContain("kind_string = 'Client'");
}
@@ -291,7 +291,7 @@ describe('EndPointMetrics - V5 Query Payload Tests', () => {
expect(query.filter.expression).toContain('staging');
// Also verify domain filter is still present
expect(query.filter.expression).toContain(
"http_host = 'api.internal.com'",
"(net.peer.name = 'api.internal.com' OR server.address = 'api.internal.com')",
);
// Verify client kind filter is present
expect(query.filter.expression).toContain("kind_string = 'Client'");

View File

@@ -34,6 +34,7 @@ function StatusCodeBarCharts({
endPointStatusCodeBarChartsDataQuery,
endPointStatusCodeLatencyBarChartsDataQuery,
domainName,
endPointName,
filters,
timeRange,
onDragSelect,
@@ -47,6 +48,7 @@ function StatusCodeBarCharts({
unknown
>;
domainName: string;
endPointName: string;
filters: IBuilderQuery['filters'];
timeRange: {
startTime: number;
@@ -142,11 +144,11 @@ function StatusCodeBarCharts({
const widget = useMemo<Widgets>(
() =>
getStatusCodeBarChartWidgetData(domainName, {
getStatusCodeBarChartWidgetData(domainName, endPointName, {
items: [...(filters?.items || [])],
op: filters?.op || 'AND',
}),
[domainName, filters],
[domainName, endPointName, filters],
);
const graphClickHandler = useCallback(
@@ -164,7 +166,6 @@ function StatusCodeBarCharts({
xValue,
TWO_AND_HALF_MINUTES_IN_MILLISECONDS,
);
handleGraphClick({
xValue,
yValue,

View File

@@ -12,7 +12,7 @@ export const VIEW_TYPES = {
// Span attribute keys - these are the source of truth for all attribute keys
export const SPAN_ATTRIBUTES = {
HTTP_URL: 'http_url',
URL_PATH: 'http.url',
RESPONSE_STATUS_CODE: 'response_status_code',
SERVER_NAME: 'http_host',
SERVER_PORT: 'net.peer.port',

View File

@@ -280,7 +280,7 @@ describe('API Monitoring Utils', () => {
const endpointFilter = result?.items?.find(
(item) =>
item.key &&
item.key.key === SPAN_ATTRIBUTES.HTTP_URL &&
item.key.key === SPAN_ATTRIBUTES.URL_PATH &&
item.value === endPointName,
);
expect(endpointFilter).toBeDefined();
@@ -344,12 +344,13 @@ describe('API Monitoring Utils', () => {
describe('getFormattedEndPointDropDownData', () => {
it('should format endpoint dropdown data correctly', () => {
// Arrange
const URL_PATH_KEY = SPAN_ATTRIBUTES.HTTP_URL;
const URL_PATH_KEY = SPAN_ATTRIBUTES.URL_PATH;
const mockData = [
{
data: {
// eslint-disable-next-line sonarjs/no-duplicate-string
[URL_PATH_KEY]: '/api/users',
'url.full': 'http://example.com/api/users',
A: 150, // count or other metric
},
},
@@ -357,6 +358,7 @@ describe('API Monitoring Utils', () => {
data: {
// eslint-disable-next-line sonarjs/no-duplicate-string
[URL_PATH_KEY]: '/api/orders',
'url.full': 'http://example.com/api/orders',
A: 75,
},
},
@@ -404,7 +406,7 @@ describe('API Monitoring Utils', () => {
it('should handle items without URL path', () => {
// Arrange
const URL_PATH_KEY = SPAN_ATTRIBUTES.HTTP_URL;
const URL_PATH_KEY = SPAN_ATTRIBUTES.URL_PATH;
type MockDataType = {
data: {
[key: string]: string | number;
@@ -710,11 +712,13 @@ describe('API Monitoring Utils', () => {
it('should generate widget configuration for status code bar chart', () => {
// Arrange
const domainName = 'test-domain';
const endPointName = '/api/test';
const filters = { items: [], op: 'AND' };
// Act
const result = getStatusCodeBarChartWidgetData(
domainName,
endPointName,
filters as IBuilderQuery['filters'],
);
@@ -737,11 +741,21 @@ describe('API Monitoring Utils', () => {
if (domainFilter) {
expect(domainFilter.value).toBe(domainName);
}
// Should have endpoint filter if provided
const endpointFilter = queryData.filters?.items?.find(
(item) => item.key && item.key.key === SPAN_ATTRIBUTES.URL_PATH,
);
expect(endpointFilter).toBeDefined();
if (endpointFilter) {
expect(endpointFilter.value).toBe(endPointName);
}
});
it('should include custom filters in the widget configuration', () => {
// Arrange
const domainName = 'test-domain';
const endPointName = '/api/test';
const customFilter = {
id: 'custom-filter',
key: {
@@ -757,6 +771,7 @@ describe('API Monitoring Utils', () => {
// Act
const result = getStatusCodeBarChartWidgetData(
domainName,
endPointName,
filters as IBuilderQuery['filters'],
);

View File

@@ -25,7 +25,7 @@ jest.mock('container/GridCardLayout/GridCard', () => ({
type="button"
data-testid="row-click-button"
onClick={(): void =>
customOnRowClick({ [SPAN_ATTRIBUTES.HTTP_URL]: '/api/test' })
customOnRowClick({ [SPAN_ATTRIBUTES.URL_PATH]: '/api/test' })
}
>
Click Row

View File

@@ -6,10 +6,10 @@
* These tests validate the migration from V4 to V5 format for getAllEndpointsWidgetData:
* - Filter format change: filters.items[] → filter.expression
* - Aggregation format: aggregateAttribute → aggregations[] array
* - Domain filter: http_host = '${domainName}'
* - Domain filter: (net.peer.name OR server.address)
* - Kind filter: kind_string = 'Client'
* - Four queries: A (count), B (p99 latency), C (max timestamp), D (error count - disabled)
* - GroupBy: http_url with type 'attribute'
* - GroupBy: Both http.url AND url.full with type 'attribute'
*/
import { getAllEndpointsWidgetData } from 'container/ApiMonitoring/utils';
import {
@@ -18,8 +18,6 @@ import {
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { SPAN_ATTRIBUTES } from '../Explorer/Domains/DomainDetails/constants';
describe('AllEndpointsWidget - V5 Migration Validation', () => {
const mockDomainName = 'api.example.com';
const emptyFilters: IBuilderQuery['filters'] = {
@@ -94,28 +92,28 @@ describe('AllEndpointsWidget - V5 Migration Validation', () => {
const [queryA, queryB, queryC, queryD] = widget.query.builder.queryData;
const baseExpression = `http_host = '${mockDomainName}' AND kind_string = 'Client'`;
const baseExpression = `(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}') AND kind_string = 'Client'`;
// Queries A, B, C have identical base filter
expect(queryA.filter?.expression).toBe(
`${baseExpression} AND ${SPAN_ATTRIBUTES.HTTP_URL} EXISTS`,
`${baseExpression} AND (http.url EXISTS OR url.full EXISTS)`,
);
expect(queryB.filter?.expression).toBe(
`${baseExpression} AND ${SPAN_ATTRIBUTES.HTTP_URL} EXISTS`,
`${baseExpression} AND (http.url EXISTS OR url.full EXISTS)`,
);
expect(queryC.filter?.expression).toBe(
`${baseExpression} AND ${SPAN_ATTRIBUTES.HTTP_URL} EXISTS`,
`${baseExpression} AND (http.url EXISTS OR url.full EXISTS)`,
);
// Query D has additional has_error filter
expect(queryD.filter?.expression).toBe(
`${baseExpression} AND has_error = true AND ${SPAN_ATTRIBUTES.HTTP_URL} EXISTS`,
`${baseExpression} AND has_error = true AND (http.url EXISTS OR url.full EXISTS)`,
);
});
});
describe('2. GroupBy Structure', () => {
it(`default groupBy includes ${SPAN_ATTRIBUTES.HTTP_URL} with type attribute`, () => {
it('default groupBy includes both http.url and url.full with type attribute', () => {
const widget = getAllEndpointsWidgetData(
emptyGroupBy,
mockDomainName,
@@ -126,13 +124,23 @@ describe('AllEndpointsWidget - V5 Migration Validation', () => {
// All queries should have the same default groupBy
queryData.forEach((query) => {
expect(query.groupBy).toHaveLength(1);
expect(query.groupBy).toHaveLength(2);
// http.url
expect(query.groupBy).toContainEqual({
dataType: DataTypes.String,
isColumn: false,
isJSON: false,
key: SPAN_ATTRIBUTES.HTTP_URL,
key: 'http.url',
type: 'attribute',
});
// url.full
expect(query.groupBy).toContainEqual({
dataType: DataTypes.String,
isColumn: false,
isJSON: false,
key: 'url.full',
type: 'attribute',
});
});
@@ -162,18 +170,19 @@ describe('AllEndpointsWidget - V5 Migration Validation', () => {
// All queries should have defaults + custom groupBy
queryData.forEach((query) => {
expect(query.groupBy).toHaveLength(3); // 1 default + 2 custom
expect(query.groupBy).toHaveLength(4); // 2 defaults + 2 custom
// First two should be defaults (http_url)
expect(query.groupBy[0].key).toBe(SPAN_ATTRIBUTES.HTTP_URL);
// First two should be defaults (http.url, url.full)
expect(query.groupBy[0].key).toBe('http.url');
expect(query.groupBy[1].key).toBe('url.full');
// Last two should be custom (matching subset of properties)
expect(query.groupBy[1]).toMatchObject({
expect(query.groupBy[2]).toMatchObject({
dataType: DataTypes.String,
key: 'service.name',
type: 'resource',
});
expect(query.groupBy[2]).toMatchObject({
expect(query.groupBy[3]).toMatchObject({
dataType: DataTypes.String,
key: 'deployment.environment',
type: 'resource',

View File

@@ -258,7 +258,7 @@ describe('EndPointDetails Component', () => {
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({
key: expect.objectContaining({ key: SPAN_ATTRIBUTES.HTTP_URL }),
key: expect.objectContaining({ key: SPAN_ATTRIBUTES.URL_PATH }),
value: '/api/test',
}),
]),
@@ -278,7 +278,7 @@ describe('EndPointDetails Component', () => {
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({
key: expect.objectContaining({ key: SPAN_ATTRIBUTES.HTTP_URL }),
key: expect.objectContaining({ key: SPAN_ATTRIBUTES.URL_PATH }),
value: '/api/test',
}),
]),
@@ -360,7 +360,7 @@ describe('EndPointDetails Component', () => {
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({
key: expect.objectContaining({ key: SPAN_ATTRIBUTES.HTTP_URL }),
key: expect.objectContaining({ key: SPAN_ATTRIBUTES.URL_PATH }),
value: '/api/test',
}),
]),
@@ -373,7 +373,7 @@ describe('EndPointDetails Component', () => {
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({
key: expect.objectContaining({ key: SPAN_ATTRIBUTES.HTTP_URL }),
key: expect.objectContaining({ key: SPAN_ATTRIBUTES.URL_PATH }),
value: '/api/test',
}),
]),

View File

@@ -191,7 +191,7 @@ describe('EndPointsDropDown Component', () => {
it('formats data using the utility function', () => {
const mockRows = [
{ data: { [SPAN_ATTRIBUTES.HTTP_URL]: '/api/test', A: 10 } },
{ data: { [SPAN_ATTRIBUTES.URL_PATH]: '/api/test', A: 10 } },
];
const dataProps = {

View File

@@ -6,18 +6,15 @@
* These tests validate the migration from V4 to V5 format for the third payload
* in getEndPointDetailsQueryPayload (endpoint dropdown data):
* - Filter format change: filters.items[] → filter.expression
* - Domain handling: http_host = '${domainName}'
* - Domain handling: (net.peer.name OR server.address)
* - Kind filter: kind_string = 'Client'
* - Existence check: http_url EXISTS
* - Existence check: (http.url EXISTS OR url.full EXISTS)
* - Aggregation: count() expression
* - GroupBy: http_url with type 'attribute'
* - GroupBy: Both http.url AND url.full with type 'attribute'
*/
import { getEndPointDetailsQueryPayload } from 'container/ApiMonitoring/utils';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { SPAN_ATTRIBUTES } from '../Explorer/Domains/DomainDetails/constants';
describe('EndpointDropdown - V5 Migration Validation', () => {
const mockDomainName = 'api.example.com';
const mockStartTime = 1000;
@@ -46,9 +43,9 @@ describe('EndpointDropdown - V5 Migration Validation', () => {
expect(typeof queryA.filter?.expression).toBe('string');
expect(queryA).not.toHaveProperty('filters');
// Base filter 1: Domain http_host = '${domainName}'
// Base filter 1: Domain (net.peer.name OR server.address)
expect(queryA.filter?.expression).toContain(
`http_host = '${mockDomainName}'`,
`(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
);
// Base filter 2: Kind
@@ -56,7 +53,7 @@ describe('EndpointDropdown - V5 Migration Validation', () => {
// Base filter 3: Existence check
expect(queryA.filter?.expression).toContain(
`${SPAN_ATTRIBUTES.HTTP_URL} EXISTS`,
'(http.url EXISTS OR url.full EXISTS)',
);
// V5 Aggregation format: aggregations array (not aggregateAttribute)
@@ -67,11 +64,16 @@ describe('EndpointDropdown - V5 Migration Validation', () => {
});
expect(queryA).not.toHaveProperty('aggregateAttribute');
// GroupBy: http_url
expect(queryA.groupBy).toHaveLength(1);
// GroupBy: Both http.url and url.full
expect(queryA.groupBy).toHaveLength(2);
expect(queryA.groupBy).toContainEqual({
key: SPAN_ATTRIBUTES.HTTP_URL,
dataType: DataTypes.String,
key: 'http.url',
dataType: 'string',
type: 'attribute',
});
expect(queryA.groupBy).toContainEqual({
key: 'url.full',
dataType: 'string',
type: 'attribute',
});
});
@@ -118,7 +120,53 @@ describe('EndpointDropdown - V5 Migration Validation', () => {
// Exact filter expression with custom filters merged
expect(expression).toBe(
`${SPAN_ATTRIBUTES.SERVER_NAME} = 'api.example.com' AND kind_string = 'Client' AND ${SPAN_ATTRIBUTES.HTTP_URL} EXISTS service.name = 'user-service' AND deployment.environment = 'production'`,
"(net.peer.name = 'api.example.com' OR server.address = 'api.example.com') AND kind_string = 'Client' AND (http.url EXISTS OR url.full EXISTS) service.name = 'user-service' AND deployment.environment = 'production'",
);
});
});
describe('3. HTTP URL Filter Special Handling', () => {
it('converts http.url filter to (http.url OR url.full) expression', () => {
const filtersWithHttpUrl: IBuilderQuery['filters'] = {
items: [
{
id: 'http-url-filter',
key: {
key: 'http.url',
dataType: 'string' as any,
type: 'tag',
},
op: '=',
value: '/api/users',
},
{
id: 'service-filter',
key: {
key: 'service.name',
dataType: 'string' as any,
type: 'resource',
},
op: '=',
value: 'user-service',
},
],
op: 'AND',
};
const payload = getEndPointDetailsQueryPayload(
mockDomainName,
mockStartTime,
mockEndTime,
filtersWithHttpUrl,
);
const dropdownQuery = payload[2];
const expression =
dropdownQuery.query.builder.queryData[0].filter?.expression;
// CRITICAL: Exact filter expression with http.url converted to OR logic
expect(expression).toBe(
"(net.peer.name = 'api.example.com' OR server.address = 'api.example.com') AND kind_string = 'Client' AND (http.url EXISTS OR url.full EXISTS) service.name = 'user-service' AND (http.url = '/api/users' OR url.full = '/api/users')",
);
});
});

View File

@@ -33,7 +33,7 @@ describe('MetricOverTime - V5 Migration Validation', () => {
expect(queryData).not.toHaveProperty('filters.items');
});
it('uses new domain filter format: (http_host)', () => {
it('uses new domain filter format: (net.peer.name OR server.address)', () => {
const widget = getRateOverTimeWidgetData(
mockDomainName,
mockEndpointName,
@@ -44,7 +44,7 @@ describe('MetricOverTime - V5 Migration Validation', () => {
// Verify EXACT new filter format with OR operator
expect(queryData?.filter?.expression).toContain(
`http_host = '${mockDomainName}'`,
`(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
);
// Endpoint name is used in legend, not filter
@@ -90,7 +90,7 @@ describe('MetricOverTime - V5 Migration Validation', () => {
// Verify domain filter is present
expect(queryData?.filter?.expression).toContain(
`http_host = '${mockDomainName}'`,
`(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
);
// Verify custom filters are merged into the expression
@@ -120,7 +120,7 @@ describe('MetricOverTime - V5 Migration Validation', () => {
expect(queryData).not.toHaveProperty('filters.items');
});
it('uses new domain filter format: (http_host)', () => {
it('uses new domain filter format: (net.peer.name OR server.address)', () => {
const widget = getLatencyOverTimeWidgetData(
mockDomainName,
mockEndpointName,
@@ -132,7 +132,7 @@ describe('MetricOverTime - V5 Migration Validation', () => {
// Verify EXACT new filter format with OR operator
expect(queryData.filter).toBeDefined();
expect(queryData?.filter?.expression).toContain(
`http_host = '${mockDomainName}'`,
`(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
);
// Endpoint name is used in legend, not filter
@@ -166,7 +166,7 @@ describe('MetricOverTime - V5 Migration Validation', () => {
// Verify domain filter is present
expect(queryData?.filter?.expression).toContain(
`http_host = '${mockDomainName}' service.name = 'user-service'`,
`(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}') service.name = 'user-service'`,
);
});
});

View File

@@ -142,6 +142,7 @@ describe('StatusCodeBarCharts', () => {
endTime: 1609545600000,
};
const mockDomainName = 'test-domain';
const mockEndPointName = '/api/test';
const onDragSelectMock = jest.fn();
const refetchFn = jest.fn();
@@ -231,6 +232,7 @@ describe('StatusCodeBarCharts', () => {
endPointStatusCodeBarChartsDataQuery={mockStatusCodeQuery as any}
endPointStatusCodeLatencyBarChartsDataQuery={mockLatencyQuery as any}
domainName={mockDomainName}
endPointName={mockEndPointName}
filters={mockFilters}
timeRange={mockTimeRange}
onDragSelect={onDragSelectMock}
@@ -266,6 +268,7 @@ describe('StatusCodeBarCharts', () => {
endPointStatusCodeBarChartsDataQuery={mockStatusCodeQuery as any}
endPointStatusCodeLatencyBarChartsDataQuery={mockLatencyQuery as any}
domainName={mockDomainName}
endPointName={mockEndPointName}
filters={mockFilters}
timeRange={mockTimeRange}
onDragSelect={onDragSelectMock}
@@ -308,6 +311,7 @@ describe('StatusCodeBarCharts', () => {
endPointStatusCodeBarChartsDataQuery={mockStatusCodeQuery as any}
endPointStatusCodeLatencyBarChartsDataQuery={mockLatencyQuery as any}
domainName={mockDomainName}
endPointName={mockEndPointName}
filters={mockFilters}
timeRange={mockTimeRange}
onDragSelect={onDragSelectMock}
@@ -352,6 +356,7 @@ describe('StatusCodeBarCharts', () => {
endPointStatusCodeBarChartsDataQuery={mockStatusCodeQuery as any}
endPointStatusCodeLatencyBarChartsDataQuery={mockLatencyQuery as any}
domainName={mockDomainName}
endPointName={mockEndPointName}
filters={mockFilters}
timeRange={mockTimeRange}
onDragSelect={onDragSelectMock}
@@ -399,6 +404,7 @@ describe('StatusCodeBarCharts', () => {
endPointStatusCodeBarChartsDataQuery={mockStatusCodeQuery as any}
endPointStatusCodeLatencyBarChartsDataQuery={mockLatencyQuery as any}
domainName={mockDomainName}
endPointName={mockEndPointName}
filters={mockFilters}
timeRange={mockTimeRange}
onDragSelect={onDragSelectMock}
@@ -413,6 +419,7 @@ describe('StatusCodeBarCharts', () => {
// but we've confirmed the function is mocked and ready to be tested
expect(getStatusCodeBarChartWidgetData).toHaveBeenCalledWith(
mockDomainName,
mockEndPointName,
expect.objectContaining({
items: [],
op: 'AND',
@@ -460,6 +467,7 @@ describe('StatusCodeBarCharts', () => {
endPointStatusCodeBarChartsDataQuery={mockStatusCodeQuery as any}
endPointStatusCodeLatencyBarChartsDataQuery={mockLatencyQuery as any}
domainName={mockDomainName}
endPointName={mockEndPointName}
filters={mockCustomFilters as IBuilderQuery['filters']}
timeRange={mockTimeRange}
onDragSelect={onDragSelectMock}
@@ -469,6 +477,7 @@ describe('StatusCodeBarCharts', () => {
// Assert widget creation was called with the correct parameters
expect(getStatusCodeBarChartWidgetData).toHaveBeenCalledWith(
mockDomainName,
mockEndPointName,
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({ id: 'custom-filter' }),

View File

@@ -10,7 +10,7 @@
*
* V5 Changes:
* - Filter format change: filters.items[] → filter.expression
* - Domain filter: (http_host)
* - Domain filter: (net.peer.name OR server.address)
* - Kind filter: kind_string = 'Client'
* - stepInterval: 60 → null
* - Grouped by response_status_code
@@ -47,9 +47,9 @@ describe('StatusCodeBarCharts - V5 Migration Validation', () => {
expect(typeof queryA.filter?.expression).toBe('string');
expect(queryA).not.toHaveProperty('filters.items');
// Base filter 1: Domain (http_host)
// Base filter 1: Domain (net.peer.name OR server.address)
expect(queryA.filter?.expression).toContain(
`http_host = '${mockDomainName}'`,
`(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
);
// Base filter 2: Kind
@@ -96,9 +96,9 @@ describe('StatusCodeBarCharts - V5 Migration Validation', () => {
expect(typeof queryA.filter?.expression).toBe('string');
expect(queryA).not.toHaveProperty('filters.items');
// Base filter 1: Domain (http_host)
// Base filter 1: Domain (net.peer.name OR server.address)
expect(queryA.filter?.expression).toContain(
`http_host = '${mockDomainName}'`,
`(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
);
// Base filter 2: Kind
@@ -177,7 +177,7 @@ describe('StatusCodeBarCharts - V5 Migration Validation', () => {
expect(callsExpression).toBe(latencyExpression);
// Verify base filters
expect(callsExpression).toContain('http_host');
expect(callsExpression).toContain('net.peer.name');
expect(callsExpression).toContain("kind_string = 'Client'");
// Verify custom filters are merged
@@ -187,4 +187,51 @@ describe('StatusCodeBarCharts - V5 Migration Validation', () => {
expect(callsExpression).toContain('production');
});
});
describe('4. HTTP URL Filter Handling', () => {
it('converts http.url filter to (http.url OR url.full) expression in both charts', () => {
const filtersWithHttpUrl: IBuilderQuery['filters'] = {
items: [
{
id: 'http-url-filter',
key: {
key: 'http.url',
dataType: 'string' as any,
type: 'tag',
},
op: '=',
value: '/api/metrics',
},
],
op: 'AND',
};
const payload = getEndPointDetailsQueryPayload(
mockDomainName,
mockStartTime,
mockEndTime,
filtersWithHttpUrl,
);
const callsChartQuery = payload[4];
const latencyChartQuery = payload[5];
const callsExpression =
callsChartQuery.query.builder.queryData[0].filter?.expression;
const latencyExpression =
latencyChartQuery.query.builder.queryData[0].filter?.expression;
// CRITICAL: http.url converted to OR logic
expect(callsExpression).toContain(
"(http.url = '/api/metrics' OR url.full = '/api/metrics')",
);
expect(latencyExpression).toContain(
"(http.url = '/api/metrics' OR url.full = '/api/metrics')",
);
// Base filters still present
expect(callsExpression).toContain('net.peer.name');
expect(callsExpression).toContain("kind_string = 'Client'");
});
});
});

View File

@@ -6,8 +6,8 @@
* These tests validate the migration from V4 to V5 format for the second payload
* in getEndPointDetailsQueryPayload (status code table data):
* - Filter format change: filters.items[] → filter.expression
* - URL handling: Special logic for http_url
* - Domain filter: http_host = '${domainName}'
* - URL handling: Special logic for (http.url OR url.full)
* - Domain filter: (net.peer.name OR server.address)
* - Kind filter: kind_string = 'Client'
* - Kind filter: response_status_code EXISTS
* - Three queries: A (count), B (p99 latency), C (rate)
@@ -45,9 +45,9 @@ describe('StatusCodeTable - V5 Migration Validation', () => {
expect(typeof queryA.filter?.expression).toBe('string');
expect(queryA).not.toHaveProperty('filters.items');
// Base filter 1: Domain (http_host)
// Base filter 1: Domain (net.peer.name OR server.address)
expect(queryA.filter?.expression).toContain(
`http_host = '${mockDomainName}'`,
`(net.peer.name = '${mockDomainName}' OR server.address = '${mockDomainName}')`,
);
// Base filter 2: Kind
@@ -149,7 +149,7 @@ describe('StatusCodeTable - V5 Migration Validation', () => {
statusCodeQuery.query.builder.queryData[0].filter?.expression;
// Base filters present
expect(expression).toContain('http_host');
expect(expression).toContain('net.peer.name');
expect(expression).toContain("kind_string = 'Client'");
expect(expression).toContain('response_status_code EXISTS');
@@ -165,4 +165,62 @@ describe('StatusCodeTable - V5 Migration Validation', () => {
expect(queries[1].filter?.expression).toBe(queries[2].filter?.expression);
});
});
describe('4. HTTP URL Filter Handling', () => {
it('converts http.url filter to (http.url OR url.full) expression', () => {
const filtersWithHttpUrl: IBuilderQuery['filters'] = {
items: [
{
id: 'http-url-filter',
key: {
key: 'http.url',
dataType: 'string' as any,
type: 'tag',
},
op: '=',
value: '/api/users',
},
{
id: 'service-filter',
key: {
key: 'service.name',
dataType: 'string' as any,
type: 'resource',
},
op: '=',
value: 'user-service',
},
],
op: 'AND',
};
const payload = getEndPointDetailsQueryPayload(
mockDomainName,
mockStartTime,
mockEndTime,
filtersWithHttpUrl,
);
const statusCodeQuery = payload[1];
const expression =
statusCodeQuery.query.builder.queryData[0].filter?.expression;
// CRITICAL: http.url converted to OR logic
expect(expression).toContain(
"(http.url = '/api/users' OR url.full = '/api/users')",
);
// Other filters still present
expect(expression).toContain('service.name');
expect(expression).toContain('user-service');
// Base filters present
expect(expression).toContain('net.peer.name');
expect(expression).toContain("kind_string = 'Client'");
expect(expression).toContain('response_status_code EXISTS');
// All ANDed together (at least 2 ANDs: domain+kind, custom filter, url condition)
expect(expression?.match(/AND/g)?.length).toBeGreaterThanOrEqual(2);
});
});
});

View File

@@ -84,7 +84,7 @@ describe('TopErrors', () => {
{
columns: [
{
name: SPAN_ATTRIBUTES.HTTP_URL,
name: 'http.url',
fieldDataType: 'string',
fieldContext: 'attribute',
},
@@ -124,7 +124,7 @@ describe('TopErrors', () => {
table: {
rows: [
{
http_url: '/api/test',
'http.url': '/api/test',
A: 100,
},
],
@@ -206,7 +206,7 @@ describe('TopErrors', () => {
expect(navigateMock).toHaveBeenCalledWith({
filters: expect.arrayContaining([
expect.objectContaining({
key: expect.objectContaining({ key: SPAN_ATTRIBUTES.HTTP_URL }),
key: expect.objectContaining({ key: 'http.url' }),
op: '=',
value: '/api/test',
}),
@@ -335,7 +335,7 @@ describe('TopErrors', () => {
// Verify all required filters are present
expect(filterExpression).toContain(
`kind_string = 'Client' AND ${SPAN_ATTRIBUTES.HTTP_URL} EXISTS AND ${SPAN_ATTRIBUTES.SERVER_NAME} = 'test-domain' AND has_error = true`,
`kind_string = 'Client' AND (http.url EXISTS OR url.full EXISTS) AND (net.peer.name = 'test-domain' OR server.address = 'test-domain') AND has_error = true`,
);
});
});

View File

@@ -15,6 +15,7 @@ import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsAppli
import { convertNanoToMilliseconds } from 'container/MetricsExplorer/Summary/utils';
import dayjs from 'dayjs';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { RowData } from 'lib/query/createTableColumnsFromQuery';
import { cloneDeep } from 'lodash-es';
import { ArrowUpDown, ChevronDown, ChevronRight, Info } from 'lucide-react';
import { getWidgetQuery } from 'pages/MessagingQueues/MQDetails/MetricPage/MetricPageUtil';
@@ -56,12 +57,12 @@ export const getDisplayValue = (value: unknown): string =>
isEmptyFilterValue(value) ? '-' : String(value);
export const getDomainNameFilterExpression = (domainName: string): string =>
`http_host = '${domainName}'`;
`(net.peer.name = '${domainName}' OR server.address = '${domainName}')`;
export const clientKindExpression = `kind_string = 'Client'`;
/**
* Converts filters to expression
* Converts filters to expression, handling http.url specially by creating (http.url OR url.full) condition
* @param filters Filters to convert
* @param baseExpression Base expression to combine with filters
* @returns Filter expression string
@@ -74,6 +75,34 @@ export const convertFiltersWithUrlHandling = (
return baseExpression;
}
// Check if filters contain http.url (SPAN_ATTRIBUTES.URL_PATH)
const httpUrlFilter = filters.items?.find(
(item) => item.key?.key === SPAN_ATTRIBUTES.URL_PATH,
);
// If http.url filter exists, create modified filters with (http.url OR url.full)
if (httpUrlFilter && httpUrlFilter.value) {
// Remove ALL http.url filters from items (guards against duplicates)
const otherFilters = filters.items?.filter(
(item) => item.key?.key !== SPAN_ATTRIBUTES.URL_PATH,
);
// Convert to expression first with other filters
const {
filter: intermediateFilter,
} = convertFiltersToExpressionWithExistingQuery(
{ ...filters, items: otherFilters || [] },
baseExpression,
);
// Add the OR condition for http.url and url.full
const urlValue = httpUrlFilter.value;
const urlCondition = `(http.url = '${urlValue}' OR url.full = '${urlValue}')`;
return intermediateFilter.expression.trim()
? `${intermediateFilter.expression} AND ${urlCondition}`
: urlCondition;
}
const { filter } = convertFiltersToExpressionWithExistingQuery(
filters,
baseExpression,
@@ -342,7 +371,7 @@ export const formatDataForTable = (
});
};
const urlExpression = `${SPAN_ATTRIBUTES.HTTP_URL} EXISTS`;
const urlExpression = `(url.full EXISTS OR http.url EXISTS)`;
export const getDomainMetricsQueryPayload = (
domainName: string,
@@ -559,7 +588,14 @@ const defaultGroupBy = [
dataType: DataTypes.String,
isColumn: false,
isJSON: false,
key: SPAN_ATTRIBUTES.HTTP_URL,
key: SPAN_ATTRIBUTES.URL_PATH,
type: 'attribute',
},
{
dataType: DataTypes.String,
isColumn: false,
isJSON: false,
key: 'url.full',
type: 'attribute',
},
// {
@@ -831,8 +867,8 @@ function buildFilterExpression(
): string {
const baseFilterParts = [
`kind_string = 'Client'`,
`${SPAN_ATTRIBUTES.HTTP_URL} EXISTS`,
`${SPAN_ATTRIBUTES.SERVER_NAME} = '${domainName}'`,
`(http.url EXISTS OR url.full EXISTS)`,
`(net.peer.name = '${domainName}' OR server.address = '${domainName}')`,
`has_error = true`,
];
if (showStatusCodeErrors) {
@@ -874,7 +910,12 @@ export const getTopErrorsQueryPayload = (
filter: { expression: filterExpression },
groupBy: [
{
name: SPAN_ATTRIBUTES.HTTP_URL,
name: 'http.url',
fieldDataType: 'string',
fieldContext: 'attribute',
},
{
name: 'url.full',
fieldDataType: 'string',
fieldContext: 'attribute',
},
@@ -1093,11 +1134,11 @@ export const formatEndPointsDataForTable = (
if (!isGroupedByAttribute) {
formattedData = data?.map((endpoint) => {
const { port } = extractPortAndEndpoint(
(endpoint.data[SPAN_ATTRIBUTES.HTTP_URL] as string) || '',
(endpoint.data[SPAN_ATTRIBUTES.URL_PATH] as string) || '',
);
return {
key: v4(),
endpointName: (endpoint.data[SPAN_ATTRIBUTES.HTTP_URL] as string) || '-',
endpointName: (endpoint.data[SPAN_ATTRIBUTES.URL_PATH] as string) || '-',
port,
callCount:
endpoint.data.A === 'n/a' || endpoint.data.A === undefined
@@ -1221,7 +1262,9 @@ export const formatTopErrorsDataForTable = (
return {
key: v4(),
endpointName: getDisplayValue(rowObj[SPAN_ATTRIBUTES.HTTP_URL]),
endpointName: getDisplayValue(
rowObj[SPAN_ATTRIBUTES.URL_PATH] || rowObj['url.full'],
),
statusCode: getDisplayValue(rowObj[SPAN_ATTRIBUTES.RESPONSE_STATUS_CODE]),
statusMessage: getDisplayValue(rowObj.status_message),
count: getDisplayValue(rowObj.__result_0),
@@ -1238,10 +1281,10 @@ export const getTopErrorsCoRelationQueryFilters = (
{
id: 'ea16470b',
key: {
key: SPAN_ATTRIBUTES.HTTP_URL,
key: 'http.url',
dataType: DataTypes.String,
type: 'tag',
id: `${SPAN_ATTRIBUTES.HTTP_URL}--string--tag--false`,
id: 'http.url--string--tag--false',
},
op: '=',
value: endPointName,
@@ -1738,7 +1781,7 @@ export const getEndPointDetailsQueryPayload = (
filters || { items: [], op: 'AND' },
`${getDomainNameFilterExpression(
domainName,
)} AND ${clientKindExpression} AND ${SPAN_ATTRIBUTES.HTTP_URL} EXISTS`,
)} AND ${clientKindExpression} AND (http.url EXISTS OR url.full EXISTS)`,
),
},
expression: 'A',
@@ -1750,7 +1793,12 @@ export const getEndPointDetailsQueryPayload = (
orderBy: [],
groupBy: [
{
key: SPAN_ATTRIBUTES.HTTP_URL,
key: SPAN_ATTRIBUTES.URL_PATH,
dataType: DataTypes.String,
type: 'attribute',
},
{
key: 'url.full',
dataType: DataTypes.String,
type: 'attribute',
},
@@ -2177,7 +2225,7 @@ export const getEndPointZeroStateQueryPayload = (
orderBy: [],
groupBy: [
{
key: SPAN_ATTRIBUTES.HTTP_URL,
key: SPAN_ATTRIBUTES.URL_PATH,
dataType: DataTypes.String,
type: 'tag',
},
@@ -2371,7 +2419,8 @@ export const statusCodeWidgetInfo = [
interface EndPointDropDownResponseRow {
data: {
[SPAN_ATTRIBUTES.HTTP_URL]: string;
[SPAN_ATTRIBUTES.URL_PATH]: string;
'url.full': string;
A: number;
};
}
@@ -2390,8 +2439,8 @@ export const getFormattedEndPointDropDownData = (
}
return data.map((row) => ({
key: v4(),
label: row.data[SPAN_ATTRIBUTES.HTTP_URL] || '-',
value: row.data[SPAN_ATTRIBUTES.HTTP_URL] || '-',
label: row.data[SPAN_ATTRIBUTES.URL_PATH] || row.data['url.full'] || '-',
value: row.data[SPAN_ATTRIBUTES.URL_PATH] || row.data['url.full'] || '-',
}));
};
@@ -2720,6 +2769,7 @@ export const groupStatusCodes = (
export const getStatusCodeBarChartWidgetData = (
domainName: string,
endPointName: string,
filters: IBuilderQuery['filters'],
): Widgets => ({
query: {
@@ -2748,6 +2798,20 @@ export const getStatusCodeBarChartWidgetData = (
op: '=',
value: domainName,
},
...(endPointName
? [
{
id: '8b1be6f0',
key: {
dataType: DataTypes.String,
key: SPAN_ATTRIBUTES.URL_PATH,
type: 'tag',
},
op: '=',
value: endPointName,
},
]
: []),
...(filters?.items || []),
],
op: 'AND',
@@ -2869,7 +2933,7 @@ export const getAllEndpointsWidgetData = (
filters,
`${getDomainNameFilterExpression(
domainName,
)} AND ${clientKindExpression} AND http_url EXISTS`,
)} AND ${clientKindExpression} AND (http.url EXISTS OR url.full EXISTS)`,
),
},
functions: [],
@@ -2901,7 +2965,7 @@ export const getAllEndpointsWidgetData = (
filters,
`${getDomainNameFilterExpression(
domainName,
)} AND ${clientKindExpression} AND http_url EXISTS`,
)} AND ${clientKindExpression} AND (http.url EXISTS OR url.full EXISTS)`,
),
},
functions: [],
@@ -2933,7 +2997,7 @@ export const getAllEndpointsWidgetData = (
filters,
`${getDomainNameFilterExpression(
domainName,
)} AND ${clientKindExpression} AND http_url EXISTS`,
)} AND ${clientKindExpression} AND (http.url EXISTS OR url.full EXISTS)`,
),
},
functions: [],
@@ -2965,7 +3029,7 @@ export const getAllEndpointsWidgetData = (
filters,
`${getDomainNameFilterExpression(
domainName,
)} AND ${clientKindExpression} AND has_error = true AND http_url EXISTS`,
)} AND ${clientKindExpression} AND has_error = true AND (http.url EXISTS OR url.full EXISTS)`,
),
},
functions: [],
@@ -2996,12 +3060,24 @@ export const getAllEndpointsWidgetData = (
);
widget.renderColumnCell = {
[SPAN_ATTRIBUTES.HTTP_URL]: (url: string | number): ReactNode => {
if (isEmptyFilterValue(url) || !url || url === 'n/a') {
[SPAN_ATTRIBUTES.URL_PATH]: (
url: string | number,
record?: RowData,
): ReactNode => {
// First try to use the url from the column value
let urlValue = url;
// If url is empty/null and we have the record, fallback to url.full
if (isEmptyFilterValue(url) && record) {
const { 'url.full': urlFull } = record;
urlValue = urlFull;
}
if (!urlValue || urlValue === 'n/a') {
return <span>-</span>;
}
const { endpoint } = extractPortAndEndpoint(String(url));
const { endpoint } = extractPortAndEndpoint(String(urlValue));
return <span>{getDisplayValue(endpoint)}</span>;
},
A: (numOfCalls: any): ReactNode => (
@@ -3056,8 +3132,8 @@ export const getAllEndpointsWidgetData = (
};
widget.customColTitles = {
[SPAN_ATTRIBUTES.HTTP_URL]: 'Endpoint',
[SPAN_ATTRIBUTES.SERVER_PORT]: 'Port',
[SPAN_ATTRIBUTES.URL_PATH]: 'Endpoint',
'net.peer.port': 'Port',
};
widget.title = (
@@ -3082,10 +3158,12 @@ export const getAllEndpointsWidgetData = (
</div>
);
widget.hiddenColumns = ['url.full'];
return widget;
};
const keysToRemove = [SPAN_ATTRIBUTES.HTTP_URL, 'A', 'B', 'C', 'F1'];
const keysToRemove = ['http.url', 'url.full', 'A', 'B', 'C', 'F1'];
export const getGroupByFiltersFromGroupByValues = (
rowData: any,
@@ -3143,7 +3221,7 @@ export const getRateOverTimeWidgetData = (
filter: {
expression: convertFiltersWithUrlHandling(
filters || { items: [], op: 'AND' },
`http_host = '${domainName}'`,
`(net.peer.name = '${domainName}' OR server.address = '${domainName}')`,
),
},
functions: [],
@@ -3194,7 +3272,7 @@ export const getLatencyOverTimeWidgetData = (
filter: {
expression: convertFiltersWithUrlHandling(
filters || { items: [], op: 'AND' },
`http_host = '${domainName}'`,
`(net.peer.name = '${domainName}' OR server.address = '${domainName}')`,
),
},
functions: [],

View File

@@ -1,6 +1,7 @@
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useState } from 'react';
import { useMutation } from 'react-query';
import { useCopyToClipboard } from 'react-use';
import { Color } from '@signozhq/design-tokens';
import {
@@ -14,16 +15,14 @@ import {
Tag,
Typography,
} from 'antd';
import {
RenderErrorResponseDTO,
ZeustypesHostDTO,
} from 'api/generated/services/sigNoz.schemas';
import { useGetHosts, usePutHost } from 'api/generated/services/zeus';
import updateSubDomainAPI from 'api/customDomain/updateSubDomain';
import { AxiosError } from 'axios';
import LaunchChatSupport from 'components/LaunchChatSupport/LaunchChatSupport';
import { useGetDeploymentsData } from 'hooks/CustomDomain/useGetDeploymentsData';
import { useNotifications } from 'hooks/useNotifications';
import { InfoIcon, Link2, Pencil } from 'lucide-react';
import { useAppContext } from 'providers/App/App';
import { HostsProps } from 'types/api/customDomain/types';
import './CustomDomainSettings.styles.scss';
@@ -36,7 +35,7 @@ export default function CustomDomainSettings(): JSX.Element {
const { notifications } = useNotifications();
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [isPollingEnabled, setIsPollingEnabled] = useState(false);
const [hosts, setHosts] = useState<ZeustypesHostDTO[] | null>(null);
const [hosts, setHosts] = useState<HostsProps[] | null>(null);
const [updateDomainError, setUpdateDomainError] = useState<AxiosError | null>(
null,
@@ -58,37 +57,36 @@ export default function CustomDomainSettings(): JSX.Element {
};
const {
data: hostsData,
isLoading: isLoadingHosts,
isFetching: isFetchingHosts,
refetch: refetchHosts,
} = useGetHosts();
data: deploymentsData,
isLoading: isLoadingDeploymentsData,
isFetching: isFetchingDeploymentsData,
refetch: refetchDeploymentsData,
} = useGetDeploymentsData(true);
const {
mutate: updateSubDomain,
isLoading: isLoadingUpdateCustomDomain,
} = usePutHost<AxiosError<RenderErrorResponseDTO>>();
const stripProtocol = (url: string): string => {
return url?.split('://')[1] ?? url;
};
const dnsSuffix = useMemo(() => {
const defaultHost = hosts?.find((h) => h.is_default);
return defaultHost?.url && defaultHost?.name
? defaultHost.url.split(`${defaultHost.name}.`)[1] || ''
: '';
}, [hosts]);
} = useMutation(updateSubDomainAPI, {
onSuccess: () => {
setIsPollingEnabled(true);
refetchDeploymentsData();
setIsEditModalOpen(false);
},
onError: (error: AxiosError) => {
setUpdateDomainError(error);
setIsPollingEnabled(false);
},
});
useEffect(() => {
if (isFetchingHosts || !hostsData) {
if (isFetchingDeploymentsData) {
return;
}
if (hostsData.status === 'success') {
setHosts(hostsData.data.hosts ?? null);
if (deploymentsData?.data?.status === 'success') {
setHosts(deploymentsData.data.data.hosts);
const activeCustomDomain = hostsData.data.hosts?.find(
const activeCustomDomain = deploymentsData.data.data.hosts.find(
(host) => !host.is_default,
);
@@ -99,36 +97,32 @@ export default function CustomDomainSettings(): JSX.Element {
}
}
if (hostsData.data.state !== 'HEALTHY' && isPollingEnabled) {
if (deploymentsData?.data?.data?.state !== 'HEALTHY' && isPollingEnabled) {
setTimeout(() => {
refetchHosts();
refetchDeploymentsData();
}, 3000);
}
if (hostsData.data.state === 'HEALTHY') {
if (deploymentsData?.data?.data.state === 'HEALTHY') {
setIsPollingEnabled(false);
}
}, [hostsData, refetchHosts, isPollingEnabled, isFetchingHosts]);
}, [
deploymentsData,
refetchDeploymentsData,
isPollingEnabled,
isFetchingDeploymentsData,
]);
const onUpdateCustomDomainSettings = (): void => {
editForm
.validateFields()
.then((values) => {
if (values.subdomain) {
updateSubDomain(
{ data: { name: values.subdomain } },
{
onSuccess: () => {
setIsPollingEnabled(true);
refetchHosts();
setIsEditModalOpen(false);
},
onError: (error: AxiosError<RenderErrorResponseDTO>) => {
setUpdateDomainError(error as AxiosError);
setIsPollingEnabled(false);
},
updateSubDomain({
data: {
name: values.subdomain,
},
);
});
setCustomDomainDetails({
subdomain: values.subdomain,
@@ -140,8 +134,10 @@ export default function CustomDomainSettings(): JSX.Element {
});
};
const onCopyUrlHandler = (url: string): void => {
setCopyUrl(stripProtocol(url));
const onCopyUrlHandler = (host: string): void => {
const url = `${host}.${deploymentsData?.data.data.cluster.region.dns}`;
setCopyUrl(url);
notifications.success({
message: 'Copied to clipboard',
});
@@ -161,7 +157,7 @@ export default function CustomDomainSettings(): JSX.Element {
</div>
<div className="custom-domain-settings-content">
{!isLoadingHosts && (
{!isLoadingDeploymentsData && (
<Card className="custom-domain-settings-card">
<div className="custom-domain-settings-content-header">
Team {org?.[0]?.displayName} Information
@@ -173,9 +169,10 @@ export default function CustomDomainSettings(): JSX.Element {
<div
className="custom-domain-url"
key={host.name}
onClick={(): void => onCopyUrlHandler(host.url || '')}
onClick={(): void => onCopyUrlHandler(host.name)}
>
<Link2 size={12} /> {stripProtocol(host.url || '')}
<Link2 size={12} /> {host.name}.
{deploymentsData?.data.data.cluster.region.dns}
{host.is_default && <Tag color={Color.BG_ROBIN_500}>Default</Tag>}
</div>
))}
@@ -184,7 +181,11 @@ export default function CustomDomainSettings(): JSX.Element {
<div className="custom-domain-url-edit-btn">
<Button
className="periscope-btn"
disabled={isLoadingHosts || isFetchingHosts || isPollingEnabled}
disabled={
isLoadingDeploymentsData ||
isFetchingDeploymentsData ||
isPollingEnabled
}
type="default"
icon={<Pencil size={10} />}
onClick={(): void => setIsEditModalOpen(true)}
@@ -197,7 +198,7 @@ export default function CustomDomainSettings(): JSX.Element {
{isPollingEnabled && (
<Alert
className="custom-domain-update-status"
message={`Updating your URL to ⎯ ${customDomainDetails?.subdomain}.${dnsSuffix}. This may take a few mins.`}
message={`Updating your URL to ⎯ ${customDomainDetails?.subdomain}.${deploymentsData?.data.data.cluster.region.dns}. This may take a few mins.`}
type="info"
icon={<InfoIcon size={12} />}
/>
@@ -205,7 +206,7 @@ export default function CustomDomainSettings(): JSX.Element {
</Card>
)}
{isLoadingHosts && (
{isLoadingDeploymentsData && (
<Card className="custom-domain-settings-card">
<Skeleton
className="custom-domain-settings-skeleton"
@@ -254,7 +255,7 @@ export default function CustomDomainSettings(): JSX.Element {
addonBefore={updateDomainError && <InfoIcon size={12} color="red" />}
placeholder="Enter Domain"
onChange={(): void => setUpdateDomainError(null)}
addonAfter={dnsSuffix}
addonAfter={deploymentsData?.data.data.cluster.region.dns}
autoFocus
/>
</Form.Item>
@@ -266,8 +267,7 @@ export default function CustomDomainSettings(): JSX.Element {
{updateDomainError.status === 409 ? (
<Alert
message={
(updateDomainError?.response?.data as RenderErrorResponseDTO)?.error
?.message ||
(updateDomainError?.response?.data as { error?: string })?.error ||
'Youve already updated the custom domain once today. To make further changes, please contact our support team for assistance.'
}
type="warning"
@@ -275,10 +275,7 @@ export default function CustomDomainSettings(): JSX.Element {
/>
) : (
<Typography.Text type="danger">
{
(updateDomainError?.response?.data as RenderErrorResponseDTO)?.error
?.message
}
{(updateDomainError.response?.data as { error: string })?.error}
</Typography.Text>
)}
</div>

View File

@@ -1,128 +0,0 @@
import { GetHosts200 } from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import CustomDomainSettings from '../CustomDomainSettings';
const ZEUS_HOSTS_ENDPOINT = '*/api/v2/zeus/hosts';
const mockHostsResponse: GetHosts200 = {
status: 'success',
data: {
name: 'accepted-starfish',
state: 'HEALTHY',
tier: 'PREMIUM',
hosts: [
{
name: 'accepted-starfish',
is_default: true,
url: 'https://accepted-starfish.test.cloud',
},
{
name: 'custom-host',
is_default: false,
url: 'https://custom-host.test.cloud',
},
],
},
};
describe('CustomDomainSettings', () => {
afterEach(() => server.resetHandlers());
it('renders host URLs with protocol stripped and marks the default host', async () => {
server.use(
rest.get(ZEUS_HOSTS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(mockHostsResponse)),
),
);
render(<CustomDomainSettings />);
await screen.findByText(/accepted-starfish\.test\.cloud/i);
await screen.findByText(/custom-host\.test\.cloud/i);
expect(screen.getByText('Default')).toBeInTheDocument();
});
it('opens edit modal with DNS suffix derived from the default host', async () => {
server.use(
rest.get(ZEUS_HOSTS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(mockHostsResponse)),
),
);
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<CustomDomainSettings />);
await screen.findByText(/accepted-starfish\.test\.cloud/i);
await user.click(
screen.getByRole('button', { name: /customize team[']s url/i }),
);
expect(
screen.getByRole('dialog', { name: /customize your team[']s url/i }),
).toBeInTheDocument();
// DNS suffix is the part of the default host URL after the name prefix
expect(screen.getByText('test.cloud')).toBeInTheDocument();
});
it('submits PUT to /zeus/hosts with the entered subdomain as the payload', async () => {
let capturedBody: Record<string, unknown> = {};
server.use(
rest.get(ZEUS_HOSTS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(mockHostsResponse)),
),
rest.put(ZEUS_HOSTS_ENDPOINT, async (req, res, ctx) => {
capturedBody = await req.json<Record<string, unknown>>();
return res(ctx.status(200), ctx.json({}));
}),
);
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<CustomDomainSettings />);
await screen.findByText(/accepted-starfish\.test\.cloud/i);
await user.click(
screen.getByRole('button', { name: /customize team[']s url/i }),
);
const input = screen.getByPlaceholderText(/enter domain/i);
await user.clear(input);
await user.type(input, 'myteam');
await user.click(screen.getByRole('button', { name: /apply changes/i }));
await waitFor(() => {
expect(capturedBody).toEqual({ name: 'myteam' });
});
});
it('shows contact support option when domain update returns 409', async () => {
server.use(
rest.get(ZEUS_HOSTS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(mockHostsResponse)),
),
rest.put(ZEUS_HOSTS_ENDPOINT, (_, res, ctx) =>
res(
ctx.status(409),
ctx.json({ error: { message: 'Already updated today' } }),
),
),
);
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<CustomDomainSettings />);
await screen.findByText(/accepted-starfish\.test\.cloud/i);
await user.click(
screen.getByRole('button', { name: /customize team[']s url/i }),
);
await user.type(screen.getByPlaceholderText(/enter domain/i), 'myteam');
await user.click(screen.getByRole('button', { name: /apply changes/i }));
expect(
await screen.findByRole('button', { name: /contact support/i }),
).toBeInTheDocument();
});
});

View File

@@ -34,9 +34,6 @@ function DashboardVariableSelection(): JSX.Element | null {
const sortedVariablesArray = useDashboardVariablesSelector(
(state) => state.sortedVariablesArray,
);
const dynamicVariableOrder = useDashboardVariablesSelector(
(state) => state.dynamicVariableOrder,
);
const dependencyData = useDashboardVariablesSelector(
(state) => state.dependencyData,
);
@@ -55,11 +52,10 @@ function DashboardVariableSelection(): JSX.Element | null {
}, [getUrlVariables, updateUrlVariable, dashboardVariables]);
// Memoize the order key to avoid unnecessary triggers
const variableOrderKey = useMemo(() => {
const queryVariableOrderKey = dependencyData?.order?.join(',') ?? '';
const dynamicVariableOrderKey = dynamicVariableOrder?.join(',') ?? '';
return `${queryVariableOrderKey}|${dynamicVariableOrderKey}`;
}, [dependencyData?.order, dynamicVariableOrder]);
const dependencyOrderKey = useMemo(
() => dependencyData?.order?.join(',') ?? '',
[dependencyData?.order],
);
// Initialize fetch store then start a new fetch cycle.
// Runs on dependency order changes, and time range changes.
@@ -70,7 +66,7 @@ function DashboardVariableSelection(): JSX.Element | null {
initializeVariableFetchStore(allVariableNames);
enqueueFetchOfAllVariables();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [variableOrderKey, minTime, maxTime]);
}, [dependencyOrderKey, minTime, maxTime]);
// Performance optimization: For dynamic variables with allSelected=true, we don't store
// individual values in localStorage since we can always derive them from available options.

View File

@@ -1,203 +0,0 @@
/* eslint-disable sonarjs/no-duplicate-string */
import { act, render } from '@testing-library/react';
import {
dashboardVariablesStore,
setDashboardVariablesStore,
updateDashboardVariablesStore,
} from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStore';
import {
IDashboardVariables,
IDashboardVariablesStoreState,
} from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreTypes';
import {
enqueueFetchOfAllVariables,
initializeVariableFetchStore,
} from 'providers/Dashboard/store/variableFetchStore';
import { IDashboardVariable } from 'types/api/dashboard/getAll';
import DashboardVariableSelection from '../DashboardVariableSelection';
// Mock providers/Dashboard/Dashboard
const mockSetSelectedDashboard = jest.fn();
const mockUpdateLocalStorageDashboardVariables = jest.fn();
jest.mock('providers/Dashboard/Dashboard', () => ({
useDashboard: (): Record<string, unknown> => ({
setSelectedDashboard: mockSetSelectedDashboard,
updateLocalStorageDashboardVariables: mockUpdateLocalStorageDashboardVariables,
}),
}));
// Mock hooks/dashboard/useVariablesFromUrl
const mockUpdateUrlVariable = jest.fn();
const mockGetUrlVariables = jest.fn().mockReturnValue({});
jest.mock('hooks/dashboard/useVariablesFromUrl', () => ({
__esModule: true,
default: (): Record<string, unknown> => ({
updateUrlVariable: mockUpdateUrlVariable,
getUrlVariables: mockGetUrlVariables,
}),
}));
// Mock variableFetchStore functions
jest.mock('providers/Dashboard/store/variableFetchStore', () => ({
initializeVariableFetchStore: jest.fn(),
enqueueFetchOfAllVariables: jest.fn(),
enqueueDescendantsOfVariable: jest.fn(),
}));
// Mock initializeDefaultVariables
jest.mock('providers/Dashboard/initializeDefaultVariables', () => ({
initializeDefaultVariables: jest.fn(),
}));
// Mock react-redux useSelector for globalTime
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: jest.fn().mockReturnValue({ minTime: 1000, maxTime: 2000 }),
}));
// Mock VariableItem to avoid rendering complexity
jest.mock('../VariableItem', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="variable-item" />,
}));
function createVariable(
overrides: Partial<IDashboardVariable> = {},
): IDashboardVariable {
return {
id: 'test-id',
name: 'test-var',
description: '',
type: 'QUERY',
sort: 'DISABLED',
showALLOption: false,
multiSelect: false,
order: 0,
...overrides,
};
}
function resetStore(): void {
dashboardVariablesStore.set(() => ({
dashboardId: '',
variables: {},
sortedVariablesArray: [],
dependencyData: null,
variableTypes: {},
dynamicVariableOrder: [],
}));
}
describe('DashboardVariableSelection', () => {
beforeEach(() => {
resetStore();
jest.clearAllMocks();
});
it('should call initializeVariableFetchStore and enqueueFetchOfAllVariables on mount', () => {
const variables: IDashboardVariables = {
env: createVariable({ name: 'env', type: 'QUERY', order: 0 }),
};
setDashboardVariablesStore({ dashboardId: 'dash-1', variables });
render(<DashboardVariableSelection />);
expect(initializeVariableFetchStore).toHaveBeenCalledWith(['env']);
expect(enqueueFetchOfAllVariables).toHaveBeenCalled();
});
it('should re-trigger fetch cycle when dynamicVariableOrder changes', () => {
const variables: IDashboardVariables = {
env: createVariable({ name: 'env', type: 'QUERY', order: 0 }),
};
setDashboardVariablesStore({ dashboardId: 'dash-1', variables });
render(<DashboardVariableSelection />);
// Clear mocks after initial render
(initializeVariableFetchStore as jest.Mock).mockClear();
(enqueueFetchOfAllVariables as jest.Mock).mockClear();
// Add a DYNAMIC variable which changes dynamicVariableOrder
act(() => {
updateDashboardVariablesStore({
dashboardId: 'dash-1',
variables: {
env: createVariable({ name: 'env', type: 'QUERY', order: 0 }),
dyn1: createVariable({ name: 'dyn1', type: 'DYNAMIC', order: 1 }),
},
});
});
expect(initializeVariableFetchStore).toHaveBeenCalledWith(
expect.arrayContaining(['env', 'dyn1']),
);
expect(enqueueFetchOfAllVariables).toHaveBeenCalled();
});
it('should re-trigger fetch cycle when a dynamic variable is removed', () => {
const variables: IDashboardVariables = {
env: createVariable({ name: 'env', type: 'QUERY', order: 0 }),
dyn1: createVariable({ name: 'dyn1', type: 'DYNAMIC', order: 1 }),
dyn2: createVariable({ name: 'dyn2', type: 'DYNAMIC', order: 2 }),
};
setDashboardVariablesStore({ dashboardId: 'dash-1', variables });
render(<DashboardVariableSelection />);
(initializeVariableFetchStore as jest.Mock).mockClear();
(enqueueFetchOfAllVariables as jest.Mock).mockClear();
// Remove dyn2, changing dynamicVariableOrder from ['dyn1','dyn2'] to ['dyn1']
act(() => {
updateDashboardVariablesStore({
dashboardId: 'dash-1',
variables: {
env: createVariable({ name: 'env', type: 'QUERY', order: 0 }),
dyn1: createVariable({ name: 'dyn1', type: 'DYNAMIC', order: 1 }),
},
});
});
expect(initializeVariableFetchStore).toHaveBeenCalledWith(['env', 'dyn1']);
expect(enqueueFetchOfAllVariables).toHaveBeenCalled();
});
it('should NOT re-trigger fetch cycle when dynamicVariableOrder stays the same', () => {
const variables: IDashboardVariables = {
env: createVariable({ name: 'env', type: 'QUERY', order: 0 }),
dyn1: createVariable({ name: 'dyn1', type: 'DYNAMIC', order: 1 }),
};
setDashboardVariablesStore({ dashboardId: 'dash-1', variables });
render(<DashboardVariableSelection />);
(initializeVariableFetchStore as jest.Mock).mockClear();
(enqueueFetchOfAllVariables as jest.Mock).mockClear();
// Update a non-dynamic variable's selectedValue — dynamicVariableOrder unchanged
act(() => {
const snapshot = dashboardVariablesStore.getSnapshot();
dashboardVariablesStore.set(
(): IDashboardVariablesStoreState => ({
...snapshot,
variables: {
...snapshot.variables,
env: {
...snapshot.variables.env,
selectedValue: 'production',
},
},
}),
);
});
expect(initializeVariableFetchStore).not.toHaveBeenCalled();
expect(enqueueFetchOfAllVariables).not.toHaveBeenCalled();
});
});

View File

@@ -1,6 +1,7 @@
import { useCallback } from 'react';
import ChartWrapper from 'container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper';
import HistogramTooltip from 'lib/uPlotV2/components/Tooltip/HistogramTooltip';
import { buildTooltipContent } from 'lib/uPlotV2/components/Tooltip/utils';
import {
HistogramTooltipProps,
TooltipRenderArgs,
@@ -21,11 +22,21 @@ export default function Histogram(props: HistogramChartProps): JSX.Element {
if (customRenderTooltip) {
return customRenderTooltip(props);
}
const content = buildTooltipContent({
data: props.uPlotInstance.data,
series: props.uPlotInstance.series,
dataIndexes: props.dataIndexes,
activeSeriesIndex: props.seriesIndex,
uPlotInstance: props.uPlotInstance,
yAxisUnit: rest.yAxisUnit ?? '',
decimalPrecision: rest.decimalPrecision,
});
const tooltipProps: HistogramTooltipProps = {
...props,
timezone: rest.timezone,
yAxisUnit: rest.yAxisUnit,
decimalPrecision: rest.decimalPrecision,
content,
};
return <HistogramTooltip {...tooltipProps} />;
},

View File

@@ -1,6 +1,7 @@
import { useCallback } from 'react';
import ChartWrapper from 'container/DashboardContainer/visualization/charts/ChartWrapper/ChartWrapper';
import TimeSeriesTooltip from 'lib/uPlotV2/components/Tooltip/TimeSeriesTooltip';
import { buildTooltipContent } from 'lib/uPlotV2/components/Tooltip/utils';
import {
TimeSeriesTooltipProps,
TooltipRenderArgs,
@@ -16,11 +17,21 @@ export default function TimeSeries(props: TimeSeriesChartProps): JSX.Element {
if (customRenderTooltip) {
return customRenderTooltip(props);
}
const content = buildTooltipContent({
data: props.uPlotInstance.data,
series: props.uPlotInstance.series,
dataIndexes: props.dataIndexes,
activeSeriesIndex: props.seriesIndex,
uPlotInstance: props.uPlotInstance,
yAxisUnit: rest.yAxisUnit ?? '',
decimalPrecision: rest.decimalPrecision,
});
const tooltipProps: TimeSeriesTooltipProps = {
...props,
timezone: rest.timezone,
yAxisUnit: rest.yAxisUnit,
decimalPrecision: rest.decimalPrecision,
content,
};
return <TimeSeriesTooltip {...tooltipProps} />;
},

View File

@@ -1,22 +1,3 @@
.chart-manager-series-label {
width: 100%;
min-width: 0;
max-width: 100%;
cursor: pointer;
border: none;
background-color: transparent;
color: inherit;
text-align: left;
padding: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
&:disabled {
cursor: not-allowed;
}
}
.chart-manager-container {
width: 100%;
max-height: calc(40% - 40px);

View File

@@ -1,28 +1,24 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Button, Input } from 'antd';
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
import { ResizeTable } from 'components/ResizeTable';
import { getGraphManagerTableColumns } from 'container/GridCardLayout/GridCard/FullView/TableRender/GraphManagerColumns';
import { ExtendedChartDataset } from 'container/GridCardLayout/GridCard/FullView/types';
import { getDefaultTableDataSet } from 'container/GridCardLayout/GridCard/FullView/utils';
import { useNotifications } from 'hooks/useNotifications';
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
import { usePlotContext } from 'lib/uPlotV2/context/PlotContext';
import useLegendsSync from 'lib/uPlotV2/hooks/useLegendsSync';
import { useDashboard } from 'providers/Dashboard/Dashboard';
import { getChartManagerColumns } from './getChartMangerColumns';
import { ExtendedChartDataset, getDefaultTableDataSet } from './utils';
import './ChartManager.styles.scss';
interface ChartManagerProps {
config: UPlotConfigBuilder;
alignedData: uPlot.AlignedData;
yAxisUnit?: string;
decimalPrecision?: PrecisionOption;
onCancel?: () => void;
}
const X_AXIS_INDEX = 0;
/**
* ChartManager provides a tabular view to manage the visibility of
* individual series on a uPlot chart.
@@ -32,12 +28,16 @@ const X_AXIS_INDEX = 0;
* - filter series by label
* - toggle individual series on/off
* - persist the visibility configuration to local storage.
*
* @param config - `UPlotConfigBuilder` instance used to derive chart options.
* @param alignedData - uPlot aligned data used to build the initial table dataset.
* @param yAxisUnit - Optional unit label for Y-axis values shown in the table.
* @param onCancel - Optional callback invoked when the user cancels the dialog.
*/
export default function ChartManager({
config,
alignedData,
yAxisUnit,
decimalPrecision = PrecisionOptionsEnum.TWO,
onCancel,
}: ChartManagerProps): JSX.Element {
const { notifications } = useNotifications();
@@ -53,13 +53,8 @@ export default function ChartManager({
const { isDashboardLocked } = useDashboard();
const [tableDataSet, setTableDataSet] = useState<ExtendedChartDataset[]>(() =>
getDefaultTableDataSet(
config.getConfig() as uPlot.Options,
alignedData,
decimalPrecision,
),
getDefaultTableDataSet(config.getConfig() as uPlot.Options, alignedData),
);
const [filterValue, setFilterValue] = useState('');
const graphVisibilityState = useMemo(
() =>
@@ -72,62 +67,46 @@ export default function ChartManager({
useEffect(() => {
setTableDataSet(
getDefaultTableDataSet(
config.getConfig() as uPlot.Options,
alignedData,
decimalPrecision,
),
getDefaultTableDataSet(config.getConfig() as uPlot.Options, alignedData),
);
setFilterValue('');
}, [alignedData, config, decimalPrecision]);
}, [alignedData, config]);
const handleFilterChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>): void => {
setFilterValue(e.target.value.toLowerCase());
const filterHandler = useCallback(
(event: React.ChangeEvent<HTMLInputElement>): void => {
const value = event.target.value.toString().toLowerCase();
const updatedDataSet = tableDataSet.map((item) => {
if (item.label?.toLocaleLowerCase().includes(value)) {
return { ...item, show: true };
}
return { ...item, show: false };
});
setTableDataSet(updatedDataSet);
},
[],
[tableDataSet],
);
const handleToggleSeriesOnOff = useCallback(
(index: number): void => {
onToggleSeriesOnOff(index);
},
[onToggleSeriesOnOff],
const dataSource = useMemo(
() =>
tableDataSet.filter(
(item, index) => index !== 0 && item.show, // skipping the first item as it is the x-axis
),
[tableDataSet],
);
const dataSource = useMemo(() => {
const filter = filterValue.trim();
return tableDataSet.filter((item, index) => {
if (index === X_AXIS_INDEX) {
return false;
}
if (!filter) {
return true;
}
return item.label?.toLowerCase().includes(filter) ?? false;
});
}, [tableDataSet, filterValue]);
const columns = useMemo(
() =>
getChartManagerColumns({
getGraphManagerTableColumns({
tableDataSet,
checkBoxOnChangeHandler: (_e, index) => {
onToggleSeriesOnOff(index);
},
graphVisibilityState,
onToggleSeriesOnOff: handleToggleSeriesOnOff,
onToggleSeriesVisibility,
labelClickedHandler: onToggleSeriesVisibility,
yAxisUnit,
isGraphDisabled: isDashboardLocked,
decimalPrecision,
}),
[
tableDataSet,
graphVisibilityState,
handleToggleSeriesOnOff,
onToggleSeriesVisibility,
yAxisUnit,
isDashboardLocked,
decimalPrecision,
],
// eslint-disable-next-line react-hooks/exhaustive-deps
[tableDataSet, graphVisibilityState, yAxisUnit, isDashboardLocked],
);
const handleSave = useCallback((): void => {
@@ -135,18 +114,15 @@ export default function ChartManager({
notifications.success({
message: 'The updated graphs & legends are saved',
});
onCancel?.();
if (onCancel) {
onCancel();
}
}, [syncSeriesVisibilityToLocalStorage, notifications, onCancel]);
return (
<div className="chart-manager-container">
<div className="chart-manager-header">
<Input
placeholder="Filter Series"
value={filterValue}
onChange={handleFilterChange}
data-testid="filter-input"
/>
<Input onChange={filterHandler} placeholder="Filter Series" />
<div className="chart-manager-actions-container">
<Button type="default" onClick={onCancel}>
Cancel
@@ -160,10 +136,10 @@ export default function ChartManager({
<ResizeTable
columns={columns}
dataSource={dataSource}
virtual
rowKey="index"
scroll={{ y: 200 }}
pagination={false}
virtual
/>
</div>
</div>

View File

@@ -1,31 +0,0 @@
import { Tooltip } from 'antd';
import './ChartManager.styles.scss';
interface SeriesLabelProps {
label: string;
labelIndex: number;
onClick: (idx: number) => void;
disabled?: boolean;
}
export function SeriesLabel({
label,
labelIndex,
onClick,
disabled,
}: SeriesLabelProps): JSX.Element {
return (
<Tooltip placement="topLeft" title={label}>
<button
className="chart-manager-series-label"
disabled={disabled}
type="button"
data-testid={`series-label-button-${labelIndex}`}
onClick={(): void => onClick(labelIndex)}
>
{label}
</button>
</Tooltip>
);
}

View File

@@ -1,172 +0,0 @@
import userEvent from '@testing-library/user-event';
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
import { render, screen } from 'tests/test-utils';
import ChartManager from '../ChartManager';
const mockSyncSeriesVisibilityToLocalStorage = jest.fn();
const mockNotificationsSuccess = jest.fn();
jest.mock('lib/uPlotV2/context/PlotContext', () => ({
usePlotContext: (): {
onToggleSeriesOnOff: jest.Mock;
onToggleSeriesVisibility: jest.Mock;
syncSeriesVisibilityToLocalStorage: jest.Mock;
} => ({
onToggleSeriesOnOff: jest.fn(),
onToggleSeriesVisibility: jest.fn(),
syncSeriesVisibilityToLocalStorage: mockSyncSeriesVisibilityToLocalStorage,
}),
}));
jest.mock('lib/uPlotV2/hooks/useLegendsSync', () => ({
__esModule: true,
default: (): {
legendItemsMap: { [key: number]: { show: boolean; label: string } };
} => ({
legendItemsMap: {
0: { show: true, label: 'Time' },
1: { show: true, label: 'Series 1' },
2: { show: true, label: 'Series 2' },
},
}),
}));
jest.mock('providers/Dashboard/Dashboard', () => ({
useDashboard: (): { isDashboardLocked: boolean } => ({
isDashboardLocked: false,
}),
}));
jest.mock('hooks/useNotifications', () => ({
useNotifications: (): { notifications: { success: jest.Mock } } => ({
notifications: {
success: mockNotificationsSuccess,
},
}),
}));
jest.mock('components/ResizeTable', () => {
const MockTable = ({
dataSource,
columns,
}: {
dataSource: { index: number; label?: string }[];
columns: { key: string; title: string }[];
}): JSX.Element => (
<div data-testid="resize-table">
{columns.map((col) => (
<span key={col.key}>{col.title}</span>
))}
{dataSource.map((row) => (
<div key={row.index} data-testid={`row-${row.index}`}>
{row.label}
</div>
))}
</div>
);
return { ResizeTable: MockTable };
});
const createMockConfig = (): { getConfig: () => uPlot.Options } => ({
getConfig: (): uPlot.Options => ({
width: 100,
height: 100,
series: [
{ label: 'Time', value: 'time' },
{ label: 'Series 1', scale: 'y' },
{ label: 'Series 2', scale: 'y' },
],
}),
});
const createAlignedData = (): uPlot.AlignedData => [
[1000, 2000, 3000],
[10, 20, 30],
[1, 2, 3],
];
describe('ChartManager', () => {
const mockOnCancel = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
});
it('renders filter input and action buttons', () => {
render(
<ChartManager
config={createMockConfig() as any}
alignedData={createAlignedData()}
onCancel={mockOnCancel}
/>,
);
expect(screen.getByPlaceholderText('Filter Series')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Cancel/ })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Save/ })).toBeInTheDocument();
});
it('renders ResizeTable with data', () => {
render(
<ChartManager
config={createMockConfig() as UPlotConfigBuilder}
alignedData={createAlignedData()}
/>,
);
expect(screen.getByTestId('resize-table')).toBeInTheDocument();
});
it('calls onCancel when Cancel button is clicked', async () => {
render(
<ChartManager
config={createMockConfig() as UPlotConfigBuilder}
alignedData={createAlignedData()}
onCancel={mockOnCancel}
/>,
);
await userEvent.click(screen.getByRole('button', { name: /Cancel/ }));
expect(mockOnCancel).toHaveBeenCalledTimes(1);
});
it('filters table data when typing in filter input', async () => {
render(
<ChartManager
config={createMockConfig() as UPlotConfigBuilder}
alignedData={createAlignedData()}
/>,
);
// Before filter: both Series 1 and Series 2 rows are visible
expect(screen.getByTestId('row-1')).toBeInTheDocument();
expect(screen.getByTestId('row-2')).toBeInTheDocument();
const filterInput = screen.getByTestId('filter-input');
await userEvent.type(filterInput, 'Series 1');
// After filter: only Series 1 row is visible, Series 2 row is filtered out
expect(screen.getByTestId('row-1')).toBeInTheDocument();
expect(screen.queryByTestId('row-2')).not.toBeInTheDocument();
});
it('calls syncSeriesVisibilityToLocalStorage, notifications.success, and onCancel when Save is clicked', async () => {
render(
<ChartManager
config={createMockConfig() as UPlotConfigBuilder}
alignedData={createAlignedData()}
onCancel={mockOnCancel}
/>,
);
await userEvent.click(screen.getByRole('button', { name: /Save/ }));
expect(mockSyncSeriesVisibilityToLocalStorage).toHaveBeenCalledTimes(1);
expect(mockNotificationsSuccess).toHaveBeenCalledWith({
message: 'The updated graphs & legends are saved',
});
expect(mockOnCancel).toHaveBeenCalledTimes(1);
});
});

View File

@@ -1,39 +0,0 @@
import userEvent from '@testing-library/user-event';
import { render, screen } from 'tests/test-utils';
import { SeriesLabel } from '../SeriesLabel';
describe('SeriesLabel', () => {
it('renders the label text', () => {
render(
<SeriesLabel label="Test Series Label" labelIndex={1} onClick={jest.fn()} />,
);
expect(screen.getByTestId('series-label-button-1')).toHaveTextContent(
'Test Series Label',
);
});
it('calls onClick with labelIndex when clicked', async () => {
const onClick = jest.fn();
render(<SeriesLabel label="Series A" labelIndex={2} onClick={onClick} />);
await userEvent.click(screen.getByTestId('series-label-button-2'));
expect(onClick).toHaveBeenCalledWith(2);
expect(onClick).toHaveBeenCalledTimes(1);
});
it('renders disabled button when disabled prop is true', () => {
render(
<SeriesLabel label="Disabled" labelIndex={0} onClick={jest.fn()} disabled />,
);
const button = screen.getByTestId('series-label-button-0');
expect(button).toBeDisabled();
});
it('has chart-manager-series-label class', () => {
render(<SeriesLabel label="Label" labelIndex={0} onClick={jest.fn()} />);
const button = screen.getByTestId('series-label-button-0');
expect(button).toHaveClass('chart-manager-series-label');
});
});

View File

@@ -1,167 +0,0 @@
import { render } from '@testing-library/react';
import { Y_AXIS_UNIT_NAMES } from 'components/YAxisUnitSelector/constants';
import { UniversalYAxisUnit } from 'components/YAxisUnitSelector/types';
import { getChartManagerColumns } from '../getChartMangerColumns';
import { ExtendedChartDataset } from '../utils';
const createMockDataset = (
index: number,
overrides: Partial<ExtendedChartDataset> = {},
): ExtendedChartDataset =>
({
index,
label: `Series ${index}`,
show: true,
sum: 100,
avg: 50,
min: 10,
max: 90,
stroke: '#ff0000',
...overrides,
} as ExtendedChartDataset);
describe('getChartManagerColumns', () => {
const tableDataSet: ExtendedChartDataset[] = [
createMockDataset(0, { label: 'Time' }),
createMockDataset(1),
createMockDataset(2),
];
const graphVisibilityState = [true, true, false];
const onToggleSeriesOnOff = jest.fn();
const onToggleSeriesVisibility = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
});
it('returns columns with expected structure', () => {
const columns = getChartManagerColumns({
tableDataSet,
graphVisibilityState,
onToggleSeriesOnOff,
onToggleSeriesVisibility,
});
expect(columns).toHaveLength(6);
expect(columns[0].key).toBe('index');
expect(columns[1].key).toBe('label');
expect(columns[2].key).toBe('avg');
expect(columns[3].key).toBe('sum');
expect(columns[4].key).toBe('max');
expect(columns[5].key).toBe('min');
});
it('includes Label column with title', () => {
const columns = getChartManagerColumns({
tableDataSet,
graphVisibilityState,
onToggleSeriesOnOff,
onToggleSeriesVisibility,
});
const labelCol = columns.find((c) => c.key === 'label');
expect(labelCol!.title).toBe('Label');
});
it('formats column titles with yAxisUnit', () => {
const columns = getChartManagerColumns({
tableDataSet,
graphVisibilityState,
onToggleSeriesOnOff,
onToggleSeriesVisibility,
yAxisUnit: 'ms',
});
const avgCol = columns.find((c) => c.key === 'avg');
expect(avgCol!.title).toBe(
`Avg (in ${Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.MILLISECONDS]})`,
);
});
it('numeric column render returns formatted string with yAxisUnit', () => {
const columns = getChartManagerColumns({
tableDataSet,
graphVisibilityState,
onToggleSeriesOnOff,
onToggleSeriesVisibility,
yAxisUnit: 'ms',
});
const avgCol = columns.find((c) => c.key === 'avg');
const renderFn = avgCol?.render as
| ((val: number, record: ExtendedChartDataset, index: number) => string)
| undefined;
expect(renderFn).toBeDefined();
const output = renderFn!(123.45, tableDataSet[1], 1);
expect(output).toBe('123.45 ms');
});
it('numeric column render formats zero when value is undefined', () => {
const columns = getChartManagerColumns({
tableDataSet,
graphVisibilityState,
onToggleSeriesOnOff,
onToggleSeriesVisibility,
yAxisUnit: 'none',
});
const sumCol = columns.find((c) => c.key === 'sum');
const renderFn = sumCol?.render as
| ((
val: number | undefined,
record: ExtendedChartDataset,
index: number,
) => string)
| undefined;
const output = renderFn!(undefined, tableDataSet[1], 1);
expect(output).toBe('0');
});
it('label column render displays label text and is clickable', () => {
const columns = getChartManagerColumns({
tableDataSet,
graphVisibilityState,
onToggleSeriesOnOff,
onToggleSeriesVisibility,
});
const labelCol = columns.find((c) => c.key === 'label');
const renderFn = labelCol!.render as
| ((
label: string,
record: ExtendedChartDataset,
index: number,
) => JSX.Element)
| undefined;
expect(renderFn).toBeDefined();
const renderResult = renderFn!('Series 1', tableDataSet[1], 1);
const { getByRole } = render(renderResult);
expect(getByRole('button', { name: 'Series 1' })).toBeInTheDocument();
});
it('index column render renders checkbox with correct checked state', () => {
const columns = getChartManagerColumns({
tableDataSet,
graphVisibilityState,
onToggleSeriesOnOff,
onToggleSeriesVisibility,
});
const indexCol = columns.find((c) => c.key === 'index');
const renderFn = indexCol!.render as
| ((
_val: unknown,
record: ExtendedChartDataset,
index: number,
) => JSX.Element)
| undefined;
expect(renderFn).toBeDefined();
const { container } = render(renderFn!(null, tableDataSet[1], 1));
const checkbox = container.querySelector('input[type="checkbox"]');
expect(checkbox).toBeInTheDocument();
expect(checkbox).toBeChecked(); // graphVisibilityState[1] is true
});
});

View File

@@ -1,113 +0,0 @@
import { PrecisionOptionsEnum } from 'components/Graph/types';
import {
formatTableValueWithUnit,
getDefaultTableDataSet,
getTableColumnTitle,
} from '../utils';
describe('ChartManager utils', () => {
describe('getDefaultTableDataSet', () => {
const createOptions = (seriesCount: number): uPlot.Options => ({
series: Array.from({ length: seriesCount }, (_, i) =>
i === 0
? { label: 'Time', value: 'time' }
: { label: `Series ${i}`, scale: 'y' },
),
width: 100,
height: 100,
});
it('returns one row per series with computed stats', () => {
const options = createOptions(3);
const data: uPlot.AlignedData = [
[1000, 2000, 3000],
[10, 20, 30],
[1, 2, 3],
];
const result = getDefaultTableDataSet(options, data);
expect(result).toHaveLength(3);
expect(result[0]).toMatchObject({
index: 0,
label: 'Time',
show: true,
});
expect(result[1]).toMatchObject({
index: 1,
label: 'Series 1',
show: true,
sum: 60,
avg: 20,
max: 30,
min: 10,
});
expect(result[2]).toMatchObject({
index: 2,
label: 'Series 2',
show: true,
sum: 6,
avg: 2,
max: 3,
min: 1,
});
});
it('handles empty data arrays', () => {
const options = createOptions(2);
const data: uPlot.AlignedData = [[], []];
const result = getDefaultTableDataSet(options, data);
expect(result[0]).toMatchObject({
sum: 0,
avg: 0,
max: 0,
min: 0,
});
});
it('respects decimalPrecision parameter', () => {
const options = createOptions(2);
const data: uPlot.AlignedData = [[1000], [123.454]];
const resultTwo = getDefaultTableDataSet(
options,
data,
PrecisionOptionsEnum.TWO,
);
expect(resultTwo[1].avg).toBe(123.45);
const resultZero = getDefaultTableDataSet(
options,
data,
PrecisionOptionsEnum.ZERO,
);
expect(resultZero[1].avg).toBe(123);
});
});
describe('formatTableValueWithUnit', () => {
it('formats value with unit', () => {
const result = formatTableValueWithUnit(1234.56, 'ms');
expect(result).toBe('1.23 s');
});
it('falls back to none format when yAxisUnit is undefined', () => {
const result = formatTableValueWithUnit(123.45);
expect(result).toBe('123.45');
});
});
describe('getTableColumnTitle', () => {
it('returns title only when yAxisUnit is undefined', () => {
expect(getTableColumnTitle('Avg')).toBe('Avg');
});
it('returns title with unit when yAxisUnit is provided', () => {
const result = getTableColumnTitle('Avg', 'ms');
expect(result).toBe('Avg (in Milliseconds (ms))');
});
});
});

View File

@@ -1,94 +0,0 @@
import { ColumnType } from 'antd/es/table';
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
import CustomCheckBox from 'container/GridCardLayout/GridCard/FullView/TableRender/CustomCheckBox';
import { SeriesLabel } from './SeriesLabel';
import {
ExtendedChartDataset,
formatTableValueWithUnit,
getTableColumnTitle,
} from './utils';
export interface GetChartManagerColumnsParams {
tableDataSet: ExtendedChartDataset[];
graphVisibilityState: boolean[];
onToggleSeriesOnOff: (index: number) => void;
onToggleSeriesVisibility: (index: number) => void;
yAxisUnit?: string;
decimalPrecision?: PrecisionOption;
isGraphDisabled?: boolean;
}
export function getChartManagerColumns({
tableDataSet,
graphVisibilityState,
onToggleSeriesOnOff,
onToggleSeriesVisibility,
yAxisUnit,
decimalPrecision = PrecisionOptionsEnum.TWO,
isGraphDisabled,
}: GetChartManagerColumnsParams): ColumnType<ExtendedChartDataset>[] {
return [
{
title: '',
width: 50,
dataIndex: 'index',
key: 'index',
render: (_: unknown, record: ExtendedChartDataset): JSX.Element => (
<CustomCheckBox
data={tableDataSet}
graphVisibilityState={graphVisibilityState}
index={record.index}
disabled={isGraphDisabled}
checkBoxOnChangeHandler={(_e, idx): void => onToggleSeriesOnOff(idx)}
/>
),
},
{
title: 'Label',
width: 300,
dataIndex: 'label',
key: 'label',
render: (label: string, record: ExtendedChartDataset): JSX.Element => (
<SeriesLabel
label={label ?? ''}
labelIndex={record.index}
disabled={isGraphDisabled}
onClick={onToggleSeriesVisibility}
/>
),
},
{
title: getTableColumnTitle('Avg', yAxisUnit),
width: 90,
dataIndex: 'avg',
key: 'avg',
render: (val: number | undefined): string =>
formatTableValueWithUnit(val ?? 0, yAxisUnit, decimalPrecision),
},
{
title: getTableColumnTitle('Sum', yAxisUnit),
width: 90,
dataIndex: 'sum',
key: 'sum',
render: (val: number | undefined): string =>
formatTableValueWithUnit(val ?? 0, yAxisUnit, decimalPrecision),
},
{
title: getTableColumnTitle('Max', yAxisUnit),
width: 90,
dataIndex: 'max',
key: 'max',
render: (val: number | undefined): string =>
formatTableValueWithUnit(val ?? 0, yAxisUnit, decimalPrecision),
},
{
title: getTableColumnTitle('Min', yAxisUnit),
width: 90,
dataIndex: 'min',
key: 'min',
render: (val: number | undefined): string =>
formatTableValueWithUnit(val ?? 0, yAxisUnit, decimalPrecision),
},
];
}

View File

@@ -1,93 +0,0 @@
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
import { Y_AXIS_UNIT_NAMES } from 'components/YAxisUnitSelector/constants';
import uPlot from 'uplot';
/** Extended series with computed stats for table display */
export type ExtendedChartDataset = uPlot.Series & {
show: boolean;
sum: number;
avg: number;
min: number;
max: number;
index: number;
};
function roundToDecimalPrecision(
value: number,
decimalPrecision: PrecisionOption = PrecisionOptionsEnum.TWO,
): number {
if (
typeof value !== 'number' ||
Number.isNaN(value) ||
value === Infinity ||
value === -Infinity
) {
return 0;
}
if (decimalPrecision === PrecisionOptionsEnum.FULL) {
return value;
}
// regex to match the decimal precision for the given decimal precision
const regex = new RegExp(`^-?\\d*\\.?0*\\d{0,${decimalPrecision}}`);
const matched = value ? value.toFixed(decimalPrecision).match(regex) : null;
return matched ? parseFloat(matched[0]) : 0;
}
/** Build table dataset from uPlot options and aligned data */
export function getDefaultTableDataSet(
options: uPlot.Options,
data: uPlot.AlignedData,
decimalPrecision: PrecisionOption = PrecisionOptionsEnum.TWO,
): ExtendedChartDataset[] {
return options.series.map(
(series: uPlot.Series, index: number): ExtendedChartDataset => {
const arr = (data[index] as number[]) ?? [];
const sum = arr.reduce((a, b) => a + b, 0) || 0;
const count = arr.length || 1;
const hasValues = arr.length > 0;
return {
...series,
index,
show: true,
sum: roundToDecimalPrecision(sum, decimalPrecision),
avg: roundToDecimalPrecision(sum / count, decimalPrecision),
max: hasValues
? roundToDecimalPrecision(Math.max(...arr), decimalPrecision)
: 0,
min: hasValues
? roundToDecimalPrecision(Math.min(...arr), decimalPrecision)
: 0,
};
},
);
}
/** Format numeric value for table display using yAxisUnit */
export function formatTableValueWithUnit(
value: number,
yAxisUnit?: string,
decimalPrecision: PrecisionOption = PrecisionOptionsEnum.TWO,
): string {
return `${getYAxisFormattedValue(
String(value),
yAxisUnit ?? 'none',
decimalPrecision,
)}`;
}
/** Format column header with optional unit */
export function getTableColumnTitle(title: string, yAxisUnit?: string): string {
if (!yAxisUnit) {
return title;
}
const universalName =
Y_AXIS_UNIT_NAMES[yAxisUnit as keyof typeof Y_AXIS_UNIT_NAMES];
if (!universalName) {
return `${title} (in ${yAxisUnit})`;
}
return `${title} (in ${universalName})`;
}

View File

@@ -96,7 +96,6 @@ function BarPanel(props: PanelWrapperProps): JSX.Element {
config={config}
alignedData={chartData}
yAxisUnit={widget.yAxisUnit}
decimalPrecision={widget.decimalPrecision}
onCancel={onToggleModelHandler}
/>
);
@@ -106,7 +105,6 @@ function BarPanel(props: PanelWrapperProps): JSX.Element {
chartData,
widget.yAxisUnit,
onToggleModelHandler,
widget.decimalPrecision,
]);
const onPlotDestroy = useCallback(() => {

View File

@@ -95,7 +95,6 @@ function TimeSeriesPanel(props: PanelWrapperProps): JSX.Element {
config={config}
alignedData={chartData}
yAxisUnit={widget.yAxisUnit}
decimalPrecision={widget.decimalPrecision}
onCancel={onToggleModelHandler}
/>
);
@@ -105,7 +104,6 @@ function TimeSeriesPanel(props: PanelWrapperProps): JSX.Element {
chartData,
widget.yAxisUnit,
onToggleModelHandler,
widget.decimalPrecision,
]);
return (

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

@@ -2,10 +2,10 @@
import { useEffect, useState } from 'react';
import { Button, Skeleton, Tag, Typography } from 'antd';
import logEvent from 'api/common/logEvent';
import { useGetHosts } from 'api/generated/services/zeus';
import ROUTES from 'constants/routes';
import { useGetDeploymentsData } from 'hooks/CustomDomain/useGetDeploymentsData';
import history from 'lib/history';
import { Link2 } from 'lucide-react';
import { Globe, Link2 } from 'lucide-react';
import Card from 'periscope/components/Card/Card';
import { useAppContext } from 'providers/App/App';
import { LicensePlatform } from 'types/api/licensesV3/getActive';
@@ -26,21 +26,36 @@ function DataSourceInfo({
const isEnabled =
activeLicense && activeLicense.platform === LicensePlatform.CLOUD;
const { data: hostsData, isError } = useGetHosts({
query: { enabled: isEnabled || false },
});
const {
data: deploymentsData,
isError: isErrorDeploymentsData,
} = useGetDeploymentsData(isEnabled || false);
const [region, setRegion] = useState<string>('');
const [url, setUrl] = useState<string>('');
useEffect(() => {
if (hostsData) {
const defaultHost = hostsData?.data.hosts?.find((h) => h.is_default);
if (defaultHost?.url) {
const url = defaultHost?.url?.split('://')[1] ?? '';
setUrl(url);
if (deploymentsData) {
switch (deploymentsData?.data.data.cluster.region.name) {
case 'in':
setRegion('India');
break;
case 'us':
setRegion('United States');
break;
case 'eu':
setRegion('Europe');
break;
default:
setRegion(deploymentsData?.data.data.cluster.region.name);
break;
}
setUrl(
`${deploymentsData?.data.data.name}.${deploymentsData?.data.data.cluster.region.dns}`,
);
}
}, [hostsData]);
}, [deploymentsData]);
const renderNotSendingData = (): JSX.Element => (
<>
@@ -108,8 +123,14 @@ function DataSourceInfo({
</Button>
</div>
{!isError && hostsData && (
{!isErrorDeploymentsData && deploymentsData && (
<div className="workspace-details">
<div className="workspace-region">
<Globe size={10} />
<Typography>{region}</Typography>
</div>
<div className="workspace-url">
<Link2 size={12} />
@@ -135,11 +156,17 @@ function DataSourceInfo({
Hello there, Welcome to your SigNoz workspace
</Typography>
{!isError && hostsData && (
{!isErrorDeploymentsData && deploymentsData && (
<Card className="welcome-card">
<Card.Content>
<div className="workspace-ready-container">
<div className="workspace-details">
<div className="workspace-region">
<Globe size={10} />
<Typography>{region}</Typography>
</div>
<div className="workspace-url">
<Link2 size={12} />

View File

@@ -1,69 +0,0 @@
import { GetHosts200 } from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import { render, screen } from 'tests/test-utils';
import DataSourceInfo from '../DataSourceInfo';
const ZEUS_HOSTS_ENDPOINT = '*/api/v2/zeus/hosts';
const mockHostsResponse: GetHosts200 = {
status: 'success',
data: {
name: 'accepted-starfish',
state: 'HEALTHY',
tier: 'PREMIUM',
hosts: [
{
name: 'accepted-starfish',
is_default: true,
url: 'https://accepted-starfish.test.cloud',
},
{
name: 'custom-host',
is_default: false,
url: 'https://custom-host.test.cloud',
},
],
},
};
describe('DataSourceInfo', () => {
afterEach(() => server.resetHandlers());
it('renders the default workspace URL with protocol stripped', async () => {
server.use(
rest.get(ZEUS_HOSTS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(mockHostsResponse)),
),
);
render(<DataSourceInfo dataSentToSigNoz={false} isLoading={false} />);
await screen.findByText(/accepted-starfish\.test\.cloud/i);
});
it('does not render workspace URL when GET /zeus/hosts fails', async () => {
server.use(
rest.get(ZEUS_HOSTS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(500), ctx.json({})),
),
);
render(<DataSourceInfo dataSentToSigNoz={false} isLoading={false} />);
await screen.findByText(/Your workspace is ready/i);
expect(screen.queryByText(/signoz\.cloud/i)).not.toBeInTheDocument();
});
it('renders workspace URL in the data-received view when telemetry is flowing', async () => {
server.use(
rest.get(ZEUS_HOSTS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(mockHostsResponse)),
),
);
render(<DataSourceInfo dataSentToSigNoz={true} isLoading={false} />);
await screen.findByText(/accepted-starfish\.test\.cloud/i);
});
});

View File

@@ -178,9 +178,7 @@ export default function HostsListTable({
indicator: <Spin indicator={<LoadingOutlined size={14} spin />} />,
}}
tableLayout="fixed"
rowKey={(record): string =>
(record as HostRowData & { key: string }).key ?? record.hostName
}
rowKey={(record): string => record.hostName}
onChange={handleTableChange}
onRow={(record): { onClick: () => void; className: string } => ({
onClick: (): void => handleRowClick(record),

View File

@@ -126,8 +126,7 @@
background: var(--bg-ink-500);
}
.ant-table-cell:has(.hostname-column-value),
.ant-table-cell:has(.hostname-cell-missing) {
.ant-table-cell:has(.hostname-column-value) {
background: var(--bg-ink-400);
}
@@ -140,23 +139,6 @@
letter-spacing: -0.07px;
}
.hostname-cell-missing {
display: flex;
align-items: center;
gap: 4px;
}
.hostname-cell-placeholder {
color: var(--Vanilla-400, #c0c1c3);
}
.hostname-cell-warning-icon {
display: inline-flex;
align-items: center;
margin-left: 4px;
cursor: help;
}
.status-cell {
.active-tag {
color: var(--bg-forest-500);
@@ -375,8 +357,7 @@
color: var(--bg-ink-500);
}
.ant-table-cell:has(.hostname-column-value),
.ant-table-cell:has(.hostname-cell-missing) {
.ant-table-cell:has(.hostname-column-value) {
background: var(--bg-vanilla-100);
}
@@ -384,10 +365,6 @@
color: var(--bg-ink-300);
}
.hostname-cell-placeholder {
color: var(--text-ink-300);
}
.ant-table-tbody > tr:hover > td {
background: rgba(0, 0, 0, 0.04);
}

View File

@@ -1,24 +1,13 @@
import { render, screen } from '@testing-library/react';
import { HostData, TimeSeries } from 'api/infraMonitoring/getHostLists';
import { render } from '@testing-library/react';
import {
formatDataForTable,
GetHostsQuickFiltersConfig,
HostnameCell,
} from '../utils';
import { formatDataForTable, GetHostsQuickFiltersConfig } from '../utils';
const PROGRESS_BAR_CLASS = '.progress-bar';
const emptyTimeSeries: TimeSeries = {
labels: {},
labelsArray: [],
values: [],
};
describe('InfraMonitoringHosts utils', () => {
describe('formatDataForTable', () => {
it('should format host data correctly', () => {
const mockData: HostData[] = [
const mockData = [
{
hostName: 'test-host',
active: true,
@@ -27,12 +16,8 @@ describe('InfraMonitoringHosts utils', () => {
wait: 0.05,
load15: 2.5,
os: 'linux',
cpuTimeSeries: emptyTimeSeries,
memoryTimeSeries: emptyTimeSeries,
waitTimeSeries: emptyTimeSeries,
load15TimeSeries: emptyTimeSeries,
},
];
] as any;
const result = formatDataForTable(mockData);
@@ -61,7 +46,7 @@ describe('InfraMonitoringHosts utils', () => {
});
it('should handle inactive hosts', () => {
const mockData: HostData[] = [
const mockData = [
{
hostName: 'test-host',
active: false,
@@ -70,12 +55,12 @@ describe('InfraMonitoringHosts utils', () => {
wait: 0.02,
load15: 1.2,
os: 'linux',
cpuTimeSeries: emptyTimeSeries,
memoryTimeSeries: emptyTimeSeries,
waitTimeSeries: emptyTimeSeries,
load15TimeSeries: emptyTimeSeries,
cpuTimeSeries: [],
memoryTimeSeries: [],
waitTimeSeries: [],
load15TimeSeries: [],
},
];
] as any;
const result = formatDataForTable(mockData);
@@ -83,65 +68,6 @@ describe('InfraMonitoringHosts utils', () => {
expect(inactiveTag.container.textContent).toBe('INACTIVE');
expect(inactiveTag.container.querySelector('.inactive')).toBeTruthy();
});
it('should set hostName to empty string when host has no hostname', () => {
const mockData: HostData[] = [
{
hostName: '',
active: true,
cpu: 0.5,
memory: 0.4,
wait: 0.01,
load15: 1.0,
os: 'linux',
cpuTimeSeries: emptyTimeSeries,
memoryTimeSeries: emptyTimeSeries,
waitTimeSeries: emptyTimeSeries,
load15TimeSeries: emptyTimeSeries,
},
];
const result = formatDataForTable(mockData);
expect(result[0].hostName).toBe('');
expect(result[0].key).toBe('-0');
});
});
describe('HostnameCell', () => {
it('should render hostname when present (case A: no icon)', () => {
const { container } = render(<HostnameCell hostName="gke-prod-1" />);
expect(container.querySelector('.hostname-column-value')).toBeTruthy();
expect(container.textContent).toBe('gke-prod-1');
expect(container.querySelector('.hostname-cell-missing')).toBeFalsy();
expect(container.querySelector('.hostname-cell-warning-icon')).toBeFalsy();
});
it('should render placeholder and icon when hostName is empty (case B)', () => {
const { container } = render(<HostnameCell hostName="" />);
expect(screen.getByText('-')).toBeTruthy();
expect(container.querySelector('.hostname-cell-missing')).toBeTruthy();
const iconWrapper = container.querySelector('.hostname-cell-warning-icon');
expect(iconWrapper).toBeTruthy();
expect(iconWrapper?.getAttribute('aria-label')).toBe(
'Missing host.name metadata',
);
expect(iconWrapper?.getAttribute('tabindex')).toBe('0');
// Tooltip with "Learn how to configure →" link is shown on hover/focus
});
it('should render placeholder and icon when hostName is whitespace only (case C)', () => {
const { container } = render(<HostnameCell hostName=" " />);
expect(screen.getByText('-')).toBeTruthy();
expect(container.querySelector('.hostname-cell-missing')).toBeTruthy();
expect(container.querySelector('.hostname-cell-warning-icon')).toBeTruthy();
});
it('should render placeholder and icon when hostName is undefined (case D)', () => {
const { container } = render(<HostnameCell hostName={undefined} />);
expect(screen.getByText('-')).toBeTruthy();
expect(container.querySelector('.hostname-cell-missing')).toBeTruthy();
expect(container.querySelector('.hostname-cell-warning-icon')).toBeTruthy();
});
});
describe('GetHostsQuickFiltersConfig', () => {

View File

@@ -1,7 +1,7 @@
import { Dispatch, SetStateAction } from 'react';
import { InfoCircleOutlined } from '@ant-design/icons';
import { Color } from '@signozhq/design-tokens';
import { Progress, TabsProps, Tag, Tooltip, Typography } from 'antd';
import { Progress, TabsProps, Tag, Tooltip } from 'antd';
import { ColumnType } from 'antd/es/table';
import {
HostData,
@@ -14,7 +14,6 @@ import {
} from 'components/QuickFilters/types';
import TabLabel from 'components/TabLabel';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { TriangleAlert } from 'lucide-react';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
@@ -25,7 +24,6 @@ import HostsList from './HostsList';
import './InfraMonitoring.styles.scss';
export interface HostRowData {
key?: string;
hostName: string;
cpu: React.ReactNode;
memory: React.ReactNode;
@@ -34,59 +32,6 @@ export interface HostRowData {
active: React.ReactNode;
}
const HOSTNAME_DOCS_URL =
'https://signoz.io/docs/infrastructure-monitoring/hostmetrics/#host-name-is-blankempty';
export function HostnameCell({
hostName,
}: {
hostName?: string | null;
}): React.ReactElement {
const isEmpty = !hostName || !hostName.trim();
if (!isEmpty) {
return <div className="hostname-column-value">{hostName}</div>;
}
return (
<div className="hostname-cell-missing">
<Typography.Text type="secondary" className="hostname-cell-placeholder">
-
</Typography.Text>
<Tooltip
title={
<div>
Missing host.name metadata.
<br />
<a
href={HOSTNAME_DOCS_URL}
target="_blank"
rel="noopener noreferrer"
onClick={(e): void => e.stopPropagation()}
>
Learn how to configure
</a>
</div>
}
trigger={['hover', 'focus']}
>
<span
className="hostname-cell-warning-icon"
tabIndex={0}
role="img"
aria-label="Missing host.name metadata"
onClick={(e): void => e.stopPropagation()}
onKeyDown={(e): void => {
if (e.key === 'Enter' || e.key === ' ') {
e.stopPropagation();
}
}}
>
<TriangleAlert size={14} color={Color.BG_CHERRY_500} />
</span>
</Tooltip>
</div>
);
}
export interface HostsListTableProps {
isLoading: boolean;
isError: boolean;
@@ -130,8 +75,8 @@ export const getHostsListColumns = (): ColumnType<HostRowData>[] => [
dataIndex: 'hostName',
key: 'hostName',
width: 250,
render: (value: string | undefined): React.ReactNode => (
<HostnameCell hostName={value ?? ''} />
render: (value: string): React.ReactNode => (
<div className="hostname-column-value">{value}</div>
),
},
{

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

@@ -36,6 +36,24 @@ jest.mock('react-router-dom', () => {
};
});
// Mock deployments data hook to avoid unrelated network calls in this page
jest.mock(
'hooks/CustomDomain/useGetDeploymentsData',
(): Record<string, unknown> => ({
useGetDeploymentsData: (): {
data: undefined;
isLoading: boolean;
isFetching: boolean;
isError: boolean;
} => ({
data: undefined,
isLoading: false,
isFetching: false,
isError: false,
}),
}),
);
const TEST_CREATED_UPDATED = '2024-01-01T00:00:00Z';
const TEST_EXPIRES_AT = '2030-01-01T00:00:00Z';
const TEST_WORKSPACE_ID = 'w1';

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