mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-24 17:21:06 +00:00
Compare commits
16 Commits
nv/exec-st
...
fix/trunca
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e45107015 | ||
|
|
94016b4f35 | ||
|
|
1664c29cf4 | ||
|
|
f4bc90da34 | ||
|
|
02de020642 | ||
|
|
570e622a46 | ||
|
|
381cda6821 | ||
|
|
9dbe4db00e | ||
|
|
da35d99714 | ||
|
|
f955bb952a | ||
|
|
cb0adcc618 | ||
|
|
b14b634bce | ||
|
|
7ea0d57417 | ||
|
|
1e08a94ab8 | ||
|
|
cbfbb103af | ||
|
|
fbca5e7d80 |
@@ -15,3 +15,4 @@ paths:
|
||||
- When defining types, keep the structure of file to have any constants and variables first, then exported types and exported methods and then finally the unexported types and methods.
|
||||
- Never import types or other modules in migration files, duplicate the required type or method to keep migration free from changes.
|
||||
- Always run the gofmt tool for formating beforing commiting any changes.
|
||||
- **Never copy through a pointer dereference** (`copied := *original`). It copies only the top level: pointer, slice and map fields stay shared, so changing the copy can change the original. Use the type's `Copy()` when it has one (`QueryBuilderFormula.Copy`); otherwise create a new struct literal from the fields you need. A `Copy()` itself may dereference, as long as it then replaces every pointer, slice and map field.
|
||||
|
||||
2
.github/workflows/e2eci.yaml
vendored
2
.github/workflows/e2eci.yaml
vendored
@@ -94,7 +94,7 @@ jobs:
|
||||
postgres:15 \
|
||||
clickhouse/clickhouse-server:25.12.5 \
|
||||
clickhouse/clickhouse-keeper:25.12.5 \
|
||||
signoz/signoz-otel-collector:v0.144.16-rc.1 \
|
||||
signoz/signoz-otel-collector:v0.144.17 \
|
||||
wiremock/wiremock:2.35.1-1 \
|
||||
| xargs -P 0 -n 1 docker pull -q
|
||||
- name: python
|
||||
|
||||
7
.github/workflows/integrationci.yaml
vendored
7
.github/workflows/integrationci.yaml
vendored
@@ -85,13 +85,18 @@ jobs:
|
||||
- wal
|
||||
clickhouse-version:
|
||||
- 25.12.5
|
||||
- 26.8.34
|
||||
signoz-otel-collector-version:
|
||||
- v0.144.16-rc.1
|
||||
- v0.144.17
|
||||
postgres-version:
|
||||
- 15
|
||||
exclude:
|
||||
- sqlstore-provider: postgres
|
||||
clickhouse-version: 26.8.34
|
||||
if: |
|
||||
((github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
|
||||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))) && contains(github.event.pull_request.labels.*.name, 'safe-to-integrate')
|
||||
continue-on-error: ${{ matrix.clickhouse-version == '26.8.34' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
|
||||
@@ -474,6 +474,14 @@ auditor:
|
||||
compression: lz4
|
||||
# The maximum time to drain buffered events on shutdown. Undelivered events are dropped after it.
|
||||
shutdown_timeout: 30s
|
||||
tls:
|
||||
# Whether to connect to the brokers over TLS.
|
||||
enabled: false
|
||||
# The PEM CA bundle that verifies broker certificates. Empty uses the system roots.
|
||||
ca_file: ""
|
||||
# The client certificate and key, for brokers that require client auth. Set both or neither.
|
||||
cert_file: ""
|
||||
key_file: ""
|
||||
|
||||
##################### Cloud Integration #####################
|
||||
cloudintegration:
|
||||
|
||||
@@ -16274,13 +16274,22 @@ paths:
|
||||
where it is case-sensitive and % and _ act as wildcards. For keys, a context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.'
|
||||
type: string
|
||||
- description: The key whose values to return, such as service.name. A context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
- description: 'The key whose values to return, such as service.name. With fieldContext
|
||||
set, it is the stored name as is. Otherwise a context prefix such as resource.service.name
|
||||
sets the context and a type suffix such as service.name:string sets fieldDataType
|
||||
when that is empty; as in filter expressions, a prefixed name also matches
|
||||
a key stored under the full name, whose values come first: log.level returns
|
||||
values of a key named log.level, then of the log field level.'
|
||||
in: query
|
||||
name: name
|
||||
schema:
|
||||
description: The key whose values to return, such as service.name. A context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
description: 'The key whose values to return, such as service.name. With
|
||||
fieldContext set, it is the stored name as is. Otherwise a context prefix
|
||||
such as resource.service.name sets the context and a type suffix such
|
||||
as service.name:string sets fieldDataType when that is empty; as in filter
|
||||
expressions, a prefixed name also matches a key stored under the full
|
||||
name, whose values come first: log.level returns values of a key named
|
||||
log.level, then of the log field level.'
|
||||
type: string
|
||||
- description: Filter expression already applied in the explorer. When set,
|
||||
relatedValues lists the values seen on data matching it.
|
||||
@@ -28927,13 +28936,22 @@ paths:
|
||||
where it is case-sensitive and % and _ act as wildcards. For keys, a context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.'
|
||||
type: string
|
||||
- description: The key whose values to return, such as service.name. A context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
- description: 'The key whose values to return, such as service.name. With fieldContext
|
||||
set, it is the stored name as is. Otherwise a context prefix such as resource.service.name
|
||||
sets the context and a type suffix such as service.name:string sets fieldDataType
|
||||
when that is empty; as in filter expressions, a prefixed name also matches
|
||||
a key stored under the full name, whose values come first: log.level returns
|
||||
values of a key named log.level, then of the log field level.'
|
||||
in: query
|
||||
name: name
|
||||
schema:
|
||||
description: The key whose values to return, such as service.name. A context
|
||||
prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
description: 'The key whose values to return, such as service.name. With
|
||||
fieldContext set, it is the stored name as is. Otherwise a context prefix
|
||||
such as resource.service.name sets the context and a type suffix such
|
||||
as service.name:string sets fieldDataType when that is empty; as in filter
|
||||
expressions, a prefixed name also matches a key stored under the full
|
||||
name, whose values come first: log.level returns values of a key named
|
||||
log.level, then of the log field level.'
|
||||
type: string
|
||||
- description: Filter expression already applied in the explorer. When set,
|
||||
relatedValues lists the values seen on data matching it.
|
||||
|
||||
@@ -2,7 +2,10 @@ package kafkaauditor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
"github.com/twmb/franz-go/plugin/kslog"
|
||||
@@ -10,6 +13,7 @@ import (
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/auditor"
|
||||
"github.com/SigNoz/signoz/pkg/auditor/auditorserver"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
"github.com/SigNoz/signoz/pkg/licensing"
|
||||
"github.com/SigNoz/signoz/pkg/types/audittypes"
|
||||
@@ -39,13 +43,25 @@ func newProvider(_ context.Context, providerSettings factory.ProviderSettings, c
|
||||
|
||||
// Acks from all in-sync replicas, idempotent writes and unbounded record retries are franz-go defaults and are kept as is.
|
||||
// A delivery timeout or retry limit lets franz-go < v1.22.2 ack a record that was never written (twmb/franz-go#1484).
|
||||
client, err := kgo.NewClient(
|
||||
opts := []kgo.Opt{
|
||||
kgo.SeedBrokers(config.Kafka.Brokers...),
|
||||
kgo.ClientID(config.Kafka.ClientID),
|
||||
kgo.ProducerBatchCompression(compressionCodec(config.Kafka.Compression)),
|
||||
kgo.ProducerLinger(0),
|
||||
kgo.WithLogger(kslog.New(settings.Logger())),
|
||||
)
|
||||
}
|
||||
|
||||
if config.Kafka.TLS.Enabled {
|
||||
tlsConfig, err := newTLSConfig(config.Kafka.TLS)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// franz-go sets ServerName per broker from the dialed address.
|
||||
opts = append(opts, kgo.DialTLSConfig(tlsConfig))
|
||||
}
|
||||
|
||||
client, err := kgo.NewClient(opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -130,3 +146,30 @@ func compressionCodec(name string) kgo.CompressionCodec {
|
||||
return kgo.NoCompression()
|
||||
}
|
||||
}
|
||||
|
||||
func newTLSConfig(config auditor.TLSConfig) (*tls.Config, error) {
|
||||
tlsConfig := &tls.Config{}
|
||||
|
||||
if config.CAFile != "" {
|
||||
caPEM, err := os.ReadFile(config.CAFile)
|
||||
if err != nil {
|
||||
return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot read auditor::kafka::tls::ca_file")
|
||||
}
|
||||
|
||||
tlsConfig.RootCAs = x509.NewCertPool()
|
||||
if !tlsConfig.RootCAs.AppendCertsFromPEM(caPEM) {
|
||||
return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "auditor::kafka::tls::ca_file %q holds no PEM certificate", config.CAFile)
|
||||
}
|
||||
}
|
||||
|
||||
if config.CertFile != "" {
|
||||
cert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)
|
||||
if err != nil {
|
||||
return nil, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "cannot load auditor::kafka::tls::cert_file and auditor::kafka::tls::key_file")
|
||||
}
|
||||
|
||||
tlsConfig.Certificates = []tls.Certificate{cert}
|
||||
}
|
||||
|
||||
return tlsConfig, nil
|
||||
}
|
||||
|
||||
269
ee/auditor/kafkaauditor/tls_test.go
Normal file
269
ee/auditor/kafkaauditor/tls_test.go
Normal file
@@ -0,0 +1,269 @@
|
||||
package kafkaauditor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/twmb/franz-go/pkg/kfake"
|
||||
"github.com/twmb/franz-go/pkg/kgo"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/auditor"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
|
||||
"github.com/SigNoz/signoz/pkg/types/audittypes"
|
||||
"github.com/SigNoz/signoz/pkg/types/coretypes"
|
||||
"github.com/SigNoz/signoz/pkg/version"
|
||||
)
|
||||
|
||||
func TestExport_MutualTLS(t *testing.T) {
|
||||
certificates := newTestCertificates(t)
|
||||
|
||||
cluster, err := kfake.NewCluster(
|
||||
kfake.NumBrokers(1),
|
||||
kfake.SeedTopics(1, "tls_audit"),
|
||||
kfake.TLS(&tls.Config{
|
||||
Certificates: []tls.Certificate{certificates.server},
|
||||
ClientCAs: certificates.caPool,
|
||||
ClientAuth: tls.RequireAndVerifyClientCert,
|
||||
}),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(cluster.Close)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
tls auditor.TLSConfig
|
||||
err bool
|
||||
}{
|
||||
{
|
||||
name: "CAAndClientCertificate_Delivers",
|
||||
tls: certificates.client,
|
||||
},
|
||||
{
|
||||
name: "TLSDisabled_Fails",
|
||||
tls: auditor.TLSConfig{},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
name: "WithoutClientCertificate_Fails",
|
||||
tls: auditor.TLSConfig{Enabled: true, CAFile: certificates.client.CAFile},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
name: "WithoutCA_Fails",
|
||||
tls: auditor.TLSConfig{Enabled: true, CertFile: certificates.client.CertFile, KeyFile: certificates.client.KeyFile},
|
||||
err: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
config := auditor.Config{
|
||||
Provider: "kafka",
|
||||
BufferSize: 10,
|
||||
BatchSize: 5,
|
||||
FlushInterval: 50 * time.Millisecond,
|
||||
Kafka: auditor.KafkaConfig{
|
||||
Brokers: cluster.ListenAddrs(),
|
||||
Topic: "tls_audit",
|
||||
ClientID: "signoz-tls-test",
|
||||
Compression: "lz4",
|
||||
ShutdownTimeout: 30 * time.Second,
|
||||
TLS: testCase.tls,
|
||||
},
|
||||
}
|
||||
|
||||
auditor, err := newProvider(context.Background(), instrumentationtest.New().ToProviderSettings(), config, nil, version.Info)
|
||||
require.NoError(t, err)
|
||||
provider := auditor.(*provider)
|
||||
defer provider.client.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
err = provider.export(ctx, []audittypes.AuditEvent{newTestEvent(coretypes.ResourceUser, coretypes.VerbCreate, testCase.name)})
|
||||
if testCase.err {
|
||||
assert.True(t, errors.Is(err, context.DeadlineExceeded))
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
consumerTLS, err := newTLSConfig(certificates.client)
|
||||
require.NoError(t, err)
|
||||
|
||||
consumer, err := kgo.NewClient(
|
||||
kgo.SeedBrokers(cluster.ListenAddrs()...),
|
||||
kgo.DialTLSConfig(consumerTLS),
|
||||
kgo.ConsumeTopics("tls_audit"),
|
||||
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
defer consumer.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
fetches := consumer.PollFetches(ctx)
|
||||
require.Empty(t, fetches.Errors())
|
||||
assert.Len(t, fetches.Records(), 1)
|
||||
}
|
||||
|
||||
func TestNewTLSConfig(t *testing.T) {
|
||||
certificates := newTestCertificates(t)
|
||||
|
||||
notPEMFile := filepath.Join(t.TempDir(), "not-pem.crt")
|
||||
require.NoError(t, os.WriteFile(notPEMFile, []byte("not a pem"), 0o600))
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
config auditor.TLSConfig
|
||||
err bool
|
||||
wantRootCAs bool
|
||||
wantCertificates int
|
||||
}{
|
||||
{
|
||||
name: "NoFiles_UsesSystemRoots",
|
||||
config: auditor.TLSConfig{Enabled: true},
|
||||
},
|
||||
{
|
||||
name: "CAOnly",
|
||||
config: auditor.TLSConfig{Enabled: true, CAFile: certificates.client.CAFile},
|
||||
wantRootCAs: true,
|
||||
},
|
||||
{
|
||||
name: "CAAndClientCertificate",
|
||||
config: certificates.client,
|
||||
wantRootCAs: true,
|
||||
wantCertificates: 1,
|
||||
},
|
||||
{
|
||||
name: "CAFileMissing",
|
||||
config: auditor.TLSConfig{Enabled: true, CAFile: filepath.Join(t.TempDir(), "missing-ca.crt")},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
name: "CAFileNotPEM",
|
||||
config: auditor.TLSConfig{Enabled: true, CAFile: notPEMFile},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
name: "KeyFileMissing",
|
||||
config: auditor.TLSConfig{Enabled: true, CertFile: certificates.client.CertFile, KeyFile: filepath.Join(t.TempDir(), "missing.key")},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
name: "CertFileNotPEM",
|
||||
config: auditor.TLSConfig{Enabled: true, CertFile: notPEMFile, KeyFile: certificates.client.KeyFile},
|
||||
err: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
tlsConfig, err := newTLSConfig(testCase.config)
|
||||
if testCase.err {
|
||||
assert.True(t, errors.Ast(err, errors.TypeInvalidInput))
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.wantRootCAs, tlsConfig.RootCAs != nil)
|
||||
assert.Len(t, tlsConfig.Certificates, testCase.wantCertificates)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type testCertificates struct {
|
||||
caPool *x509.CertPool
|
||||
server tls.Certificate
|
||||
client auditor.TLSConfig
|
||||
}
|
||||
|
||||
// Issues a CA, a broker certificate for 127.0.0.1 and a client certificate, writing the client side as ca.crt, tls.crt and tls.key.
|
||||
func newTestCertificates(t *testing.T) testCertificates {
|
||||
t.Helper()
|
||||
|
||||
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
require.NoError(t, err)
|
||||
|
||||
caTemplate := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: "test-ca"},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(time.Hour),
|
||||
IsCA: true,
|
||||
BasicConstraintsValid: true,
|
||||
KeyUsage: x509.KeyUsageCertSign,
|
||||
}
|
||||
caDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey)
|
||||
require.NoError(t, err)
|
||||
ca, err := x509.ParseCertificate(caDER)
|
||||
require.NoError(t, err)
|
||||
|
||||
serverCertPEM, serverKeyPEM := issueTestCertificate(t, ca, caKey, &x509.Certificate{
|
||||
SerialNumber: big.NewInt(2),
|
||||
Subject: pkix.Name{CommonName: "broker"},
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
})
|
||||
server, err := tls.X509KeyPair(serverCertPEM, serverKeyPEM)
|
||||
require.NoError(t, err)
|
||||
|
||||
clientCertPEM, clientKeyPEM := issueTestCertificate(t, ca, caKey, &x509.Certificate{
|
||||
SerialNumber: big.NewInt(3),
|
||||
Subject: pkix.Name{CommonName: "signoz"},
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
|
||||
})
|
||||
|
||||
dir := t.TempDir()
|
||||
client := auditor.TLSConfig{
|
||||
Enabled: true,
|
||||
CAFile: filepath.Join(dir, "ca.crt"),
|
||||
CertFile: filepath.Join(dir, "tls.crt"),
|
||||
KeyFile: filepath.Join(dir, "tls.key"),
|
||||
}
|
||||
require.NoError(t, os.WriteFile(client.CAFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0o600))
|
||||
require.NoError(t, os.WriteFile(client.CertFile, clientCertPEM, 0o600))
|
||||
require.NoError(t, os.WriteFile(client.KeyFile, clientKeyPEM, 0o600))
|
||||
|
||||
caPool := x509.NewCertPool()
|
||||
caPool.AddCert(ca)
|
||||
|
||||
return testCertificates{caPool: caPool, server: server, client: client}
|
||||
}
|
||||
|
||||
func issueTestCertificate(t *testing.T, ca *x509.Certificate, caKey *ecdsa.PrivateKey, template *x509.Certificate) ([]byte, []byte) {
|
||||
t.Helper()
|
||||
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
require.NoError(t, err)
|
||||
|
||||
template.NotBefore = time.Now().Add(-time.Hour)
|
||||
template.NotAfter = time.Now().Add(time.Hour)
|
||||
template.KeyUsage = x509.KeyUsageDigitalSignature
|
||||
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, ca, &key.PublicKey, caKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
keyDER, err := x509.MarshalECPrivateKey(key)
|
||||
require.NoError(t, err)
|
||||
|
||||
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
|
||||
}
|
||||
@@ -28,7 +28,7 @@ You are operating within a constrained context window and strict system prompts.
|
||||
- UI primitives come from `@signozhq/ui` (subpath imports) and icons from `@signozhq/icons`. No new `antd` component or direct icon library (`lucide-react`) where `@signozhq/ui` has an equivalent; `signoz/no-antd-components` enforces part of this list.
|
||||
- Exception: a control added beside `antd` siblings of the same kind (a tab in an `antd` tab strip) matches them until that surface migrates. Say so in the PR.
|
||||
- When `@signozhq/ui` or `@signozhq/icons` lacks what you need, say so in the PR before reaching for another library.
|
||||
- Before styling a `@signozhq/ui` component, check its props in `node_modules/@signozhq/ui/dist/<component>/*.d.ts` for `className`/`style` support; some omit them. Avoid overriding the component's CSS vars unless explicitly needed.
|
||||
- Never override a `@signozhq/ui` component's styles: no `--<component>-*` CSS variables, no `:global` class or `data-*` selectors, no restyling through `className`/`style`. Use its props, and put layout on a wrapper you own. When it can't do what the design needs, file a UI suggestion in `SigNoz/uforge-pod` (`ui-suggestion.yml` template) and link it in the PR.
|
||||
- When writing code that could need authorization checks, read ./src/lib/authz/README.md
|
||||
- A flow that gains a request also gates on that request's permission: a rename that now reads the view first needs `read` as well as `update`.
|
||||
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.
|
||||
|
||||
@@ -9,12 +9,12 @@
|
||||
- [ ] No deep class nesting (max 3 class levels; pseudo-classes/elements and parent-reference selectors like `&.active`, `&#bar` are not counted)
|
||||
- [ ] No hardcoded colors - use `--l1/l2/l3-*` semantic tokens (not `--bg-*` primitives)
|
||||
- [ ] No magic numbers - use `--spacing-*` tokens
|
||||
- [ ] Typography uses `--periscope-font-size-*` or `--font-size-*` tokens
|
||||
- [ ] @signozhq/ui overrides use CSS variables, not direct class overrides
|
||||
- [ ] Global escapes only for third-party overrides
|
||||
- [ ] Typography uses `--{variant}-{size}-{weight}-*` text style tokens (see Typography)
|
||||
- [ ] No overrides of `@signozhq/ui` components (see below)
|
||||
- [ ] Global escapes only for third-party overrides (`@signozhq/ui` is not third-party)
|
||||
- [ ] No ID selectors
|
||||
- [ ] No bare element selectors
|
||||
- [ ] Keyframes use `:local(@keyframes name)` to avoid global collisions
|
||||
- [ ] Keyframes are declared in the module with plain `@keyframes name` (already local)
|
||||
|
||||
## Config (vite.config.ts)
|
||||
|
||||
@@ -77,7 +77,7 @@ css: {
|
||||
|
||||
// BAD: Nesting creates separate classes you might not expect
|
||||
.button {
|
||||
.icon { } // -> styles.icon (separate class, not scoped under .button)
|
||||
.icon { } // -> styles.icon, but the rule is `.button .icon`: it only matches inside .button
|
||||
}
|
||||
|
||||
// GOOD: Flat structure
|
||||
@@ -289,88 +289,32 @@ Use L1/L2/L3 semantic tokens - they handle light/dark theme automatically.
|
||||
- L2 = elevated surfaces (cards, panels)
|
||||
- L3 = nested/inset elements
|
||||
|
||||
## Overriding @signozhq/ui Components
|
||||
## @signozhq/ui Components
|
||||
|
||||
Components expose CSS variables for customization.
|
||||
Don't override them. That covers setting a component's `--<component>-*` CSS variables, targeting its classes or `data-*` attributes through `:global(...)`, and restyling it with `className` or `style`. An override keeps working until the component changes, then breaks with no type error or lint warning, and the screen drifts from every other one using that component.
|
||||
|
||||
You can ensure they exist by looking at ./node_modules/@signozhq/ui/dist.
|
||||
Never write a override without confirm it exists.
|
||||
|
||||
Override via:
|
||||
|
||||
### Method 1: CSS Variables (Preferred)
|
||||
|
||||
Each component exposes `--<component>-<property>` variables:
|
||||
- Use the component's props (`variant`, `color`, `size`, ...) for how it looks.
|
||||
- Put layout (position, margin, width inside a flex or grid parent) on a wrapper element you own.
|
||||
- If the component can't do what the design needs, file a [UI suggestion](https://github.com/SigNoz/uforge-pod/issues/new?template=ui-suggestion.yml) in `SigNoz/uforge-pod` and ship with the component as it renders until the suggestion is decided. Link the issue in the PR.
|
||||
|
||||
```scss
|
||||
// Override Button
|
||||
.customButton {
|
||||
--button-background: var(--success-background);
|
||||
--button-border-radius: var(--radius-2);
|
||||
--button-padding: var(--spacing-4) var(--spacing-8);
|
||||
--button-font-size: var(--label-base-400-font-size);
|
||||
// BAD: Restyling the component
|
||||
.saveButton {
|
||||
--button-primary-background-color: var(--success-background);
|
||||
}
|
||||
|
||||
// Override Input
|
||||
.customInput {
|
||||
--input-height: 2.5rem;
|
||||
--input-border-color: var(--l2-border);
|
||||
--input-padding: var(--spacing-2) var(--spacing-6);
|
||||
--input-placeholder-color: var(--l3-foreground);
|
||||
.toolbar :global([data-variant="outlined"]) {
|
||||
--button-variant-outlined-border: 1px solid var(--accent-primary);
|
||||
}
|
||||
|
||||
// Override nested parts
|
||||
.customInput {
|
||||
--input-prefix-padding: 0 var(--spacing-4) 0 var(--spacing-6);
|
||||
--input-suffix-color: var(--accent-primary);
|
||||
// GOOD: Layout on your own wrapper, looks from props
|
||||
.toolbarActions {
|
||||
display: flex;
|
||||
gap: var(--spacing-4);
|
||||
margin-left: auto;
|
||||
}
|
||||
```
|
||||
|
||||
### Method 2: Data Attributes
|
||||
|
||||
Components use data attributes for variants/states. Target them for state-specific overrides:
|
||||
|
||||
```scss
|
||||
// Target variant
|
||||
.wrapper :global([data-variant="outlined"]) {
|
||||
--button-border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
// Target size
|
||||
.wrapper :global([data-size="sm"]) {
|
||||
--button-font-size: var(--label-small-400-font-size);
|
||||
}
|
||||
|
||||
// Target color
|
||||
.wrapper :global([data-color="destructive"]) {
|
||||
--button-background: var(--danger-background);
|
||||
}
|
||||
|
||||
// Target state (Radix patterns)
|
||||
.popover :global([data-state="open"]) {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.tooltip :global([data-side="top"]) {
|
||||
margin-bottom: var(--spacing-2);
|
||||
}
|
||||
```
|
||||
|
||||
### Common Component CSS Variables
|
||||
|
||||
**Button:**
|
||||
- `--button-background`, `--button-border-radius`, `--button-padding`
|
||||
- `--button-font-size`, `--button-height`, `--button-gap`
|
||||
- `--button-hover-background`, `--button-disabled-opacity`
|
||||
|
||||
**Input:**
|
||||
- `--input-height`, `--input-border-color`, `--input-background`
|
||||
- `--input-padding`, `--input-font-size`, `--input-placeholder-color`
|
||||
- `--input-focus-outline-color`, `--input-hover-border-color`
|
||||
- `--input-prefix-*`, `--input-suffix-*` for adornments
|
||||
|
||||
**General pattern:** `--<component>-<property>` or `--<component>-<state>-<property>`
|
||||
|
||||
## Good Patterns
|
||||
|
||||
### Structure
|
||||
@@ -434,24 +378,21 @@ Components use data attributes for variants/states. Target them for state-specif
|
||||
|
||||
### Keyframes (Local Scoping)
|
||||
|
||||
Without `:local()`, keyframe names are global and can clash across modules:
|
||||
CSS Modules scope `@keyframes` like classes: the build renames `fadeIn` to `_fadeIn_<hash>` and rewrites every `animation` in the same module that names it. Don't wrap it in `:local(...)`; Sass rejects `:local(@keyframes fadeIn)` with `expected selector`.
|
||||
|
||||
```scss
|
||||
// BAD: Global keyframe - can conflict with other modules
|
||||
// GOOD: Local to this module
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
// GOOD: Locally scoped keyframe
|
||||
:local(@keyframes fadeIn) {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
.modal {
|
||||
animation: fadeIn 200ms ease;
|
||||
}
|
||||
|
||||
// BAD: Doesn't compile
|
||||
:local(@keyframes fadeIn) { }
|
||||
```
|
||||
|
||||
## JS Import Patterns
|
||||
|
||||
@@ -6,6 +6,8 @@ const LOG_EVENT_MOCK_PATH = '<rootDir>/src/__tests__/logEventMock.ts';
|
||||
|
||||
const config: Config.InitialOptions = {
|
||||
silent: true,
|
||||
// CI runners are slow enough that multi-step userEvent tests pass 5s.
|
||||
testTimeout: 10000,
|
||||
clearMocks: true,
|
||||
coverageDirectory: 'coverage',
|
||||
coverageReporters: ['text', 'cobertura', 'html', 'json-summary'],
|
||||
|
||||
@@ -137,6 +137,8 @@ window.getComputedStyle = function (
|
||||
return {
|
||||
display: '',
|
||||
visibility: '',
|
||||
width: '',
|
||||
height: '',
|
||||
opacity: '1',
|
||||
animationName: 'none',
|
||||
getPropertyValue: () => '',
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"@sentry/vite-plugin": "5.3.0",
|
||||
"@signozhq/design-tokens": "2.8.0",
|
||||
"@signozhq/icons": "0.4.0",
|
||||
"@signozhq/noz-client": "1.13.0",
|
||||
"@signozhq/ui": "0.4.0-rc.5",
|
||||
"@tanstack/react-table": "8.21.3",
|
||||
"@tanstack/react-virtual": "3.13.22",
|
||||
|
||||
16
frontend/pnpm-lock.yaml
generated
16
frontend/pnpm-lock.yaml
generated
@@ -82,6 +82,9 @@ importers:
|
||||
'@signozhq/icons':
|
||||
specifier: 0.4.0
|
||||
version: 0.4.0
|
||||
'@signozhq/noz-client':
|
||||
specifier: 1.13.0
|
||||
version: 1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
|
||||
'@signozhq/ui':
|
||||
specifier: 0.4.0-rc.5
|
||||
version: 0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
|
||||
@@ -3248,6 +3251,13 @@ packages:
|
||||
'@signozhq/icons@0.4.0':
|
||||
resolution: {integrity: sha512-QctNvNPlQlsefFdIVmSy/P/7a1IcQ3IryKP0KPMqtoqew3q89FGUmFa5IfEJ7Z3CHhtG1zaXwBKqP72QkLyA3g==}
|
||||
|
||||
'@signozhq/noz-client@1.13.0':
|
||||
resolution: {integrity: sha512-130L2xomHnQZK8ZtAst34qFz9d2rSF/JYpg9gKvJkZVS9+46CPZeTW8Va9PNS9Oa5owezVHIXZStTEbsHIxnwg==}
|
||||
peerDependencies:
|
||||
axios: ^1.20.0
|
||||
react: ^18.2.0
|
||||
react-query: ^3.39.3
|
||||
|
||||
'@signozhq/ui@0.4.0-rc.5':
|
||||
resolution: {integrity: sha512-WlJMfeDfvL2hjMpTpHhhND/tuK7X0sfXQlx6E1ZG+6E/DYHpuhYljfvW3E6/BohIlHFlTyCs/ZMl9wnV2k9Zcw==}
|
||||
peerDependencies:
|
||||
@@ -12373,6 +12383,12 @@ snapshots:
|
||||
|
||||
'@signozhq/icons@0.4.0': {}
|
||||
|
||||
'@signozhq/noz-client@1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)':
|
||||
dependencies:
|
||||
axios: 1.21.1
|
||||
react: 18.2.0
|
||||
react-query: 3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
|
||||
|
||||
'@signozhq/ui@0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)':
|
||||
dependencies:
|
||||
'@base-ui/react': 1.8.0(@date-fns/tz@1.4.1)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
* to resume, which each return a new executionId to open a fresh SSE stream.
|
||||
*
|
||||
* Types in this file re-use the OpenAPI-generated DTOs in
|
||||
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`.
|
||||
* `@signozhq/noz-client`.
|
||||
* Local types are defined only when the UI needs a different shape — for
|
||||
* example, the SSE event union adds a literal `type` discriminator that the
|
||||
* generated event DTOs leave loose.
|
||||
@@ -60,7 +60,7 @@ import type {
|
||||
PageTypeDTO,
|
||||
ToolCallEventDTO,
|
||||
ToolResultEventDTO,
|
||||
} from './sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
|
||||
import {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -15619,7 +15619,7 @@ export type GetFieldsValuesParams = {
|
||||
searchText?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The key whose values to return, such as service.name. A context prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
* @description The key whose values to return, such as service.name. With fieldContext set, it is the stored name as is. Otherwise a context prefix such as resource.service.name sets the context and a type suffix such as service.name:string sets fieldDataType when that is empty; as in filter expressions, a prefixed name also matches a key stored under the full name, whose values come first: log.level returns values of a key named log.level, then of the log field level.
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
@@ -17236,7 +17236,7 @@ export type GetRuleHistoryFilterValuesParams = {
|
||||
searchText?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The key whose values to return, such as service.name. A context prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
* @description The key whose values to return, such as service.name. With fieldContext set, it is the stored name as is. Otherwise a context prefix such as resource.service.name sets the context and a type suffix such as service.name:string sets fieldDataType when that is empty; as in filter expressions, a prefixed name also matches a key stored under the full name, whose values come first: log.level returns values of a key named log.level, then of the log field level.
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
|
||||
@@ -21,6 +21,7 @@ import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
convertBuilderQueriesToV5,
|
||||
createAggregation,
|
||||
mapPanelTypeToRequestType,
|
||||
prepareQueryRangePayloadV5,
|
||||
} from './prepareQueryRangePayloadV5';
|
||||
@@ -1015,3 +1016,47 @@ describe('convertBuilderQueriesToV5 builder query type', () => {
|
||||
expect(buildEnvelope(builderQueryType, 'trace').type).toBe('builder_query');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createAggregation fallback', () => {
|
||||
const logsQuery = (expression: string): Partial<IBuilderQuery> => ({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregations: [{ expression }],
|
||||
});
|
||||
|
||||
it('sends no aggregation for a heatmap with no field', () => {
|
||||
expect(createAggregation(logsQuery(''), PANEL_TYPES.HEATMAP)).toStrictEqual(
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a field on a heatmap and turns it into count() elsewhere', () => {
|
||||
expect(
|
||||
createAggregation(logsQuery('duration_nano'), PANEL_TYPES.HEATMAP),
|
||||
).toStrictEqual([{ expression: 'duration_nano' }]);
|
||||
expect(
|
||||
createAggregation(logsQuery('duration_nano'), PANEL_TYPES.TIME_SERIES),
|
||||
).toStrictEqual([{ expression: 'count()' }]);
|
||||
});
|
||||
|
||||
it('still defaults other panels to count()', () => {
|
||||
expect(
|
||||
createAggregation(logsQuery(''), PANEL_TYPES.TIME_SERIES),
|
||||
).toStrictEqual([{ expression: 'count()' }]);
|
||||
});
|
||||
|
||||
it('sends the field of a logs heatmap query', () => {
|
||||
const [envelope] = convertBuilderQueriesToV5(
|
||||
{
|
||||
A: {
|
||||
...logsQuery('duration_nano'),
|
||||
queryName: 'A',
|
||||
} as IBuilderQuery,
|
||||
},
|
||||
mapPanelTypeToRequestType(PANEL_TYPES.HEATMAP),
|
||||
PANEL_TYPES.HEATMAP,
|
||||
);
|
||||
expect((envelope.spec as LogBuilderQuery).aggregations).toStrictEqual([
|
||||
{ expression: 'duration_nano' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,8 @@ import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
|
||||
import { foldAISlot } from 'lib/query/builderSlot';
|
||||
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
|
||||
import { parseAggregations } from 'lib/query/aggregationExpression';
|
||||
import { aggregatesDistributionField } from 'lib/query/distributionField';
|
||||
import { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
import { DynamicVariableSuggestion } from 'providers/Dashboard/store/dynamicVariableSuggestions';
|
||||
@@ -240,32 +242,6 @@ function createBaseSpec(
|
||||
};
|
||||
}
|
||||
|
||||
// Utility to parse aggregation expressions with optional alias
|
||||
export function parseAggregations(
|
||||
expression: string,
|
||||
availableAlias?: string,
|
||||
): { expression: string; alias?: string }[] {
|
||||
const result: { expression: string; alias?: string }[] = [];
|
||||
// Matches function calls like "count()" or "sum(field)" with optional alias like "as 'alias'"
|
||||
// Handles quoted ('alias'), dash-separated (field-name), and unquoted values after "as" keyword
|
||||
const regex =
|
||||
/([a-zA-Z0-9_]+\([^)]*\))(?:\s*as\s+((?:'[^']*'|"[^"]*"|[a-zA-Z0-9_-]+)))?/g;
|
||||
let match = regex.exec(expression);
|
||||
while (match !== null) {
|
||||
const expr = match[1];
|
||||
let alias = match[2] || availableAlias; // Use provided alias or availableAlias if not matched
|
||||
if (alias) {
|
||||
// Remove quotes if present
|
||||
alias = alias.replace(/^['"]|['"]$/g, '');
|
||||
result.push({ expression: expr, alias });
|
||||
} else {
|
||||
result.push({ expression: expr });
|
||||
}
|
||||
match = regex.exec(expression);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createAggregation(
|
||||
queryData: any,
|
||||
panelType?: PANEL_TYPES,
|
||||
@@ -310,18 +286,28 @@ export function createAggregation(
|
||||
];
|
||||
}
|
||||
|
||||
// A heatmap buckets the field the user names; count() would be rejected as one.
|
||||
// Elsewhere a field is not an aggregation, so it falls back to count().
|
||||
const isDistributionField = aggregatesDistributionField(
|
||||
panelType,
|
||||
queryData.dataSource,
|
||||
);
|
||||
const fallback = isDistributionField ? [] : [{ expression: 'count()' }];
|
||||
|
||||
if (queryData.aggregations?.length > 0) {
|
||||
return queryData.aggregations.flatMap(
|
||||
(agg: { expression: string; alias?: string }) => {
|
||||
const parsedAggregations = parseAggregations(agg.expression, agg?.alias);
|
||||
return isEmpty(parsedAggregations)
|
||||
? [{ expression: 'count()' }]
|
||||
: parsedAggregations;
|
||||
const parsedAggregations = parseAggregations(
|
||||
agg.expression,
|
||||
agg?.alias,
|
||||
isDistributionField,
|
||||
);
|
||||
return isEmpty(parsedAggregations) ? fallback : parsedAggregations;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return [{ expression: 'count()' }];
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
1
frontend/src/auto-import-registry.d.ts
vendored
1
frontend/src/auto-import-registry.d.ts
vendored
@@ -12,4 +12,5 @@
|
||||
|
||||
import '@signozhq/design-tokens';
|
||||
import '@signozhq/icons';
|
||||
import '@signozhq/noz-client';
|
||||
import '@signozhq/ui';
|
||||
|
||||
@@ -31,7 +31,7 @@ interface Props {
|
||||
placeholder?: string;
|
||||
// Rendered at the end of the search row (e.g. the New Dashboard action).
|
||||
rightSlot?: ReactNode;
|
||||
// Rendered in the filters row after the chips. A function receives the draft.
|
||||
// Rendered in the filters row before the chips. A function receives the draft.
|
||||
extraFilters?: ReactNode | ((api: ExtraFiltersApi) => ReactNode);
|
||||
// Shows Clear even when the query is empty.
|
||||
hasExtraFilters?: boolean;
|
||||
@@ -142,6 +142,9 @@ function FilterZone({
|
||||
className={styles.filterControls}
|
||||
data-testid={`${testIdPrefix}-filter-zone`}
|
||||
>
|
||||
{typeof extraFilters === 'function'
|
||||
? extraFilters({ draft, applyDraft, setDraft })
|
||||
: extraFilters}
|
||||
<FilterChips
|
||||
{...createdByProps}
|
||||
updated={reflected.updated}
|
||||
@@ -150,9 +153,6 @@ function FilterZone({
|
||||
onApply={run}
|
||||
disabled={disabled}
|
||||
/>
|
||||
{typeof extraFilters === 'function'
|
||||
? extraFilters({ draft, applyDraft, setDraft })
|
||||
: extraFilters}
|
||||
{(!isEmpty || hasExtraFilters) && (
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { type MouseEvent, useCallback, useMemo, useRef } from 'react';
|
||||
import {
|
||||
type FocusEvent,
|
||||
type MouseEvent,
|
||||
useCallback,
|
||||
useMemo,
|
||||
useRef,
|
||||
} from 'react';
|
||||
import {
|
||||
autocompletion,
|
||||
closeCompletion,
|
||||
@@ -67,6 +73,20 @@ function SearchBar({
|
||||
const onSubmitRef = useRef(handleSubmit);
|
||||
onSubmitRef.current = handleSubmit;
|
||||
|
||||
// Leaving the box runs an unrun draft, e.g. terms picked from the suggestions.
|
||||
// A blur from switching windows or tabs does not.
|
||||
const handleBlur = useCallback(
|
||||
(event: FocusEvent<HTMLDivElement>): void => {
|
||||
const stillInside = event.currentTarget.contains(
|
||||
event.relatedTarget as Node | null,
|
||||
);
|
||||
if (!stillInside && dirty && !disabled && document.hasFocus()) {
|
||||
handleSubmit();
|
||||
}
|
||||
},
|
||||
[dirty, disabled, handleSubmit],
|
||||
);
|
||||
|
||||
const extensions = useMemo(
|
||||
() => [
|
||||
dslHighlight,
|
||||
@@ -127,7 +147,10 @@ function SearchBar({
|
||||
|
||||
return (
|
||||
<div className={styles.wrapper}>
|
||||
<div className={cx(styles.field, { [styles.disabled]: disabled })}>
|
||||
<div
|
||||
className={cx(styles.field, { [styles.disabled]: disabled })}
|
||||
onBlur={handleBlur}
|
||||
>
|
||||
<Search
|
||||
size={12}
|
||||
color={Color.BG_VANILLA_400}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import type { DslGrammar } from '../../dsl/types';
|
||||
import SearchBar from '../SearchBar';
|
||||
|
||||
type SearchBarProps = ComponentProps<typeof SearchBar>;
|
||||
|
||||
const GRAMMAR: DslGrammar = {
|
||||
fields: [{ key: 'name', type: 'string' }],
|
||||
dynamicKey: { detail: 'tag', prefix: '' },
|
||||
};
|
||||
|
||||
function renderSearchBar(props: { dirty: boolean; disabled?: boolean }): {
|
||||
onSubmit: jest.MockedFunction<SearchBarProps['onSubmit']>;
|
||||
onSubmitted: jest.MockedFunction<NonNullable<SearchBarProps['onSubmitted']>>;
|
||||
} {
|
||||
const onSubmit = jest.fn() as jest.MockedFunction<SearchBarProps['onSubmit']>;
|
||||
const onSubmitted = jest.fn() as jest.MockedFunction<
|
||||
NonNullable<SearchBarProps['onSubmitted']>
|
||||
>;
|
||||
render(
|
||||
<>
|
||||
<SearchBar
|
||||
value="name = 'x'"
|
||||
grammar={GRAMMAR}
|
||||
testIdPrefix="list-search"
|
||||
onChange={jest.fn()}
|
||||
onSubmit={onSubmit}
|
||||
onSubmitted={onSubmitted}
|
||||
dirty={props.dirty}
|
||||
disabled={props.disabled}
|
||||
/>
|
||||
<button type="button" data-testid="outside">
|
||||
outside
|
||||
</button>
|
||||
</>,
|
||||
);
|
||||
return { onSubmit, onSubmitted };
|
||||
}
|
||||
|
||||
function searchContent(): HTMLElement {
|
||||
return screen
|
||||
.getByTestId('list-search')
|
||||
.querySelector('.cm-content') as HTMLElement;
|
||||
}
|
||||
|
||||
describe('SearchBar — run on blur', () => {
|
||||
let hasFocus: jest.SpyInstance<boolean, []>;
|
||||
|
||||
beforeEach(() => {
|
||||
// jsdom reports no focus once it leaves the editor; a focused browser window does.
|
||||
hasFocus = jest.spyOn(document, 'hasFocus').mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('runs an unrun draft when focus leaves the box', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit, onSubmitted } = renderSearchBar({ dirty: true });
|
||||
|
||||
await user.click(searchContent());
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
expect(onSubmitted).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('does nothing when the draft was already run', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit } = renderSearchBar({ dirty: false });
|
||||
|
||||
await user.click(searchContent());
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does nothing when focus leaves the window', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit } = renderSearchBar({ dirty: true });
|
||||
|
||||
await user.click(searchContent());
|
||||
hasFocus.mockReturnValue(false);
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs once when Run query is clicked with an unrun draft', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit } = renderSearchBar({ dirty: true });
|
||||
|
||||
await user.click(searchContent());
|
||||
await user.click(screen.getByTestId('list-search-submit'));
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
.headerZone {
|
||||
// Sticks to the top of a scrolling list so the heading and filters stay put
|
||||
// while results scroll beneath. The DSL suggestion popup (z-index 1000) still
|
||||
// layers above it.
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
gap: 14px;
|
||||
padding: 20px 24px;
|
||||
background: var(--l2-background);
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import styles from './ListHeaderZone.module.scss';
|
||||
|
||||
interface Props {
|
||||
/** Rendered regardless of whether the list has anything in it. */
|
||||
children: ReactNode;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
function ListHeaderZone({ children, testId }: Props): JSX.Element {
|
||||
return (
|
||||
<div className={styles.headerZone} data-testid={testId}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ListHeaderZone;
|
||||
@@ -106,8 +106,10 @@ function QueryAddOns({
|
||||
|
||||
if (
|
||||
panelType === PANEL_TYPES.HEATMAP &&
|
||||
query.dataSource === DataSource.METRICS &&
|
||||
!HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
|
||||
!(
|
||||
query.dataSource === DataSource.METRICS &&
|
||||
HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
|
||||
)
|
||||
) {
|
||||
addOns = [...addOns, BUCKET_OPTIONS];
|
||||
}
|
||||
@@ -436,6 +438,7 @@ function QueryAddOns({
|
||||
onChange={handleChangeOrderByKeys}
|
||||
isRawQuery={isRawQuery}
|
||||
isNewQueryV2
|
||||
panelType={panelType ?? undefined}
|
||||
placeholder={placeholderOf(QueryBuilderField.OrderBy)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -107,8 +107,8 @@ export const BASE_ADD_ONS = (
|
||||
|
||||
export const REDUCE_TO = toAddOn(QueryBuilderField.ReduceTo);
|
||||
|
||||
// Offered only by a heatmap over metrics: the bucket axis is what a heatmap plots
|
||||
// against, and no other panel type sends one. A histogram brings its own buckets.
|
||||
// Offered only by a heatmap: the bucket axis is what a heatmap plots against, and no
|
||||
// other panel type sends one. A histogram metric brings its own buckets.
|
||||
export const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
|
||||
ATTRIBUTE_TYPES.HISTOGRAM,
|
||||
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
// Fills the row like the filter and Group By boxes.
|
||||
.select {
|
||||
flex: 1;
|
||||
min-width: 400px;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Combobox } from '@signozhq/ui/combobox';
|
||||
import { TelemetrytypesFieldDataTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
|
||||
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
|
||||
import useDebounce from 'hooks/useDebounce';
|
||||
import { getDistributionFieldPlaceholder } from 'lib/query/distributionField';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DATA_SOURCE_TO_SIGNAL } from 'types/common/queryBuilder';
|
||||
|
||||
import { toDistributionFieldOptions } from './distributionFieldOptions';
|
||||
|
||||
import Styles from './DistributionFieldSelect.module.scss';
|
||||
|
||||
/** A logs or traces heatmap's aggregation: the one numeric field it buckets. */
|
||||
export default function DistributionFieldSelect({
|
||||
queryData,
|
||||
onChange,
|
||||
}: {
|
||||
queryData: IBuilderQuery;
|
||||
onChange?: (field: string) => void;
|
||||
}): JSX.Element {
|
||||
const [search, setSearch] = useState('');
|
||||
const searchText = useDebounce(search, DEBOUNCE_DELAY);
|
||||
|
||||
// The keys API caps its answer, so a field past the cap is reached by searching.
|
||||
const {
|
||||
data: fieldKeys,
|
||||
isLoading,
|
||||
isFetching,
|
||||
} = useFieldKeysSuggestion(
|
||||
{
|
||||
signal: DATA_SOURCE_TO_SIGNAL[queryData.dataSource],
|
||||
searchText,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.number,
|
||||
},
|
||||
queryData.builderQueryType,
|
||||
{ keepPreviousData: true },
|
||||
);
|
||||
|
||||
const [aggregation] = queryData.aggregations ?? [];
|
||||
const selectedField =
|
||||
aggregation && 'expression' in aggregation ? aggregation.expression : '';
|
||||
|
||||
const items = useMemo(
|
||||
() => toDistributionFieldOptions(fieldKeys ?? [], selectedField),
|
||||
[fieldKeys, selectedField],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={Styles.select}>
|
||||
<Combobox
|
||||
items={items}
|
||||
value={selectedField || undefined}
|
||||
onChange={(field): void => onChange?.(field ?? '')}
|
||||
allowClear
|
||||
placeholder={getDistributionFieldPlaceholder(queryData.dataSource)}
|
||||
searchInputProps={{
|
||||
placeholder: 'Search numeric fields',
|
||||
loading: isFetching,
|
||||
onChange: setSearch,
|
||||
}}
|
||||
loading={isLoading}
|
||||
noContent="No numeric fields"
|
||||
testId="distribution-field-select"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
IBuilderQuery,
|
||||
IBuilderTraceOperator,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { aggregatesDistributionField } from 'lib/query/distributionField';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
} from '../../queryBuilderFields.utils';
|
||||
|
||||
import { isScalarPanelType } from '../panelTypes';
|
||||
import DistributionFieldSelect from './DistributionFieldSelect';
|
||||
import QueryAggregationSelect from './QueryAggregationSelect';
|
||||
|
||||
import './QueryAggregation.styles.scss';
|
||||
@@ -63,17 +65,21 @@ function QueryAggregationOptions({
|
||||
data-testid="query-aggregation-container"
|
||||
>
|
||||
<div className="aggregation-container">
|
||||
<QueryAggregationSelect
|
||||
onChange={onChange}
|
||||
queryData={queryData}
|
||||
maxAggregations={
|
||||
panelType === PANEL_TYPES.VALUE ||
|
||||
panelType === PANEL_TYPES.PIE ||
|
||||
panelType === PANEL_TYPES.TOP_LIST
|
||||
? 1
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{aggregatesDistributionField(panelType, dataSource) ? (
|
||||
<DistributionFieldSelect queryData={queryData} onChange={onChange} />
|
||||
) : (
|
||||
<QueryAggregationSelect
|
||||
onChange={onChange}
|
||||
queryData={queryData}
|
||||
maxAggregations={
|
||||
panelType === PANEL_TYPES.VALUE ||
|
||||
panelType === PANEL_TYPES.PIE ||
|
||||
panelType === PANEL_TYPES.TOP_LIST
|
||||
? 1
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!stepInterval.hidden && (
|
||||
<div className="query-aggregation-interval">
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import {
|
||||
TelemetrytypesFieldContextDTO,
|
||||
TelemetrytypesFieldDataTypeDTO,
|
||||
TelemetrytypesSignalDTO,
|
||||
type GetFieldsKeys200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import DistributionFieldSelect from '../DistributionFieldSelect';
|
||||
|
||||
const keysResponse: GetFieldsKeys200 = {
|
||||
status: 'success',
|
||||
data: {
|
||||
complete: true,
|
||||
keys: {
|
||||
duration_nano: [
|
||||
{
|
||||
name: 'duration_nano',
|
||||
fieldContext: TelemetrytypesFieldContextDTO.span,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
|
||||
signal: TelemetrytypesSignalDTO.traces,
|
||||
},
|
||||
],
|
||||
quantity: [
|
||||
{
|
||||
name: 'quantity',
|
||||
fieldContext: TelemetrytypesFieldContextDTO.attribute,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
|
||||
signal: TelemetrytypesSignalDTO.traces,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const tracesQuery = (expression: string): IBuilderQuery => ({
|
||||
...(initialQueriesMap.traces.builder.queryData[0] as IBuilderQuery),
|
||||
aggregations: [{ expression }],
|
||||
});
|
||||
|
||||
describe('DistributionFieldSelect', () => {
|
||||
const requests: URLSearchParams[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
server.use(
|
||||
rest.get(`${ENVIRONMENT.baseURL}/api/v1/fields/keys`, (req, res, ctx) => {
|
||||
requests.push(req.url.searchParams);
|
||||
return res(ctx.status(200), ctx.json(keysResponse));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the saved field', () => {
|
||||
render(
|
||||
<DistributionFieldSelect
|
||||
queryData={tracesQuery('duration_nano')}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('distribution-field-select')).toHaveTextContent(
|
||||
'duration_nano',
|
||||
);
|
||||
});
|
||||
|
||||
it('picks a numeric field, keeping its context', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={onChange} />,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await screen.findByTestId(
|
||||
'distribution-field-select-item-attribute.quantity',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('distribution-field-select-search'),
|
||||
'attribute.quantity{Enter}',
|
||||
);
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
|
||||
expect(requests[0].get('fieldDataType')).toBe(
|
||||
TelemetrytypesFieldDataTypeDTO.number,
|
||||
);
|
||||
expect(requests[0].get('signal')).toBe('traces');
|
||||
});
|
||||
|
||||
it('replaces the saved field with the newly picked one', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect
|
||||
queryData={tracesQuery('duration_nano')}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await screen.findByTestId(
|
||||
'distribution-field-select-item-attribute.quantity',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('distribution-field-select-search'),
|
||||
'attribute.quantity{Enter}',
|
||||
);
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
|
||||
});
|
||||
|
||||
it('only offers listed fields: typed text is a filter, not a value', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await screen.findByTestId(
|
||||
'distribution-field-select-item-attribute.quantity',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('distribution-field-select-search'),
|
||||
'no_such_field',
|
||||
);
|
||||
|
||||
await screen.findByText('No numeric fields');
|
||||
expect(
|
||||
screen.queryByTestId('distribution-field-select-item-no_such_field'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('searches the server for typed text, past the listed fields', async () => {
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
pointerEventsCheck: 0,
|
||||
});
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await user.type(
|
||||
await screen.findByTestId('distribution-field-select-search'),
|
||||
'queue',
|
||||
);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(DEBOUNCE_DELAY);
|
||||
});
|
||||
|
||||
await waitFor(() => expect(requests.at(-1)?.get('searchText')).toBe('queue'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { TelemetrytypesFieldContextDTO as FieldContext } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import {
|
||||
toDistributionFieldOptions,
|
||||
toDistributionFieldText,
|
||||
} from '../distributionFieldOptions';
|
||||
|
||||
const key = (
|
||||
name: string,
|
||||
fieldContext: FieldContext,
|
||||
): { name: string; fieldContext: FieldContext } => ({ name, fieldContext });
|
||||
|
||||
const KEYS = [
|
||||
key('quantity', FieldContext.resource),
|
||||
key('duration_nano', FieldContext.span),
|
||||
key('quantity', FieldContext.attribute),
|
||||
key('total_tokens', FieldContext.trace),
|
||||
key('latency', FieldContext.body),
|
||||
key('duration_nano', FieldContext.span),
|
||||
];
|
||||
|
||||
describe('toDistributionFieldText', () => {
|
||||
it.each([
|
||||
[key('duration_nano', FieldContext.span), 'duration_nano'],
|
||||
[key('severity_number', FieldContext.log), 'severity_number'],
|
||||
[
|
||||
key('http.status_code', FieldContext.attribute),
|
||||
'attribute.http.status_code',
|
||||
],
|
||||
[key('latency', FieldContext.body), 'body.latency'],
|
||||
])('%j → %s', (fieldKey, text) => {
|
||||
expect(toDistributionFieldText(fieldKey)).toBe(text);
|
||||
});
|
||||
});
|
||||
|
||||
const item = (
|
||||
text: string,
|
||||
): { type: 'item'; label: string; value: string } => ({
|
||||
type: 'item',
|
||||
label: text,
|
||||
value: text,
|
||||
});
|
||||
|
||||
describe('toDistributionFieldOptions', () => {
|
||||
it('groups columns first, keeps contexts apart, drops trace keys and repeats', () => {
|
||||
expect(toDistributionFieldOptions(KEYS, 'duration_nano')).toStrictEqual([
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Columns',
|
||||
value: 'column',
|
||||
items: [item('duration_nano')],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Attribute',
|
||||
value: 'attribute',
|
||||
items: [item('attribute.quantity')],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Resource',
|
||||
value: 'resource',
|
||||
items: [item('resource.quantity')],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Body',
|
||||
value: 'body',
|
||||
items: [item('body.latency')],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('leads with a saved field the keys do not carry', () => {
|
||||
const options = toDistributionFieldOptions(KEYS, 'queue-depth');
|
||||
expect(options[0]).toStrictEqual(item('queue-depth'));
|
||||
expect(options).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('adds nothing for an empty or listed field', () => {
|
||||
expect(toDistributionFieldOptions(KEYS, '')).toHaveLength(4);
|
||||
expect(toDistributionFieldOptions(KEYS, 'body.latency')).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import type {
|
||||
ComboboxItemType,
|
||||
ComboboxOptionItemType,
|
||||
} from '@signozhq/ui/combobox';
|
||||
import { TelemetrytypesFieldContextDTO as FieldContext } from 'api/generated/services/sigNoz.schemas';
|
||||
import { upperFirst } from 'lodash-es';
|
||||
import type { TelemetryFieldKey } from 'types/api/v5/queryRange';
|
||||
|
||||
// Span and log columns are read by their name alone; anything else keeps its
|
||||
// context so `attribute.quantity` and `resource.quantity` stay apart.
|
||||
const COLUMN_CONTEXTS = new Set<string | undefined>([
|
||||
FieldContext.span,
|
||||
FieldContext.log,
|
||||
FieldContext[''],
|
||||
]);
|
||||
|
||||
const GROUP_ORDER: string[] = [
|
||||
'column',
|
||||
FieldContext.attribute,
|
||||
FieldContext.resource,
|
||||
];
|
||||
|
||||
const headingOf = (group: string): string =>
|
||||
group === 'column' ? 'Columns' : upperFirst(group);
|
||||
|
||||
const toItem = (text: string): ComboboxOptionItemType => ({
|
||||
type: 'item',
|
||||
label: text,
|
||||
value: text,
|
||||
});
|
||||
|
||||
/** The key text the querier parses back into this key (`GetFieldKeyFromKeyText`). */
|
||||
export function toDistributionFieldText(key: TelemetryFieldKey): string {
|
||||
return COLUMN_CONTEXTS.has(key.fieldContext)
|
||||
? key.name
|
||||
: `${key.fieldContext}.${key.name}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Numeric keys grouped by context, each one once. `trace.*` keys are per-trace
|
||||
* aggregates, which a heatmap cannot bucket. A saved field the keys do not carry
|
||||
* leads as its own item, so the combobox can still show it.
|
||||
*/
|
||||
export function toDistributionFieldOptions(
|
||||
keys: TelemetryFieldKey[],
|
||||
selectedField: string,
|
||||
): ComboboxItemType[] {
|
||||
const byGroup = new Map<string, Set<string>>();
|
||||
keys
|
||||
.filter((key) => key.fieldContext !== FieldContext.trace)
|
||||
.forEach((key) => {
|
||||
const group = COLUMN_CONTEXTS.has(key.fieldContext)
|
||||
? 'column'
|
||||
: String(key.fieldContext);
|
||||
byGroup.set(
|
||||
group,
|
||||
(byGroup.get(group) ?? new Set()).add(toDistributionFieldText(key)),
|
||||
);
|
||||
});
|
||||
|
||||
const isSelectedListed = [...byGroup.values()].some((texts) =>
|
||||
texts.has(selectedField),
|
||||
);
|
||||
const rank = (group: string): number => {
|
||||
const index = GROUP_ORDER.indexOf(group);
|
||||
return index === -1 ? GROUP_ORDER.length : index;
|
||||
};
|
||||
|
||||
const groups = [...byGroup.entries()]
|
||||
.sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
|
||||
.map(([group, texts]): ComboboxItemType => ({
|
||||
type: 'group',
|
||||
label: headingOf(group),
|
||||
value: group,
|
||||
items: [...texts].map(toItem),
|
||||
}));
|
||||
|
||||
return selectedField && !isSelectedListed
|
||||
? [toItem(selectedField), ...groups]
|
||||
: groups;
|
||||
}
|
||||
@@ -506,7 +506,7 @@ describe('QueryAddOns', () => {
|
||||
);
|
||||
}
|
||||
|
||||
it('is offered on a metrics heatmap only', () => {
|
||||
it('is offered on a metrics heatmap', () => {
|
||||
renderHeatmap();
|
||||
|
||||
expect(
|
||||
@@ -532,23 +532,16 @@ describe('QueryAddOns', () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is not offered on a heatmap over another signal', () => {
|
||||
render(
|
||||
<QueryAddOns
|
||||
query={baseQuery({ dataSource: DataSource.LOGS })}
|
||||
version="v5"
|
||||
isRawQuery={false}
|
||||
showReduceTo={false}
|
||||
panelType={PANEL_TYPES.HEATMAP}
|
||||
index={0}
|
||||
isForTraceOperator={false}
|
||||
/>,
|
||||
);
|
||||
it.each([DataSource.LOGS, DataSource.TRACES])(
|
||||
'is offered on a %s heatmap',
|
||||
(dataSource) => {
|
||||
renderHeatmap({ dataSource });
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('query-add-on-bucket_options'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
expect(
|
||||
screen.getByTestId('query-add-on-bucket_options'),
|
||||
).toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([ATTRIBUTE_TYPES.HISTOGRAM, ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM])(
|
||||
'is not offered for a %s metric, which carries its own buckets',
|
||||
|
||||
@@ -8,7 +8,7 @@ import QueryAggregationOptions from '../QueryV2/QueryAggregation/QueryAggregatio
|
||||
|
||||
jest.mock('../QueryV2/QueryAggregation/QueryAggregationSelect', () => ({
|
||||
__esModule: true,
|
||||
default: (): null => null,
|
||||
default: (): JSX.Element => <div data-testid="aggregation-select" />,
|
||||
}));
|
||||
|
||||
const queryData = initialQueriesMap.traces.builder
|
||||
@@ -69,3 +69,18 @@ describe('QueryAggregationOptions step interval', () => {
|
||||
expect(screen.getByText('every')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('QueryAggregationOptions on a heatmap', () => {
|
||||
it.each([
|
||||
[PANEL_TYPES.HEATMAP, DataSource.TRACES, true],
|
||||
[PANEL_TYPES.HEATMAP, DataSource.METRICS, false],
|
||||
[PANEL_TYPES.TIME_SERIES, DataSource.TRACES, false],
|
||||
])(
|
||||
'%s over %s renders the field picker: %s',
|
||||
(panelType, dataSource, picker) => {
|
||||
renderFor(panelType, dataSource);
|
||||
expect(!!screen.queryByTestId('distribution-field-select')).toBe(picker);
|
||||
expect(!!screen.queryByTestId('aggregation-select')).toBe(!picker);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { useState } from 'react';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { ChevronDown, ChevronRight, Undo2 } from '@signozhq/icons';
|
||||
|
||||
@@ -22,31 +20,6 @@ export function CheckboxFilterV2Header({
|
||||
onToggleOpen,
|
||||
onClear,
|
||||
}: CheckboxFilterHeaderProps): JSX.Element {
|
||||
const [isTitleTruncated, setIsTitleTruncated] = useState(false);
|
||||
|
||||
const measureTitle = (el: HTMLElement | null): void => {
|
||||
if (el) {
|
||||
setIsTitleTruncated(el.scrollWidth > el.clientWidth);
|
||||
}
|
||||
};
|
||||
|
||||
const titleText = (
|
||||
<Typography
|
||||
ref={measureTitle}
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
display="inline-block"
|
||||
minWidth={0}
|
||||
textOverflow="ellipsis"
|
||||
textTransform="capitalize"
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
);
|
||||
|
||||
return (
|
||||
<section
|
||||
role="button"
|
||||
@@ -67,7 +40,19 @@ export function CheckboxFilterV2Header({
|
||||
) : (
|
||||
<ChevronRight size={13} cursor="pointer" />
|
||||
)}
|
||||
<Tooltip title={isTitleTruncated ? title : undefined}>{titleText}</Tooltip>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
display="inline-block"
|
||||
minWidth={0}
|
||||
textOverflow="ellipsis"
|
||||
textTransform="capitalize"
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
</section>
|
||||
{isOpen && canReset && (
|
||||
<section className={styles.rightAction}>
|
||||
|
||||
@@ -120,43 +120,4 @@ describe('CheckboxFilterV2Header', () => {
|
||||
expect(onToggleOpen).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('title tooltip', () => {
|
||||
// jsdom has no layout, so truncation is simulated at the prototype level
|
||||
// before mount (the component measures in a layout effect).
|
||||
function mockTitleWidths(scrollWidth: number, clientWidth: number): void {
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'scrollWidth', 'get')
|
||||
.mockReturnValue(scrollWidth);
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'clientWidth', 'get')
|
||||
.mockReturnValue(clientWidth);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('shows the full name on hover when the title is truncated', async () => {
|
||||
mockTitleWidths(200, 100);
|
||||
const user = userEvent.setup();
|
||||
render(<CheckboxFilterV2Header {...defaultProps} />);
|
||||
|
||||
await user.hover(screen.getByText(defaultProps.title));
|
||||
|
||||
await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
|
||||
defaultProps.title,
|
||||
);
|
||||
});
|
||||
|
||||
it('shows no tooltip when the title fits', async () => {
|
||||
mockTitleWidths(100, 100);
|
||||
const user = userEvent.setup();
|
||||
render(<CheckboxFilterV2Header {...defaultProps} />);
|
||||
|
||||
await user.hover(screen.getByText(defaultProps.title));
|
||||
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -114,6 +114,19 @@ export const loadingFiltersHandlers = [
|
||||
),
|
||||
];
|
||||
|
||||
export const longTitleConfig = [
|
||||
{
|
||||
attributeKey: {
|
||||
dataType: DataTypes.Int64,
|
||||
key: 'http.request.content_length_uncompressed',
|
||||
type: 'tag',
|
||||
},
|
||||
defaultOpen: false,
|
||||
title: 'Http Request Content Length Uncompressed',
|
||||
type: FiltersType.CHECKBOX,
|
||||
},
|
||||
];
|
||||
|
||||
export const LONG_FILTER_VALUES = [
|
||||
'checkout-service.production-eu-central-1.svc.cluster.local',
|
||||
'payments-authorisation-worker.production-us-east-2.svc.cluster.local',
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { GlobalMockArgs } from '@/storybook/globals';
|
||||
import QuickFilters from '../QuickFilters';
|
||||
import {
|
||||
dirtySettings,
|
||||
hoverTruncatedTitle,
|
||||
openQueryPicker,
|
||||
openSettings,
|
||||
} from './__story_mockdata__/quickFilters.play';
|
||||
@@ -18,6 +19,7 @@ import {
|
||||
handlers,
|
||||
LONG_FILTER_VALUES,
|
||||
loadingFiltersHandlers,
|
||||
longTitleConfig,
|
||||
MANY_FILTER_VALUES,
|
||||
queryBuilder,
|
||||
selectedServiceQueryBuilder,
|
||||
@@ -159,6 +161,15 @@ export const Tooltips: GlobalArgsStory = {
|
||||
},
|
||||
};
|
||||
|
||||
/** A section title too long for the rail: hovering it shows the full title once. */
|
||||
export const TruncatedTitle: GlobalArgsStory = {
|
||||
args: { config: longTitleConfig },
|
||||
parameters: {
|
||||
msw: { handlers: [noSavedFiltersHandler, ...handlers] },
|
||||
},
|
||||
play: hoverTruncatedTitle,
|
||||
};
|
||||
|
||||
const [firstQuery] = queryBuilder.currentQuery.builder.queryData;
|
||||
|
||||
/** Interaction: the query picker lists every query the filters can follow. */
|
||||
|
||||
@@ -8,9 +8,12 @@ import { QuickFilterManagePermissions } from 'lib/authz/hooks/useAuthZ/permissio
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { grantsAll } from '@/storybook/access/access';
|
||||
import { hoverTruncatableText } from '@/storybook/play/truncatedText';
|
||||
import type { GlobalMockArgs } from '@/storybook/globals';
|
||||
|
||||
import type QuickFilters from '../../QuickFilters';
|
||||
import { longTitleConfig } from '../QuickFilters.stories.mocks';
|
||||
import { FiltersType } from '../../types';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
@@ -61,6 +64,26 @@ export const dirtySettings = async (context: PlayContext): Promise<void> => {
|
||||
await screen.findByRole('button', { name: 'Save changes' });
|
||||
};
|
||||
|
||||
export const hoverTruncatedTitle = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
const [filter] = args.config ?? [];
|
||||
// Duration and slider sections render no title of their own.
|
||||
if (filter?.type !== FiltersType.CHECKBOX || !filter.title) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [label] = await within(canvasElement).findAllByText(
|
||||
filter.title,
|
||||
{},
|
||||
UNTIL_LOADED,
|
||||
);
|
||||
await hoverTruncatableText(label, filter.title, {
|
||||
cut: filter.title === longTitleConfig[0].title || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
export const openQueryPicker = async ({
|
||||
canvasElement,
|
||||
}: PlayContext): Promise<void> => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { lazy } from 'react';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
|
||||
@@ -98,4 +99,30 @@ describe('RouteTab component', () => {
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'Tab2' }));
|
||||
expect(onChangeHandler).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the tab bar while a lazy tab loads', async () => {
|
||||
let resolveTab: (module: { default: () => JSX.Element }) => void = () => {};
|
||||
const LazyTab = lazy(
|
||||
() =>
|
||||
new Promise<{ default: () => JSX.Element }>((resolve) => {
|
||||
resolveTab = resolve;
|
||||
}),
|
||||
);
|
||||
render(
|
||||
<RouteTab
|
||||
routes={[{ ...testRoutes[0], Component: LazyTab }, testRoutes[1]]}
|
||||
activeKey="Tab1"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole('tab', { name: 'Tab1' })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByLabelText('loading').closest('.ant-spin')?.parentElement,
|
||||
).toHaveStyle({ height: '100%' });
|
||||
|
||||
resolveTab({ default: DummyComponent1 });
|
||||
await expect(
|
||||
screen.findByText('Dummy Component 1'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { Suspense } from 'react';
|
||||
import { Tabs, TabsProps } from 'antd';
|
||||
import cx from 'classnames';
|
||||
import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import Spinner from 'components/Spinner';
|
||||
import { buildRoutePath } from 'lib/router/buildRoutePath';
|
||||
import { matchRoute } from 'lib/router/matchRoute';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
@@ -58,7 +60,11 @@ function RouteTab({
|
||||
tabKey: route,
|
||||
children: (
|
||||
<OverlayScrollbar>
|
||||
<Component />
|
||||
<Suspense
|
||||
fallback={<Spinner size="large" tip="Loading..." height="100%" />}
|
||||
>
|
||||
<Component />
|
||||
</Suspense>
|
||||
</OverlayScrollbar>
|
||||
),
|
||||
}));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { PageTypeDTO } from '@signozhq/noz-client';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
--input-focus-background: transparent;
|
||||
--input-focus-outline-width: 0;
|
||||
--input-box-shadow: none;
|
||||
--input-font-size: var(--periscope-font-size-base);
|
||||
--input-font-size: var(--label-base-400-font-size);
|
||||
--input-line-height: 20px;
|
||||
--input-placeholder-color: color-mix(
|
||||
in srgb,
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
}
|
||||
|
||||
.heading {
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-medium);
|
||||
font-size: var(--label-small-500-font-size);
|
||||
font-weight: var(--label-small-500-font-weight);
|
||||
line-height: 1;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
@@ -34,9 +34,9 @@
|
||||
--button-height: auto;
|
||||
--button-padding: var(--spacing-4) var(--spacing-6);
|
||||
--button-border-radius: var(--radius-3);
|
||||
--button-font-size: var(--periscope-font-size-base);
|
||||
--button-font-size: var(--label-base-400-font-size);
|
||||
--button-size-line-height: var(--line-height-20);
|
||||
--button-font-weight: var(--font-weight-normal);
|
||||
--button-font-weight: var(--label-base-400-font-weight);
|
||||
--button-variant-outlined-background-color: var(--l3-background-60);
|
||||
--button-variant-outlined-border: none;
|
||||
--button-variant-outlined-color: var(--l2-foreground);
|
||||
|
||||
@@ -16,11 +16,11 @@ import {
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import type { MessageActionDTO } from '@signozhq/noz-client';
|
||||
import {
|
||||
ApplyFilterSignalDTO,
|
||||
MessageActionKindDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import {
|
||||
restoreExecution,
|
||||
revertExecution,
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
MessageActionDTO,
|
||||
MessageActionKindDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { MessageActionDTO, MessageActionKindDTO } from '@signozhq/noz-client';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { getCurrentLocation, navigate } from 'lib/router/navigation';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { undoExecution } from 'api/ai-assistant/chat';
|
||||
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import type { MessageActionDTO } from '@signozhq/noz-client';
|
||||
import {
|
||||
ApplyFilterSignalDTO,
|
||||
MessageActionKindDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ApplyFilterSignalDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { ApplyFilterSignalDTO } from '@signozhq/noz-client';
|
||||
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
ApplyFilterSignalDTO,
|
||||
MessageActionKindDTO,
|
||||
SavedViewEntityDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import {
|
||||
getSavedView,
|
||||
listSavedViews,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
type MessageActionDTO,
|
||||
MessageActionKindDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
|
||||
import {
|
||||
isSavedViewOpenAction,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
ApplyFilterSignalDTO,
|
||||
type MessageActionDTOQuery,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { MessageActionDTOQuery } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import type { MessageActionDTOQuery } from '@signozhq/noz-client';
|
||||
import { normalizeTimeToMs } from 'utils/timeUtils';
|
||||
|
||||
export interface ActionTimeRange {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import {
|
||||
ApplyFilterSignalDTO,
|
||||
SavedViewEntityDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import type { MessageActionDTO } from '@signozhq/noz-client';
|
||||
import { ApplyFilterSignalDTO, SavedViewEntityDTO } from '@signozhq/noz-client';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { ResourceType } from './resourceRoute';
|
||||
|
||||
@@ -31,8 +31,8 @@
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-medium);
|
||||
font-size: var(--label-small-500-font-size);
|
||||
font-weight: var(--label-small-500-font-weight);
|
||||
line-height: 18px;
|
||||
letter-spacing: -0.005em;
|
||||
}
|
||||
@@ -54,7 +54,7 @@
|
||||
|
||||
.soloThought {
|
||||
margin: 0;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
line-height: var(--line-height-20);
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l2-foreground);
|
||||
@@ -64,8 +64,8 @@
|
||||
|
||||
// While Noz works, the row names the step it's on.
|
||||
.live .activitySummary {
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-weight: var(--font-weight-normal);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
font-weight: var(--paragraph-base-400-font-weight);
|
||||
line-height: var(--line-height-20);
|
||||
@include shimmer-text(var(--l3-foreground), var(--l1-foreground));
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@
|
||||
border: none;
|
||||
background: none;
|
||||
font: inherit;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
line-height: var(--line-height-20);
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l1-foreground);
|
||||
@@ -90,7 +90,7 @@ button.title {
|
||||
}
|
||||
|
||||
.detail {
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
line-height: var(--line-height-20);
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l2-foreground);
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
}
|
||||
|
||||
.headerLabel {
|
||||
font-size: var(--font-size-sm);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
line-height: var(--line-height-20);
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l1-foreground);
|
||||
@@ -61,7 +61,7 @@
|
||||
|
||||
.summary {
|
||||
margin: 0;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
line-height: var(--line-height-20);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import type {
|
||||
ApprovalEventDTO,
|
||||
ApprovalEventDTODiff,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import {
|
||||
Check,
|
||||
Columns2,
|
||||
|
||||
@@ -134,8 +134,8 @@
|
||||
--button-padding: 7px #{$padding-inline};
|
||||
--button-border-radius: 0;
|
||||
--button-justify-content: flex-start;
|
||||
--button-font-size: var(--periscope-font-size-base);
|
||||
--button-font-weight: var(--font-weight-normal);
|
||||
--button-font-size: var(--label-base-400-font-size);
|
||||
--button-font-weight: var(--label-base-400-font-weight);
|
||||
--button-variant-ghost-color: var(--l2-foreground);
|
||||
--button-variant-ghost-hover-color: var(--l1-foreground);
|
||||
--button-variant-ghost-hover-background-color: var(--l3-background);
|
||||
@@ -180,8 +180,8 @@
|
||||
height: 44px;
|
||||
padding: 0 var(--spacing-7);
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
font-size: var(--label-small-600-font-size);
|
||||
font-weight: var(--label-small-600-font-weight);
|
||||
line-height: 1;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l3-background-60);
|
||||
color: var(--l2-foreground);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-medium);
|
||||
font-size: var(--label-small-500-font-size);
|
||||
font-weight: var(--label-small-500-font-weight);
|
||||
line-height: 15px;
|
||||
transition:
|
||||
background-color 0.12s,
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
}
|
||||
|
||||
.headerLabel {
|
||||
font-size: var(--font-size-sm);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
line-height: var(--line-height-20);
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--l1-foreground);
|
||||
@@ -48,7 +48,7 @@
|
||||
|
||||
.message {
|
||||
margin: 0;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
line-height: var(--line-height-20);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
@@ -6,11 +6,11 @@ import { Input } from '@signozhq/ui/input';
|
||||
import { Select } from '@signozhq/ui/select';
|
||||
import type { SelectItemType } from '@signozhq/ui/select';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ClarificationFieldTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { ClarificationFieldTypeDTO } from '@signozhq/noz-client';
|
||||
import type {
|
||||
ClarificationEventDTO,
|
||||
ClarificationFieldEventDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import { CircleHelp, Send, X } from '@signozhq/icons';
|
||||
|
||||
import { AIAssistantEvents } from '../../events';
|
||||
|
||||
@@ -53,7 +53,7 @@
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.005em;
|
||||
color: var(--text-vanilla-400);
|
||||
@@ -73,7 +73,7 @@
|
||||
// Wide enough to hold the action buttons that replace it.
|
||||
min-width: 16px;
|
||||
text-align: right;
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-size: var(--paragraph-small-400-font-size);
|
||||
line-height: 18px;
|
||||
color: var(--l3-foreground);
|
||||
opacity: calc(1 - var(--actions-opacity, 0));
|
||||
@@ -87,7 +87,7 @@
|
||||
width: 100%;
|
||||
border-bottom: 1px solid var(--accent-primary);
|
||||
--input-padding: 1px 0;
|
||||
--input-font-size: var(--periscope-font-size-base);
|
||||
--input-font-size: var(--label-base-400-font-size);
|
||||
--input-hover-border-color: transparent;
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
--button-border-radius: 3px;
|
||||
--button-justify-content: flex-start;
|
||||
--button-gap: var(--spacing-4);
|
||||
--button-font-weight: var(--font-weight-normal);
|
||||
--button-font-weight: var(--label-base-400-font-weight);
|
||||
--button-variant-outlined-background-color: var(--l2-background);
|
||||
--button-variant-outlined-border: 1px solid var(--l1-border);
|
||||
--button-variant-outlined-color: var(--l2-foreground);
|
||||
@@ -144,8 +144,8 @@
|
||||
.groupLabel {
|
||||
display: block;
|
||||
padding: 0 0 7px;
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
font-size: var(--label-small-600-font-size);
|
||||
font-weight: var(--label-small-600-font-weight);
|
||||
line-height: 1;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
}
|
||||
|
||||
.note {
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-medium);
|
||||
font-size: var(--label-small-500-font-size);
|
||||
font-weight: var(--label-small-500-font-weight);
|
||||
line-height: 1;
|
||||
font-feature-settings:
|
||||
'tnum' on,
|
||||
|
||||
@@ -71,7 +71,7 @@
|
||||
align-items: flex-start;
|
||||
background: var(--l2-background);
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
border-bottom-left-radius: var(--radius-2);
|
||||
}
|
||||
|
||||
@@ -274,7 +274,7 @@
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
font-variant-numeric: tabular-nums;
|
||||
word-break: normal;
|
||||
|
||||
@@ -286,8 +286,8 @@
|
||||
|
||||
th {
|
||||
padding-block: 13px;
|
||||
font-size: var(--periscope-font-size-small);
|
||||
font-weight: var(--font-weight-medium);
|
||||
font-size: var(--label-small-500-font-size);
|
||||
font-weight: var(--label-small-500-font-weight);
|
||||
line-height: 1;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
|
||||
@@ -5,7 +5,7 @@ import remarkGfm from 'remark-gfm';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { RotateCw, TriangleAlert } from '@signozhq/icons';
|
||||
|
||||
import { RetryActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { RetryActionDTO } from '@signozhq/noz-client';
|
||||
|
||||
// Side-effect: registers all built-in block types into the BlockRegistry
|
||||
import '../blocks';
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import React from 'react';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import {
|
||||
ErrorCodeDTO,
|
||||
RetryActionDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { ErrorCodeDTO, RetryActionDTO } from '@signozhq/noz-client';
|
||||
|
||||
import { Message } from '../../../types';
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useTimezone } from 'providers/Timezone';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
import { FeedbackRatingDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { FeedbackRatingDTO } from '@signozhq/noz-client';
|
||||
import { AIAssistantEvents } from '../../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
|
||||
|
||||
@@ -6,7 +6,7 @@ import remarkGfm from 'remark-gfm';
|
||||
import type {
|
||||
ApprovalEventDTO,
|
||||
ClarificationEventDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
|
||||
import { useVariant } from '../../VariantContext';
|
||||
import { StreamingEventItem } from '../../types';
|
||||
|
||||
@@ -44,8 +44,8 @@
|
||||
--button-height: 32px;
|
||||
--button-padding: 0 var(--spacing-6);
|
||||
--button-border-radius: var(--radius-round);
|
||||
--button-font-size: var(--periscope-font-size-base);
|
||||
--button-font-weight: var(--font-weight-normal);
|
||||
--button-font-size: var(--label-base-400-font-size);
|
||||
--button-font-weight: var(--label-base-400-font-weight);
|
||||
--button-secondary-background-color: var(--l3-background);
|
||||
--button-secondary-hover-background-color: var(--l3-background-hover);
|
||||
--button-secondary-solid-foreground: var(--l1-foreground);
|
||||
|
||||
@@ -7,7 +7,7 @@ import { ArrowDown } from '@signozhq/icons';
|
||||
import type {
|
||||
ApprovalEventDTO,
|
||||
ClarificationEventDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
import { AIAssistantEvents } from '../../events';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ChipDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import type { ChipDTO } from '@signozhq/noz-client';
|
||||
|
||||
/** Static empty-state chips used when the contextual chips API is unavailable. */
|
||||
export const EMPTY_STATE_CHIPS_FALLBACK: ChipDTO[] = [
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useMemo } from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
|
||||
import { getEmptyStateChips } from 'api/ai-assistant/chat';
|
||||
import type { ChipDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import type { ChipDTO } from '@signozhq/noz-client';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
|
||||
import { useResolvePageType } from 'hooks/aiAssistant/useResolvePageType';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { PageTypeDTO } from '@signozhq/noz-client';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { matchRoute } from 'lib/router/matchRoute';
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
MessageContextDTOType,
|
||||
MessageRoleDTO,
|
||||
RetryActionDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import type {
|
||||
MessageContext,
|
||||
SSEEvent,
|
||||
|
||||
@@ -7,8 +7,8 @@ import { immer } from 'zustand/middleware/immer';
|
||||
import type {
|
||||
MessageActionDTO,
|
||||
MessageSummaryDTOBlocksAnyOfItem,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { RetryActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import { RetryActionDTO } from '@signozhq/noz-client';
|
||||
|
||||
import {
|
||||
approveExecution,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
/**
|
||||
* UI types for the AI Assistant.
|
||||
*
|
||||
* Wherever the OpenAPI-generated DTOs in
|
||||
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`
|
||||
* Wherever the OpenAPI-generated DTOs in `@signozhq/noz-client`
|
||||
* already capture the right shape, this module re-exports them.
|
||||
*
|
||||
* A type is defined locally only when the UI needs a different shape than
|
||||
@@ -20,7 +19,7 @@ import type {
|
||||
MessageActionDTO,
|
||||
MessageActionKindDTO,
|
||||
RetryActionDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import type { MessageContext } from 'api/ai-assistant/chat';
|
||||
|
||||
/** Client-only file attachment — no API equivalent (uploads happen via data URLs). */
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { AxiosError } from 'axios';
|
||||
import {
|
||||
ErrorCodeDTO,
|
||||
RetryActionDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { ErrorCodeDTO, RetryActionDTO } from '@signozhq/noz-client';
|
||||
|
||||
import { resolveAssistantError } from '../resolveAssistantError';
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
RetryActionDTO,
|
||||
type ErrorBodyDTO,
|
||||
type ErrorResponseDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
|
||||
export interface AssistantErrorResolution {
|
||||
/** User-facing copy: code-specific FE copy → backend message → caller fallback. */
|
||||
|
||||
@@ -83,6 +83,7 @@ import { MeterAggregateOperator } from 'types/common/queryBuilder';
|
||||
import { USER_ROLES } from 'types/roles';
|
||||
import { getDaysUntilExpiry } from 'utils/timeUtils';
|
||||
|
||||
import 'components/LearnMore/LearnMore.styles.scss';
|
||||
import './IngestionSettings.styles.scss';
|
||||
|
||||
const { Option } = Select;
|
||||
|
||||
@@ -59,29 +59,6 @@ export function AlertsEmptyState({
|
||||
return (
|
||||
<div className={styles.alertListContainer}>
|
||||
<div className={styles.alertListViewContent}>
|
||||
<div>
|
||||
<Typography
|
||||
variant="label"
|
||||
size="large"
|
||||
weight="regular"
|
||||
color="main"
|
||||
as="h1"
|
||||
marginY={4}
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Alert Rules
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Create and manage alert rules for your resources.
|
||||
</Typography>
|
||||
</div>
|
||||
<section className={styles.emptyAlertInfoContainer}>
|
||||
<div className={styles.alertContent}>
|
||||
<section className={styles.heading}>
|
||||
|
||||
@@ -15,18 +15,6 @@
|
||||
background: var(--l1-background);
|
||||
}
|
||||
|
||||
.headerZone {
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
gap: 14px;
|
||||
padding: 20px 24px;
|
||||
background: var(--l2-background);
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
}
|
||||
|
||||
.tableContainer {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -35,6 +35,10 @@ describe('ListAlertRules — empty states', () => {
|
||||
expect(
|
||||
screen.getByText('Create an Alert Rule to get started'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('alert-rules-list-search')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('list-alerts-new-alert-button'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// New Alert Rule button is visible and triggers safeNavigate to ALERTS_NEW.
|
||||
await user.click(screen.getByTestId('add-alert'));
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import {
|
||||
alertRulesFixture,
|
||||
listRulesV3Response,
|
||||
} from 'mocks-server/__mockdata__/alert_rules';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { renderListAlertRules } from './_helpers';
|
||||
@@ -7,6 +13,25 @@ describe('ListAlertRules — list rendering', () => {
|
||||
jest.setSystemTime(new Date('2023-10-20T12:00:00Z'));
|
||||
});
|
||||
|
||||
it('asks for rules sorted by status, firing first, by default', async () => {
|
||||
const requests: URLSearchParams[] = [];
|
||||
server.use(
|
||||
rest.get('http://localhost/api/v3/rules', (req, res, ctx) => {
|
||||
requests.push(req.url.searchParams);
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(listRulesV3Response(alertRulesFixture, req.url.searchParams)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
expect(requests[0].get('sort')).toBe('state');
|
||||
expect(requests[0].get('order')).toBe('desc');
|
||||
});
|
||||
|
||||
it('renders alert rules from API', async () => {
|
||||
renderListAlertRules();
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { safeNavigateMock } from '__tests__/safeNavigateMock';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { useAlertRuleViewsStore } from 'container/ListAlertRules/useAlertRuleViewsStore';
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { renderListAlertRules } from './_helpers';
|
||||
@@ -7,6 +8,7 @@ import { renderListAlertRules } from './_helpers';
|
||||
describe('ListAlertRules — row click navigation', () => {
|
||||
beforeEach(() => {
|
||||
jest.setSystemTime(new Date('2023-10-20T12:00:00Z'));
|
||||
useAlertRuleViewsStore.setState({ recent: [] });
|
||||
});
|
||||
|
||||
it('clicking a row calls safeNavigate to alerts/overview with ruleId', async () => {
|
||||
@@ -29,6 +31,22 @@ describe('ListAlertRules — row click navigation', () => {
|
||||
expect(url).not.toContain('compositeQuery=');
|
||||
});
|
||||
|
||||
it('records an opened rule as recently viewed, most recent first', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
useAlertRuleViewsStore.setState({ recent: ['rule-2', 'rule-1'] });
|
||||
renderListAlertRules();
|
||||
|
||||
const ruleCell = await screen.findByTestId('alert-row-rule-1-name');
|
||||
await user.click(ruleCell.closest('td') as HTMLElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useAlertRuleViewsStore.getState().recent).toStrictEqual([
|
||||
'rule-1',
|
||||
'rule-2',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it('ctrl+click on a row navigates with newTab option', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
|
||||
@@ -19,6 +19,16 @@ import {
|
||||
|
||||
const QUERY = "name CONTAINS 'CPU'";
|
||||
|
||||
function getSearchContent(): HTMLElement {
|
||||
const content = screen
|
||||
.getByTestId('alert-rules-list-search')
|
||||
.querySelector<HTMLElement>('.cm-content');
|
||||
if (!content) {
|
||||
throw new Error('Search editor content not found');
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
function lastRequest(requests: URLSearchParams[]): URLSearchParams {
|
||||
return requests[requests.length - 1];
|
||||
}
|
||||
@@ -26,6 +36,10 @@ function lastRequest(requests: URLSearchParams[]): URLSearchParams {
|
||||
describe('ListAlertRules — search', () => {
|
||||
let requests: URLSearchParams[];
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setSystemTime(new Date('2023-10-20T12:00:00Z'));
|
||||
requests = [];
|
||||
@@ -129,6 +143,43 @@ describe('ListAlertRules — search', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('runs the draft when the search box loses focus', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
// jsdom reports no focus once it lands on <body>; a focused browser window does.
|
||||
jest.spyOn(document, 'hasFocus').mockReturnValue(true);
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
|
||||
await user.click(getSearchContent());
|
||||
setSearchDraft(QUERY);
|
||||
await user.click(document.body);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(lastRequest(requests).get('query')).toBe(QUERY);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(getCurrentNuqsSearchParams().get('query')).toBe(QUERY);
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the draft unrun when focus leaves the window', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
|
||||
await screen.findByText('High CPU Alert');
|
||||
|
||||
await user.click(getSearchContent());
|
||||
setSearchDraft(QUERY);
|
||||
jest.spyOn(document, 'hasFocus').mockReturnValue(false);
|
||||
await user.click(document.body);
|
||||
|
||||
expect(requests.some((r) => r.has('query'))).toBe(false);
|
||||
expect(
|
||||
screen.getByTestId('alert-rules-list-search-dirty'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('sends the selected states once, as repeated states= params, when the dropdown closes', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderListAlertRules();
|
||||
|
||||
@@ -33,16 +33,16 @@ const makeRule = (overrides: Partial<AlertRule>): AlertRule => ({
|
||||
});
|
||||
|
||||
describe('toListSort', () => {
|
||||
it('returns the default sort when orderBy is null', () => {
|
||||
it('returns the default sort, status first, when orderBy is null', () => {
|
||||
expect(toListSort(null)).toStrictEqual({
|
||||
sort: RuletypesListSortDTO.updated_at,
|
||||
sort: RuletypesListSortDTO.state,
|
||||
order: RuletypesListOrderDTO.desc,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the default sort for an unknown column', () => {
|
||||
expect(toListSort({ columnName: 'labels', order: 'asc' })).toStrictEqual({
|
||||
sort: RuletypesListSortDTO.updated_at,
|
||||
sort: RuletypesListSortDTO.state,
|
||||
order: RuletypesListOrderDTO.desc,
|
||||
});
|
||||
});
|
||||
@@ -71,10 +71,16 @@ describe('toListSort', () => {
|
||||
describe('toOrderBy', () => {
|
||||
it('returns null for the default sort', () => {
|
||||
expect(
|
||||
toOrderBy(RuletypesListSortDTO.updated_at, RuletypesListOrderDTO.desc),
|
||||
toOrderBy(RuletypesListSortDTO.state, RuletypesListOrderDTO.desc),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the previous default, updated_at desc, as an explicit sort', () => {
|
||||
expect(
|
||||
toOrderBy(RuletypesListSortDTO.updated_at, RuletypesListOrderDTO.desc),
|
||||
).toStrictEqual<SortState>({ columnName: 'updatedAt', order: 'desc' });
|
||||
});
|
||||
|
||||
it('returns the column for a non-default sort', () => {
|
||||
expect(
|
||||
toOrderBy(RuletypesListSortDTO.created_at, RuletypesListOrderDTO.asc),
|
||||
|
||||
@@ -131,7 +131,7 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
beforeEach(() => {
|
||||
jest.setSystemTime(new Date('2023-10-20T12:00:00Z'));
|
||||
localStorage.removeItem(LOCALSTORAGE.ALERT_RULES_LIST_VIEWS);
|
||||
useAlertRuleViewsStore.setState({ railCollapsed: false });
|
||||
useAlertRuleViewsStore.setState({ railCollapsed: false, recent: [] });
|
||||
});
|
||||
|
||||
describe('builtin views', () => {
|
||||
@@ -141,7 +141,9 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
await screen.findByText('High CPU Alert');
|
||||
expect(viewItem('mine')).toHaveTextContent('My alert rules');
|
||||
expect(viewItem('all')).toHaveTextContent('All alert rules');
|
||||
expect(viewItem('recent')).toHaveTextContent('Recently viewed');
|
||||
expect(viewItem('firing')).toHaveTextContent('Firing');
|
||||
expect(viewItem('enabled')).toHaveTextContent('Enabled');
|
||||
expect(viewItem('disabled')).toHaveTextContent('Disabled');
|
||||
expect(activeHeading()).toHaveTextContent('All alert rules');
|
||||
expect(
|
||||
@@ -174,6 +176,66 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('Enabled sends every state except disabled', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const requests = captureRulesRequests();
|
||||
renderListAlertRules();
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
await selectView(user, 'enabled');
|
||||
|
||||
const enabled = ['inactive', 'pending', 'recovering', 'firing', 'nodata'];
|
||||
await waitFor(() => {
|
||||
expect(lastRequest(requests).getAll('states')).toStrictEqual(enabled);
|
||||
});
|
||||
expect(lastRequest(requests).has('query')).toBe(false);
|
||||
expect(activeHeading()).toHaveTextContent('Enabled');
|
||||
});
|
||||
|
||||
it('Recently viewed lists the opened rules in visit order from one large page', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const requests = captureRulesRequests();
|
||||
useAlertRuleViewsStore.setState({ recent: ['rule-3', 'rule-1'] });
|
||||
renderListAlertRules();
|
||||
await screen.findByTestId('alert-row-rule-2-name');
|
||||
|
||||
await selectView(user, 'recent');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(lastRequest(requests).get('limit')).toBe('200');
|
||||
});
|
||||
expect(lastRequest(requests).get('offset')).toBe('0');
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByTestId('alert-row-rule-2-name'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
const names = screen
|
||||
.getAllByTestId(/^alert-row-.+-name$/)
|
||||
.map((cell) => cell.textContent);
|
||||
expect(names).toStrictEqual(['Healthy Alert', 'High CPU Alert']);
|
||||
expect(activeHeading()).toHaveTextContent('Recently viewed');
|
||||
});
|
||||
|
||||
it('an empty Recently viewed keeps the search and says how it fills', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
await screen.findByTestId('alert-row-rule-1-name');
|
||||
|
||||
await selectView(user, 'recent');
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('no-results-title'),
|
||||
).resolves.toHaveTextContent('No recently viewed alert rules');
|
||||
expect(screen.getByTestId('no-results-subtitle')).toHaveTextContent(
|
||||
'Alert rules you open will appear here.',
|
||||
);
|
||||
expect(screen.getByTestId('alert-rules-list-search')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('no-results-clear-button'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('My alert rules filters by the current user as creator', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const requests = captureRulesRequests();
|
||||
@@ -217,7 +279,7 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
version: 'v1',
|
||||
query: 'foo',
|
||||
states: [],
|
||||
sort: 'updated_at',
|
||||
sort: 'state',
|
||||
order: 'desc',
|
||||
},
|
||||
});
|
||||
@@ -492,6 +554,37 @@ describe('ListAlertRules — saved views rail', () => {
|
||||
expect(urlParam('view')).toBe('view-2');
|
||||
});
|
||||
|
||||
it('marks the empty query when a sort changes on a view without one', async () => {
|
||||
server.use(
|
||||
rest.get('http://localhost/api/v2/rule_views', (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
data: {
|
||||
views: [
|
||||
{
|
||||
...ruleViewsFixture[0],
|
||||
data: { ...ruleViewsFixture[0].data, query: '', states: [] },
|
||||
},
|
||||
],
|
||||
},
|
||||
status: 'success',
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
renderListAlertRules();
|
||||
await selectView(user, 'view-1');
|
||||
await waitFor(() => expect(urlParam('orderBy')).toBe(VIEW_1_ORDER_BY));
|
||||
expect(urlParam('query')).toBeNull();
|
||||
|
||||
await user.click(screen.getByTitle('Alert Name'));
|
||||
|
||||
await waitFor(() => expect(urlParam('query')).toBe(''));
|
||||
expect(urlParam('view')).toBe('view-1');
|
||||
});
|
||||
|
||||
it('keeps a cleared view filter cleared on reload', async () => {
|
||||
const requests = captureRulesRequests();
|
||||
renderListAlertRules({ initialRoute: '/?view=view-1&query=' });
|
||||
|
||||
@@ -49,7 +49,7 @@ function RuleStatesFilter({
|
||||
<MultiSelectFilter
|
||||
value={draft}
|
||||
options={STATE_OPTIONS}
|
||||
placeholder="State"
|
||||
placeholder="Status"
|
||||
testId="alert-rules-filter-states"
|
||||
onChange={handleChange}
|
||||
onDropdownVisibleChange={handleDropdownVisibleChange}
|
||||
|
||||
@@ -3,6 +3,7 @@ import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
|
||||
import NoResultsEmptyState from 'components/Alerts/NoResultsEmptyState';
|
||||
import InvalidQueryState from 'components/ListFilter/InvalidQueryState/InvalidQueryState';
|
||||
import ListCommandHeader from 'components/ListViews/ListCommandHeader/ListCommandHeader';
|
||||
import ListHeaderZone from 'components/ListViews/ListHeaderZone/ListHeaderZone';
|
||||
import ListStatusBar from 'components/ListViews/ListStatusBar/ListStatusBar';
|
||||
import ViewsRail from 'components/ListViews/ViewsRail/ViewsRail';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
@@ -27,7 +28,13 @@ import { useAlertRulesHandlers } from './useAlertRulesHandlers';
|
||||
import { useAlertRulesListFilter } from './useAlertRulesListFilter';
|
||||
import { useAlertRuleViews } from './useAlertRuleViews';
|
||||
import { useAlertRuleViewsStore } from './useAlertRuleViewsStore';
|
||||
import { DEFAULT_RULE_VIEW, RULE_BUILTIN_VIEWS } from './list.config';
|
||||
import {
|
||||
DEFAULT_RULE_VIEW,
|
||||
findRuleBuiltinView,
|
||||
RULE_BUILTIN_VIEWS,
|
||||
} from './list.config';
|
||||
import { useRuleViewCtx } from './useRuleViewCtx';
|
||||
import { ruleListEmptyState } from './utils';
|
||||
|
||||
const QUERY_PARAMS_CONFIG = {
|
||||
orderBy: 'orderBy',
|
||||
@@ -35,6 +42,9 @@ const QUERY_PARAMS_CONFIG = {
|
||||
limit: 'limit',
|
||||
} as const;
|
||||
|
||||
// Client-filtered views (Recently viewed) narrow one page of the API's max size.
|
||||
const CLIENT_VIEW_LIMIT = 200;
|
||||
|
||||
const DEFAULT_PAGE = 1;
|
||||
const DEFAULT_LIMIT = 10;
|
||||
|
||||
@@ -63,7 +73,7 @@ function ListAlertRules(): JSX.Element {
|
||||
},
|
||||
);
|
||||
|
||||
const { filter, applyFilter, submitQuery, changeStates } =
|
||||
const { filter, applyFilter, submitQuery, changeStates, changeSort } =
|
||||
useAlertRulesListFilter({ orderBy, setOrderBy, setPage });
|
||||
|
||||
const ruleViews = useAlertRuleViews({ filter, applyFilter });
|
||||
@@ -74,21 +84,25 @@ function ListAlertRules(): JSX.Element {
|
||||
setRailCollapsed(!railCollapsed);
|
||||
}, [setRailCollapsed, railCollapsed]);
|
||||
|
||||
const viewCtx = useRuleViewCtx();
|
||||
const clientFilter = findRuleBuiltinView(ruleViews.activeViewId)?.clientFilter;
|
||||
const clientView = !!clientFilter;
|
||||
|
||||
const listParams = useMemo(
|
||||
() => ({
|
||||
query: filter.query || undefined,
|
||||
states: filter.states.length ? filter.states : undefined,
|
||||
sort: filter.sort,
|
||||
order: filter.order,
|
||||
limit,
|
||||
offset: (page - 1) * limit,
|
||||
limit: clientView ? CLIENT_VIEW_LIMIT : limit,
|
||||
offset: clientView ? 0 : (page - 1) * limit,
|
||||
}),
|
||||
[filter, limit, page],
|
||||
[filter, limit, page, clientView],
|
||||
);
|
||||
|
||||
const {
|
||||
rules,
|
||||
total,
|
||||
rules: fetchedRules,
|
||||
total: fetchedTotal,
|
||||
labels,
|
||||
reservedKeywords,
|
||||
isFetching,
|
||||
@@ -97,6 +111,19 @@ function ListAlertRules(): JSX.Element {
|
||||
refetch,
|
||||
} = useAlertRulesData(listParams);
|
||||
|
||||
const clientRules = useMemo(
|
||||
() => (clientFilter ? clientFilter(fetchedRules, viewCtx) : null),
|
||||
[clientFilter, fetchedRules, viewCtx],
|
||||
);
|
||||
const rules = useMemo(
|
||||
() =>
|
||||
clientRules
|
||||
? clientRules.slice((page - 1) * limit, page * limit)
|
||||
: fetchedRules,
|
||||
[clientRules, fetchedRules, page, limit],
|
||||
);
|
||||
const total = clientRules ? clientRules.length : fetchedTotal;
|
||||
|
||||
const { creatorOptions, source } = useAlertRulesFilterSource({
|
||||
rules,
|
||||
labels,
|
||||
@@ -150,10 +177,16 @@ function ListAlertRules(): JSX.Element {
|
||||
}, [action, columns, handleEdit]);
|
||||
|
||||
const hasActiveFilters = filter.query.length > 0 || filter.states.length > 0;
|
||||
const isEmptyDueToFilters =
|
||||
!isFetching && total === 0 && (hasActiveFilters || !!queryError);
|
||||
const isEmptyNoRules =
|
||||
!isFetching && !isError && !queryError && !hasActiveFilters && total === 0;
|
||||
const { isEmptyDueToFilters, isEmptyNoRules, noResults, onClear } =
|
||||
ruleListEmptyState({
|
||||
isFetching,
|
||||
isError,
|
||||
queryError,
|
||||
hasActiveFilters,
|
||||
total,
|
||||
viewEmptyState: findRuleBuiltinView(ruleViews.activeViewId)?.emptyState,
|
||||
onClear: handleClearFilters,
|
||||
});
|
||||
|
||||
const activeLabel =
|
||||
ruleViews.activeView?.name ??
|
||||
@@ -182,32 +215,30 @@ function ListAlertRules(): JSX.Element {
|
||||
deleteDescription="Views are shared across your organization, so this removes it for everyone. Alert rules are not affected."
|
||||
/>
|
||||
<div className={styles.main}>
|
||||
{!isEmptyNoRules && (
|
||||
<div className={styles.headerZone}>
|
||||
<ListCommandHeader
|
||||
label={activeLabel}
|
||||
count={total}
|
||||
isCountLoading={isFetching}
|
||||
isModified={ruleViews.isModified}
|
||||
testIdPrefix="alert-rules"
|
||||
action={
|
||||
<AlertRulesHeaderActions
|
||||
columns={columns}
|
||||
canAddAlert={addNewAlert}
|
||||
onNewAlert={handleNewAlert}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<AlertRulesFilterZone
|
||||
query={filter.query}
|
||||
states={filter.states}
|
||||
creatorOptions={creatorOptions}
|
||||
source={source}
|
||||
onQueryChange={submitQuery}
|
||||
onStatesChange={changeStates}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<ListHeaderZone testId="alert-rules-header-zone">
|
||||
<ListCommandHeader
|
||||
label={activeLabel}
|
||||
count={total}
|
||||
isCountLoading={isFetching}
|
||||
isModified={ruleViews.isModified}
|
||||
testIdPrefix="alert-rules"
|
||||
action={
|
||||
<AlertRulesHeaderActions
|
||||
columns={columns}
|
||||
canAddAlert={addNewAlert && !isEmptyNoRules}
|
||||
onNewAlert={handleNewAlert}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<AlertRulesFilterZone
|
||||
query={filter.query}
|
||||
states={filter.states}
|
||||
creatorOptions={creatorOptions}
|
||||
source={source}
|
||||
onQueryChange={submitQuery}
|
||||
onStatesChange={changeStates}
|
||||
/>
|
||||
</ListHeaderZone>
|
||||
|
||||
<div ref={containerRef} className={styles.tableContainer}>
|
||||
{isError ? (
|
||||
@@ -220,9 +251,9 @@ function ListAlertRules(): JSX.Element {
|
||||
/>
|
||||
) : isEmptyDueToFilters ? (
|
||||
<NoResultsEmptyState
|
||||
title="No matching alert rules"
|
||||
subtitle="No alert rules match your search. Try adjusting your search criteria."
|
||||
onClear={handleClearFilters}
|
||||
title={noResults.title}
|
||||
subtitle={noResults.description}
|
||||
onClear={onClear}
|
||||
clearButtonText="Clear Search"
|
||||
/>
|
||||
) : isEmptyNoRules ? (
|
||||
@@ -236,6 +267,7 @@ function ListAlertRules(): JSX.Element {
|
||||
getItemKey={(row): string => row.id ?? ''}
|
||||
columnStorageKey="alert-rules-columns"
|
||||
enableQueryParams={QUERY_PARAMS_CONFIG}
|
||||
onSort={changeSort}
|
||||
onRowClick={handleRowClick}
|
||||
onRowClickNewTab={handleRowClickNewTab}
|
||||
pagination={{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { BellOff, Flame, Layers, User } from '@signozhq/icons';
|
||||
import { Bell, BellOff, Clock, Flame, Layers, User } from '@signozhq/icons';
|
||||
import { clause } from 'components/ListFilter/dsl/filterQuery';
|
||||
import type {
|
||||
ClauseBuilder,
|
||||
@@ -7,7 +7,7 @@ import type {
|
||||
} from 'components/ListFilter/dsl/types';
|
||||
import type { BuiltinViewConfig } from 'components/ListViews/types';
|
||||
|
||||
import type { RuleListFilter, RuleViewCtx } from './types';
|
||||
import type { AlertRule, RuleListFilter, RuleViewCtx } from './types';
|
||||
|
||||
// Mirrors pkg/types/ruletypes/list_filter.go. Label keys go under `labels.`.
|
||||
export const RULES_DSL_GRAMMAR = {
|
||||
@@ -44,9 +44,14 @@ const where: ClauseBuilder<
|
||||
(typeof RULES_DSL_GRAMMAR)['fields'][number]['key']
|
||||
> = clause;
|
||||
|
||||
type RuleViewConfig = BuiltinViewConfig<RuleListFilter, RuleViewCtx>;
|
||||
type RuleViewConfig = BuiltinViewConfig<RuleListFilter, RuleViewCtx, AlertRule>;
|
||||
|
||||
const ENABLED_STATES = Object.values(RuletypesAlertStateDTO).filter(
|
||||
(state) => state !== RuletypesAlertStateDTO.disabled,
|
||||
);
|
||||
|
||||
// Built-in views replace query and states; the current sort/order is kept.
|
||||
// `clientFilter` views narrow one large fetched page in the browser.
|
||||
const views = [
|
||||
{
|
||||
id: 'mine',
|
||||
@@ -59,6 +64,24 @@ const views = [
|
||||
states: [],
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'recent',
|
||||
label: 'Recently viewed',
|
||||
icon: Clock,
|
||||
section: 'personal',
|
||||
filter: (current): RuleListFilter => ({ ...current, query: '', states: [] }),
|
||||
// Keeps visit order, whatever the active sort.
|
||||
clientFilter: (rows, { recent }): AlertRule[] => {
|
||||
const order = new Map(recent.map((id, index) => [id, index]));
|
||||
return rows
|
||||
.filter((rule) => !!rule.id && order.has(rule.id))
|
||||
.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0));
|
||||
},
|
||||
emptyState: {
|
||||
title: 'No recently viewed alert rules',
|
||||
description: 'Alert rules you open will appear here.',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'all',
|
||||
label: 'All alert rules',
|
||||
@@ -77,6 +100,17 @@ const views = [
|
||||
states: [RuletypesAlertStateDTO.firing],
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'enabled',
|
||||
label: 'Enabled',
|
||||
icon: Bell,
|
||||
section: 'system',
|
||||
filter: (current): RuleListFilter => ({
|
||||
...current,
|
||||
query: '',
|
||||
states: ENABLED_STATES,
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'disabled',
|
||||
label: 'Disabled',
|
||||
@@ -95,3 +129,6 @@ export type RuleViewId = (typeof views)[number]['id'];
|
||||
export const RULE_BUILTIN_VIEWS: readonly RuleViewConfig[] = views;
|
||||
|
||||
export const DEFAULT_RULE_VIEW: RuleViewId = 'all';
|
||||
|
||||
export const findRuleBuiltinView = (id: string): RuleViewConfig | undefined =>
|
||||
RULE_BUILTIN_VIEWS.find((v) => v.id === id);
|
||||
|
||||
@@ -19,4 +19,5 @@ export type RuleView = SavedListView<RuleListFilter>;
|
||||
|
||||
export interface RuleViewCtx {
|
||||
userEmail: string;
|
||||
recent: string[];
|
||||
}
|
||||
|
||||
@@ -20,8 +20,7 @@ export interface UseAlertRuleViewsResult extends UseListViewsResult<RuleListFilt
|
||||
}
|
||||
|
||||
// A link carrying only `view=<custom id>` gets that view's filter applied once
|
||||
// the views load; a link carrying its own filter params keeps them. Clearing a
|
||||
// custom view's filter writes an empty `query=` so a reload keeps it cleared.
|
||||
// the views load; a link carrying its own filter params keeps them.
|
||||
export function useAlertRuleViews({
|
||||
filter,
|
||||
applyFilter,
|
||||
@@ -42,21 +41,12 @@ export function useAlertRuleViews({
|
||||
});
|
||||
|
||||
const { activeView } = views;
|
||||
const [rawQuery, setRawQuery] = useQueryState(ALERT_RULES_PARAMS.QUERY);
|
||||
const [rawQuery] = useQueryState(ALERT_RULES_PARAMS.QUERY);
|
||||
const startedFromViewLink = useRef(
|
||||
isDefaultRuleListFilter(filter) && rawQuery === null,
|
||||
);
|
||||
const hasResolvedLinkedView = useRef(false);
|
||||
|
||||
// Declared before the restore so it skips the render that applies a linked view.
|
||||
const clearedCustomView =
|
||||
!!activeView && rawQuery === null && isDefaultRuleListFilter(filter);
|
||||
useEffect(() => {
|
||||
if (hasResolvedLinkedView.current && clearedCustomView) {
|
||||
void setRawQuery('', { clearOnDefault: false, history: 'replace' });
|
||||
}
|
||||
}, [clearedCustomView, setRawQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
if (hasResolvedLinkedView.current || api.isLoading) {
|
||||
return;
|
||||
|
||||
@@ -2,18 +2,29 @@ import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
|
||||
// Most-recently-viewed list is capped so it stays a useful shortlist.
|
||||
const RECENT_LIMIT = 20;
|
||||
|
||||
interface AlertRuleViewsState {
|
||||
railCollapsed: boolean;
|
||||
recent: string[]; // rule ids, most-recent first
|
||||
setRailCollapsed: (collapsed: boolean) => void;
|
||||
markViewed: (id: string) => void;
|
||||
}
|
||||
|
||||
export const useAlertRuleViewsStore = create<AlertRuleViewsState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
railCollapsed: false,
|
||||
recent: [],
|
||||
setRailCollapsed: (collapsed): void => {
|
||||
set({ railCollapsed: collapsed });
|
||||
},
|
||||
markViewed: (id): void => {
|
||||
set((s) => ({
|
||||
recent: [id, ...s.recent.filter((r) => r !== id)].slice(0, RECENT_LIMIT),
|
||||
}));
|
||||
},
|
||||
}),
|
||||
{ name: LOCALSTORAGE.ALERT_RULES_LIST_VIEWS },
|
||||
),
|
||||
|
||||
@@ -8,6 +8,7 @@ import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { isModifierKeyPressed } from 'utils/app';
|
||||
|
||||
import type { AlertRule } from './types';
|
||||
import { useAlertRuleViewsStore } from './useAlertRuleViewsStore';
|
||||
|
||||
interface UseAlertRulesHandlersReturn {
|
||||
handleEdit: (
|
||||
@@ -24,6 +25,16 @@ export function useAlertRulesHandlers(
|
||||
): UseAlertRulesHandlersReturn {
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
const params = useUrlQuery();
|
||||
const markViewed = useAlertRuleViewsStore((s) => s.markViewed);
|
||||
|
||||
const markRuleViewed = useCallback(
|
||||
(rule: Pick<AlertRule, 'id'>): void => {
|
||||
if (rule.id) {
|
||||
markViewed(rule.id);
|
||||
}
|
||||
},
|
||||
[markViewed],
|
||||
);
|
||||
|
||||
const getEditUrl = useCallback(
|
||||
(rule: Pick<AlertRule, 'id'>): string => {
|
||||
@@ -36,9 +47,10 @@ export function useAlertRulesHandlers(
|
||||
|
||||
const handleEdit = useCallback(
|
||||
(rule: Pick<AlertRule, 'id'>, options?: { newTab?: boolean }): void => {
|
||||
markRuleViewed(rule);
|
||||
safeNavigate(getEditUrl(rule), options);
|
||||
},
|
||||
[getEditUrl, safeNavigate],
|
||||
[getEditUrl, safeNavigate, markRuleViewed],
|
||||
);
|
||||
|
||||
const handleNewAlert = useCallback(
|
||||
@@ -57,6 +69,7 @@ export function useAlertRulesHandlers(
|
||||
const { handleRowClick, handleRowClickNewTab } = useTableRowClick<AlertRule>({
|
||||
getUrl: getEditUrl,
|
||||
onNavigate: safeNavigate,
|
||||
onBeforeNavigate: markRuleViewed,
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import type { SortState } from 'components/TanStackTableView/types';
|
||||
import { useQueryState } from 'nuqs';
|
||||
|
||||
import { useAlertRulesQuery, useAlertRulesStates } from './hooks';
|
||||
import {
|
||||
ALERT_RULES_PARAMS,
|
||||
useAlertRulesQuery,
|
||||
useAlertRulesStates,
|
||||
} from './hooks';
|
||||
import { findRuleBuiltinView } from './list.config';
|
||||
import type { RuleListFilter } from './types';
|
||||
import { toListSort, toOrderBy } from './utils';
|
||||
|
||||
@@ -16,6 +22,8 @@ interface UseAlertRulesListFilterResult {
|
||||
applyFilter: (filter: RuleListFilter) => void;
|
||||
submitQuery: (query: string) => void;
|
||||
changeStates: (states: string[]) => void;
|
||||
/** The table writes `orderBy` itself; this only keeps a custom view's empty query. */
|
||||
changeSort: () => void;
|
||||
}
|
||||
|
||||
// The v3 list filter, read from and written to the URL. Every change goes back to page 1.
|
||||
@@ -42,21 +50,42 @@ export function useAlertRulesListFilter({
|
||||
[setQuery, setStates, setOrderBy, setPage],
|
||||
);
|
||||
|
||||
// Clearing a custom view's filter writes an empty `query=`, so a reload does
|
||||
// not re-apply the view.
|
||||
const [viewId] = useQueryState(ALERT_RULES_PARAMS.VIEW);
|
||||
const onCustomView = !!viewId && !findRuleBuiltinView(viewId);
|
||||
const pinEmptyQuery = useCallback((): void => {
|
||||
void setQuery('', { clearOnDefault: false });
|
||||
}, [setQuery]);
|
||||
|
||||
const submitQuery = useCallback(
|
||||
(next: string): void => {
|
||||
void setQuery(next || null);
|
||||
if (!next && onCustomView) {
|
||||
pinEmptyQuery();
|
||||
} else {
|
||||
void setQuery(next || null);
|
||||
}
|
||||
setPage(1);
|
||||
},
|
||||
[setQuery, setPage],
|
||||
[onCustomView, pinEmptyQuery, setQuery, setPage],
|
||||
);
|
||||
|
||||
const changeStates = useCallback(
|
||||
(next: string[]): void => {
|
||||
void setStates(next.length ? next : null);
|
||||
if (!query && onCustomView) {
|
||||
pinEmptyQuery();
|
||||
}
|
||||
setPage(1);
|
||||
},
|
||||
[setStates, setPage],
|
||||
[setStates, query, onCustomView, pinEmptyQuery, setPage],
|
||||
);
|
||||
|
||||
return { filter, applyFilter, submitQuery, changeStates };
|
||||
const changeSort = useCallback((): void => {
|
||||
if (!query && onCustomView) {
|
||||
pinEmptyQuery();
|
||||
}
|
||||
}, [query, onCustomView, pinEmptyQuery]);
|
||||
|
||||
return { filter, applyFilter, submitQuery, changeStates, changeSort };
|
||||
}
|
||||
|
||||
@@ -2,8 +2,13 @@ import { useMemo } from 'react';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
|
||||
import type { RuleViewCtx } from './types';
|
||||
import { useAlertRuleViewsStore } from './useAlertRuleViewsStore';
|
||||
|
||||
export function useRuleViewCtx(): RuleViewCtx {
|
||||
const { user } = useAppContext();
|
||||
return useMemo(() => ({ userEmail: user.email }), [user.email]);
|
||||
const recent = useAlertRuleViewsStore((s) => s.recent);
|
||||
return useMemo(
|
||||
() => ({ userEmail: user.email, recent }),
|
||||
[user.email, recent],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
RuletypesListOrderDTO,
|
||||
RuletypesListSortDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import type { EmptyStateCopy } from 'components/ListViews/types';
|
||||
import type { SortState } from 'components/TanStackTableView/types';
|
||||
import { dataSourceForAlertType } from 'constants/alerts';
|
||||
|
||||
@@ -45,7 +46,8 @@ const COLUMN_TO_SORT: Record<string, RuletypesListSortDTO> = {
|
||||
updatedAt: RuletypesListSortDTO.updated_at,
|
||||
};
|
||||
|
||||
export const DEFAULT_RULE_LIST_SORT = RuletypesListSortDTO.updated_at;
|
||||
// Status, highest rank first: firing, nodata, pending, recovering, inactive, disabled.
|
||||
export const DEFAULT_RULE_LIST_SORT = RuletypesListSortDTO.state;
|
||||
export const DEFAULT_RULE_LIST_ORDER = RuletypesListOrderDTO.desc;
|
||||
|
||||
// `rule_list_filter_invalid`: DSL syntax / key / operator; `rule_list_invalid`: other list params.
|
||||
@@ -114,3 +116,48 @@ export const DEFAULT_RULE_LIST_FILTER: RuleListFilter = {
|
||||
export function isDefaultRuleListFilter(filter: RuleListFilter): boolean {
|
||||
return isSameRuleListFilter(filter, DEFAULT_RULE_LIST_FILTER);
|
||||
}
|
||||
|
||||
interface RuleListEmptyStateArgs {
|
||||
isFetching: boolean;
|
||||
isError: boolean;
|
||||
queryError: string | null;
|
||||
hasActiveFilters: boolean;
|
||||
total: number;
|
||||
viewEmptyState?: EmptyStateCopy;
|
||||
onClear: () => void;
|
||||
}
|
||||
|
||||
interface RuleListEmptyState {
|
||||
isEmptyDueToFilters: boolean;
|
||||
isEmptyNoRules: boolean;
|
||||
noResults: EmptyStateCopy;
|
||||
// Unset for an empty view with its own copy (Recently viewed): no search to clear.
|
||||
onClear?: () => void;
|
||||
}
|
||||
|
||||
export function ruleListEmptyState({
|
||||
isFetching,
|
||||
isError,
|
||||
queryError,
|
||||
hasActiveFilters,
|
||||
total,
|
||||
viewEmptyState,
|
||||
onClear,
|
||||
}: RuleListEmptyStateArgs): RuleListEmptyState {
|
||||
const viewEmptyCopy =
|
||||
hasActiveFilters || queryError ? undefined : viewEmptyState;
|
||||
const isEmpty = !isFetching && total === 0;
|
||||
const noResults: EmptyStateCopy = viewEmptyCopy ?? {
|
||||
title: 'No matching alert rules',
|
||||
description:
|
||||
'No alert rules match your search. Try adjusting your search criteria.',
|
||||
};
|
||||
return {
|
||||
isEmptyDueToFilters:
|
||||
isEmpty && (hasActiveFilters || !!queryError || !!viewEmptyCopy),
|
||||
isEmptyNoRules:
|
||||
isEmpty && !isError && !queryError && !hasActiveFilters && !viewEmptyCopy,
|
||||
noResults,
|
||||
onClear: viewEmptyCopy ? undefined : onClear,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import {
|
||||
IBuilderQuery,
|
||||
OrderByPayload,
|
||||
@@ -10,6 +11,8 @@ export type OrderByFilterProps = {
|
||||
entityVersion?: string;
|
||||
isNewQueryV2?: boolean;
|
||||
placeholder?: string;
|
||||
/** A logs or traces heatmap aggregates a field, which Order by then offers. */
|
||||
panelType?: PANEL_TYPES;
|
||||
};
|
||||
|
||||
export type OrderByFilterValue = {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user