Compare commits

..

6 Commits

Author SHA1 Message Date
Vinícius Lourenço
8caad10117 test(e2e): disable response compression on the e2e server 2026-11-23 22:54:20 -03:00
Vinícius Lourenço
b8b05031d2 perf(web): serve precompressed gzip twins of the frontend files 2026-11-23 22:54:19 -03:00
Vinícius Lourenço
fc2d7b0bf8 feat(apiserver): add apiserver.compression.enabled and level 2026-11-23 22:54:15 -03:00
Vinícius Lourenço
18ab0c86b1 perf(http): swap gorilla compress handler for klauspost gzhttp 2026-11-23 22:54:15 -03:00
Vinícius Lourenço
649c3a250c build(web): pin hashed asset names that the immutable cache relies on 2026-11-23 22:46:11 -03:00
Vinícius Lourenço
f7b1383427 perf(web): cache hashed frontend assets as immutable 2026-11-23 22:46:09 -03:00
154 changed files with 5384 additions and 2425 deletions

View File

@@ -15,4 +15,3 @@ 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.

View File

@@ -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.17 \
signoz/signoz-otel-collector:v0.144.16-rc.1 \
wiremock/wiremock:2.35.1-1 \
| xargs -P 0 -n 1 docker pull -q
- name: python

View File

@@ -85,18 +85,13 @@ jobs:
- wal
clickhouse-version:
- 25.12.5
- 26.8.34
signoz-otel-collector-version:
- v0.144.17
- v0.144.16-rc.1
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

View File

@@ -165,6 +165,12 @@ apiserver:
- /api/v1/health
- /api/v1/version
- /
compression:
# Gzip responses on the fly. Turn off when a proxy in front already compresses.
# Web files shipped with a .gz twin are served precompressed either way.
enabled: true
# Gzip level, from 1 (fastest) to 9 (smallest), or -1 for the default.
level: -1
##################### Querier #####################
querier:
@@ -474,14 +480,6 @@ 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:

View File

@@ -2,10 +2,7 @@ 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"
@@ -13,7 +10,6 @@ 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"
@@ -43,25 +39,13 @@ 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).
opts := []kgo.Opt{
client, err := kgo.NewClient(
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
}
@@ -146,30 +130,3 @@ 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
}

View File

@@ -1,269 +0,0 @@
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})
}

3
frontend/.gitignore vendored
View File

@@ -1,4 +1,7 @@
# Vite copies public/ unhashed, and the Go server caches /assets/ as immutable
/public/assets/
# Sentry Config File
.env.sentry-build-plugin
.qodo

View File

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

View File

@@ -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 `--{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)
- [ ] 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
- [ ] No ID selectors
- [ ] No bare element selectors
- [ ] Keyframes are declared in the module with plain `@keyframes name` (already local)
- [ ] Keyframes use `:local(@keyframes name)` to avoid global collisions
## Config (vite.config.ts)
@@ -77,7 +77,7 @@ css: {
// BAD: Nesting creates separate classes you might not expect
.button {
.icon { } // -> styles.icon, but the rule is `.button .icon`: it only matches inside .button
.icon { } // -> styles.icon (separate class, not scoped under .button)
}
// GOOD: Flat structure
@@ -289,32 +289,88 @@ Use L1/L2/L3 semantic tokens - they handle light/dark theme automatically.
- L2 = elevated surfaces (cards, panels)
- L3 = nested/inset elements
## @signozhq/ui Components
## Overriding @signozhq/ui Components
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.
Components expose CSS variables for customization.
- 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.
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:
```scss
// BAD: Restyling the component
.saveButton {
--button-primary-background-color: var(--success-background);
// 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);
}
.toolbar :global([data-variant="outlined"]) {
--button-variant-outlined-border: 1px solid var(--accent-primary);
// 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);
}
// GOOD: Layout on your own wrapper, looks from props
.toolbarActions {
display: flex;
gap: var(--spacing-4);
margin-left: auto;
// Override nested parts
.customInput {
--input-prefix-padding: 0 var(--spacing-4) 0 var(--spacing-6);
--input-suffix-color: var(--accent-primary);
}
```
### 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
@@ -378,21 +434,24 @@ Don't override them. That covers setting a component's `--<component>-*` CSS var
### Keyframes (Local Scoping)
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`.
Without `:local()`, keyframe names are global and can clash across modules:
```scss
// GOOD: Local to this module
// BAD: Global keyframe - can conflict with other modules
@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

View File

@@ -6,8 +6,6 @@ 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'],

View File

@@ -137,8 +137,6 @@ window.getComputedStyle = function (
return {
display: '',
visibility: '',
width: '',
height: '',
opacity: '1',
animationName: 'none',
getPropertyValue: () => '',

View File

@@ -56,7 +56,6 @@
"@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",

View File

@@ -82,9 +82,6 @@ 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)
@@ -3251,13 +3248,6 @@ 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:
@@ -12383,12 +12373,6 @@ 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)

View File

@@ -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
* `@signozhq/noz-client`.
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`.
* 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 '@signozhq/noz-client';
} from './sigNozAIAssistantAPI.schemas';
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

View File

@@ -21,7 +21,6 @@ import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import {
convertBuilderQueriesToV5,
createAggregation,
mapPanelTypeToRequestType,
prepareQueryRangePayloadV5,
} from './prepareQueryRangePayloadV5';
@@ -1016,47 +1015,3 @@ 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' },
]);
});
});

View File

@@ -5,8 +5,6 @@ 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';
@@ -242,6 +240,32 @@ 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,
@@ -286,28 +310,18 @@ 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,
isDistributionField,
);
return isEmpty(parsedAggregations) ? fallback : parsedAggregations;
const parsedAggregations = parseAggregations(agg.expression, agg?.alias);
return isEmpty(parsedAggregations)
? [{ expression: 'count()' }]
: parsedAggregations;
},
);
}
return fallback;
return [{ expression: 'count()' }];
}
/**

View File

@@ -12,5 +12,4 @@
import '@signozhq/design-tokens';
import '@signozhq/icons';
import '@signozhq/noz-client';
import '@signozhq/ui';

View File

@@ -1,15 +0,0 @@
.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);
}

View File

@@ -1,19 +0,0 @@
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;

View File

@@ -106,10 +106,8 @@ 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];
}
@@ -438,7 +436,6 @@ function QueryAddOns({
onChange={handleChangeOrderByKeys}
isRawQuery={isRawQuery}
isNewQueryV2
panelType={panelType ?? undefined}
placeholder={placeholderOf(QueryBuilderField.OrderBy)}
/>
</div>

View File

@@ -107,8 +107,8 @@ export const BASE_ADD_ONS = (
export const REDUCE_TO = toAddOn(QueryBuilderField.ReduceTo);
// 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.
// 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.
export const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
ATTRIBUTE_TYPES.HISTOGRAM,
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,

View File

@@ -1,5 +0,0 @@
// Fills the row like the filter and Group By boxes.
.select {
flex: 1;
min-width: 400px;
}

View File

@@ -1,69 +0,0 @@
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>
);
}

View File

@@ -6,7 +6,6 @@ import {
IBuilderQuery,
IBuilderTraceOperator,
} from 'types/api/queryBuilder/queryBuilderData';
import { aggregatesDistributionField } from 'lib/query/distributionField';
import { DataSource } from 'types/common/queryBuilder';
import {
@@ -20,7 +19,6 @@ import {
} from '../../queryBuilderFields.utils';
import { isScalarPanelType } from '../panelTypes';
import DistributionFieldSelect from './DistributionFieldSelect';
import QueryAggregationSelect from './QueryAggregationSelect';
import './QueryAggregation.styles.scss';
@@ -65,21 +63,17 @@ function QueryAggregationOptions({
data-testid="query-aggregation-container"
>
<div className="aggregation-container">
{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
}
/>
)}
<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">

View File

@@ -1,163 +0,0 @@
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'));
});
});

View File

@@ -1,84 +0,0 @@
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);
});
});

View File

@@ -1,81 +0,0 @@
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;
}

View File

@@ -506,7 +506,7 @@ describe('QueryAddOns', () => {
);
}
it('is offered on a metrics heatmap', () => {
it('is offered on a metrics heatmap only', () => {
renderHeatmap();
expect(
@@ -532,16 +532,23 @@ describe('QueryAddOns', () => {
).not.toBeInTheDocument();
});
it.each([DataSource.LOGS, DataSource.TRACES])(
'is offered on a %s heatmap',
(dataSource) => {
renderHeatmap({ dataSource });
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}
/>,
);
expect(
screen.getByTestId('query-add-on-bucket_options'),
).toBeInTheDocument();
},
);
expect(
screen.queryByTestId('query-add-on-bucket_options'),
).not.toBeInTheDocument();
});
it.each([ATTRIBUTE_TYPES.HISTOGRAM, ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM])(
'is not offered for a %s metric, which carries its own buckets',

View File

@@ -8,7 +8,7 @@ import QueryAggregationOptions from '../QueryV2/QueryAggregation/QueryAggregatio
jest.mock('../QueryV2/QueryAggregation/QueryAggregationSelect', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="aggregation-select" />,
default: (): null => null,
}));
const queryData = initialQueriesMap.traces.builder
@@ -69,18 +69,3 @@ 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);
},
);
});

View File

@@ -1,4 +1,3 @@
import { lazy } from 'react';
import { navigate } from 'lib/router/navigation';
import { fireEvent, render, screen } from 'tests/test-utils';
@@ -99,30 +98,4 @@ 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();
});
});

View File

@@ -1,9 +1,7 @@
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';
@@ -60,11 +58,7 @@ function RouteTab({
tabKey: route,
children: (
<OverlayScrollbar>
<Suspense
fallback={<Spinner size="large" tip="Loading..." height="100%" />}
>
<Component />
</Suspense>
<Component />
</OverlayScrollbar>
),
}));

View File

@@ -1,4 +1,4 @@
import { PageTypeDTO } from '@signozhq/noz-client';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';

View File

@@ -8,7 +8,7 @@
--input-focus-background: transparent;
--input-focus-outline-width: 0;
--input-box-shadow: none;
--input-font-size: var(--label-base-400-font-size);
--input-font-size: var(--periscope-font-size-base);
--input-line-height: 20px;
--input-placeholder-color: color-mix(
in srgb,

View File

@@ -12,8 +12,8 @@
}
.heading {
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
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(--label-base-400-font-size);
--button-font-size: var(--periscope-font-size-base);
--button-size-line-height: var(--line-height-20);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-weight: var(--font-weight-normal);
--button-variant-outlined-background-color: var(--l3-background-60);
--button-variant-outlined-border: none;
--button-variant-outlined-color: var(--l2-foreground);

View File

@@ -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 '@signozhq/noz-client';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
restoreExecution,
revertExecution,

View File

@@ -1,4 +1,7 @@
import { MessageActionDTO, MessageActionKindDTO } from '@signozhq/noz-client';
import {
MessageActionDTO,
MessageActionKindDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import logEvent from 'api/common/logEvent';
import { getCurrentLocation, navigate } from 'lib/router/navigation';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';

View File

@@ -1,9 +1,9 @@
import { undoExecution } from 'api/ai-assistant/chat';
import type { MessageActionDTO } from '@signozhq/noz-client';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';

View File

@@ -1,4 +1,4 @@
import { ApplyFilterSignalDTO } from '@signozhq/noz-client';
import { ApplyFilterSignalDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';

View File

@@ -2,7 +2,7 @@ import {
ApplyFilterSignalDTO,
MessageActionKindDTO,
SavedViewEntityDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
getSavedView,
listSavedViews,

View File

@@ -1,7 +1,7 @@
import {
type MessageActionDTO,
MessageActionKindDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
isSavedViewOpenAction,

View File

@@ -1,7 +1,7 @@
import {
ApplyFilterSignalDTO,
type MessageActionDTOQuery,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';

View File

@@ -1,4 +1,4 @@
import type { MessageActionDTOQuery } from '@signozhq/noz-client';
import type { MessageActionDTOQuery } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { normalizeTimeToMs } from 'utils/timeUtils';
export interface ActionTimeRange {

View File

@@ -1,5 +1,8 @@
import type { MessageActionDTO } from '@signozhq/noz-client';
import { ApplyFilterSignalDTO, SavedViewEntityDTO } from '@signozhq/noz-client';
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
SavedViewEntityDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { DataSource } from 'types/common/queryBuilder';
import { ResourceType } from './resourceRoute';

View File

@@ -31,8 +31,8 @@
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 18px;
letter-spacing: -0.005em;
}
@@ -54,7 +54,7 @@
.soloThought {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
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(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
font-size: var(--periscope-font-size-base);
font-weight: var(--font-weight-normal);
line-height: var(--line-height-20);
@include shimmer-text(var(--l3-foreground), var(--l1-foreground));
}

View File

@@ -59,7 +59,7 @@
border: none;
background: none;
font: inherit;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -90,7 +90,7 @@ button.title {
}
.detail {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l2-foreground);

View File

@@ -42,7 +42,7 @@
}
.headerLabel {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -61,7 +61,7 @@
.summary {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l2-foreground);
}

View File

@@ -8,7 +8,7 @@ import { Tooltip } from '@signozhq/ui/tooltip';
import type {
ApprovalEventDTO,
ApprovalEventDTODiff,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
Check,
Columns2,

View File

@@ -134,8 +134,8 @@
--button-padding: 7px #{$padding-inline};
--button-border-radius: 0;
--button-justify-content: flex-start;
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--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(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;

View File

@@ -8,8 +8,8 @@
border-radius: var(--radius-2);
background: var(--l3-background-60);
color: var(--l2-foreground);
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
line-height: 15px;
transition:
background-color 0.12s,

View File

@@ -40,7 +40,7 @@
}
.headerLabel {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--font-size-sm);
line-height: var(--line-height-20);
letter-spacing: -0.005em;
color: var(--l1-foreground);
@@ -48,7 +48,7 @@
.message {
margin: 0;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l2-foreground);
}

View File

@@ -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 '@signozhq/noz-client';
import { ClarificationFieldTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type {
ClarificationEventDTO,
ClarificationFieldEventDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { CircleHelp, Send, X } from '@signozhq/icons';
import { AIAssistantEvents } from '../../events';

View File

@@ -53,7 +53,7 @@
}
.title {
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
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(--paragraph-small-400-font-size);
font-size: var(--periscope-font-size-small);
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(--label-base-400-font-size);
--input-font-size: var(--periscope-font-size-base);
--input-hover-border-color: transparent;
}

View File

@@ -56,7 +56,7 @@
--button-border-radius: 3px;
--button-justify-content: flex-start;
--button-gap: var(--spacing-4);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-weight: var(--font-weight-normal);
--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(--label-small-600-font-size);
font-weight: var(--label-small-600-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
text-transform: uppercase;
letter-spacing: 0.04em;

View File

@@ -14,8 +14,8 @@
}
.note {
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
font-feature-settings:
'tnum' on,

View File

@@ -71,7 +71,7 @@
align-items: flex-start;
background: var(--l2-background);
color: var(--l1-foreground);
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
border-bottom-left-radius: var(--radius-2);
}
@@ -274,7 +274,7 @@
width: max-content;
min-width: 100%;
border-collapse: collapse;
font-size: var(--paragraph-base-400-font-size);
font-size: var(--periscope-font-size-base);
font-variant-numeric: tabular-nums;
word-break: normal;
@@ -286,8 +286,8 @@
th {
padding-block: 13px;
font-size: var(--label-small-500-font-size);
font-weight: var(--label-small-500-font-weight);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-medium);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;

View File

@@ -5,7 +5,7 @@ import remarkGfm from 'remark-gfm';
import { Button } from '@signozhq/ui/button';
import { RotateCw, TriangleAlert } from '@signozhq/icons';
import { RetryActionDTO } from '@signozhq/noz-client';
import { RetryActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
// Side-effect: registers all built-in block types into the BlockRegistry
import '../blocks';

View File

@@ -1,6 +1,9 @@
import React from 'react';
import { render, screen, userEvent } from 'tests/test-utils';
import { ErrorCodeDTO, RetryActionDTO } from '@signozhq/noz-client';
import {
ErrorCodeDTO,
RetryActionDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { Message } from '../../../types';

View File

@@ -10,7 +10,7 @@ import { useTimezone } from 'providers/Timezone';
import logEvent from 'api/common/logEvent';
import { FeedbackRatingDTO } from '@signozhq/noz-client';
import { FeedbackRatingDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { AIAssistantEvents } from '../../events';
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';

View File

@@ -6,7 +6,7 @@ import remarkGfm from 'remark-gfm';
import type {
ApprovalEventDTO,
ClarificationEventDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { useVariant } from '../../VariantContext';
import { StreamingEventItem } from '../../types';

View File

@@ -44,8 +44,8 @@
--button-height: 32px;
--button-padding: 0 var(--spacing-6);
--button-border-radius: var(--radius-round);
--button-font-size: var(--label-base-400-font-size);
--button-font-weight: var(--label-base-400-font-weight);
--button-font-size: var(--periscope-font-size-base);
--button-font-weight: var(--font-weight-normal);
--button-secondary-background-color: var(--l3-background);
--button-secondary-hover-background-color: var(--l3-background-hover);
--button-secondary-solid-foreground: var(--l1-foreground);

View File

@@ -7,7 +7,7 @@ import { ArrowDown } from '@signozhq/icons';
import type {
ApprovalEventDTO,
ClarificationEventDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import logEvent from 'api/common/logEvent';
import { AIAssistantEvents } from '../../events';

View File

@@ -1,4 +1,4 @@
import type { ChipDTO } from '@signozhq/noz-client';
import type { ChipDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
/** Static empty-state chips used when the contextual chips API is unavailable. */
export const EMPTY_STATE_CHIPS_FALLBACK: ChipDTO[] = [

View File

@@ -2,7 +2,7 @@ import { useMemo } from 'react';
import { useQuery } from 'react-query';
import { getEmptyStateChips } from 'api/ai-assistant/chat';
import type { ChipDTO } from '@signozhq/noz-client';
import type { ChipDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useResolvePageType } from 'hooks/aiAssistant/useResolvePageType';

View File

@@ -1,4 +1,4 @@
import { PageTypeDTO } from '@signozhq/noz-client';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { matchRoute } from 'lib/router/matchRoute';

View File

@@ -4,7 +4,7 @@ import {
MessageContextDTOType,
MessageRoleDTO,
RetryActionDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type {
MessageContext,
SSEEvent,

View File

@@ -7,8 +7,8 @@ import { immer } from 'zustand/middleware/immer';
import type {
MessageActionDTO,
MessageSummaryDTOBlocksAnyOfItem,
} from '@signozhq/noz-client';
import { RetryActionDTO } from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { RetryActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
approveExecution,

View File

@@ -1,7 +1,8 @@
/**
* UI types for the AI Assistant.
*
* Wherever the OpenAPI-generated DTOs in `@signozhq/noz-client`
* Wherever the OpenAPI-generated DTOs in
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`
* already capture the right shape, this module re-exports them.
*
* A type is defined locally only when the UI needs a different shape than
@@ -19,7 +20,7 @@ import type {
MessageActionDTO,
MessageActionKindDTO,
RetryActionDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { MessageContext } from 'api/ai-assistant/chat';
/** Client-only file attachment — no API equivalent (uploads happen via data URLs). */

View File

@@ -1,5 +1,8 @@
import { AxiosError } from 'axios';
import { ErrorCodeDTO, RetryActionDTO } from '@signozhq/noz-client';
import {
ErrorCodeDTO,
RetryActionDTO,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { resolveAssistantError } from '../resolveAssistantError';

View File

@@ -4,7 +4,7 @@ import {
RetryActionDTO,
type ErrorBodyDTO,
type ErrorResponseDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
export interface AssistantErrorResolution {
/** User-facing copy: code-specific FE copy → backend message → caller fallback. */

View File

@@ -83,7 +83,6 @@ 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;

View File

@@ -59,6 +59,29 @@ 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}>

View File

@@ -15,6 +15,18 @@
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;

View File

@@ -35,10 +35,6 @@ 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'));

View File

@@ -3,7 +3,6 @@ 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';
@@ -183,30 +182,32 @@ 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}>
<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>
{!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>
)}
<div ref={containerRef} className={styles.tableContainer}>
{isError ? (

View File

@@ -1,4 +1,3 @@
import type { PANEL_TYPES } from 'constants/queryBuilder';
import {
IBuilderQuery,
OrderByPayload,
@@ -11,8 +10,6 @@ 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 = {

View File

@@ -23,7 +23,6 @@ export function OrderByFilter({
entityVersion,
isNewQueryV2 = false,
placeholder,
panelType,
}: OrderByFilterProps): JSX.Element {
const getPopupContainer = useSelectPopupContainer();
const {
@@ -53,9 +52,8 @@ export function OrderByFilter({
// Get parsed aggregation options using createAggregation only for QueryV2
const parsedAggregationOptions = useMemo(
() =>
isNewQueryV2 ? getParsedAggregationOptionsForOrderBy(query, panelType) : [],
[query, isNewQueryV2, panelType],
() => (isNewQueryV2 ? getParsedAggregationOptionsForOrderBy(query) : []),
[query, isNewQueryV2],
);
const optionsData = useMemo(() => {

View File

@@ -1,42 +1,13 @@
import { QueryClient, QueryClientProvider } from 'react-query';
import ROUTES from 'constants/routes';
import { customRoleResponse } from 'mocks-server/__mockdata__/roles';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import {
act,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import {
AUTHZ_CHECK_URL,
authzMockResponse,
setupAuthzAdmin,
} from 'lib/authz/utils/authz-test-utils';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
import { getCurrentLocation } from 'lib/router/navigation';
import CreateEditRolePage from '../CreateEditRolePage';
jest.mock('@monaco-editor/react', () => ({
__esModule: true,
default: ({
value,
onChange,
}: {
value: string;
onChange: (next?: string) => void;
}): JSX.Element => (
<textarea
data-testid="monaco-editor"
value={value}
onChange={(e): void => onChange(e.target.value)}
/>
),
}));
const CUSTOM_ROLE_ID = '019c24aa-3333-0001-aaaa-111111111111';
const rolesApiBase = '*/api/v1/roles';
const VIEW_ROLE_URL = `${ROUTES.ROLE_DETAILS.replace(
@@ -437,125 +408,4 @@ describe('EditRolePage', () => {
);
});
});
describe('JSON view opened from the URL', () => {
const roleGrants = roleWithTransactionGroups.data.transactionGroups;
function renderJsonView(client?: QueryClient): ReturnType<typeof render> {
const page = <CreateEditRolePage />;
return render(
client ? (
<QueryClientProvider client={client}>{page}</QueryClientProvider>
) : (
page
),
undefined,
{
initialRoute: `/settings/roles/${CUSTOM_ROLE_ID}/edit?name=Custom%20Role&viewMode=json`,
},
);
}
function readBuffer(editor: HTMLElement): unknown {
return JSON.parse((editor as HTMLTextAreaElement).value);
}
it('shows the role grants when the role loads after the authz check', async () => {
server.use(
rest.get(`${rolesApiBase}/:id`, (_req, res, ctx) =>
res(ctx.delay(300), ctx.status(200), ctx.json(roleWithTransactionGroups)),
),
);
renderJsonView();
const editor = await screen.findByTestId('monaco-editor');
expect(readBuffer(editor)).toStrictEqual(roleGrants);
});
it('shows the role grants when the role loads before the authz check', async () => {
server.use(
rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
const payload = await req.json();
return res(
ctx.delay(300),
ctx.status(200),
ctx.json(
authzMockResponse(
payload,
payload.map(() => true),
),
),
);
}),
);
renderJsonView();
const editor = await screen.findByTestId('monaco-editor');
expect(readBuffer(editor)).toStrictEqual(roleGrants);
});
it('saves what was typed in the buffer even when the role refetches afterwards', async () => {
const updatedBodies: unknown[] = [];
let roleReads = 0;
server.use(
rest.get(`${rolesApiBase}/:id`, (_req, res, ctx) => {
roleReads += 1;
return res(
ctx.status(200),
ctx.json(
roleReads === 1
? roleWithTransactionGroups
: {
...roleWithTransactionGroups,
data: {
...roleWithTransactionGroups.data,
transactionGroups: [
{
objectGroup: {
resource: { kind: 'role', type: 'role' },
selectors: ['*'],
},
relation: 'update',
},
],
},
},
),
);
}),
rest.put(`${rolesApiBase}/:id`, async (req, res, ctx) => {
updatedBodies.push(await req.json());
return res(ctx.status(200), ctx.json({ status: 'success' }));
}),
);
const user = userEvent.setup();
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
renderJsonView(client);
const editor = await screen.findByTestId('monaco-editor');
await user.type(editor, '[[]', {
initialSelectionStart: 0,
initialSelectionEnd: (editor as HTMLTextAreaElement).value.length,
});
await act(async () => {
await client.invalidateQueries();
});
await waitFor(() => {
expect(roleReads).toBeGreaterThan(1);
});
await user.click(screen.getByTestId('save-button'));
await waitFor(() => {
expect(updatedBodies).toHaveLength(1);
});
expect(updatedBodies[0]).toMatchObject({ transactionGroups: [] });
});
});
});

View File

@@ -86,9 +86,6 @@ export function useCreateEditRolePageActions(
const { mutateAsync: updateRole, isLoading: isUpdating } =
useUpdateRolePermissions();
const isSaving = isCreating || isUpdating;
// Editors read their initial value once, so stay loading until the fetched
// role has been copied into local state.
const isSeedingFromRole = !!rolePermissionsData && !isInitialized;
useEffect(() => {
if (rolePermissionsData && !isInitialized) {
@@ -232,7 +229,7 @@ export function useCreateEditRolePageActions(
setEditorMode: handleModeChange,
resources: localResources,
setResources: handleResourcesChange,
isLoading: isLoadingPermissions || isSeedingFromRole,
isLoading: isLoadingPermissions,
isSaving,
hasUnsavedChanges,
handleSave,

View File

@@ -1,5 +1,5 @@
import { renderHook } from '@testing-library/react';
import { PageTypeDTO } from '@signozhq/noz-client';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { AIAssistantVariant } from 'container/AIAssistant/VariantContext';
import ROUTES from 'constants/routes';
import { mockAppLocation } from 'tests/router-mocks';

View File

@@ -2,7 +2,7 @@ import { useMemo } from 'react';
import { useAppLocation } from 'lib/router/useAppLocation';
import { PageTypeDTO } from '@signozhq/noz-client';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { resolvePageType } from 'container/AIAssistant/resolvePageType';
import { useVariant } from 'container/AIAssistant/VariantContext';

View File

@@ -433,57 +433,4 @@ describe('useQueryBuilderOperations - Empty Aggregate Attribute Type', () => {
);
});
});
describe('handleChangeQueryData on a heatmap', () => {
it('moves the sort on the old field to the new one', () => {
setupMockQueryBuilder('heatmap');
const result = renderHookWithProps({
entityVersion: ENTITY_VERSION_V5,
query: {
...defaultMockQuery,
dataSource: DataSource.TRACES,
aggregations: [{ expression: 'duration_nano' }],
orderBy: [{ columnName: 'duration_nano', order: 'desc' }],
},
});
act(() => {
result.current.handleChangeQueryData('aggregations', [
{ expression: 'attribute.quantity' },
]);
});
expect(mockHandleSetQueryData).toHaveBeenLastCalledWith(
0,
expect.objectContaining({
aggregations: [{ expression: 'attribute.quantity' }],
orderBy: [{ columnName: 'attribute.quantity', order: 'desc' }],
}),
);
});
});
describe('handleChangeDataSource', () => {
it.each([
['heatmap', ''],
['time_series', 'count() '],
])(
'seeds the traces aggregation on a %s panel with %j',
(panelType, expression) => {
setupMockQueryBuilder(panelType);
const result = renderHookWithProps({ entityVersion: ENTITY_VERSION_V5 });
act(() => {
result.current.handleChangeDataSource(DataSource.TRACES);
});
expect(mockHandleSetQueryData).toHaveBeenLastCalledWith(
0,
expect.objectContaining({
dataSource: DataSource.TRACES,
aggregations: [{ expression }],
}),
);
},
);
});
});

View File

@@ -29,11 +29,6 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getMetricsOperatorsByAttributeType } from 'lib/newQueryBuilder/getMetricsOperatorsByAttributeType';
import { getOperatorsBySourceAndPanelType } from 'lib/newQueryBuilder/getOperatorsBySourceAndPanelType';
import { findDataTypeOfOperator } from 'lib/query/findDataTypeOfOperator';
import {
aggregatesDistributionField,
setDistributionField,
toDistributionAggregation,
} from 'lib/query/distributionField';
import { isEmpty, isEqual } from 'lodash-es';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import {
@@ -481,12 +476,7 @@ export const useQueryOperations: UseQueryOperations = ({
newQueryData = newQueryData ? newQueryData : newQuery;
setOperators(newOperators);
handleSetQueryData(
index,
aggregatesDistributionField(panelType, newQueryData.dataSource)
? toDistributionAggregation(newQueryData)
: newQueryData,
);
handleSetQueryData(index, newQueryData);
},
[
isRawQuery,
@@ -516,18 +506,13 @@ export const useQueryOperations: UseQueryOperations = ({
const handleChangeQueryData: HandleChangeQueryData | HandleChangeQueryDataV5 =
useCallback(
(key: string, value: any) => {
// A heatmap's sort names its field, so it follows a field change.
const newQuery =
key === 'aggregations' &&
aggregatesDistributionField(panelType, query.dataSource)
? setDistributionField(query, value?.[0]?.expression ?? '')
: {
...query,
[key]:
key === LEGEND && typeof value === 'string'
? getFormatedLegend(value)
: value,
};
const newQuery = {
...query,
[key]:
key === LEGEND && typeof value === 'string'
? getFormatedLegend(value)
: value,
};
if (isForTraceOperator) {
handleSetTraceOperatorData(index, newQuery);
@@ -538,7 +523,6 @@ export const useQueryOperations: UseQueryOperations = ({
[
query,
index,
panelType,
handleSetQueryData,
handleSetTraceOperatorData,
isForTraceOperator,

View File

@@ -1,27 +0,0 @@
import { parseAggregations } from '../aggregationExpression';
describe('parseAggregations', () => {
it.each([
['duration_nano', [{ expression: 'duration_nano' }]],
['attribute.queue_depth', [{ expression: 'attribute.queue_depth' }]],
['attribute.queue-depth', [{ expression: 'attribute.queue-depth' }]],
['body.latency as lat', [{ expression: 'body.latency', alias: 'lat' }]],
[
"count() as 'total' avg(code.lineno)",
[
{ expression: 'count()', alias: 'total' },
{ expression: 'avg(code.lineno)' },
],
],
// Words beside a call are not aggregations of their own.
['count() AS total', [{ expression: 'count()' }]],
['p99(duration_nano) by service', [{ expression: 'p99(duration_nano)' }]],
['sum(a', []],
])('parses %s', (input, expected) => {
expect(parseAggregations(input, undefined, true)).toStrictEqual(expected);
});
it('leaves a field out unless asked to read one', () => {
expect(parseAggregations('duration_nano')).toStrictEqual([]);
});
});

View File

@@ -1,193 +0,0 @@
import { initialQueriesMap } from 'constants/queryBuilder';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import {
getDistributionFieldPlaceholder,
setDistributionField,
toDistributionAggregation,
fromDistributionAggregation,
} from '../distributionField';
const queryOf = (
dataSource: DataSource,
expressions: string[],
): IBuilderQuery => ({
...(initialQueriesMap[dataSource].builder.queryData[0] as IBuilderQuery),
aggregations: expressions.map((expression) => ({ expression })),
});
describe('getDistributionFieldPlaceholder', () => {
it.each([
[DataSource.TRACES, 'Numeric field to bucket, e.g. duration_nano'],
[DataSource.LOGS, 'Numeric field to bucket'],
])('%s → %s', (dataSource, expected) => {
expect(getDistributionFieldPlaceholder(dataSource)).toBe(expected);
});
});
describe('toDistributionAggregation', () => {
it.each([DataSource.TRACES, DataSource.LOGS])(
'clears a %s count() for the user to pick a field',
(dataSource) => {
expect(
toDistributionAggregation(queryOf(dataSource, ['count()'])).aggregations,
).toStrictEqual([{ expression: '' }]);
},
);
it.each(['attribute.batch_size', 'attribute.queue-depth'])(
'keeps the bare field %s',
(field) => {
const query = queryOf(DataSource.LOGS, [field]);
expect(toDistributionAggregation(query)).toBe(query);
},
);
it('keeps the field of a one-argument call', () => {
expect(
toDistributionAggregation(
queryOf(DataSource.LOGS, ['avg(attribute.latency)']),
).aggregations,
).toStrictEqual([{ expression: 'attribute.latency' }]);
});
it.each(['count_distinct(service.name)', 'countIf(status>=500)'])(
'clears the field rather than bucket the argument of %s',
(expression) => {
expect(
toDistributionAggregation(queryOf(DataSource.TRACES, [expression]))
.aggregations,
).toStrictEqual([{ expression: '' }]);
},
);
it('keeps a field with an alias', () => {
const query = queryOf(DataSource.LOGS, ['body.latency as lat']);
expect(toDistributionAggregation(query)).toBe(query);
});
it('renames an order on the aggregation alias to the field', () => {
const query = {
...queryOf(DataSource.TRACES, []),
aggregations: [{ expression: 'p99(duration_nano)', alias: 'lat' }],
orderBy: [{ columnName: 'lat', order: 'desc' }],
};
expect(toDistributionAggregation(query).orderBy).toStrictEqual([
{ columnName: 'duration_nano', order: 'desc' },
]);
});
it('keeps the field of an inline-aliased call and moves the order on its alias', () => {
const query = {
...queryOf(DataSource.TRACES, ["p99(duration_nano) as 'lat'"]),
orderBy: [{ columnName: 'lat', order: 'desc' }],
};
const next = toDistributionAggregation(query);
expect(next.aggregations).toStrictEqual([{ expression: 'duration_nano' }]);
expect(next.orderBy).toStrictEqual([
{ columnName: 'duration_nano', order: 'desc' },
]);
});
it('drops the order on an aggregation it clears', () => {
const query = {
...queryOf(DataSource.LOGS, ['count()']),
orderBy: [
{ columnName: 'count()', order: 'desc' },
{ columnName: 'timestamp', order: 'asc' },
],
};
expect(toDistributionAggregation(query).orderBy).toStrictEqual([
{ columnName: 'timestamp', order: 'asc' },
]);
});
it('drops orders on every aggregation it clears', () => {
const query = {
...queryOf(DataSource.TRACES, [
'avg(duration_nano) max(attribute.quantity)',
'count() as total',
]),
orderBy: [
{ columnName: 'max(attribute.quantity)', order: 'desc' },
{ columnName: 'total', order: 'asc' },
{ columnName: 'timestamp', order: 'asc' },
],
};
expect(toDistributionAggregation(query).orderBy).toStrictEqual([
{ columnName: 'timestamp', order: 'asc' },
]);
});
it('renames an order on the aggregation to the field', () => {
const query = {
...queryOf(DataSource.TRACES, ['p99(duration_nano)']),
orderBy: [{ columnName: 'p99(duration_nano)', order: 'desc' }],
};
expect(toDistributionAggregation(query).orderBy).toStrictEqual([
{ columnName: 'duration_nano', order: 'desc' },
]);
});
it('leaves a metrics query alone', () => {
const query = initialQueriesMap.metrics.builder.queryData[0];
expect(toDistributionAggregation(query)).toBe(query);
});
});
describe('fromDistributionAggregation', () => {
it.each([
['duration_nano', 'p90(duration_nano)'],
['', 'count()'],
])('turns the field %j into %s', (field, expression) => {
expect(
fromDistributionAggregation(queryOf(DataSource.TRACES, [field]))
.aggregations,
).toStrictEqual([{ expression }]);
});
it('drops the alias out of the field', () => {
expect(
fromDistributionAggregation(
queryOf(DataSource.LOGS, ['body.latency as lat']),
).aggregations,
).toStrictEqual([{ expression: 'p90(body.latency)' }]);
});
it('renames an order on the field to the new aggregation', () => {
const query = {
...queryOf(DataSource.TRACES, ['duration_nano']),
orderBy: [{ columnName: 'duration_nano', order: 'asc' }],
};
expect(fromDistributionAggregation(query).orderBy).toStrictEqual([
{ columnName: 'p90(duration_nano)', order: 'asc' },
]);
});
it.each([['count()'], ['count()', 'avg(x)']])(
'leaves function aggregations %j alone',
(...expressions) => {
const query = queryOf(DataSource.LOGS, expressions);
expect(fromDistributionAggregation(query)).toBe(query);
},
);
});
describe('setDistributionField', () => {
const sorted = {
...queryOf(DataSource.TRACES, ['duration_nano']),
orderBy: [{ columnName: 'duration_nano', order: 'desc' }],
};
it('moves the sort on the old field to the new one', () => {
expect(setDistributionField(sorted, 'attribute.quantity')).toMatchObject({
aggregations: [{ expression: 'attribute.quantity' }],
orderBy: [{ columnName: 'attribute.quantity', order: 'desc' }],
});
});
it('drops the sort when the field is cleared', () => {
expect(setDistributionField(sorted, '').orderBy).toStrictEqual([]);
});
});

View File

@@ -62,28 +62,6 @@ describe('handleQueryChange bucket options', () => {
expect(result.builder.queryFormulas[0].bucketOptions).toBeUndefined();
});
it.each([DataSource.LOGS, DataSource.TRACES])(
'keeps the axis of a %s query that stays a heatmap',
(dataSource) => {
const base = initialQueriesMap[dataSource];
const result = handleQueryChange(
PANEL_TYPES.HEATMAP,
{
...base,
builder: {
...base.builder,
queryData: [{ ...base.builder.queryData[0], bucketOptions }],
},
},
PANEL_TYPES.HEATMAP,
);
expect(result.builder.queryData[0].bucketOptions).toStrictEqual(
bucketOptions,
);
},
);
it('leaves the rest of the formula intact', () => {
const result = handleQueryChange(
PANEL_TYPES.TIME_SERIES,
@@ -124,17 +102,6 @@ describe('handleQueryChange trace operator', () => {
expect(result.builder.queryTraceOperator).toStrictEqual([]);
});
// A heatmap request takes one builder query and rejects a trace operator.
it('drops the trace operator when switching to a heatmap', () => {
const result = handleQueryChange(
PANEL_TYPES.HEATMAP,
queryWithTraceOperator(),
PANEL_TYPES.TIME_SERIES,
);
expect(result.builder.queryTraceOperator).toStrictEqual([]);
});
it('keeps the trace operator when switching to a table', () => {
const result = handleQueryChange(
PANEL_TYPES.TABLE,

View File

@@ -1,46 +0,0 @@
/** An `as` alias: quoted, or an unquoted word that may carry dashes. */
export const ALIAS = `(?:'[^']*'|"[^"]*"|[a-zA-Z0-9_-]+)`;
export const unquoteAlias = (alias: string): string =>
alias.replace(/^['"]|['"]$/g, '');
/**
* A logs or traces heatmap's aggregation: one field with an optional alias.
* The field mirrors the querier's HeatmapAggregationField: no call, no whitespace.
*/
export const DISTRIBUTION_FIELD = new RegExp(
`^\\s*([^\\s()]+)(?:\\s+as\\s+(${ALIAS}))?\\s*$`,
);
// Utility to parse aggregation expressions with optional alias
export function parseAggregations(
expression: string,
availableAlias?: string,
allowDistributionField = false,
): { 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 = new RegExp(
`([a-zA-Z0-9_]+\\([^)]*\\))(?:\\s*as\\s+(${ALIAS}))?`,
'g',
);
// With no call at all, the whole expression may be the field a logs/traces
// heatmap buckets, e.g. "duration_nano"
let match =
regex.exec(expression) ??
(allowDistributionField ? DISTRIBUTION_FIELD.exec(expression) : null);
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 = unquoteAlias(alias);
result.push({ expression: expr, alias });
} else {
result.push({ expression: expr });
}
match = regex.exec(expression);
}
return result;
}

View File

@@ -1,140 +0,0 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
import type {
IBuilderQuery,
OrderByPayload,
} from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import type { LogAggregation, TraceAggregation } from 'types/api/v5/queryRange';
import {
ALIAS,
DISTRIBUTION_FIELD,
parseAggregations,
unquoteAlias,
} from './aggregationExpression';
// A numeric one-argument call such as `p99(duration_nano) as lat`; group 1 is the
// field, group 2 the inline alias. Other functions (`count_distinct`, `countIf`)
// take text or a condition.
const NUMERIC_FIELD_CALL = new RegExp(
`^\\s*(?:avg|sum|min|max|p\\d{2})\\(\\s*([^\\s(),]+)\\s*\\)(?:\\s+as\\s+(${ALIAS}))?\\s*$`,
);
/** The percentile a field or histogram metric gets when it leaves a heatmap. */
export const DEFAULT_PERCENTILE = 'p90';
type FieldAggregation = TraceAggregation | LogAggregation;
const fieldAggregations = (query: IBuilderQuery): FieldAggregation[] =>
(query.aggregations ?? []).filter(
(aggregation): aggregation is FieldAggregation => 'expression' in aggregation,
);
function isLogsOrTraces(
dataSource: DataSource,
): dataSource is DataSource.LOGS | DataSource.TRACES {
return dataSource === DataSource.LOGS || dataSource === DataSource.TRACES;
}
/** Whether the query's aggregation is a field rather than a function call. */
export function aggregatesDistributionField(
panelType: string | null | undefined,
dataSource: DataSource,
): boolean {
return panelType === PANEL_TYPES.HEATMAP && isLogsOrTraces(dataSource);
}
/**
* Replaces every aggregation with `to`. Order-by names an aggregation by its alias
* when it has one, else its expression: the order on `from` moves to `to`, or is
* dropped when `to` is empty, and orders on `removedKeys` go.
*/
function replaceAggregation(
query: IBuilderQuery,
from: Partial<FieldAggregation> | undefined,
to: string,
removedKeys: string[] = [],
): IBuilderQuery {
const fromKey = from?.alias || from?.expression;
const isFrom = (order: OrderByPayload): boolean =>
Boolean(fromKey) && order.columnName === fromKey;
return {
...query,
aggregations: [{ expression: to }],
orderBy: query.orderBy
?.filter((order) =>
isFrom(order) ? Boolean(to) : !removedKeys.includes(order.columnName),
)
.map((order) => (isFrom(order) ? { ...order, columnName: to } : order)),
};
}
export function getDistributionFieldPlaceholder(
dataSource: DataSource,
): string {
return dataSource === DataSource.TRACES
? 'Numeric field to bucket, e.g. duration_nano'
: 'Numeric field to bucket';
}
/**
* Logs and traces heatmaps bucket a field; any function aggregation is
* rejected, so a numeric `fn(field)` keeps its field and anything else leaves
* the field for the user to pick.
*/
export function toDistributionAggregation(query: IBuilderQuery): IBuilderQuery {
if (!isLogsOrTraces(query.dataSource)) {
return query;
}
const aggregations = fieldAggregations(query);
const [first] = aggregations;
const hasOneAggregation = aggregations.length === 1;
if (hasOneAggregation && DISTRIBUTION_FIELD.test(first.expression ?? '')) {
return query;
}
const fieldCall = hasOneAggregation
? NUMERIC_FIELD_CALL.exec(first.expression ?? '')
: null;
const inlineAlias = fieldCall?.[2] && unquoteAlias(fieldCall[2]);
const removedKeys = aggregations
.flatMap(({ expression, alias }) =>
parseAggregations(expression ?? '', alias),
)
.map(({ expression, alias }) => alias || expression);
return replaceAggregation(
query,
{ ...first, alias: first?.alias || inlineAlias },
fieldCall?.[1] ?? '',
removedKeys,
);
}
/** Picks `field` as the heatmap's aggregation; a sort on the old field follows it. */
export function setDistributionField(
query: IBuilderQuery,
field: string,
): IBuilderQuery {
const [first] = fieldAggregations(query);
return replaceAggregation(query, first, field);
}
/** Inverse of `toDistributionAggregation`: every other panel needs a function aggregation. */
export function fromDistributionAggregation(
query: IBuilderQuery,
): IBuilderQuery {
const aggregations = fieldAggregations(query);
if (!isLogsOrTraces(query.dataSource) || aggregations.length !== 1) {
return query;
}
const [first] = aggregations;
const expression = first.expression?.trim() ?? '';
const field = DISTRIBUTION_FIELD.exec(expression)?.[1];
if (expression && !field) {
return query;
}
return replaceAggregation(
query,
{ alias: first.alias, expression: field },
field ? `${DEFAULT_PERCENTILE}(${field})` : 'count()',
);
}

View File

@@ -175,9 +175,7 @@ export function rebuildBuilderForPanelType(
}),
queryFormulas: withHeatmapBucketOptions(builder.queryFormulas, newPanelType),
queryTraceOperator:
newPanelType === PANEL_TYPES.LIST ||
newPanelType === PANEL_TYPES.SCATTER ||
newPanelType === PANEL_TYPES.HEATMAP
newPanelType === PANEL_TYPES.LIST || newPanelType === PANEL_TYPES.SCATTER
? []
: builder.queryTraceOperator,
};

View File

@@ -122,10 +122,12 @@ const RAW_ROWS_METRICS: readonly BuilderField[] = omit(
// `functions` and `having` are dropped rather than carried: the heatmap request
// rejects both. Logs and traces keep the metrics aggregations too, because the map is
// keyed by the query's own signal, which a switch can still be holding.
const HEATMAP: readonly BuilderField[] = [
...omit(SERIES_METRICS, 'functions', 'having'),
'bucketOptions',
];
const HEATMAP: readonly BuilderField[] = omit(
SERIES_METRICS,
'functions',
'having',
);
const HEATMAP_METRICS: readonly BuilderField[] = [...HEATMAP, 'bucketOptions'];
/** Each cell gets its own copy; a shared instance would let cells contaminate
* each other. */
@@ -148,7 +150,7 @@ export const panelTypeDataSourceFormValuesMap: Record<
[PANEL_TYPES.AREA]: bySource(SERIES, SERIES_METRICS),
[PANEL_TYPES.BAR]: bySource(SERIES, SERIES_METRICS),
[PANEL_TYPES.HISTOGRAM]: bySource(SERIES, SERIES_METRICS),
[PANEL_TYPES.HEATMAP]: bySource(HEATMAP, HEATMAP),
[PANEL_TYPES.HEATMAP]: bySource(HEATMAP, HEATMAP_METRICS),
[PANEL_TYPES.TABLE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.PIE]: bySource(SERIES, SCALAR_METRICS),
[PANEL_TYPES.SCATTER]: bySource(SERIES, SCALAR_METRICS),

View File

@@ -52,14 +52,6 @@
font-variant-numeric: tabular-nums;
}
.bucketLabel {
padding: var(--spacing-2) var(--gutter) 0;
font-family: var(--font-mono);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
overflow-wrap: anywhere;
}
.filter {
display: flex;
align-items: center;

View File

@@ -38,7 +38,6 @@ export default function HeatmapTooltip({
series,
visibleGroups,
groupColor,
bucketLabel,
yAxisUnit,
decimalPrecision,
timezone,
@@ -140,15 +139,6 @@ export default function HeatmapTooltip({
{isPinned && <TooltipPinnedBadge />}
</div>
{bucketLabel && (
<div
className={Styles.bucketLabel}
data-testid="heatmap-tooltip-bucket-label"
>
{bucketLabel}
</div>
)}
{filterLabel && (
<div
className={Styles.filter}

View File

@@ -112,22 +112,6 @@ describe('HeatmapTooltip — cell identity', () => {
expect(screen.getByTestId('heatmap-tooltip-count')).toHaveTextContent('455');
});
it('names what the grid measures when the panel supplies it', () => {
renderTooltip({ bucketLabel: 'Traces · duration_nano' });
expect(screen.getByTestId('heatmap-tooltip-bucket-label')).toHaveTextContent(
'Traces · duration_nano',
);
});
it('leaves the bucket label out when there is none', () => {
renderTooltip();
expect(
screen.queryByTestId('heatmap-tooltip-bucket-label'),
).not.toBeInTheDocument();
});
it('marks the surface as pinned so the border picks up the ring', () => {
renderTooltip({ isPinned: true });

View File

@@ -121,8 +121,6 @@ export interface HeatmapTooltipProps
visibleGroups: string[];
/** Same colour the legend and the densest cells use. */
groupColor: string;
/** What the bucket axis measures, e.g. `Traces · duration_nano`. */
bucketLabel?: string;
}
export interface ScatterTooltipProps

View File

@@ -29,7 +29,7 @@
align-items: center;
justify-content: space-between;
gap: var(--spacing-6);
font-size: var(--label-base-500-font-size);
font-size: var(--font-size-sm);
font-weight: 500;
}
@@ -37,7 +37,7 @@
.subtitle {
padding-left: calc(12px + var(--spacing-3));
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
}
@@ -58,7 +58,7 @@
.code {
flex-shrink: 0;
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
color: var(--muted-foreground);
}
@@ -100,7 +100,7 @@
align-items: center;
gap: var(--spacing-2);
font-family: var(--font-mono);
font-size: var(--paragraph-small-400-font-size);
font-size: var(--font-size-xs);
letter-spacing: -0.01em;
font-variant-numeric: tabular-nums;
}

View File

@@ -68,7 +68,6 @@ export default function Heatmap(props: HeatmapChartProps): JSX.Element {
yAxisUnit,
decimalPrecision,
timezone,
bucketLabel,
showVisualMap = true,
showLegend = true,
legendPosition = LegendPosition.BOTTOM,
@@ -254,7 +253,6 @@ export default function Heatmap(props: HeatmapChartProps): JSX.Element {
yAxisUnit={yAxisUnit}
decimalPrecision={boundaryPrecision}
timezone={timezone}
bucketLabel={bucketLabel}
canPinTooltip={canPinTooltip}
renderTooltipFooter={renderTooltipFooter}
/>
@@ -269,7 +267,6 @@ export default function Heatmap(props: HeatmapChartProps): JSX.Element {
yAxisUnit,
boundaryPrecision,
timezone,
bucketLabel,
canPinTooltip,
renderTooltipFooter,
],

View File

@@ -142,8 +142,6 @@ export interface HeatmapChartProps {
yAxisUnit?: string;
decimalPrecision?: PrecisionOption;
timezone?: Timezone;
/** What the bucket axis measures, shown in the tooltip header, e.g. `Traces · duration_nano`. */
bucketLabel?: string;
/** Colour bar below the grid. Default true. */
showVisualMap?: boolean;
/** Default true; hidden anyway when there is only one group. The label isolates

View File

@@ -11,7 +11,7 @@ import type {
MessageSummaryDTO,
ThreadDetailResponseDTO,
ThreadListResponseDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
ApplyFilterSignalDTO,
ApprovalActionTypeDTO,
@@ -22,7 +22,7 @@ import {
MessageActionKindDTO,
MessageContentTypeDTO,
MessageRoleDTO,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type {
Conversation,
ConversationStreamState,

View File

@@ -3,11 +3,11 @@
* Do not hand-edit: regenerate instead.
*/
import type { MessageSummaryDTO } from '@signozhq/noz-client';
import type { MessageSummaryDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import {
MessageContextDTOSource,
MessageContextDTOType,
} from '@signozhq/noz-client';
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { MessageBlock } from 'container/AIAssistant/types';
/** The opening question's contexts: the thread shows the @-picked ones, not the page it was asked from. */

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