Compare commits

..

13 Commits

Author SHA1 Message Date
nityanandagohain
ea10c2542e fix(trace-details): search attribute names and resource attributes, and return search warnings
A word matched attribute values only and never a resource attribute, so a
service or pod name found nothing. A search on an unknown key came back
empty without a reason; it now carries the filter's warnings.

Assisted-by: Claude Fable 5.2
2026-11-20 16:22:04 +05:30
nityanandagohain
9436019094 Merge branch 'issue_nerve_651_3' into issue_nerve_651_4
# Conflicts:
#	pkg/modules/tracedetail/impltracedetail/module.go
#	pkg/types/spantypes/trace_inspect.go
#	pkg/types/spantypes/trace_inspect_test.go
#	pkg/types/spantypes/trace_span_record.go
#	tests/integration/tests/tracedetail/05_inspect.py
2026-11-20 16:21:33 +05:30
nityanandagohain
da6c366e8e fix(trace-details): order the levels below a span by time and bound a selected record
A level below a span was listed parent by parent, and selected values were
budgeted in characters, so escaped or multi-byte text passed the response
limit. A call with selectFields no longer computes the percentile again.

Assisted-by: Claude Fable 5.2
2026-11-20 15:54:05 +05:30
nityanandagohain
07b1ddf645 Merge branch 'issue_nerve_651_2' into issue_nerve_651_3
# Conflicts:
#	pkg/modules/tracedetail/impltracedetail/module.go
#	pkg/types/spantypes/trace_inspect.go
#	pkg/types/spantypes/trace_inspect_test.go
#	pkg/types/spantypes/trace_overview.go
#	pkg/types/spantypes/trace_span_record.go
#	tests/integration/tests/tracedetail/05_inspect.py
2026-11-20 15:53:38 +05:30
nityanandagohain
141f5cd1f4 fix(trace-details): cut the tree in time order and shorten long span names
A level that did not fit was cut parent by parent, and a statement used as
a span name could push the overview past its size limit.

Also puts exported declarations first and inlines the integration test's
helpers.

Assisted-by: Claude Fable 5.2
2026-11-20 15:49:54 +05:30
nityanandagohain
9dabe4e2c3 Merge branch 'issue_nerve_651_1' into issue_nerve_651_2
# Conflicts:
#	pkg/modules/tracedetail/impltracedetail/handler.go
2026-11-20 15:41:04 +05:30
nityanandagohain
690a2af781 chore(trace-details): regenerate the api spec for the trace inspect routes
Assisted-by: Claude Fable 5.2
2026-11-20 15:38:17 +05:30
nityanandagohain
82c8c1c43d refactor(trace-details): split the trace inspect contract into three routes
One route returned one of three shapes behind a type field, which needed
optional sibling fields. Each part now has its own route and response type.

Assisted-by: Claude Fable 5.2
2026-11-20 15:38:16 +05:30
nityanandagohain
047561e669 feat(trace-details): add search and the full span list to the trace inspect endpoint
GET /api/v1/traces/{traceID}/inspect now returns the find part:
  -  takes plain words, a filter expression, or both, such as
    . Words match the span name, the status
    message, attribute values and events, ignoring case. Each match carries
    the span, its parent and where the words were found.
  -  returns every span as a line in tree order; with , that
    span and every span below it.
  - cputime         unlimited
filesize        unlimited
datasize        unlimited
stacksize       7MB
coredumpsize    0kB
addressspace    unlimited
memorylocked    unlimited
maxproc         6000
descriptors     1048575 sets the page size, 20 for a search and 400 for , at most
    1000. The same call with the  returns the next page.

  Plain words need a way to compile free text for a signal without a full-text
  column, so the filter visitor gains an optional FullTextCondition hook.

  A span's JSON attributes are searched when it has them, its map attributes
  otherwise.

  This completes the endpoint: nothing answers 501 any more.

  Refs SigNoz/nerve-pod#651
2026-11-20 15:15:53 +05:30
nityanandagohain
f557a6563f feat(trace-details): open a span in the trace inspect endpoint
GET /api/v1/traces/{traceID}/inspect?spanId=... now returns the span part:
  - the span's summary and full record; values over 500 characters are cut and
    listed in
  - the levels above it, the parent first, then the root
  - the levels below it, each with its total and its first 20 spans in time order
  - where its duration sits among spans of the same name and service in the
    hour before it; left out when it is not ready within 2 seconds

   sets the number of levels, 1 to 10, 2 by default.
  returns only the named attributes, of the span and of its events, in full as
  far as the response allows; this is how a prompt or a stack trace is read.

  A span that is not in the trace answers 404.  and  answer
  501 until the next PR.

  Refs SigNoz/nerve-pod#651
2026-11-20 14:53:59 +05:30
nityanandagohain
255b6fa1ac feat(trace-details): build the span tree and the overview of the trace inspect endpoint
GET /api/v1/traces/{traceID}/inspect now returns the overview. Like the
  waterfall, each call loads the trace's spans with one narrow query and builds
  the tree in memory, with each span's own time, level and the number of spans
  below it. There is no cache and no cap on the number of spans.

  From the tree it returns:
  - identity, with per-service totals and gen_ai usage
  - the spans where each error started, failures not marked as errors, the
    slowest spans by own time, the most expensive gen_ai spans, span links
  - the tree: the first 50 spans, level by level from the root, in time order;
    a trace of up to 50 spans also carries each span's record when they fit

  Every list pages with its nextCursor, and every item carries the span's
  direct parent. A page loads only what its list needs. Span attributes are
  read from the JSON column when it is filled, without the feature flag.

  spanId, search and allSpans answer 501 until the next PRs.

  Refs SigNoz/nerve-pod#651
2026-11-19 21:49:28 +05:30
nityanandagohain
75686f4004 fix(trace-details): update the trace inspect contract for the tree and the span cap 2026-11-19 21:18:30 +05:30
nityanandagohain
2df97d39e2 feat(trace-details): add the API contract for the trace inspect endpoint
Adds GET /api/v1/traces/{traceID}/inspect to the API spec with its query
  parameters and response types. The handler answers 501 for now; the
  implementation follows in separate PRs (overview, open a span, search).

  The response holds one of three parts, named by :
  - overview: identity, errors, failures not marked as errors, slowest spans,
    most expensive spans, span links and the tree
  - span: one span's summary and full record, with its ancestors and descendants
  - find: the spans matching a search, or every span with allSpans

  Every list has total, items and nextCursor, and every item starts with the
  span and its direct parent.

  Refs SigNoz/nerve-pod#651
2026-11-19 16:42:40 +05:30
1900 changed files with 31105 additions and 47959 deletions

View File

@@ -86,7 +86,7 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
zeus.Config{},
noopzeus.NewProviderFactory(),
licensing.Config{},
func(_ sqlstore.SQLStore, _ zeus.Zeus, _ organization.Getter, _ analytics.Analytics, _ cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
func(_ sqlstore.SQLStore, _ zeus.Zeus, _ organization.Getter, _ analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return nooplicensing.NewFactory()
},
func(_ zeus.Zeus, _ licensing.Licensing) subscription.Subscription {

View File

@@ -103,8 +103,8 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
enterprisezeus.Config(),
httpzeus.NewProviderFactory(),
enterpriselicensing.Config(24*time.Hour, 3),
func(sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return httplicensing.NewProviderFactory(sqlstore, zeus, orgGetter, analytics, cache)
func(sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return httplicensing.NewProviderFactory(sqlstore, zeus, orgGetter, analytics)
},
func(zeus zeus.Zeus, licensing licensing.Licensing) subscription.Subscription {
return httpsubscription.New(zeus, licensing)

View File

@@ -261,8 +261,8 @@ alertmanager:
nflog:
# Interval between garbage collection and snapshotting of the notification logs. The snapshot will be stored in the state store.
maintenance_interval: 15m
# Retention of the notification logs. Must be at least twice the longest repeat interval, which is 8760h for rules with re-notify off.
retention: 17520h
# Retention of the notification logs.
retention: 120h
##################### Emailing #####################
emailing:

File diff suppressed because it is too large Load Diff

View File

@@ -1,26 +0,0 @@
package httplicensing
import (
"encoding/json"
"time"
"github.com/SigNoz/signoz/pkg/types/licensetypes"
)
const (
activeLicenseCacheKey string = "active_license"
activeLicenseCacheTTL time.Duration = 5 * time.Minute
)
// A nil License means the organization has no active license.
type cachedActiveLicense struct {
License *licensetypes.License
}
func (typ cachedActiveLicense) MarshalBinary() ([]byte, error) {
return json.Marshal(typ)
}
func (typ *cachedActiveLicense) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, typ)
}

View File

@@ -7,7 +7,6 @@ import (
"github.com/SigNoz/signoz/ee/licensing/licensingstore/sqllicensingstore"
"github.com/SigNoz/signoz/pkg/analytics"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/licensing"
@@ -26,17 +25,16 @@ type provider struct {
settings factory.ScopedProviderSettings
orgGetter organization.Getter
analytics analytics.Analytics
cache cache.Cache
stopChan chan struct{}
}
func NewProviderFactory(store sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
func NewProviderFactory(store sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return factory.NewProviderFactory(factory.MustNewName("http"), func(ctx context.Context, providerSettings factory.ProviderSettings, config licensing.Config) (licensing.Licensing, error) {
return New(ctx, providerSettings, config, store, zeus, orgGetter, analytics, cache)
return New(ctx, providerSettings, config, store, zeus, orgGetter, analytics)
})
}
func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Config, sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) (licensing.Licensing, error) {
func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Config, sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) (licensing.Licensing, error) {
settings := factory.NewScopedProviderSettings(ps, "github.com/SigNoz/signoz/ee/licensing/httplicensing")
licensestore := sqllicensingstore.New(sqlstore)
return &provider{
@@ -47,7 +45,6 @@ func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Conf
orgGetter: orgGetter,
stopChan: make(chan struct{}),
analytics: analytics,
cache: cache,
}, nil
}
@@ -112,7 +109,6 @@ func (provider *provider) Activate(ctx context.Context, organizationID valuer.UU
return nil, err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return license, nil
}
@@ -154,38 +150,25 @@ func (provider *provider) Delete(ctx context.Context, organizationID valuer.UUID
return errors.WithAdditionalf(err, "license %s cannot be deleted", licenseID.StringValue())
}
if err := provider.store.Delete(ctx, organizationID, licenseID); err != nil {
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return nil
return provider.store.Delete(ctx, organizationID, licenseID)
}
// Caches both an active license and no active license, but never a store error.
func (provider *provider) GetActive(ctx context.Context, organizationID valuer.UUID) (*licensetypes.License, error) {
if cached, ok := provider.getActiveFromCache(ctx, organizationID); ok {
if cached.License == nil {
return nil, licensetypes.ErrActiveLicenseNotFound(organizationID)
}
return cached.License, nil
}
activeLicense, err := provider.getActiveFromStore(ctx, organizationID)
if err != nil && !errors.Ast(err, errors.TypeNotFound) {
storableLicenses, err := provider.store.GetAll(ctx, organizationID)
if err != nil {
return nil, err
}
if cacheErr := provider.cache.Set(ctx, organizationID, activeLicenseCacheKey, &cachedActiveLicense{License: activeLicense}, activeLicenseCacheTTL); cacheErr != nil {
provider.settings.Logger().WarnContext(ctx, "failed to write active license to cache", errors.Attr(cacheErr), slog.String("org_id", organizationID.StringValue()))
activeLicense, err := licensetypes.GetActiveLicenseFromStorableLicenses(storableLicenses, organizationID)
if err != nil {
return nil, err
}
return activeLicense, err
return activeLicense, nil
}
func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUID) error {
activeLicense, err := provider.getActiveFromStore(ctx, organizationID)
activeLicense, err := provider.GetActive(ctx, organizationID)
if err != nil {
if errors.Ast(err, errors.TypeNotFound) {
return nil
@@ -204,7 +187,6 @@ func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUI
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return nil
}
return err
@@ -221,8 +203,6 @@ func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUI
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
stats := licensetypes.NewStatsFromLicense(activeLicense)
provider.analytics.Send(ctx,
analyticstypes.Track{
@@ -269,30 +249,3 @@ func (provider *provider) Collect(ctx context.Context, orgID valuer.UUID) (map[s
return licensetypes.NewStatsFromLicense(activeLicense), nil
}
func (provider *provider) getActiveFromCache(ctx context.Context, organizationID valuer.UUID) (*cachedActiveLicense, bool) {
cached := new(cachedActiveLicense)
err := provider.cache.Get(ctx, organizationID, activeLicenseCacheKey, cached)
if err != nil {
if !errors.Ast(err, errors.TypeNotFound) {
provider.settings.Logger().WarnContext(ctx, "failed to read active license from cache", errors.Attr(err), slog.String("org_id", organizationID.StringValue()))
}
return nil, false
}
if cached.License != nil && cached.License.IsExpired() {
return nil, false
}
return cached, true
}
func (provider *provider) getActiveFromStore(ctx context.Context, organizationID valuer.UUID) (*licensetypes.License, error) {
storableLicenses, err := provider.store.GetAll(ctx, organizationID)
if err != nil {
return nil, err
}
return licensetypes.GetActiveLicenseFromStorableLicenses(storableLicenses, organizationID)
}

View File

@@ -1,214 +0,0 @@
package httplicensing
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/SigNoz/signoz/pkg/analytics/analyticstest"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/cache/cachetest"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/licensing"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/sqlstore/sqlstoretest"
"github.com/SigNoz/signoz/pkg/types/licensetypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/SigNoz/signoz/pkg/zeus"
"github.com/SigNoz/signoz/pkg/zeus/noopzeus"
)
var (
testOrganizationID = valuer.MustNewUUID("0196f794-ff30-7bee-a5f4-ef5ad315715e")
testLicenseID = valuer.MustNewUUID("0196360e-90cd-7a74-8313-1aa815ce2a67")
licenseColumns = []string{"id", "created_at", "updated_at", "key", "data", "last_validated_at", "org_id"}
)
const (
selectLicensesQuery = `SELECT (.+) FROM "license"`
updateLicenseQuery = `UPDATE "license"`
deleteLicenseQuery = `DELETE FROM "license"`
)
func newTestLicensing(t *testing.T) (licensing.Licensing, sqlmock.Sqlmock, cache.Cache) {
t.Helper()
sqlStore := sqlstoretest.New(sqlstore.Config{Provider: "sqlite"}, sqlmock.QueryMatcherRegexp)
licenseCache, err := cachetest.New(cache.Config{Provider: "memory", Memory: cache.Memory{NumCounters: 1000, MaxCost: 1 << 20}})
require.NoError(t, err)
providerSettings := instrumentationtest.New().ToProviderSettings()
noopZeus, err := noopzeus.New(context.Background(), providerSettings, zeus.Config{})
require.NoError(t, err)
licensing, err := New(context.Background(), providerSettings, licensing.Config{PollInterval: time.Hour, FailureThreshold: 3}, sqlStore, noopZeus, nil, analyticstest.New(), licenseCache)
require.NoError(t, err)
return licensing, sqlStore.Mock(), licenseCache
}
func newLicenseRows(lastValidatedAt time.Time) *sqlmock.Rows {
createdAt := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
data := `{"status":"VALID","state":"EVALUATING","platform":"SELF_HOSTED","plan":{"name":"ENTERPRISE"},"valid_from":1732146923,"valid_until":-1,"features":[],"event_queue":{}}`
return sqlmock.
NewRows(licenseColumns).
AddRow(testLicenseID.StringValue(), createdAt, createdAt, "test-license-key", data, lastValidatedAt, testOrganizationID.StringValue())
}
func TestGetActiveServesRepeatReadsFromCache(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
fromStore, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
fromCache, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, licensetypes.NewGettableLicenseWithKey(fromStore), licensetypes.NewGettableLicenseWithKey(fromCache))
assert.Equal(t, fromStore.OrganizationID, fromCache.OrganizationID)
assert.True(t, fromStore.LastValidatedAt.Equal(fromCache.LastValidatedAt))
fromStoreData, err := json.Marshal(fromStore.Data)
require.NoError(t, err)
fromCacheData, err := json.Marshal(fromCache.Data)
require.NoError(t, err)
assert.JSONEq(t, string(fromStoreData), string(fromCacheData))
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveCachesNoActiveLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(sqlmock.NewRows(licenseColumns))
for range 2 {
license, err := licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.True(t, errors.Ast(err, errors.TypeNotFound))
assert.Nil(t, license)
}
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveDoesNotCacheErrors(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
createdAt := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
licenseRowWithoutStatus := sqlmock.
NewRows(licenseColumns).
AddRow(testLicenseID.StringValue(), createdAt, createdAt, "test-license-key", `{"plan":{"name":"ENTERPRISE"}}`, createdAt, testOrganizationID.StringValue())
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(licenseRowWithoutStatus)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.ErrorContains(t, err, "license status is missing")
license, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, testLicenseID, license.ID)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveReloadsExpiredCachedLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, licenseCache := newTestLicensing(t)
expiredLicense := &licensetypes.License{
ID: valuer.GenerateUUID(),
ValidFrom: time.Now().Add(-2 * time.Hour).Unix(),
ValidUntil: time.Now().Add(-time.Hour).Unix(),
OrganizationID: testOrganizationID,
}
require.NoError(t, licenseCache.Set(ctx, testOrganizationID, activeLicenseCacheKey, &cachedActiveLicense{License: expiredLicense}, activeLicenseCacheTTL))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
license, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, testLicenseID, license.ID)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestDeleteClearsCachedActiveLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
mock.ExpectExec(deleteLicenseQuery).WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(sqlmock.NewRows(licenseColumns))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, licensing.Delete(ctx, testOrganizationID, testLicenseID))
_, err = licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.True(t, errors.Ast(err, errors.TypeNotFound))
require.NoError(t, mock.ExpectationsWereMet())
}
func TestRefreshClearsCachedActiveLicenseOnDowngrade(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
staleLastValidatedAt := time.Now().Add(-4 * time.Hour).UTC()
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectExec(updateLicenseQuery).WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, licensing.Refresh(ctx, testOrganizationID))
_, err = licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestRefreshWritesActiveLicenseFromStoreNotCache(t *testing.T) {
ctx := context.Background()
licensing, mock, licenseCache := newTestLicensing(t)
staleLastValidatedAt := time.Now().Add(-4 * time.Hour).UTC()
staleCachedLicense := &licensetypes.License{
ID: testLicenseID,
Key: "stale-cached-license-key",
ValidFrom: 1732146923,
ValidUntil: -1,
LastValidatedAt: staleLastValidatedAt,
OrganizationID: testOrganizationID,
}
require.NoError(t, licenseCache.Set(ctx, testOrganizationID, activeLicenseCacheKey, &cachedActiveLicense{License: staleCachedLicense}, activeLicenseCacheTTL))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectExec(`UPDATE "license" .*'test-license-key'`).WillReturnResult(sqlmock.NewResult(0, 1))
require.NoError(t, licensing.Refresh(ctx, testOrganizationID))
require.NoError(t, mock.ExpectationsWereMet())
}

View File

@@ -52,7 +52,7 @@ func (f *formatter) JSONIsArray(column, path string) []byte {
func (f *formatter) JSONArrayElements(column, path, alias string) ([]byte, []byte) {
var sql []byte
sql = append(sql, "jsonb_array_elements("...)
sql = append(sql, f.TextToJsonColumn(column)...)
sql = f.bunf.AppendIdent(sql, column)
sql = append(sql, f.convertJSONPathToPostgresWithMode(path, false)...)
sql = append(sql, ") AS "...)
sql = f.bunf.AppendIdent(sql, alias)

View File

@@ -213,28 +213,28 @@ func TestJSONArrayElements(t *testing.T) {
column: "data",
path: "$",
alias: "elem",
expected: `jsonb_array_elements("data"::jsonb) AS "elem"`,
expected: `jsonb_array_elements("data") AS "elem"`,
},
{
name: "root path empty",
column: "data",
path: "",
alias: "elem",
expected: `jsonb_array_elements("data"::jsonb) AS "elem"`,
expected: `jsonb_array_elements("data") AS "elem"`,
},
{
name: "nested path",
column: "metadata",
path: "$.items",
alias: "item",
expected: `jsonb_array_elements("metadata"::jsonb->'items') AS "item"`,
expected: `jsonb_array_elements("metadata"->'items') AS "item"`,
},
{
name: "deeply nested path",
column: "json_col",
path: "$.user.tags",
alias: "tag",
expected: `jsonb_array_elements("json_col"::jsonb->'user'->'tags') AS "tag"`,
expected: `jsonb_array_elements("json_col"->'user'->'tags') AS "tag"`,
},
}

View File

@@ -8,5 +8,5 @@
.title {
color: var(--l1-foreground);
font-size: var(--label-large-400-font-size);
font-size: var(--font-size-lg);
}

View File

@@ -497,11 +497,7 @@
// Requires final else in if-else-if chains (was disabled)
"signoz/no-conditional-text-nodes-with-siblings": "warn",
// Vendored from eslint-plugin-react-google-translate
"signoz/no-return-text-nodes": "warn",
"signoz/no-text-css": "warn",
// Font and text CSS in style props, CSSProperties objects and styled-components; text style goes through Typography props
"signoz/require-disable-reason": "error"
// A disable of signoz/no-text-css must say why Typography cannot render the text
"signoz/no-return-text-nodes": "warn"
},
"ignorePatterns": [
"src/parser/*.ts",

View File

@@ -40,8 +40,8 @@ const mockAliases = [
},
{
// jest: not replaced, a test asserts on the toast it fires.
find: /^@signozhq\/ui\/toast$/,
replacement: `${srcPath}/storybook/mocks/toast.mock.tsx`,
find: /^@signozhq\/ui\/sonner$/,
replacement: `${srcPath}/storybook/mocks/sonner.mock.tsx`,
},
];

View File

@@ -1,6 +1,8 @@
<!--
Every Google Fonts request the app makes is answered with an empty
stylesheet; the local faces stand in for them.
`index.html` links Inter from Google Fonts here. The link is parsed before the
msw worker has started, so that one request escapes the iframe while every
other font request the app makes is answered with an empty stylesheet; the
local faces stand in for both.
-->
<link rel="stylesheet" href="storybook-fonts.css" />
@@ -74,3 +76,49 @@
Object.defineProperty(window, 'Date', { value: FrozenDate, writable: true });
})();
</script>
<script>
// Storybook has no microphone. Chromium's recognizer asks for one and for
// Google's speech service, and the `not-allowed` or `network` it reports makes
// the assistant hide its mic for the rest of the tab. This one starts
// listening at once and hears only what a story passes to `hear`.
(() => {
class StorySpeechRecognition extends EventTarget {
static listening = null;
lang = 'en-US';
continuous = false;
interimResults = false;
onstart = null;
onresult = null;
onerror = null;
onend = null;
start() {
StorySpeechRecognition.listening = this;
setTimeout(() => this.onstart?.());
}
stop() {
if (StorySpeechRecognition.listening === this) {
StorySpeechRecognition.listening = null;
}
setTimeout(() => this.onend?.());
}
abort() {
this.stop();
}
/** An interim result: the words so far, still listening. */
hear(transcript) {
const result = Object.assign([{ transcript, confidence: 1 }], {
isFinal: false,
});
this.onresult?.({ resultIndex: 0, results: [result] });
}
}
window.SpeechRecognition = StorySpeechRecognition;
window.webkitSpeechRecognition = StorySpeechRecognition;
})();
</script>

View File

@@ -147,7 +147,6 @@ const preview: Preview = {
'Explorer',
['Overview', 'Span Drawer'],
'Trace Details',
['Overview', 'Thread'],
'Funnel Details',
],
'Metrics',

View File

@@ -1,11 +1,22 @@
/*
* The three families the app pulls from Google Fonts, served from the files in
* The five families the app pulls from Google Fonts, served from the files in
* `public/fonts` instead. `msw/appShellHandlers.ts` answers the CDN with an
* empty stylesheet so no request leaves the iframe, which without this left
* every story on a fallback for the three families `src/styles.scss` imports at
* runtime. Inter and Geist Mono come from `src/styles.scss` itself.
* every story on a fallback for the four families `src/styles.scss` imports at
* runtime, and on whatever the Inter link in `index.html` happened to fetch
* before the worker had started.
*/
@font-face {
font-family: 'Inter';
/* The comma is part of the filename and the dev server serves it raw, so it
stays literal inside the quoted url rather than percent-encoded. */
src: url('fonts/Inter-VariableFont_opsz,wght.ttf') format('truetype');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Work Sans';
src: url('fonts/WorkSans-VariableFont_wght.ttf') format('truetype');
@@ -29,3 +40,11 @@
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Geist Mono';
src: url('fonts/GeistMonoVF.woff2') format('woff2');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}

View File

@@ -14,23 +14,9 @@ module.exports = {
path.join(__dirname, 'stylelint-rules/css-modules/class-name-pattern.js'),
],
customSyntax: 'postcss-scss',
// Disables of property-disallowed-list must say why after "--"
reportDescriptionlessDisables: [
false,
{ except: ['property-disallowed-list'], severity: 'error' },
],
rules: {
// Applies to all SCSS files
'local/no-unsupported-asset-url': true,
// Text style goes through @signozhq/ui/typography props
'property-disallowed-list': [
['/^font/', '/^text-/', 'line-height', 'letter-spacing'],
{
severity: 'warning',
message: (property) =>
`Do not set "${property}" in CSS. Render the text with @signozhq/ui/typography and use its props, or disable this rule with a reason after "--" saying why Typography cannot.`,
},
],
},
overrides: [
{

View File

@@ -191,30 +191,34 @@ You can read the ./node_modules/@signozhq/design-tokens/dist/style.css to find c
### Typography
Text styles are tokens named `--{variant}-{size}-{weight}-{property}`:
- Variant: `label` (line height 1), `paragraph` (line height 18, 20 or 26px), `uppercase` (11 and 13px) or `code` (SF Mono, 11 and 13px).
- Size: `small` (11px), `base` (13px), `medium` (16px) or `large` (18px). Paragraph has no `large`; uppercase and code have only `small` and `base`.
- Weight: `400`, `500` or `600`.
- Property: `font-family`, `font-size`, `font-weight`, `line-height`, `letter-spacing` or `text-transform`.
```scss
// Font sizes (preferred)
.title {
font-family: var(--label-large-500-font-family);
font-size: var(--label-large-500-font-size);
font-weight: var(--label-large-500-font-weight);
line-height: var(--label-large-500-line-height);
letter-spacing: var(--label-large-500-letter-spacing);
font-size: var(--periscope-font-size-large); // 18px
font-size: var(--periscope-font-size-medium); // 16px
font-size: var(--periscope-font-size-base); // 13px
font-size: var(--periscope-font-size-small); // 11px
}
.hint {
font-size: var(--paragraph-small-400-font-size); // 11px
line-height: var(--paragraph-small-400-line-height); // 18px
// Alternative scale (rem-based)
.heading {
font-size: var(--font-size-xl); // 1.25rem
font-size: var(--font-size-lg); // 1.125rem
font-size: var(--font-size-base); // 1rem
font-size: var(--font-size-sm); // 0.875rem
}
.id {
font-family: var(--code-base-400-font-family);
font-size: var(--code-base-400-font-size); // 13px
// Font weights
.bold {
font-weight: var(--font-weight-semibold); // 600
font-weight: var(--font-weight-medium); // 500
font-weight: var(--font-weight-normal); // 400
}
// Line heights
.text {
line-height: var(--line-height-20); // 20px
line-height: var(--line-height-24); // 24px
}
```
@@ -308,7 +312,7 @@ Each component exposes `--<component>-<property>` variables:
--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);
--button-font-size: var(--periscope-font-size-base);
}
// Override Input
@@ -338,7 +342,7 @@ Components use data attributes for variants/states. Target them for state-specif
// Target size
.wrapper :global([data-size="sm"]) {
--button-font-size: var(--label-small-400-font-size);
--button-font-size: var(--periscope-font-size-small);
}
// Target color

View File

@@ -14,6 +14,11 @@
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="preconnect" href="https://cdn.vercel.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap"
rel="stylesheet"
/>
<title data-react-helmet="true">
Open source Observability platform | SigNoz
</title>

View File

@@ -36,8 +36,6 @@ const config: Config.InitialOptions = {
'^test-mocks/(.*)$': '<rootDir>/__mocks__/$1',
'^react-syntax-highlighter/dist/esm/(.*)$':
'<rootDir>/node_modules/react-syntax-highlighter/dist/cjs/$1',
// `antd` resolves to lib/ here; es/ deep imports must share its module instances (contexts).
'^antd/es/(.*)$': '<rootDir>/node_modules/antd/lib/$1',
'^@signozhq/(?!ui(?:/|$))([^/]+)$':
'<rootDir>/node_modules/@signozhq/$1/dist/$1.js',
},

View File

@@ -54,9 +54,9 @@
"@monaco-editor/react": "^4.7.0",
"@sentry/react": "10.57.0",
"@sentry/vite-plugin": "5.3.0",
"@signozhq/design-tokens": "2.8.0",
"@signozhq/design-tokens": "2.2.1",
"@signozhq/icons": "0.4.0",
"@signozhq/ui": "0.4.0-rc.5",
"@signozhq/ui": "0.2.0",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.13.22",
"@uiw/codemirror-theme-copilot": "4.23.11",

View File

@@ -1,170 +0,0 @@
import { ruleTester } from './rule-tester.mjs';
const message = (property) =>
`Do not set '${property}' in CSS. Render the text with @signozhq/ui/typography and use its props, or disable this rule with a reason after \`--\` saying why Typography cannot.`;
await ruleTester({
rule: 'no-text-css',
valid: [
{
name: 'layout properties in a style prop',
code: 'export const A = () => <div style={{ width: 10, color: "red" }} />;',
},
{
name: 'font properties in an object that is not a style',
code: 'export const options = { fontSize: 12, font: "12px Inter" };',
},
{
name: 'font properties in a prop that is not a style',
code: 'export const A = () => <Chart options={{ fontSize: 12 }} />;',
},
{
name: 'computed key',
code:
'const k = "fontSize";\nexport const A = () => <div style={{ [k]: 12 }} />;',
},
{
name: 'style identifier from a parameter',
code: 'export const A = ({ s }) => <div style={s} />;',
},
{
name: 'template without a styled tag',
code: 'export const s = html`font-size: 12px;`;',
},
{
name: 'styled template with layout only',
code:
"import styled from 'styled-components';\nexport const A = styled.div`\n\tdisplay: flex;\n\ttext: none;\n`;",
},
{
name: 'custom property that ends in a banned name',
code:
"import styled from 'styled-components';\nexport const A = styled.div`\n\t--my-font-size: 12px;\n`;",
},
],
invalid: [
{
name: 'inline style',
code: 'export const A = () => <div style={{ fontSize: 12, width: 1 }} />;',
errors: [{ message: message('fontSize'), line: 1, column: 38 }],
},
{
name: 'string key',
code: "export const A = () => <div style={{ 'line-height': 1 }} />;",
errors: [{ message: message('line-height') }],
},
{
name: 'every banned family',
code:
'export const A = () => (\n\t<div\n\t\tstyle={{\n\t\t\tfont: "x",\n\t\t\tfontWeight: 500,\n\t\t\tfontFamily: "x",\n\t\t\ttextAlign: "center",\n\t\t\ttextTransform: "none",\n\t\t\tlineHeight: 1,\n\t\t\tletterSpacing: 1,\n\t\t}}\n\t/>\n);',
errors: [
{ message: message('font') },
{ message: message('fontWeight') },
{ message: message('fontFamily') },
{ message: message('textAlign') },
{ message: message('textTransform') },
{ message: message('lineHeight') },
{ message: message('letterSpacing') },
],
},
{
name: 'conditional, logical and spread',
code:
'export const A = ({ a, b }) => (\n\t<div style={{ ...(a ? { fontSize: 1 } : {}), ...(b && { lineHeight: 1 }) }} />\n);',
errors: [
{ message: message('fontSize') },
{ message: message('lineHeight') },
],
},
{
name: 'style prop with a Style suffix',
code:
'export const A = () => <Card headStyle={{ fontWeight: 600 }} bodyStyle={{ padding: 0 }} />;',
errors: [{ message: message('fontWeight') }],
},
{
name: 'antd semantic styles',
code:
'export const A = () => <Modal styles={{ body: { fontSize: 12 }, header: { padding: 0 } }} />;',
errors: [{ message: message('fontSize') }],
},
{
name: 'identifier resolved to a local object',
code:
'const s = { fontSize: 12 };\nexport const A = () => (\n\t<>\n\t\t<div style={s} />\n\t\t<span style={s} />\n\t</>\n);',
errors: [{ message: message('fontSize'), line: 1, column: 13 }],
},
{
name: 'useMemo style',
code:
"import { useMemo } from 'react';\nexport const A = () => {\n\tconst s = useMemo(() => ({ textAlign: 'left' }), []);\n\treturn <div style={s} />;\n};",
errors: [{ message: message('textAlign') }],
},
{
name: 'object typed CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const s: CSSProperties = { fontStyle: 'italic' };",
errors: [{ message: message('fontStyle') }],
},
{
name:
'object typed React.CSSProperties, reported once when also used as style',
code:
"import React from 'react';\nconst s: React.CSSProperties = { fontSize: 1 };\nexport const A = () => <div style={s} />;",
errors: [{ message: message('fontSize') }],
},
{
name: 'Record of CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const s: Record<string, CSSProperties> = { a: { lineHeight: 1 } };",
errors: [{ message: message('lineHeight') }],
},
{
name: 'as and satisfies CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const a = { fontSize: 1 } as CSSProperties;\nexport const b = { fontWeight: 1 } satisfies CSSProperties;",
errors: [
{ message: message('fontSize') },
{ message: message('fontWeight') },
],
},
{
name: 'styled-components template',
code:
"import styled from 'styled-components';\nexport const A = styled.div`\n\tdisplay: flex;\n\tfont-size: 12px;\n\tcolor: ${(p) => p.c};\n\ttext-transform: none;line-height: 1;\n`;",
errors: [
{ message: message('font-size'), line: 4, column: 2 },
{ message: message('text-transform'), line: 6, column: 2 },
{ message: message('line-height'), line: 6, column: 23 },
],
},
{
name: 'function returning CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const a = (): CSSProperties => ({ fontSize: 1 });\nexport function b(): CSSProperties {\n\treturn { lineHeight: 1 };\n}",
errors: [
{ message: message('fontSize') },
{ message: message('lineHeight') },
],
},
{
name: 'strings in styled interpolations',
code:
"import styled, { css } from 'styled-components';\nexport const A = styled.div`\n\t${(p) => (p.s ? 'font-size: 11px;' : `line-height: 1;`)}\n\t${(p) => p.b && css`font-weight: 500;`}\n`;",
errors: [
{ message: message('font-size'), line: 3, column: 19 },
{ message: message('line-height'), line: 3, column: 40 },
{ message: message('font-weight'), line: 4, column: 22 },
],
},
{
name: 'styled(Component) and css helper',
code:
"import styled, { css } from 'styled-components';\nexport const A = styled(B)`letter-spacing: 1px;`;\nexport const c = css`\n\tfont-weight: 500;\n`;",
errors: [
{ message: message('letter-spacing'), line: 2, column: 28 },
{ message: message('font-weight'), line: 4, column: 2 },
],
},
],
});

View File

@@ -1,49 +0,0 @@
import { ruleTester } from './rule-tester.mjs';
const message = 'Disabling signoz/no-text-css needs a reason after `--`.';
await ruleTester({
rule: 'require-disable-reason',
valid: [
{
name: 'reason after --',
code:
'// oxlint-disable-next-line signoz/no-text-css -- canvas label\nexport const a = 1;',
},
{
name: 'block comment with a reason',
code:
'/* eslint-disable signoz/no-text-css -- email HTML */\nexport const a = 1;',
},
{
name: 'another rule without a reason',
code: '// oxlint-disable-next-line no-console\nexport const a = 1;',
},
{
name: 'disable of every rule',
code: '// eslint-disable-next-line\nexport const a = 1;',
},
{
name: 'plain comment naming the rule',
code: '// signoz/no-text-css flags font CSS\nexport const a = 1;',
},
],
invalid: [
{
name: 'next-line without a reason',
code: '// oxlint-disable-next-line signoz/no-text-css\nexport const a = 1;',
errors: [{ message, line: 1, column: 1 }],
},
{
name: 'empty reason',
code: '// eslint-disable-line signoz/no-text-css --\nexport const a = 1;',
errors: [{ message }],
},
{
name: 'among other rules',
code:
'/* oxlint-disable no-console, signoz/no-text-css */\nexport const a = 1;',
errors: [{ message }],
},
],
});

View File

@@ -1,324 +0,0 @@
/**
* Rule: no-text-css
*
* Text style (font, line height, letter spacing, case, alignment, overflow)
* belongs to Typography props, not to CSS written in a component.
*
* This rule catches font and text properties in:
* <div style={{ fontSize: 12 }} /> style and *Style props
* <Modal styles={{ body: { fontWeight: 500 } }} />
* const s: CSSProperties = { lineHeight: 1 } objects typed CSSProperties
* ({ ... }) as CSSProperties, satisfies CSSProperties
* (): CSSProperties => ({ ... }) functions returning CSSProperties
* styled.div`font-size: 12px;` styled-components templates,
* ${(p) => p.small && 'font-size: 11px;'} strings in their interpolations
*
* Identifiers passed to a style prop are followed to a local object literal.
* SCSS is covered by the stylelint config.
*/
const MESSAGE = (property) =>
`Do not set '${property}' in CSS. Render the text with @signozhq/ui/typography and use its props, or disable this rule with a reason after \`--\` saying why Typography cannot.`;
const BANNED_JS = /^(font([A-Z]\w*)?|text[A-Z]\w*|lineHeight|letterSpacing)$/;
const BANNED_CSS =
/(^|[\s;{])(font(-[a-z]+)*|text-[a-z-]+|line-height|letter-spacing)\s*:/g;
const STYLE_TAGS = new Set(['css', 'createGlobalStyle', 'keyframes']);
const FUNCTIONS = new Set([
'ArrowFunctionExpression',
'FunctionExpression',
'FunctionDeclaration',
]);
const camelCase = (name) =>
name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
function propertyName(property) {
if (property.computed) {
return null;
}
if (property.key.type === 'Identifier') {
return property.key.name;
}
if (
property.key.type === 'Literal' &&
typeof property.key.value === 'string'
) {
return property.key.value;
}
return null;
}
function isCssPropertiesType(typeNode) {
if (!typeNode || typeNode.type !== 'TSTypeReference') {
return false;
}
const name = typeNode.typeName;
if (name.type === 'Identifier') {
return name.name === 'CSSProperties';
}
return name.type === 'TSQualifiedName' && name.right.name === 'CSSProperties';
}
// Record<K, CSSProperties> and { [key: string]: CSSProperties }
function isCssPropertiesMapType(typeNode) {
if (!typeNode) {
return false;
}
if (
typeNode.type === 'TSTypeReference' &&
typeNode.typeName.type === 'Identifier' &&
typeNode.typeName.name === 'Record'
) {
const params = (typeNode.typeArguments ?? typeNode.typeParameters)?.params;
return isCssPropertiesType(params?.[1]);
}
if (typeNode.type === 'TSTypeLiteral') {
return typeNode.members.some(
(member) =>
member.type === 'TSIndexSignature' &&
isCssPropertiesType(member.typeAnnotation?.typeAnnotation),
);
}
return false;
}
function rootIdentifier(node) {
let current = node;
while (current) {
if (current.type === 'Identifier') {
return current.name;
}
if (current.type === 'MemberExpression') {
current = current.object;
} else if (current.type === 'CallExpression') {
current = current.callee;
} else {
return null;
}
}
return null;
}
function isStyleTag(tag) {
if (tag.type === 'Identifier') {
return tag.name === 'styled' || STYLE_TAGS.has(tag.name);
}
return rootIdentifier(tag) === 'styled';
}
export default {
create(context) {
const reported = new Set();
const followed = new Set();
const reportedCss = new Set();
function report(property, name) {
if (reported.has(property)) {
return;
}
reported.add(property);
context.report({ node: property.key, message: MESSAGE(name) });
}
function resolveIdentifier(identifier) {
const scope = context.sourceCode.getScope(identifier);
let current = scope;
while (current) {
const variable = current.set.get(identifier.name);
if (variable) {
const definition = variable.defs[0];
if (
definition?.node?.type === 'VariableDeclarator' &&
definition.node.init
) {
return definition.node.init;
}
return null;
}
current = current.upper;
}
return null;
}
function checkObject(object) {
for (const property of object.properties) {
if (property.type === 'SpreadElement') {
checkStyle(property.argument);
continue;
}
const name = propertyName(property);
if (name && BANNED_JS.test(camelCase(name))) {
report(property, name);
}
}
}
function checkStyle(expression) {
if (!expression) {
return;
}
switch (expression.type) {
case 'ObjectExpression':
checkObject(expression);
return;
case 'ConditionalExpression':
checkStyle(expression.consequent);
checkStyle(expression.alternate);
return;
case 'LogicalExpression':
checkStyle(expression.left);
checkStyle(expression.right);
return;
case 'TSAsExpression':
case 'TSSatisfiesExpression':
case 'TSNonNullExpression':
case 'ParenthesizedExpression':
checkStyle(expression.expression);
return;
case 'CallExpression':
// useMemo(() => ({ ... }), deps)
if (
expression.callee.type === 'Identifier' &&
expression.callee.name === 'useMemo'
) {
checkReturned(expression.arguments[0]);
}
return;
case 'Identifier': {
const init = resolveIdentifier(expression);
if (!init || followed.has(init)) {
return;
}
followed.add(init);
checkStyle(init);
return;
}
default:
}
}
function checkReturned(fn) {
if (!fn || !FUNCTIONS.has(fn.type)) {
return;
}
if (fn.body.type !== 'BlockStatement') {
checkStyle(fn.body);
return;
}
for (const statement of fn.body.body) {
if (statement.type === 'ReturnStatement') {
checkStyle(statement.argument);
}
}
}
function checkStyleMap(expression) {
if (expression?.type !== 'ObjectExpression') {
return;
}
for (const property of expression.properties) {
if (property.type === 'Property') {
checkStyle(property.value);
}
}
}
// `start` is the index of the first character after the opening quote.
function checkCss(text, start) {
for (const match of text.matchAll(BANNED_CSS)) {
const index = start + match.index + match[1].length;
if (reportedCss.has(index)) {
continue;
}
reportedCss.add(index);
context.report({
loc: {
start: context.sourceCode.getLocFromIndex(index),
end: context.sourceCode.getLocFromIndex(index + match[2].length),
},
message: MESSAGE(match[2]),
});
}
}
// CSS returned from interpolations: ${(p) => p.small && 'font-size: 11px;'}
function checkCssStrings(node) {
if (!node || typeof node.type !== 'string') {
return;
}
if (node.type === 'TemplateLiteral') {
for (const quasi of node.quasis) {
checkCss(quasi.value.raw, quasi.range[0] + 1);
}
} else if (node.type === 'Literal' && typeof node.value === 'string') {
checkCss(node.raw.slice(1, -1), node.range[0] + 1);
return;
}
for (const [key, value] of Object.entries(node)) {
if (key === 'parent') {
continue;
}
if (Array.isArray(value)) {
value.forEach(checkCssStrings);
} else if (value && typeof value === 'object') {
checkCssStrings(value);
}
}
}
function checkFunction(node) {
if (isCssPropertiesType(node.returnType?.typeAnnotation)) {
checkReturned(node);
}
}
return {
JSXAttribute(node) {
if (
node.name.type !== 'JSXIdentifier' ||
node.value?.type !== 'JSXExpressionContainer'
) {
return;
}
const name = node.name.name;
if (name === 'styles') {
checkStyleMap(node.value.expression);
} else if (name === 'style' || name.endsWith('Style')) {
checkStyle(node.value.expression);
}
},
VariableDeclarator(node) {
const type = node.id.typeAnnotation?.typeAnnotation;
if (isCssPropertiesType(type)) {
checkStyle(node.init);
} else if (isCssPropertiesMapType(type)) {
checkStyleMap(node.init);
}
},
TSAsExpression(node) {
if (isCssPropertiesType(node.typeAnnotation)) {
checkStyle(node.expression);
}
},
TSSatisfiesExpression(node) {
if (isCssPropertiesType(node.typeAnnotation)) {
checkStyle(node.expression);
} else if (isCssPropertiesMapType(node.typeAnnotation)) {
checkStyleMap(node.expression);
}
},
TaggedTemplateExpression(node) {
if (!isStyleTag(node.tag)) {
return;
}
checkCssStrings(node.quasi);
},
ArrowFunctionExpression: checkFunction,
FunctionExpression: checkFunction,
FunctionDeclaration: checkFunction,
};
},
};

View File

@@ -1,38 +0,0 @@
/**
* Rule: require-disable-reason
*
* A disable directive that names one of RULES must say why after `--`:
* // oxlint-disable-next-line signoz/no-text-css -- canvas text, not DOM
*
* Directives that disable every rule are not checked.
*/
const RULES = new Set(['signoz/no-text-css']);
const DIRECTIVE = /^\s*(?:eslint|oxlint)-disable(?:-next-line|-line)?\s+(.*)$/s;
export default {
create(context) {
return {
Program() {
for (const comment of context.sourceCode.getAllComments()) {
const match = comment.value.match(DIRECTIVE);
if (!match) {
continue;
}
const [rules, reason] = match[1].split(/\s--\s?/);
const named = rules
.split(',')
.map((rule) => rule.trim())
.filter((rule) => RULES.has(rule));
if (named.length > 0 && !reason?.trim()) {
context.report({
node: comment,
message: `Disabling ${named.join(', ')} needs a reason after \`--\`.`,
});
}
}
},
};
},
};

View File

@@ -17,8 +17,6 @@ import noConditionalTextNodesWithSiblings from './rules/no-conditional-text-node
import noReturnTextNodes from './rules/no-return-text-nodes.mjs';
import noMswInStoryFile from './rules/no-msw-in-story-file.mjs';
import noDirectReactRouterImport from './rules/no-direct-react-router-import.mjs';
import noTextCss from './rules/no-text-css.mjs';
import requireDisableReason from './rules/require-disable-reason.mjs';
export default {
meta: {
@@ -37,7 +35,5 @@ export default {
'no-return-text-nodes': noReturnTextNodes,
'no-msw-in-story-file': noMswInStoryFile,
'no-direct-react-router-import': noDirectReactRouterImport,
'no-text-css': noTextCss,
'require-disable-reason': requireDisableReason,
},
};

1187
frontend/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

View File

@@ -34,6 +34,10 @@
"title": "Partition Latency view",
"description": "Connect and Monitor Your Data Streams"
},
"dropRate": {
"title": "Drop Rate view",
"description": "Connect and Monitor Your Data Streams"
},
"metricPage": {
"title": "Metric View",
"description": "Connect and Monitor Your Data Streams"

View File

@@ -34,6 +34,10 @@
"title": "Partition Latency view",
"description": "Connect and Monitor Your Data Streams"
},
"dropRate": {
"title": "Drop Rate view",
"description": "Connect and Monitor Your Data Streams"
},
"metricPage": {
"title": "Metric View",
"description": "Connect and Monitor Your Data Streams"

View File

@@ -1746,7 +1746,7 @@ export const useTestRule = <
return useMutation(getTestRuleMutationOptions(options));
};
/**
* Returns a page of alert rules with their current evaluation state, trimmed to the fields the list page renders. Supports a filter DSL (`query`), a repeated `states` filter applied after the state overlay, sort (`updated_at`/`created_at`/`name`/`state`/`thresholds`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`). In the filter DSL, a non-reserved key is matched as a rule label directly (`team = infra`); a key that collides with a reserved keyword matches either interpretation (negative operators exclude both), and `labels.<key>` targets only the label. The response also carries the org's label pairs and the reserved filter keys for building filter suggestions.
* Returns a page of alert rules with their current evaluation state, trimmed to the fields the list page renders. Supports a filter DSL (`query`), a repeated `states` filter applied after the state overlay, sort (`updated_at`/`created_at`/`name`/`state`/`severity`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`). In the filter DSL, a non-reserved key is matched as a rule label directly (`team = infra`); a key that collides with a reserved keyword matches either interpretation (negative operators exclude both), and `labels.<key>` targets only the label. The response also carries the org's label pairs and the reserved filter keys for building filter suggestions.
* @summary List alert rules (v3)
*/
export const listRulesV3 = (

View File

@@ -34,7 +34,6 @@ import type {
ListServiceAccountKeys200,
ListServiceAccountKeysPathParameters,
ListServiceAccounts200,
ListServiceAccountsParams,
RenderErrorResponseDTO,
RevokeServiceAccountKeyPathParameters,
ServiceaccounttypesPostableFactorAPIKeyDTO,
@@ -335,48 +334,38 @@ export const invalidateGetServiceAccountRole = async (
};
/**
* Returns a page of the service accounts for an organisation. `query` is a filter expression over name, email, status, created_at and updated_at, for example `status = 'active'`; `sort`/`order` pick the ordering and `limit`/`offset` the page.
* This endpoint lists the service accounts for an organisation
* @summary List service accounts
*/
export const listServiceAccounts = (
params?: ListServiceAccountsParams,
signal?: AbortSignal,
) => {
export const listServiceAccounts = (signal?: AbortSignal) => {
return GeneratedAPIInstance<ListServiceAccounts200>({
url: `/api/v1/service_accounts`,
method: 'GET',
params,
signal,
});
};
export const getListServiceAccountsQueryKey = (
params?: ListServiceAccountsParams,
) => {
return [`/api/v1/service_accounts`, ...(params ? [params] : [])] as const;
export const getListServiceAccountsQueryKey = () => {
return [`/api/v1/service_accounts`] as const;
};
export const getListServiceAccountsQueryOptions = <
TData = Awaited<ReturnType<typeof listServiceAccounts>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
params?: ListServiceAccountsParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listServiceAccounts>>,
TError,
TData
>;
},
) => {
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listServiceAccounts>>,
TError,
TData
>;
}) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getListServiceAccountsQueryKey(params);
const queryKey = queryOptions?.queryKey ?? getListServiceAccountsQueryKey();
const queryFn: QueryFunction<
Awaited<ReturnType<typeof listServiceAccounts>>
> = ({ signal }) => listServiceAccounts(params, signal);
> = ({ signal }) => listServiceAccounts(signal);
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
Awaited<ReturnType<typeof listServiceAccounts>>,
@@ -397,17 +386,14 @@ export type ListServiceAccountsQueryError = ErrorType<RenderErrorResponseDTO>;
export function useListServiceAccounts<
TData = Awaited<ReturnType<typeof listServiceAccounts>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
params?: ListServiceAccountsParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listServiceAccounts>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getListServiceAccountsQueryOptions(params, options);
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listServiceAccounts>>,
TError,
TData
>;
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getListServiceAccountsQueryOptions(options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
@@ -421,11 +407,10 @@ export function useListServiceAccounts<
*/
export const invalidateListServiceAccounts = async (
queryClient: QueryClient,
params?: ListServiceAccountsParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getListServiceAccountsQueryKey(params) },
{ queryKey: getListServiceAccountsQueryKey() },
options,
);

View File

@@ -5284,7 +5284,6 @@ export interface TelemetrytypesTelemetryFieldKeyDTO {
}
export enum TelemetrytypesSourceDTO {
audit = 'audit',
meter = 'meter',
'' = '',
}
@@ -8043,7 +8042,7 @@ export interface DashboardtypesDashboardSpecDTO {
display: DashboardtypesDisplayDTO;
/**
* @type string
* @description The default time range, as a Prometheus duration such as 1h or 7d. The UI opens the dashboard on it, rounded up to whole minutes, when neither the URL nor the viewer's last pick sets a time range.
* @description The default time range, as a Prometheus duration such as 1h or 7d. Stored, but not applied by the UI.
*/
duration?: string;
/**
@@ -13018,7 +13017,7 @@ export enum RuletypesListSortDTO {
created_at = 'created_at',
name = 'name',
state = 'state',
thresholds = 'thresholds',
severity = 'severity',
}
/**
* The labels attached to alerts the rule fires.
@@ -13077,11 +13076,6 @@ export interface RuletypesListableRuleDTO {
* @description The current evaluation state: inactive, pending, recovering, firing, nodata or disabled.
*/
state: RuletypesAlertStateDTO;
/**
* @type array
* @description The rule's threshold names in lowercase, deduplicated and ordered critical, error, warning, info, then other names. An alert carries the name of the threshold that fired as its severity. Read-only.
*/
thresholds: string[];
/**
* @type string
* @format date-time
@@ -13104,7 +13098,7 @@ export interface RuletypesRuleViewDataDTO {
*/
query?: string;
/**
* @description The field to sort by: updated_at (the default), created_at, name, state or thresholds. Sorting by thresholds ranks each rule by its first threshold name.
* @description The field to sort by: updated_at (the default), created_at, name, state or severity.
*/
sort?: RuletypesListSortDTO;
/**
@@ -13617,13 +13611,6 @@ export interface SavedviewtypesUpdatableSavedViewDTO {
spec: SavedviewtypesSavedViewSpecDTO;
}
export enum ServiceaccounttypesDSLKeyDTO {
created_at = 'created_at',
email = 'email',
name = 'name',
status = 'status',
updated_at = 'updated_at',
}
export interface ServiceaccounttypesGettableFactorAPIKeyDTO {
/**
* @type string
@@ -13670,59 +13657,6 @@ export interface ServiceaccounttypesGettableFactorAPIKeyWithKeyDTO {
key: string;
}
export enum ServiceaccounttypesServiceAccountStatusDTO {
active = 'active',
deleted = 'deleted',
}
export interface ServiceaccounttypesServiceAccountDTO {
/**
* @type string
* @format date-time
*/
createdAt: string;
/**
* @type string
*/
email: string;
/**
* @type string
*/
id: string;
/**
* @type string
*/
name: string;
/**
* @type string
*/
orgId: string;
status: ServiceaccounttypesServiceAccountStatusDTO;
/**
* @type string
* @format date-time
*/
updatedAt: string;
}
export interface ServiceaccounttypesListableServiceAccountDTO {
/**
* @type array
* @description The filter keys the query accepts.
*/
reservedKeywords: ServiceaccounttypesDSLKeyDTO[];
/**
* @type array
* @description The service accounts on this page.
*/
serviceAccounts: ServiceaccounttypesServiceAccountDTO[];
/**
* @type integer
* @format int64
* @description The number of service accounts the filter matches across all pages.
*/
total: number;
}
export interface ServiceaccounttypesPostableFactorAPIKeyDTO {
/**
* @type integer
@@ -13753,15 +13687,39 @@ export interface ServiceaccounttypesPostableServiceAccountRoleDTO {
serviceAccountId: string;
}
export enum ServiceaccounttypesServiceAccountListOrderDTO {
asc = 'asc',
desc = 'desc',
}
export enum ServiceaccounttypesServiceAccountListSortDTO {
created_at = 'created_at',
updated_at = 'updated_at',
name = 'name',
export interface ServiceaccounttypesServiceAccountDTO {
/**
* @type string
* @format date-time
*/
createdAt?: string;
/**
* @type string
*/
email: string;
/**
* @type string
*/
id: string;
/**
* @type string
*/
name: string;
/**
* @type string
*/
orgId: string;
/**
* @type string
*/
status: string;
/**
* @type string
* @format date-time
*/
updatedAt?: string;
}
export interface ServiceaccounttypesServiceAccountRoleDTO {
/**
* @type string
@@ -13793,7 +13751,7 @@ export interface ServiceaccounttypesServiceAccountWithRolesDTO {
* @type string
* @format date-time
*/
createdAt: string;
createdAt?: string;
/**
* @type string
*/
@@ -13814,12 +13772,15 @@ export interface ServiceaccounttypesServiceAccountWithRolesDTO {
* @type array,null
*/
serviceAccountRoles: ServiceaccounttypesServiceAccountRoleDTO[] | null;
status: ServiceaccounttypesServiceAccountStatusDTO;
/**
* @type string
*/
status: string;
/**
* @type string
* @format date-time
*/
updatedAt: string;
updatedAt?: string;
}
export interface ServiceaccounttypesUpdatableFactorAPIKeyDTO {
@@ -13856,6 +13817,28 @@ export interface SpantypesEventDTO {
timeUnixNano?: number;
}
export type SpantypesEventV2DTOAttributes = { [key: string]: unknown };
export interface SpantypesEventV2DTO {
/**
* @type object
*/
attributes?: SpantypesEventV2DTOAttributes;
/**
* @type boolean
*/
isError?: boolean;
/**
* @type string
*/
name?: string;
/**
* @type integer
* @minimum 0
*/
timeUnixNano?: number;
}
export enum SpantypesFieldContextDTO {
attribute = 'attribute',
resource = 'resource',
@@ -14546,6 +14529,17 @@ export interface SpantypesGettableWaterfallTraceDTO {
uncollapsedSpans?: string[] | null;
}
export interface SpantypesLinkDTO {
/**
* @type string
*/
spanId?: string;
/**
* @type string
*/
traceId?: string;
}
export interface SpantypesPostableFlamegraphDTO {
/**
* @type array
@@ -14632,6 +14626,497 @@ export interface SpantypesPostableWaterfallDTO {
uncollapsedSpans?: string[] | null;
}
export type SpantypesSpanRecordDTOAttributes = { [key: string]: unknown };
export type SpantypesSpanRecordDTOResource = { [key: string]: string };
export interface SpantypesTruncatedFieldDTO {
/**
* @type string
*/
field: string;
/**
* @type integer
* @minimum 0
*/
length: number;
}
export interface SpantypesSpanRecordDTO {
/**
* @type object
*/
attributes: SpantypesSpanRecordDTOAttributes;
/**
* @type array
*/
events: SpantypesEventV2DTO[];
/**
* @type array
*/
links: SpantypesLinkDTO[];
/**
* @type object
*/
resource: SpantypesSpanRecordDTOResource;
/**
* @type string
*/
spanId: string;
/**
* @type string
*/
statusCode: string;
/**
* @type string
*/
statusMessage: string;
/**
* @type array
*/
truncated: SpantypesTruncatedFieldDTO[];
}
export interface SpantypesSpanSummaryDTO {
/**
* @type integer
* @minimum 0
*/
childCount: number;
/**
* @type integer
* @minimum 0
*/
durationNano: number;
/**
* @type boolean
*/
hasError: boolean;
/**
* @type string
*/
kind: string;
/**
* @type integer
* @minimum 0
*/
level: number;
/**
* @type string
*/
name: string;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
/**
* @type string
*/
parentSpanId?: string;
/**
* @type string
*/
responseStatusCode?: string;
/**
* @type string
*/
serviceName: string;
/**
* @type string
*/
spanId: string;
/**
* @type integer
* @minimum 0
*/
startOffsetNano: number;
/**
* @type integer
* @minimum 0
*/
subtreeSpanCount: number;
}
export interface SpantypesSpanTextMatchDTO {
/**
* @type string
*/
field: string;
/**
* @type string
*/
snippet: string;
}
export interface SpantypesTraceAIIdentityDTO {
/**
* @type integer
* @minimum 0
*/
modelCallCount: number;
tokens: SpantypesTraceAITokensDTO;
/**
* @type integer
* @minimum 0
*/
toolCallCount: number;
/**
* @type number
*/
totalCost?: number;
}
export interface SpantypesTraceErrorItemDTO {
/**
* @type integer
* @minimum 0
*/
errorAncestorCount: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
/**
* @type string
*/
statusMessage: string;
}
export interface SpantypesTraceErrorListDTO {
/**
* @type array
*/
items: SpantypesTraceErrorItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceExpensiveItemDTO {
/**
* @type number
*/
cost?: number;
/**
* @type integer
* @minimum 0
*/
inputTokens: number;
/**
* @type integer
* @minimum 0
*/
outputTokens: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceExpensiveListDTO {
/**
* @type array
*/
items: SpantypesTraceExpensiveItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceServiceStatsDTO {
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
/**
* @type string
*/
serviceName: string;
/**
* @type integer
* @minimum 0
*/
spanCount: number;
}
export interface SpantypesTraceIdentityDTO {
ai?: SpantypesTraceAIIdentityDTO;
/**
* @type integer
* @minimum 0
*/
durationNano: number;
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type boolean
*/
hasMissingSpans: boolean;
root?: SpantypesSpanSummaryDTO;
/**
* @type integer
* @minimum 0
*/
rootCount: number;
/**
* @type integer
* @minimum 0
*/
serviceCount: number;
/**
* @type array
*/
services: SpantypesTraceServiceStatsDTO[];
/**
* @type integer
* @minimum 0
*/
spanCount: number;
/**
* @type integer
* @minimum 0
*/
startTimestampMillis: number;
/**
* @type string
*/
traceId: string;
}
export interface SpantypesTraceLinkItemDTO {
/**
* @type integer
* @minimum 0
*/
linkCount: number;
/**
* @type array
*/
links: SpantypesLinkDTO[];
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceLinkListDTO {
/**
* @type array
*/
items: SpantypesTraceLinkItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceSlowestItemDTO {
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
/**
* @type integer
* @minimum 0
*/
spanCount: number;
}
export interface SpantypesTraceSlowestListDTO {
/**
* @type array
*/
items: SpantypesTraceSlowestItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceTreeDTO {
/**
* @type boolean
*/
complete: boolean;
/**
* @type array
*/
records?: SpantypesSpanRecordDTO[];
/**
* @type array
*/
spans: SpantypesSpanSummaryDTO[];
/**
* @type integer
* @minimum 0
*/
total: number;
}
export enum SpantypesUnmarkedFailureReasonDTO {
http_4xx = 'http_4xx',
grpc_status = 'grpc_status',
exception_event = 'exception_event',
}
export interface SpantypesTraceUnmarkedFailureItemDTO {
parent?: SpantypesSpanSummaryDTO;
reason: SpantypesUnmarkedFailureReasonDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceUnmarkedFailureListDTO {
/**
* @type array
*/
items: SpantypesTraceUnmarkedFailureItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceOverviewDTO {
errors?: SpantypesTraceErrorListDTO;
expensive?: SpantypesTraceExpensiveListDTO;
identity?: SpantypesTraceIdentityDTO;
links?: SpantypesTraceLinkListDTO;
slowest?: SpantypesTraceSlowestListDTO;
tree?: SpantypesTraceTreeDTO;
unmarkedFailures?: SpantypesTraceUnmarkedFailureListDTO;
}
export interface SpantypesTraceSpanLevelDTO {
/**
* @type integer
* @minimum 0
*/
level: number;
/**
* @type array
*/
spans: SpantypesSpanSummaryDTO[];
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceSpanPercentileDTO {
/**
* @type integer
* @minimum 0
*/
p50Nano: number;
/**
* @type integer
* @minimum 0
*/
p90Nano: number;
/**
* @type integer
* @minimum 0
*/
p99Nano: number;
/**
* @type number
* @format double
*/
position: number;
/**
* @type integer
* @minimum 0
*/
windowMinutes: number;
}
export interface SpantypesTraceSpanDetailDTO {
/**
* @type integer
* @minimum 0
*/
ancestorCount: number;
/**
* @type array
*/
ancestors: SpantypesSpanSummaryDTO[];
/**
* @type array
*/
descendants: SpantypesTraceSpanLevelDTO[];
percentile?: SpantypesTraceSpanPercentileDTO;
record: SpantypesSpanRecordDTO;
summary: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceSpanMatchDTO {
/**
* @type array
*/
matches: SpantypesSpanTextMatchDTO[];
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceSpanListDTO {
/**
* @type array
*/
items: SpantypesTraceSpanMatchDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
/**
* @type array
*/
warnings?: string[];
}
export interface SpantypesUpdatableSpanMapperDTO {
config?: SpantypesSpanMapperConfigDTO;
/**
@@ -15867,34 +16352,11 @@ export type GetServiceAccountRole200 = {
status: string;
};
export type ListServiceAccountsParams = {
/**
* @type string
* @description A filter expression over the reserved keys name, email, status, created_at and updated_at using the SigNoz filter grammar: comparisons such as =, !=, CONTAINS, LIKE, IN, < and >, single-quoted strings, RFC3339 timestamps in quotes for created_at and updated_at, combined with AND, OR and NOT, for example name CONTAINS 'ci' AND status = 'active'. A bare or quoted token without a key matches name or email case-insensitively. At most 1024 characters. Empty matches every service account.
*/
query?: string;
/**
* @description The sort column: created_at (default), updated_at or name.
*/
sort?: ServiceaccounttypesServiceAccountListSortDTO;
/**
* @description The sort order: asc or desc (default).
*/
order?: ServiceaccounttypesServiceAccountListOrderDTO;
/**
* @type integer
* @description The page size; defaults to 20 and is capped at 200.
*/
limit?: number;
/**
* @type integer
* @description The number of service accounts to skip; defaults to 0.
*/
offset?: number;
};
export type ListServiceAccounts200 = {
data: ServiceaccounttypesListableServiceAccountDTO;
/**
* @type array
*/
data: ServiceaccounttypesServiceAccountDTO[];
/**
* @type string
*/
@@ -16097,6 +16559,84 @@ export type GetTraceAggregations200 = {
status: string;
};
export type InspectTracePathParameters = {
traceID: string;
};
export type InspectTraceParams = {
/**
* @type string
* @description The nextCursor of one list of the overview; returns the next page of that list and nothing else.
*/
cursor?: string;
};
export type InspectTrace200 = {
data: SpantypesTraceOverviewDTO;
/**
* @type string
*/
status: string;
};
export type InspectTraceSpansPathParameters = {
traceID: string;
};
export type InspectTraceSpansParams = {
/**
* @type string
* @description Returns the spans that match, earliest first: words, a filter expression, or both, such as worldpay AND has_error = true. Words match the span name, status message, attributes, resource attributes and events, ignoring case. Without it every span is returned, in tree order.
*/
search?: string;
/**
* @type string
* @description A span ID; returns that span and every span below it. Cannot be combined with search.
*/
under?: string;
/**
* @type integer
* @description Page size, at most 1000; when not given, 20 with search and 400 without. A page holds fewer spans when it would pass the response size limit.
*/
limit?: number;
/**
* @type string
* @description The nextCursor of an earlier response to the same request; returns the next page.
*/
cursor?: string;
};
export type InspectTraceSpans200 = {
data: SpantypesTraceSpanListDTO;
/**
* @type string
*/
status: string;
};
export type InspectTraceSpanPathParameters = {
traceID: string;
spanID: string;
};
export type InspectTraceSpanParams = {
/**
* @type integer
* @description The number of levels of ancestors and of descendants returned, 1 to 10; 2 when not given. The root span is always returned.
*/
depth?: number;
/**
* @type array
* @description Attribute names returned without the 500 character cut; the record then holds only these attributes.
*/
selectFields?: string[];
};
export type InspectTraceSpan200 = {
data: SpantypesTraceSpanDetailDTO;
/**
* @type string
*/
status: string;
};
export type GetTraceSummaryPathParameters = {
traceID: string;
};
@@ -17646,7 +18186,7 @@ export type ListRulesV3Params = {
*/
states?: string[];
/**
* @description The field to sort by: updated_at (the default), created_at, name, state or thresholds. Sorting by thresholds ranks each rule by its first threshold name.
* @description The field to sort by: updated_at (the default), created_at, name, state or severity.
*/
sort?: RuletypesListSortDTO;
/**

View File

@@ -29,6 +29,15 @@ import type {
GetTraceThreadPathParameters,
GetWaterfallV4200,
GetWaterfallV4PathParameters,
InspectTrace200,
InspectTraceParams,
InspectTracePathParameters,
InspectTraceSpan200,
InspectTraceSpanParams,
InspectTraceSpanPathParameters,
InspectTraceSpans200,
InspectTraceSpansParams,
InspectTraceSpansPathParameters,
RenderErrorResponseDTO,
SpantypesPostableFlamegraphDTO,
SpantypesPostableTraceAggregationsDTO,
@@ -158,6 +167,352 @@ export const useGetTraceAggregations = <
> => {
return useMutation(getGetTraceAggregationsMutationOptions(options));
};
/**
* Returns the overview of a trace of any size: its identity with per-service totals, the spans where each error started, the failures not marked as errors, the slowest spans by own time, the most expensive gen_ai spans, the spans that link to other spans, and the top of the span tree. A small trace also returns each span's full record. Every list carries its total and a nextCursor when more items follow.
* @summary Inspect a trace
*/
export const inspectTrace = (
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<InspectTrace200>({
url: `/api/v1/traces/${traceID}/inspect`,
method: 'GET',
params,
signal,
});
};
export const getInspectTraceQueryKey = (
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
) => {
return [
`/api/v1/traces/${traceID}/inspect`,
...(params ? [params] : []),
] as const;
};
export const getInspectTraceQueryOptions = <
TData = Awaited<ReturnType<typeof inspectTrace>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getInspectTraceQueryKey({ traceID }, params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof inspectTrace>>> = ({
signal,
}) => inspectTrace({ traceID }, params, signal);
return {
queryKey,
queryFn,
enabled: traceID !== null && traceID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type InspectTraceQueryResult = NonNullable<
Awaited<ReturnType<typeof inspectTrace>>
>;
export type InspectTraceQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Inspect a trace
*/
export function useInspectTrace<
TData = Awaited<ReturnType<typeof inspectTrace>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getInspectTraceQueryOptions({ traceID }, params, options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Inspect a trace
*/
export const invalidateInspectTrace = async (
queryClient: QueryClient,
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getInspectTraceQueryKey({ traceID }, params) },
options,
);
return queryClient;
};
/**
* Returns the spans of a trace that match a search, each with its direct parent and where the words were found. Without a search it returns every span in tree order, or with under one span and the spans below it.
* @summary Search or list the spans of a trace
*/
export const inspectTraceSpans = (
{ traceID }: InspectTraceSpansPathParameters,
params?: InspectTraceSpansParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<InspectTraceSpans200>({
url: `/api/v1/traces/${traceID}/inspect/spans`,
method: 'GET',
params,
signal,
});
};
export const getInspectTraceSpansQueryKey = (
{ traceID }: InspectTraceSpansPathParameters,
params?: InspectTraceSpansParams,
) => {
return [
`/api/v1/traces/${traceID}/inspect/spans`,
...(params ? [params] : []),
] as const;
};
export const getInspectTraceSpansQueryOptions = <
TData = Awaited<ReturnType<typeof inspectTraceSpans>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTraceSpansPathParameters,
params?: InspectTraceSpansParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpans>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getInspectTraceSpansQueryKey({ traceID }, params);
const queryFn: QueryFunction<
Awaited<ReturnType<typeof inspectTraceSpans>>
> = ({ signal }) => inspectTraceSpans({ traceID }, params, signal);
return {
queryKey,
queryFn,
enabled: traceID !== null && traceID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpans>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type InspectTraceSpansQueryResult = NonNullable<
Awaited<ReturnType<typeof inspectTraceSpans>>
>;
export type InspectTraceSpansQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Search or list the spans of a trace
*/
export function useInspectTraceSpans<
TData = Awaited<ReturnType<typeof inspectTraceSpans>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTraceSpansPathParameters,
params?: InspectTraceSpansParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpans>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getInspectTraceSpansQueryOptions(
{ traceID },
params,
options,
);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Search or list the spans of a trace
*/
export const invalidateInspectTraceSpans = async (
queryClient: QueryClient,
{ traceID }: InspectTraceSpansPathParameters,
params?: InspectTraceSpansParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getInspectTraceSpansQueryKey({ traceID }, params) },
options,
);
return queryClient;
};
/**
* Returns one span in full: its summary and record, its nearest ancestors with the root, the spans below it level by level, and where its duration sits among recent spans of the same name and service. Long values are cut and listed in truncated; selectFields returns named attributes without the cut.
* @summary Inspect a span of a trace
*/
export const inspectTraceSpan = (
{ traceID, spanID }: InspectTraceSpanPathParameters,
params?: InspectTraceSpanParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<InspectTraceSpan200>({
url: `/api/v1/traces/${traceID}/inspect/spans/${spanID}`,
method: 'GET',
params,
signal,
});
};
export const getInspectTraceSpanQueryKey = (
{ traceID, spanID }: InspectTraceSpanPathParameters,
params?: InspectTraceSpanParams,
) => {
return [
`/api/v1/traces/${traceID}/inspect/spans/${spanID}`,
...(params ? [params] : []),
] as const;
};
export const getInspectTraceSpanQueryOptions = <
TData = Awaited<ReturnType<typeof inspectTraceSpan>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: InspectTraceSpanPathParameters,
params?: InspectTraceSpanParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpan>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ??
getInspectTraceSpanQueryKey({ traceID, spanID }, params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof inspectTraceSpan>>> = ({
signal,
}) => inspectTraceSpan({ traceID, spanID }, params, signal);
return {
queryKey,
queryFn,
enabled:
traceID !== null &&
traceID !== undefined &&
spanID !== null &&
spanID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpan>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type InspectTraceSpanQueryResult = NonNullable<
Awaited<ReturnType<typeof inspectTraceSpan>>
>;
export type InspectTraceSpanQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Inspect a span of a trace
*/
export function useInspectTraceSpan<
TData = Awaited<ReturnType<typeof inspectTraceSpan>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: InspectTraceSpanPathParameters,
params?: InspectTraceSpanParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpan>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getInspectTraceSpanQueryOptions(
{ traceID, spanID },
params,
options,
);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Inspect a span of a trace
*/
export const invalidateInspectTraceSpan = async (
queryClient: QueryClient,
{ traceID, spanID }: InspectTraceSpanPathParameters,
params?: InspectTraceSpanParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getInspectTraceSpanQueryKey({ traceID, spanID }, params) },
options,
);
return queryClient;
};
/**
* Returns the trace's time range, root span, span and error counts, and whether any spans are missing. AI traces also include token and cost totals.
* @summary Get summary for a trace

View File

@@ -12,6 +12,7 @@ export interface MessagingQueueServicePayload {
service_name?: string;
};
detailType?: MessagingQueueServiceDetailType | 'producer' | 'consumer';
evalTime?: number;
}
export interface MessagingQueuesPayloadProps {

View File

@@ -0,0 +1,23 @@
import axios from 'api';
import { DropRateAPIResponse } from 'pages/MessagingQueues/MQDetails/DropRateView/dropRateViewUtils';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { MessagingQueueServicePayload } from './getConsumerLagDetails';
export const getKafkaSpanEval = async (
props: Omit<MessagingQueueServicePayload, 'detailType' | 'variables'>,
): Promise<SuccessResponse<DropRateAPIResponse['data']> | ErrorResponse> => {
const { start, end, evalTime } = props;
const response = await axios.post(`messaging-queues/kafka/span/evaluation`, {
start,
end,
eval_time: evalTime,
});
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data.data,
};
};

View File

@@ -0,0 +1,61 @@
import { ApiV3Instance as axios } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError } from 'axios';
import createQueryParams from 'lib/createQueryParams';
import { ErrorResponse, SuccessResponse } from 'types/api';
import {
TagKeyProps,
TagKeysPayloadProps,
TagValueProps,
TagValuesPayloadProps,
} from 'types/api/metrics/getResourceAttributes';
import { DataSource, MetricAggregateOperator } from 'types/common/queryBuilder';
export const getResourceAttributesTagKeys = async (
props: TagKeyProps,
): Promise<SuccessResponse<TagKeysPayloadProps> | ErrorResponse> => {
try {
const response = await axios.get(
`/autocomplete/attribute_keys?${createQueryParams({
aggregateOperator: MetricAggregateOperator.RATE,
searchText: props.match,
dataSource: DataSource.METRICS,
aggregateAttribute: props.metricName,
})}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};
export const getResourceAttributesTagValues = async (
props: TagValueProps,
): Promise<SuccessResponse<TagValuesPayloadProps> | ErrorResponse> => {
try {
const response = await axios.get(
`/autocomplete/attribute_values?${createQueryParams({
aggregateOperator: MetricAggregateOperator.RATE,
dataSource: DataSource.METRICS,
aggregateAttribute: props.metricName,
attributeKey: props.tagKey,
searchText: '',
})}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};

View File

@@ -302,10 +302,6 @@ export function createAggregation(
reduceTo: haveReduceTo
? queryData?.aggregations?.[0]?.reduceTo || queryData?.reduceTo
: undefined,
...(queryData?.aggregations?.[0]?.comparisonSpaceAggregationParam && {
comparisonSpaceAggregationParam:
queryData.aggregations[0].comparisonSpaceAggregationParam,
}),
},
];
}

View File

@@ -1,6 +1,5 @@
import { useMutation } from 'react-query';
import { Button } from '@signozhq/ui/button';
import { Dialog } from '@signozhq/ui/dialog';
import { Button, Modal } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import { createSubscription } from 'api/generated/services/subscriptions';
import type { CreateSubscription201 } from 'api/generated/services/sigNoz.schemas';
@@ -56,51 +55,46 @@ function AddCreditCardModal({
};
return (
<Dialog
<Modal
className="add-credit-card-modal"
title={<span className="title">Add Credit Card for Chat Support</span>}
open={open}
onClose={onClose}
title="Add Credit Card for Chat Support"
testId="add-credit-card-modal"
footerSuffix={
<>
closable
onCancel={onClose}
destroyOnClose
footer={[
<Button
key="cancel"
onClick={onClose}
className="cancel-btn"
icon={<X size={16} />}
>
Cancel
</Button>,
<AuthZTooltip
key="submit"
checks={[SubscriptionCreatePermission]}
withPortal={false}
>
<Button
variant="outlined"
color="secondary"
size="md"
prefix={<X size={16} />}
onClick={onClose}
testId="add-credit-card-cancel"
type="primary"
icon={<CreditCard size={16} />}
size="middle"
loading={isLoadingBilling}
disabled={isLoadingBilling}
onClick={handleAddCreditCard}
className="add-credit-card-btn"
>
Cancel
Add Credit Card
</Button>
<AuthZTooltip checks={[SubscriptionCreatePermission]}>
<Button
variant="solid"
color="primary"
size="md"
prefix={<CreditCard size={16} />}
loading={isLoadingBilling}
onClick={handleAddCreditCard}
testId="add-credit-card-submit"
>
Add Credit Card
</Button>
</AuthZTooltip>
</>
}
</AuthZTooltip>,
]}
>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
<Typography.Text className="add-credit-card-text">
You&apos;re currently on <span className="highlight-text">Trial plan</span>.
Add a credit card to access SigNoz chat support to your workspace.
</Typography>
</Dialog>
</Typography.Text>
</Modal>
);
}

View File

@@ -1,9 +1,6 @@
.breadcrumb {
padding: var(--spacing-4) 16px var(--spacing-2);
// The antd breadcrumb provides the item spacing.
--button-padding: 0;
ol {
align-items: center;
}
@@ -11,4 +8,13 @@
:global(.ant-breadcrumb-separator) {
color: var(--muted-foreground);
}
[data-slot='button'] {
padding: 0px;
}
}
.divider {
--divider-color: var(--l1-border);
--divider-margin: 10px 0 16px 0;
}

View File

@@ -28,7 +28,7 @@ function AlertBreadcrumb({
items={breadcrumbItems}
data-testid={testId}
/>
{showDivider && <Divider spacing="10px 16px" />}
{showDivider && <Divider className={styles.divider} />}
</>
);
}

View File

@@ -1,4 +1,5 @@
.itemLast {
color: var(--button-secondary-label);
font-size: var(--button-font-size, var(--periscope-font-size-base));
line-height: var(--button-size-line-height, 16px);
}

View File

@@ -1,6 +1,6 @@
import { Copy } from '@signozhq/icons';
import { Badge, type BadgeColorType } from '@signozhq/ui/badge';
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import { Tooltip } from '@signozhq/ui/tooltip';
import cx from 'classnames';
import { useLayoutEffect, useRef, useState } from 'react';
@@ -15,14 +15,12 @@ export interface LabelColumnProps {
labels: string[];
color?: BadgeColorType;
value?: { [key: string]: string };
testId?: string;
}
function LabelColumn({
labels,
value,
color = 'primary',
testId = 'label-column',
}: LabelColumnProps): JSX.Element {
const containerRef = useRef<HTMLDivElement>(null);
const [visibleCount, setVisibleCount] = useState(labels.length);
@@ -58,7 +56,11 @@ function LabelColumn({
const remainingLabels = labels.slice(visibleCount);
return (
<div ref={containerRef} className={styles.labelColumn} data-testid={testId}>
<div
ref={containerRef}
className={styles.labelColumn}
data-testid="label-column"
>
{labels.map((label, index) => (
<LabelTag
key={label}

View File

@@ -1,6 +1,6 @@
import { Copy } from '@signozhq/icons';
import { Badge, type BadgeColorType } from '@signozhq/ui/badge';
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import { Tooltip } from '@signozhq/ui/tooltip';
import { useCopyToClipboard } from 'react-use';

View File

@@ -26,6 +26,8 @@
}
.brand-title {
font-size: 20px;
font-weight: 600;
color: var(--l1-foreground); // Primary text
margin: 0;
}

View File

@@ -28,29 +28,15 @@ function AppLoading(): JSX.Element {
<div className="brand">
<img src={signozBrandLogoUrl} alt="SigNoz" className="brand-logo" />
<Typography
variant="label"
size="large"
weight="bold"
color="main"
as="h2"
textOverflow="wrap"
>
<Typography.Title level={2} className="brand-title">
SigNoz
</Typography>
</Typography.Title>
</div>
<div className="brand-tagline">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
<Typography.Text>
OpenTelemetry-Native Logs, Metrics and Traces in a single pane
</Typography>
</Typography.Text>
</div>
<div className="loader" />

View File

@@ -1,9 +0,0 @@
import { Toaster } from '@signozhq/ui/toast';
const PAGE_INSET = { bottom: 'var(--bottom-strip-height, 0px)' };
function AppToaster(): JSX.Element {
return <Toaster position="bottom-right" pageInset={PAGE_INSET} />;
}
export default AppToaster;

View File

@@ -35,6 +35,7 @@
&__error-code {
color: var(--bg-cherry-100);
font-size: 13px;
font-weight: 500;
line-height: 1;
letter-spacing: -0.065px;
}
@@ -42,6 +43,8 @@
&__error-message {
color: var(--bg-cherry-300);
font-size: 13px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.065px;
}
@@ -72,6 +75,7 @@
&__message-item {
color: var(--bg-cherry-300);
font-size: 13px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.065px;

View File

@@ -45,8 +45,9 @@
}
.auth-footer-text {
font-family: var(--label-small-400-font-family);
font-family: var(--font-family-inter, Inter, sans-serif);
font-size: 11px;
font-weight: 400;
line-height: 1;
color: var(--l2-foreground);
text-align: center;
@@ -56,6 +57,7 @@
display: flex;
align-items: center;
gap: 6px;
text-decoration: none;
transition: opacity 0.2s ease;
&:hover {

View File

@@ -16,6 +16,7 @@
display: flex;
align-items: center;
gap: 4.9px;
text-decoration: none;
}
.auth-header-logo-icon {
@@ -25,7 +26,7 @@
}
.auth-header-logo-text {
font-family: Satoshi, var(--label-medium-500-font-family), sans-serif;
font-family: Satoshi, var(--font-family-inter, Inter), sans-serif;
font-size: 15.4px;
font-weight: 500;
line-height: 17.5px;

View File

@@ -17,3 +17,8 @@
letter-spacing: -0.01em;
color: var(--l1-foreground);
}
.divider {
--divider-color: var(--l1-border);
--divider-margin: 10px 0 16px 0;
}

View File

@@ -44,7 +44,7 @@ function BackHeader({
</Button>
<div className={styles.title}>{title}</div>
</div>
<Divider spacing="10px 16px" />
<Divider className={styles.divider} />
</>
);
}

View File

@@ -1,7 +1,6 @@
import React, { Dispatch, SetStateAction, useState } from 'react';
import { Check, Plus, X } from '@signozhq/icons';
import { Button } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Button, Flex } from 'antd';
import { Pill } from '@signozhq/ui/pill';
import Input from 'components/Input';

View File

@@ -1,7 +1,6 @@
import { useCallback, useMemo, useState } from 'react';
import { Select, Spin } from 'antd';
import { Row, Select, Spin } from 'antd';
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import Row from 'periscope/components/Row/Row';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import {

View File

@@ -23,6 +23,7 @@
.ant-table {
.ant-table-thead > tr > th {
padding: 12px;
font-weight: 500;
font-size: 12px;
line-height: 18px;
@@ -30,7 +31,10 @@
border-bottom: none;
color: var(--l2-foreground);
font-family: Inter;
font-size: 11px;
font-style: normal;
font-weight: 600;
line-height: 18px; /* 163.636% */
letter-spacing: 0.44px;
@@ -41,6 +45,7 @@
.ant-table-cell {
padding: 12px;
font-size: 13px;
line-height: 20px;
color: var(--l1-foreground);
background: var(--l1-background);
@@ -62,6 +67,12 @@
.ant-table-cell:nth-child(n + 3) {
padding-right: 24px;
}
.column-header-right {
text-align: right;
}
.column-header-left {
text-align: left;
}
.ant-table-tbody > tr > td {
border-bottom: none;
}

View File

@@ -6,15 +6,15 @@ import { Loader, Search } from '@signozhq/icons';
import { Color } from '@signozhq/design-tokens';
import {
Button,
Flex,
Input,
InputRef,
Space,
Spin,
TableColumnsType,
TableColumnType,
Tooltip,
} from 'antd';
import Space from 'periscope/components/Space/Space';
import Flex from 'periscope/components/Flex/Flex';
import { Progress } from '@signozhq/ui/progress';
import { Typography } from '@signozhq/ui/typography';
import type { FilterDropdownProps } from 'antd/lib/table/interface';
@@ -40,27 +40,10 @@ const INITIAL_PAGE_SIZE = 20;
const showPaginationItem = (total: number, range: number[]): JSX.Element => (
<>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
<Typography.Text className="numbers">
{range[0]} &#8212; {range[1]}
</Typography>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
{' '}
of {total}
</Typography>
</Typography.Text>
<Typography.Text className="total"> of {total}</Typography.Text>
</>
);
@@ -73,15 +56,22 @@ function ProgressRender(item: string | number): JSX.Element {
const percent = Number(Number(item).toFixed(1));
return (
<div className="progress-container">
<div className="progress-bar">
<Progress
percent={percent}
showInfo
color={
percent >= 90 ? 'highlight-danger' : percent >= 60 ? 'warning' : 'success'
<Progress
percent={percent}
strokeLinecap="butt"
showInfo
strokeColor={((): string => {
const cpuPercent = percent;
if (cpuPercent >= 90) {
return Color.BG_SAKURA_500;
}
/>
</div>
if (cpuPercent >= 60) {
return Color.BG_AMBER_500;
}
return Color.BG_FOREST_500;
})()}
className="progress-bar"
/>
</div>
);
}
@@ -536,18 +526,7 @@ export default function CeleryOverviewTable({
),
}}
locale={{
emptyText: isLoading ? null : (
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
No data
</Typography>
),
emptyText: isLoading ? null : <Typography.Text>No data</Typography.Text>,
}}
scroll={{ x: 'max-content' }}
showSorterTooltip

View File

@@ -24,16 +24,9 @@ function CeleryTaskConfigOptions(): JSX.Element {
return (
<div className="celery-task-filters">
<div className="celery-filters">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="visible"
>
<Typography.Text style={{ whiteSpace: 'nowrap' }}>
Task Name
</Typography>
</Typography.Text>
<Select
data-testid="celery-task-name-select"
placeholder="Task Name"

View File

@@ -49,7 +49,11 @@
.subtitle {
color: var(--l2-foreground);
font-family: Inter;
font-size: 12px;
font-style: normal;
font-weight: 400;
line-height: 20px;
}
}
}
@@ -60,6 +64,11 @@
.footer-text {
color: var(--l2-foreground);
font-family: Inter;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 20px;
}
}
}

View File

@@ -65,38 +65,15 @@ export default function CeleryTaskDetail({
width="45%"
title={
<div>
<Typography
variant="label"
size="large"
weight="bold"
color="main"
as="span"
textOverflow="wrap"
>{`Details - ${taskData.entity}`}</Typography>
<Typography.Text className="title">{`Details - ${taskData.entity}`}</Typography.Text>
<div>
<Typography
variant="paragraph"
size="small"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
<Typography.Text className="subtitle">
{`${formatTimestamp(startTime)} ${
endTime ? `- ${formatTimestamp(endTime)}` : ''
}`}
</Typography>
<Divider orientation="vertical" />
<Typography
variant="paragraph"
size="small"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
{taskData.value}
</Typography>
</Typography.Text>
<Divider type="vertical" />
<Typography.Text className="subtitle">{taskData.value}</Typography.Text>
</div>
</div>
}
@@ -111,14 +88,7 @@ export default function CeleryTaskDetail({
destroyOnClose
closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
footer={
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>{`Total Task: ${totalTask}`}</Typography>
<Typography.Text className="footer-text">{`Total Task: ${totalTask}`}</Typography.Text>
}
>
<CeleryTaskGraph

View File

@@ -7,11 +7,11 @@ import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { ViewMenuAction } from 'container/WidgetCard/config';
import { ENTITY_VERSION_V5 } from 'constants/app';
import GridCard from 'container/WidgetCard/Card';
import { Card } from 'container/WidgetCard/styles';
import { useIsDarkMode } from 'hooks/useDarkMode';
import useUrlQuery from 'hooks/useUrlQuery';
import { isEmpty } from 'lodash-es';
import { getStartAndEndTimesInMilliseconds } from 'pages/MessagingQueues/MessagingQueuesUtils';
import { UpdateTimeInterval } from 'store/actions';
import { AppState } from 'store/reducers';
@@ -33,7 +33,6 @@ import {
celerySlowestTasksTableWidgetData,
celerySuccessStateWidgetData,
celerySuccessTasksTableWidgetData,
getClickedSeries,
} from './CeleryTaskGraphUtils';
import {
CeleryTaskState,
@@ -143,19 +142,24 @@ function CeleryTaskBar({
data?: {
[key: string]: string;
},
queryData?: { inFocusOrNot: boolean },
): void => {
const clickedSeries = getClickedSeries(data, queryData);
if (!clickedSeries) {
return;
}
const { start, end } = getStartAndEndTimesInMilliseconds(xValue);
onClick?.({
...clickedSeries,
timeRange: [start, end],
widgetData,
});
// Extract entity and value from data
const [firstDataPoint] = Object.entries(data || {});
const [entity, value] = (firstDataPoint || ([] as unknown)) as [
string,
string,
];
if (!isEmpty(entity) || !isEmpty(value)) {
onClick?.({
entity,
value,
timeRange: [start, end],
widgetData,
});
}
};
const { getCustomSeries } = useGetGraphCustomSeries({
@@ -179,11 +183,10 @@ function CeleryTaskBar({
{barState === CeleryTaskState.All && (
<GridCard
widget={celeryAllStateFilteredData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
isQueryEnabled={queryEnabled}
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
onGraphClick(
celerySlowestTasksTableWidgetData,
xValue,
@@ -191,7 +194,6 @@ function CeleryTaskBar({
mouseX,
mouseY,
data,
queryData,
)
}
customSeries={getCustomSeries}
@@ -201,11 +203,10 @@ function CeleryTaskBar({
{barState === CeleryTaskState.Failed && (
<GridCard
widget={celeryFailedStateFilteredData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
isQueryEnabled={queryEnabled}
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
onGraphClick(
celeryFailedTasksTableWidgetData,
xValue,
@@ -213,7 +214,6 @@ function CeleryTaskBar({
mouseX,
mouseY,
data,
queryData,
)
}
customSeries={getCustomSeries}
@@ -222,11 +222,10 @@ function CeleryTaskBar({
{barState === CeleryTaskState.Retry && (
<GridCard
widget={celeryRetryStateFilteredData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
isQueryEnabled={queryEnabled}
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
onGraphClick(
celeryRetryTasksTableWidgetData,
xValue,
@@ -234,7 +233,6 @@ function CeleryTaskBar({
mouseX,
mouseY,
data,
queryData,
)
}
customSeries={getCustomSeries}
@@ -243,11 +241,10 @@ function CeleryTaskBar({
{barState === CeleryTaskState.Successful && (
<GridCard
widget={celerySuccessStateFilteredData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
isQueryEnabled={queryEnabled}
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
onGraphClick(
celerySuccessTasksTableWidgetData,
xValue,
@@ -255,7 +252,6 @@ function CeleryTaskBar({
mouseX,
mouseY,
data,
queryData,
)
}
customSeries={getCustomSeries}

View File

@@ -48,11 +48,15 @@
}
.worker-count-text-container {
--typography-font-size: 2.5vw;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
.celery-task-graph-worker-count-text {
font-size: 2.5vw;
text-align: center;
}
}
.worker-count-header {
@@ -144,12 +148,14 @@
.configure-option-Info-text {
color: var(--l2-foreground);
font-size: 12px;
font-weight: 400;
}
}
.row-panel {
border-radius: 4px;
background: color-mix(in srgb, var(--surface-2) 40%, transparent);
background: color-mix(in srgb, var(--card) 40%, transparent);
padding: 8px;
display: flex;
gap: 6px;
@@ -211,6 +217,7 @@
}
&__label {
font-family: 'Inter';
font-size: 14px;
color: var(--l2-foreground);
line-height: 20px;
@@ -218,7 +225,7 @@
}
&__value {
font-family: var(--code-base-400-font-family);
font-family: 'Geist Mono';
font-size: 24px;
color: var(--l1-foreground);
line-height: 32px;

View File

@@ -1,7 +1,7 @@
import { useCallback, useMemo } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch } from 'react-redux';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
@@ -22,10 +22,7 @@ import {
applyCeleryFilterOnWidgetData,
getFiltersFromQueryParams,
} from '../CeleryUtils';
import {
celeryTimeSeriesTablesWidgetData,
getClickedSeries,
} from './CeleryTaskGraphUtils';
import { celeryTimeSeriesTablesWidgetData } from './CeleryTaskGraphUtils';
function CeleryTaskGraph({
widgetData,
@@ -105,21 +102,13 @@ function CeleryTaskGraph({
widget={applyCeleryTaskFilter ? updatedWidgetData : widgetData}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
onClickHandler={(
xValue,
_yValue,
_mouseX,
_mouseY,
data,
queryData,
): void => {
const clickedSeries = getClickedSeries(data, queryData);
if (!clickedSeries) {
return;
}
const { entity, value } = clickedSeries;
onClickHandler={(xValue, _yValue, _mouseX, _mouseY, data): void => {
const { start, end } = getStartAndEndTimesInMilliseconds(xValue);
// Extract entity and value from data
const [firstDataPoint] = Object.entries(data || {});
const [entity, value] = firstDataPoint || [];
const widgetData = celeryTimeSeriesTablesWidgetData(
entity,
value,
@@ -137,7 +126,7 @@ function CeleryTaskGraph({
isQueryEnabled={queryEnabled}
openTracesButton={openTracesButton}
onOpenTraceBtnClick={onOpenTraceBtnClick}
version={ENTITY_VERSION_V5}
version={ENTITY_VERSION_V4}
customErrorMessage={customErrorMessage}
start={start}
end={end}

View File

@@ -104,16 +104,9 @@ export default function CeleryTaskGraphGrid({
<CardContainer className="row-card" isDarkMode={isDarkMode}>
<div className="row-panel">
<div className="row-panel-section">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
<Typography.Text className="section-title">
Flower Metrics
</Typography>
</Typography.Text>
{collapsedSections.metricBasedGraphs ? (
<ChevronDown
size={14}
@@ -144,31 +137,17 @@ export default function CeleryTaskGraphGrid({
/>
<Card className="celery-task-graph-worker-count">
<div className="worker-count-header">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
<Typography.Text className="worker-count-header-text">
Worker Online
</Typography>
</Typography.Text>
</div>
<div className="worker-count-text-container">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
display="inline-block"
align="center"
textOverflow="wrap"
testId="celery-worker-count"
<Typography.Text
className="celery-task-graph-worker-count-text"
data-testid="celery-worker-count"
>
{workerCount ?? '-'}
</Typography>
</Typography.Text>
</div>
</Card>
</div>
@@ -179,16 +158,9 @@ export default function CeleryTaskGraphGrid({
<CardContainer className="row-card" isDarkMode={isDarkMode}>
<div className="row-panel">
<div className="row-panel-section">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
<Typography.Text className="section-title">
Span Based Stats
</Typography>
</Typography.Text>
{collapsedSections.traceBasedGraphs ? (
<ChevronDown
size={14}
@@ -207,16 +179,9 @@ export default function CeleryTaskGraphGrid({
</CardContainer>
<div className="configure-option-Info">
{configureOptionComponent}
<Typography
variant="paragraph"
size="small"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
<Typography.Text className="configure-option-Info-text">
Click on a graph co-ordinate to see more details
</Typography>
</Typography.Text>
</div>
</div>
{!collapsedSections.traceBasedGraphs && (

View File

@@ -9,11 +9,9 @@ import {
} from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
import { getFiltersFromKeyValue } from 'pages/Celery/CeleryOverview/CeleryOverviewUtils';
import { getWidgetQuery } from 'pages/MessagingQueues/MQDetails/MetricPage/MetricPageUtil';
import { Widgets } from 'types/api/widgets/widget';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 as uuidv4 } from 'uuid';
@@ -42,29 +40,6 @@ export const getStepInterval = (startTime: number, endTime: number): number => {
return 54000; // More than a week (use monthly interval)
};
// v5 returns spans without the group-by key as an empty-label series.
const groupByKeyExists = (key: string): TagFilterItem =>
getFiltersFromKeyValue(key, '', 'tag', 'exists');
const latencyExpression = (type: string): string =>
`${type || 'p99'}(duration_nano)`;
// Without a hovered series, the click data holds only `clickedTimestamp`.
export const getClickedSeries = (
data?: Record<string, string>,
queryData?: { inFocusOrNot: boolean },
): { entity: string; value: string } | undefined => {
const series = Object.entries(data || {}).find(
([key]) => key !== 'clickedTimestamp',
);
if (!queryData?.inFocusOrNot || !series) {
return undefined;
}
const [entity, value] = series;
return { entity, value };
};
// State Graphs
export const celeryAllStateWidgetData = (
startTime: number,
@@ -81,12 +56,11 @@ export const celeryAllStateWidgetData = (
type: '',
},
aggregateOperator: 'count',
aggregations: [{ expression: 'count()' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [groupByKeyExists('celery.state')],
items: [],
op: 'AND',
},
functions: [],
@@ -134,13 +108,11 @@ export const celeryRetryStateWidgetData = (
type: '',
},
aggregateOperator: 'count',
aggregations: [{ expression: 'count()' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.hostname'),
{
id: uuidv4(),
key: {
@@ -196,13 +168,11 @@ export const celeryFailedStateWidgetData = (
type: '',
},
aggregateOperator: 'count',
aggregations: [{ expression: 'count()' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.hostname'),
{
id: uuidv4(),
key: {
@@ -258,13 +228,11 @@ export const celerySuccessStateWidgetData = (
type: '',
},
aggregateOperator: 'count',
aggregations: [{ expression: 'count()' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.hostname'),
{
id: uuidv4(),
key: {
@@ -319,12 +287,11 @@ export const celeryTasksByWorkerWidgetData = (
type: '',
},
aggregateOperator: 'rate',
aggregations: [{ expression: 'rate()' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [groupByKeyExists('celery.hostname')],
items: [],
op: 'AND',
},
functions: [],
@@ -364,9 +331,8 @@ export const celeryErrorByWorkerWidgetData = (
dataSource: DataSource.TRACES,
queryName: 'A',
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
aggregateAttribute: {
dataType: DataTypes.String,
dataType: 'string',
id: 'span_id--string----true',
key: 'span_id',
type: '',
@@ -376,7 +342,6 @@ export const celeryErrorByWorkerWidgetData = (
functions: [],
filters: {
items: [
groupByKeyExists('celery.hostname'),
{
id: uuidv4(),
key: {
@@ -409,12 +374,11 @@ export const celeryErrorByWorkerWidgetData = (
reduceTo: ReduceOperators.AVG,
},
{
dataSource: DataSource.TRACES,
dataSource: 'traces',
queryName: 'B',
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
aggregateAttribute: {
dataType: DataTypes.String,
dataType: 'string',
id: 'span_id--string----true',
key: 'span_id',
type: '',
@@ -423,7 +387,7 @@ export const celeryErrorByWorkerWidgetData = (
spaceAggregation: 'sum',
functions: [],
filters: {
items: [groupByKeyExists('celery.hostname')],
items: [],
op: 'AND',
},
expression: 'B',
@@ -443,14 +407,12 @@ export const celeryErrorByWorkerWidgetData = (
legend: '',
reduceTo: ReduceOperators.AVG,
},
],
queryFormulas: [
{
queryName: 'F1',
expression: '(A/B)*100',
disabled: false,
legend: '{{celery.hostname}}',
},
} as any,
],
yAxisUnit: 'percent',
}),
@@ -473,12 +435,11 @@ export const celeryLatencyByWorkerWidgetData = (
type: '',
},
aggregateOperator: 'p99',
aggregations: [{ expression: 'p99(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [groupByKeyExists('celery.hostname')],
items: [],
op: 'AND',
},
functions: [],
@@ -571,12 +532,11 @@ export const celeryTaskLatencyWidgetData = (
type: '',
},
aggregateOperator: type || 'p99',
aggregations: [{ expression: latencyExpression(type) }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [groupByKeyExists('celery.task_name')],
items: [],
op: 'AND',
},
functions: [],
@@ -593,7 +553,7 @@ export const celeryTaskLatencyWidgetData = (
limit: null,
orderBy: [
{
columnName: latencyExpression(type),
columnName: '#SIGNOZ_VALUE',
order: 'asc',
},
],
@@ -623,12 +583,11 @@ export const celerySlowestTasksTableWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'avg',
aggregations: [{ expression: 'avg(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [groupByKeyExists('celery.task_name')],
items: [],
op: 'AND',
},
functions: [],
@@ -645,7 +604,7 @@ export const celerySlowestTasksTableWidgetData = getWidgetQueryBuilder(
limit: 10,
orderBy: [
{
columnName: 'avg(duration_nano)',
columnName: '#SIGNOZ_VALUE',
order: 'desc',
},
],
@@ -674,13 +633,11 @@ export const celeryRetryTasksTableWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'avg',
aggregations: [{ expression: 'avg(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.task_name'),
{
id: uuidv4(),
key: {
@@ -709,7 +666,7 @@ export const celeryRetryTasksTableWidgetData = getWidgetQueryBuilder(
limit: 10,
orderBy: [
{
columnName: 'avg(duration_nano)',
columnName: '#SIGNOZ_VALUE',
order: 'desc',
},
],
@@ -739,13 +696,11 @@ export const celeryFailedTasksTableWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'avg',
aggregations: [{ expression: 'avg(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.task_name'),
{
id: uuidv4(),
key: {
@@ -774,7 +729,7 @@ export const celeryFailedTasksTableWidgetData = getWidgetQueryBuilder(
limit: null,
orderBy: [
{
columnName: 'avg(duration_nano)',
columnName: '#SIGNOZ_VALUE',
order: 'desc',
},
],
@@ -802,13 +757,11 @@ export const celerySuccessTasksTableWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'avg',
aggregations: [{ expression: 'avg(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.task_name'),
{
id: uuidv4(),
key: {
@@ -837,7 +790,7 @@ export const celerySuccessTasksTableWidgetData = getWidgetQueryBuilder(
limit: null,
orderBy: [
{
columnName: 'avg(duration_nano)',
columnName: '#SIGNOZ_VALUE',
order: 'desc',
},
],
@@ -871,13 +824,11 @@ export const celeryTimeSeriesTablesWidgetData = (
type: '',
},
aggregateOperator: 'avg',
aggregations: [{ expression: 'avg(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.task_name'),
{
id: uuidv4(),
key: {
@@ -931,7 +882,6 @@ export const celeryAllStateCountWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
@@ -969,7 +919,6 @@ export const celerySuccessStateCountWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
@@ -1019,7 +968,6 @@ export const celeryFailedStateCountWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
@@ -1069,7 +1017,6 @@ export const celeryRetryStateCountWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',

View File

@@ -1,15 +1,13 @@
import { useCallback, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import { Col, Row } from 'antd';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import logEvent from 'api/common/logEvent';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { ViewMenuAction } from 'container/WidgetCard/config';
import { ENTITY_VERSION_V5 } from 'constants/app';
import GridCard from 'container/WidgetCard/Card';
import { Card } from 'container/WidgetCard/styles';
import { Button } from 'container/MetricsApplication/Tabs/styles';
@@ -29,10 +27,7 @@ import {
getFiltersFromQueryParams,
} from '../CeleryUtils';
import { useNavigateToExplorer } from '../useNavigateToExplorer';
import {
celeryTaskLatencyWidgetData,
getClickedSeries,
} from './CeleryTaskGraphUtils';
import { celeryTaskLatencyWidgetData } from './CeleryTaskGraphUtils';
import './CeleryTaskGraph.style.scss';
@@ -133,12 +128,13 @@ function CeleryTaskLatencyGraph({
const onGraphClick = useCallback(
(type: string): OnClickPluginOpts['onClick'] =>
(xValue, yValue, mouseX, mouseY, data, queryData): Promise<void> => {
const clickedSeries = getClickedSeries(data, queryData);
if (!clickedSeries) {
return Promise.resolve();
}
setEntityData(clickedSeries);
(xValue, yValue, mouseX, mouseY, data): Promise<void> => {
const [firstDataPoint] = Object.entries(data || {});
const [entity, value] = firstDataPoint;
setEntityData({
entity,
value,
});
return onGraphClickHandler(xValue, yValue, mouseX, mouseY, type);
},
@@ -202,7 +198,6 @@ function CeleryTaskLatencyGraph({
</Button>
<GridCard
widget={updatedWidgetData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
onClickHandler={onGraphClick('Celery_p99_latency')}
@@ -224,7 +219,6 @@ function CeleryTaskLatencyGraph({
</Button>
<GridCard
widget={updatedWidgetData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
onClickHandler={onGraphClick('Celery_p95_latency')}
@@ -245,7 +239,6 @@ function CeleryTaskLatencyGraph({
</Button>
<GridCard
widget={updatedWidgetData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
onClickHandler={onGraphClick('Celery_p90_latency')}

View File

@@ -1,6 +1,5 @@
import { Dispatch, SetStateAction, useMemo } from 'react';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import { Col, Row } from 'antd';
import logEvent from 'api/common/logEvent';
import { QueryParams } from 'constants/query';
import useUrlQuery from 'hooks/useUrlQuery';
@@ -90,10 +89,7 @@ function CeleryTaskStateGraphConfig({
>
<div className="celery-task-states__label-wrapper">
<div className="celery-task-states__label">{tab.label}</div>
<div
className="celery-task-states__value"
data-testid={`celery-state-value-${tab.key}`}
>
<div className="celery-task-states__value">
{isLoading
? '-'
: isError

View File

@@ -61,13 +61,7 @@ describe('CeleryTaskGraphGrid worker count', () => {
);
const { minTime, maxTime } = store.getState().globalTime;
expect(
requests.filter((request) =>
request.compositeQuery?.queries?.some(
(query) => (query.spec as { signal?: string }).signal === 'metrics',
),
),
).toStrictEqual([
expect(requests).toStrictEqual([
{
schemaVersion: 'v1',
start: Math.floor(minTime / 1e6),

View File

@@ -1,92 +0,0 @@
import {
Querybuildertypesv5ColumnTypeDTO,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
type Querybuildertypesv5QueryRangeRequestDTO,
Querybuildertypesv5RequestTypeDTO,
type QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import { render, screen, waitFor } from 'tests/test-utils';
import {
CeleryTaskState,
CeleryTaskStateGraphConfig,
} from '../CeleryTaskStateGraphConfig';
const COUNT_PER_STATE: Record<string, number> = {
FAILURE: 12,
RETRY: 30,
SUCCESS: 958,
};
const stateOf = (body: Querybuildertypesv5QueryRangeRequestDTO): string => {
const [envelope] = body.compositeQuery?.queries ?? [];
const expression =
envelope?.type ===
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query
? (envelope.spec?.filter?.expression ?? '')
: '';
return /celery\.state = '(\w+)'/.exec(expression)?.[1] ?? '';
};
const scalarResponse = (value: number): QueryRangeV5200 => ({
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.scalar,
data: {
results: [
{
columns: [
{
name: '__result_0',
queryName: 'A',
aggregationIndex: 0,
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
},
],
data: [[value]],
},
],
},
},
});
describe('CeleryTaskStateGraphConfig', () => {
beforeEach(() => {
server.use(
rest.post('*/api/v5/query_range', async (req, res, ctx) => {
const body: Querybuildertypesv5QueryRangeRequestDTO = await req.json();
return res(
ctx.status(200),
ctx.json(scalarResponse(COUNT_PER_STATE[stateOf(body)] ?? 1000)),
);
}),
);
});
it('shows the v5 count for each task state', async () => {
render(
<CeleryTaskStateGraphConfig
barState={CeleryTaskState.All}
setBarState={jest.fn()}
/>,
);
await waitFor(() =>
expect(screen.getByTestId('celery-state-value-all')).toHaveTextContent(
'1000',
),
);
expect(screen.getByTestId('celery-state-value-failed')).toHaveTextContent(
'12',
);
expect(screen.getByTestId('celery-state-value-retry')).toHaveTextContent(
'30',
);
expect(screen.getByTestId('celery-state-value-successful')).toHaveTextContent(
'958',
);
});
});

View File

@@ -1,136 +0,0 @@
import { prepareQueryRangePayloadV5 } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { celeryOverviewErrorRateGraphData } from 'pages/Celery/CeleryOverview/CeleryOverviewGraphUtils';
import { Widgets } from 'types/api/widgets/widget';
import {
celeryAllStateWidgetData,
celeryErrorByWorkerWidgetData,
celeryLatencyByWorkerWidgetData,
celerySlowestTasksTableWidgetData,
celeryTaskLatencyWidgetData,
celeryTasksByWorkerWidgetData,
} from '../CeleryTaskGraphUtils';
const START = 1_700_000_000_000_000_000;
const END = START + 3_600_000_000_000;
const v5Queries = (
widget: Widgets,
): ReturnType<
typeof prepareQueryRangePayloadV5
>['queryPayload']['compositeQuery']['queries'] =>
prepareQueryRangePayloadV5({
query: widget.query,
graphType: PANEL_TYPES.TIME_SERIES,
selectedTime: 'GLOBAL_TIME',
start: 1_700_000_000,
end: 1_700_003_600,
}).queryPayload.compositeQuery.queries;
const builderQuery = (
name: string,
expression: string,
): ReturnType<typeof expect.objectContaining> =>
expect.objectContaining({
type: 'builder_query',
spec: expect.objectContaining({
name,
signal: 'traces',
aggregations: [{ expression }],
}),
});
const formula = (
name: string,
expression: string,
): ReturnType<typeof expect.objectContaining> =>
expect.objectContaining({
type: 'builder_formula',
spec: expect.objectContaining({ name, expression }),
});
describe('Celery widgets on query_range v5', () => {
it.each([
['tasks by worker', celeryTasksByWorkerWidgetData(START, END), 'rate()'],
[
'latency by worker',
celeryLatencyByWorkerWidgetData(START, END),
'p99(duration_nano)',
],
[
'task latency tab',
celeryTaskLatencyWidgetData('p95', START, END),
'p95(duration_nano)',
],
])('%s sends its own aggregation', (_name, widget, expression) => {
expect(v5Queries(widget)).toStrictEqual([builderQuery('A', expression)]);
});
it.each([
[
'task latency tab',
celeryTaskLatencyWidgetData('p95', START, END),
'p95(duration_nano)',
'asc',
],
[
'slowest tasks table',
celerySlowestTasksTableWidgetData,
'avg(duration_nano)',
'desc',
],
])('%s orders by its aggregation', (_name, widget, name, direction) => {
expect(v5Queries(widget)).toStrictEqual([
expect.objectContaining({
spec: expect.objectContaining({
order: [{ key: { name }, direction }],
}),
}),
]);
});
it.each([
[
'all states bar',
celeryAllStateWidgetData(START, END),
'celery.state exists',
],
[
'tasks by worker',
celeryTasksByWorkerWidgetData(START, END),
'celery.hostname exists',
],
[
'task latency tab',
celeryTaskLatencyWidgetData('p95', START, END),
'celery.task_name exists',
],
])('%s drops spans without its group-by key', (_name, widget, expression) => {
expect(v5Queries(widget)).toStrictEqual([
expect.objectContaining({
spec: expect.objectContaining({ filter: { expression } }),
}),
]);
});
it('error % by worker sends its formula as a formula', () => {
expect(v5Queries(celeryErrorByWorkerWidgetData(START, END))).toStrictEqual([
builderQuery('A', 'count_distinct(span_id)'),
builderQuery('B', 'count_distinct(span_id)'),
formula('F1', '(A/B)*100'),
]);
});
it('overview error rate sends both formulas as formulas', () => {
expect(v5Queries(celeryOverviewErrorRateGraphData(START, END))).toStrictEqual(
[
builderQuery('A', 'count_distinct(span_id)'),
builderQuery('B', 'count_distinct(span_id)'),
builderQuery('C', 'count_distinct(span_id)'),
formula('F1', '(A/C)*100'),
formula('F2', '(B/C)*100'),
],
);
});
});

View File

@@ -1,27 +0,0 @@
import { getClickedSeries } from '../CeleryTaskGraphUtils';
const focused = { queryName: 'A', inFocusOrNot: true };
const unfocused = { queryName: '', inFocusOrNot: false };
describe('getClickedSeries', () => {
it('returns the clicked series label', () => {
expect(
getClickedSeries(
{ 'celery.state': 'RETRY', clickedTimestamp: '1700000000' },
focused,
),
).toStrictEqual({ entity: 'celery.state', value: 'RETRY' });
});
it('ignores a click outside any series', () => {
expect(
getClickedSeries({ clickedTimestamp: '1700000000' }, unfocused),
).toBeUndefined();
});
it('ignores a series that has no label', () => {
expect(
getClickedSeries({ clickedTimestamp: '1700000000' }, focused),
).toBeUndefined();
});
});

View File

@@ -2,13 +2,10 @@ import { useCallback } from 'react';
import { useQueries } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
import {
getQueryPayloadFromWidgetsData,
getValueFromScalarResponse,
} from 'pages/Celery/CeleryOverview/CeleryOverviewUtils';
import { getQueryPayloadFromWidgetsData } from 'pages/Celery/CeleryOverview/CeleryOverviewUtils';
import { AppState } from 'store/reducers';
import { SuccessResponse } from 'types/api';
import { Widgets } from 'types/api/widgets/widget';
@@ -42,9 +39,9 @@ export const useGetValueFromWidget = (
const queries = useQueries(
queryPayloads().map((payload) => ({
queryKey: [...queryKey, payload, ENTITY_VERSION_V5],
queryKey: [...queryKey, payload, ENTITY_VERSION_V4],
queryFn: (): Promise<SuccessResponse<MetricRangePayloadProps>> =>
GetMetricQueryRange(payload, ENTITY_VERSION_V5),
GetMetricQueryRange(payload, ENTITY_VERSION_V4),
enabled: !!payload,
})),
);
@@ -60,7 +57,11 @@ export const useGetValueFromWidget = (
return 'Error';
}
return getValueFromScalarResponse(query.data);
const value = parseFloat(
query.data?.payload?.data?.newResult?.data?.result?.[0]?.series?.[0]
?.values?.[0]?.value || 'NaN',
);
return Number.isNaN(value) ? 'NaN' : value.toFixed(2);
});
return { values, isLoading, isError };

View File

@@ -11,7 +11,9 @@
justify-content: center;
}
&__label {
font-family: var(--code-base-400-font-family);
font-family: 'Geist Mono';
font-size: 12px;
line-height: normal;
}
&--positive {
.change-percentage-pill {

View File

@@ -1,8 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useMutation } from 'react-query';
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
import { Button, Modal } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Button, Flex, Modal } from 'antd';
import updateUserPreference from 'api/v1/user/preferences/name/update';
import cx from 'classnames';
import { USER_PREFERENCES } from 'constants/userPreferences';
@@ -98,10 +97,6 @@ function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
}
};
// TODO: antd stacks at 1000, under `@signozhq/ui` dialogs (1001). It opens on
// its own a second after load, so a dialog opened from a deep link
// (`?add-key`, `?invite=true`) covers it. Moving to the `@signozhq/ui` Dialog
// fixes it.
return (
<Modal
className={cx('changelog-modal')}

View File

@@ -1,29 +0,0 @@
import type { ComponentProps } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { fn } from 'storybook/test';
import type { GlobalMockArgs } from '@/storybook/globals';
import ChangelogModal from '../ChangelogModal';
import { changelog } from './__story_mockdata__/changelog';
type ChangelogModalArgs = ComponentProps<typeof ChangelogModal> &
GlobalMockArgs;
const meta = {
title: 'Components/Changelog Modal',
component: ChangelogModal,
args: { changelog, onClose: fn() },
} satisfies Meta<ChangelogModalArgs>;
export default meta;
type Story = StoryObj<ChangelogModalArgs>;
/** A cloud workspace: no upgrade actions, since cloud updates itself. */
export const Default: Story = {};
/** A self-hosted workspace, offered Skip for now and Update my workspace. */
export const SelfHosted: Story = {
args: { license: 'enterprise' },
};

View File

@@ -1,65 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import {
ChangelogSchema,
DeploymentType,
} from 'types/api/changelog/getChangelogByVersion';
const PUBLISHED_AT = '2026-08-12T09:00:00.000Z';
const feature = (
id: number,
title: string,
description: string,
): ChangelogSchema['features'][number] => ({
id,
documentId: `feature-${id}`,
title,
sort_order: id,
createdAt: PUBLISHED_AT,
updatedAt: PUBLISHED_AT,
publishedAt: PUBLISHED_AT,
description,
deployment_type: DeploymentType.ALL,
// Media stays null so no story reaches out to the CMS for an image.
media: null,
});
export const changelog: ChangelogSchema = {
id: 1,
documentId: 'changelog-v0-99-0',
version: 'v0.99.0',
release_date: '2026-08-12',
createdAt: PUBLISHED_AT,
updatedAt: PUBLISHED_AT,
publishedAt: PUBLISHED_AT,
features: [
feature(
1,
'Metrics explorer',
'Browse every metric you send, inspect its labels and turn it into a panel without writing a query.\n\n- Search metrics by name, type or unit\n- See cardinality per label before you group by it\n- Open any metric straight in the query builder\n\nRead more in the [metrics explorer docs](https://signoz.io/docs/metrics-management/metrics-explorer/).',
),
feature(
2,
'Trace funnels',
'Measure conversion and drop-off across a multi-service request path. Define each step as a span filter, then compare the latency and error rate between any two steps.',
),
feature(
3,
'Saved views for logs',
'Save a logs query with its columns and time range, share it with your team and pin the ones you open most.',
),
feature(
4,
'Alert history',
'Every alert now keeps a timeline of its state changes, with the value that crossed the threshold and the labels it fired for.',
),
],
bug_fixes:
'- Fixed dashboard variables losing their selection on refresh.\n- Fixed alert history pagination skipping a page.\n- Fixed the logs list jumping to the top after a live tail update.',
maintenance:
'- Upgraded the query service to Go 1.24.\n- Reduced the ClickHouse memory used by trace aggregation queries.',
};

View File

@@ -17,6 +17,10 @@
color: var(--l2-foreground);
/* Bifrost (Ancient)/Content/sm */
font-family: Inter;
font-size: 13px;
font-style: normal;
font-weight: 400;
line-height: 20px; /* 142.857% */
letter-spacing: -0.07px;

View File

@@ -17,13 +17,13 @@
pre {
color: var(--l2-foreground) !important;
font-family: var(--code-small-400-font-family) !important;
font-family: 'Geist Mono' !important;
font-size: 12px !important;
}
code {
color: var(--l1-foreground) !important;
font-family: var(--code-small-400-font-family) !important;
font-family: 'Geist Mono' !important;
font-size: 12px !important;
}
}

View File

@@ -1,3 +1,36 @@
.create-sa-modal {
max-width: 530px;
background: var(--popover);
border: 1px solid var(--secondary);
border-radius: 4px;
box-shadow: 0 4px 9px 0 rgba(0, 0, 0, 0.04);
[data-slot='dialog-header'] {
padding: var(--padding-4);
border-bottom: 1px solid var(--secondary);
flex-shrink: 0;
background: transparent;
margin: 0;
}
[data-slot='dialog-title'] {
font-size: var(--label-base-400-font-size);
font-weight: var(--label-base-400-font-weight);
line-height: var(--label-base-400-line-height);
letter-spacing: -0.065px;
color: var(--l1-foreground);
margin: 0;
}
[data-slot='dialog-description'] {
padding: 0;
.create-sa-modal__content {
padding: var(--padding-4);
}
}
}
.create-sa-form {
display: flex;
flex-direction: column;
@@ -10,11 +43,32 @@
margin-bottom: var(--spacing-4);
> label {
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
color: var(--foreground);
letter-spacing: -0.07px;
}
}
&__input {
height: 32px;
color: var(--l1-foreground);
background-color: var(--l2-background);
border-color: var(--l1-border);
font-size: var(--paragraph-base-400-font-size);
border-radius: 2px;
width: 100%;
&::placeholder {
color: var(--l3-foreground);
}
&:focus {
border-color: var(--primary);
box-shadow: none;
}
}
&__error {
font-size: var(--paragraph-small-400-font-size);
color: var(--destructive);
@@ -23,7 +77,22 @@
}
&__helper {
font-size: var(--paragraph-small-400-font-size);
color: var(--l3-foreground);
margin: calc(var(--spacing-2) * -1) 0 var(--spacing-4) 0;
line-height: var(--paragraph-small-400-line-height);
}
}
.create-sa-modal__footer {
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-end;
padding: 0 var(--padding-4);
height: 56px;
min-height: 56px;
border-top: 1px solid var(--secondary);
gap: var(--spacing-4);
flex-shrink: 0;
}

View File

@@ -5,9 +5,9 @@ import { Button } from '@signozhq/ui/button';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
import { SACreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/service-account.permissions';
import { Dialog } from '@signozhq/ui/dialog';
import { DialogFooter, DialogWrapper } from '@signozhq/ui/dialog';
import { Input } from '@signozhq/ui/input';
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import {
invalidateListServiceAccounts,
@@ -35,7 +35,7 @@ function CreateServiceAccountModal(): JSX.Element {
);
const [, setSelectedAccountId] = useQueryState(SA_QUERY_PARAMS.ACCOUNT);
const { showErrorModal } = useErrorModal();
const { showErrorModal, isErrorModalVisible } = useErrorModal();
const {
control,
@@ -82,75 +82,84 @@ function CreateServiceAccountModal(): JSX.Element {
}
return (
<Dialog
<DialogWrapper
title="New Service Account"
open={isOpen}
onClose={handleClose}
width="base"
onOpenChange={(open): void => {
if (!open) {
handleClose();
}
}}
showCloseButton
width="narrow"
className="create-sa-modal"
disableOutsideClick={isErrorModalVisible}
testId="create-service-account-modal"
footerSuffix={
<>
<Button
size="md"
type="button"
variant="solid"
color="secondary"
onClick={handleClose}
testId="create-sa-cancel-btn"
prefix={<X size={12} />}
>
Cancel
</Button>
<AuthZButton
size="md"
checks={[SACreatePermission]}
type="submit"
form="create-sa-form"
variant="solid"
color="primary"
loading={isSubmitting}
disabled={!isValid}
testId="create-sa-submit-btn"
>
Create Service Account
</AuthZButton>
</>
}
>
<AuthZGuardContent
checks={[SACreatePermission]}
fallbackOnLoading={<Skeleton active paragraph={{ rows: 1 }} />}
>
<form
id="create-sa-form"
className="create-sa-form"
onSubmit={handleSubmit(handleCreate)}
<div className="create-sa-modal__content">
<AuthZGuardContent
checks={[SACreatePermission]}
fallbackOnLoading={<Skeleton active paragraph={{ rows: 1 }} />}
>
<div className="create-sa-form__item">
<label htmlFor="sa-name">Name</label>
<Controller
name="name"
control={control}
rules={{ required: 'Name is required' }}
render={({ field }): JSX.Element => (
<Input
id="sa-name"
placeholder="Enter a name"
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
testId="create-sa-name-input"
/>
<form
id="create-sa-form"
className="create-sa-form"
onSubmit={handleSubmit(handleCreate)}
>
<div className="create-sa-form__item">
<label htmlFor="sa-name">Name</label>
<Controller
name="name"
control={control}
rules={{ required: 'Name is required' }}
render={({ field }): JSX.Element => (
<Input
id="sa-name"
placeholder="Enter a name"
className="create-sa-form__input"
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
data-testid="create-sa-name-input"
/>
)}
/>
{errors.name && (
<p className="create-sa-form__error">{errors.name.message}</p>
)}
/>
{errors.name && (
<p className="create-sa-form__error">{errors.name.message}</p>
)}
</div>
</form>
</AuthZGuardContent>
</Dialog>
</div>
</form>
</AuthZGuardContent>
</div>
<DialogFooter className="create-sa-modal__footer">
<Button
size="md"
type="button"
variant="solid"
color="secondary"
onClick={handleClose}
testId="create-sa-cancel-btn"
prefix={<X size={12} />}
>
Cancel
</Button>
<AuthZButton
size="md"
checks={[SACreatePermission]}
type="submit"
form="create-sa-form"
variant="solid"
color="primary"
loading={isSubmitting}
disabled={!isValid}
testId="create-sa-submit-btn"
>
Create Service Account
</AuthZButton>
</DialogFooter>
</DialogWrapper>
);
}

View File

@@ -1,4 +1,4 @@
import { toast } from '@signozhq/ui/toast';
import { toast } from '@signozhq/ui/sonner';
import {
setupAuthzAdmin,
setupAuthzDenyAll,
@@ -10,9 +10,9 @@ import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import CreateServiceAccountModal from '../CreateServiceAccountModal';
jest.mock('@signozhq/ui/toast', () => ({
...jest.requireActual('@signozhq/ui/toast'),
toast: { success: jest.fn(), danger: jest.fn() },
jest.mock('@signozhq/ui/sonner', () => ({
...jest.requireActual('@signozhq/ui/sonner'),
toast: { success: jest.fn(), error: jest.fn() },
}));
const mockToast = jest.mocked(toast);
@@ -23,6 +23,7 @@ jest.mock('providers/ErrorModalProvider', () => ({
...jest.requireActual('providers/ErrorModalProvider'),
useErrorModal: jest.fn(() => ({
showErrorModal,
isErrorModalVisible: false,
})),
}));
@@ -57,7 +58,7 @@ describe('CreateServiceAccountModal', () => {
// The form only renders once the create check resolves, and the name field
// registers its `required` rule on mount, so the empty-form invalid state
// settles a tick later.
await screen.findByTestId('create-sa-name-input-field');
await screen.findByTestId('create-sa-name-input');
await waitFor(() =>
expect(screen.getByTestId('create-sa-submit-btn')).toHaveAttribute(
@@ -71,7 +72,7 @@ describe('CreateServiceAccountModal', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
const nameInput = await screen.findByTestId('create-sa-name-input');
const submitBtn = await screen.findByTestId('create-sa-submit-btn');
await user.type(nameInput, 'test');
@@ -89,7 +90,7 @@ describe('CreateServiceAccountModal', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
const nameInput = await screen.findByTestId('create-sa-name-input');
await user.type(nameInput, 'Deploy Bot');
const submitBtn = screen.getByTestId('create-sa-submit-btn');
@@ -127,7 +128,7 @@ describe('CreateServiceAccountModal', () => {
renderModal();
const nameInput = await screen.findByTestId<HTMLInputElement>(
'create-sa-name-input-field',
'create-sa-name-input',
);
await user.type(nameInput, 'Deploy Bot');
const submitBtn = screen.getByTestId('create-sa-submit-btn');
@@ -159,7 +160,7 @@ describe('CreateServiceAccountModal', () => {
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
const nameInput = await screen.findByTestId('create-sa-name-input');
await user.type(nameInput, 'Dupe Bot');
const submitBtn = screen.getByTestId('create-sa-submit-btn');
@@ -208,9 +209,7 @@ describe('CreateServiceAccountModal', () => {
screen.findByText(/is not authorized to perform/i),
).resolves.toBeInTheDocument();
expect(
screen.queryByTestId('create-sa-name-input-field'),
).not.toBeInTheDocument();
expect(screen.queryByTestId('create-sa-name-input')).not.toBeInTheDocument();
expect(
screen.getByTestId('create-service-account-modal'),
).toBeInTheDocument();
@@ -245,7 +244,7 @@ describe('CreateServiceAccountModal', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
const nameInput = await screen.findByTestId('create-sa-name-input');
await user.type(nameInput, 'Bot');
await user.clear(nameInput);

View File

@@ -65,6 +65,8 @@
.valid-format-error {
margin-top: 4px;
color: var(--bg-cherry-400) !important;
font-size: 13px !important;
font-weight: 400 !important;
}
.info-text {
@@ -74,6 +76,11 @@
padding: 4px;
cursor: default;
color: var(--l2-foreground) !important;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: normal;
letter-spacing: 0.14px;
}
.info-text:hover {
@@ -97,11 +104,15 @@
gap: 6px;
.timezone__name {
font-size: 12px;
line-height: 16px;
color: var(--bg-robin-400);
font-weight: 500;
}
.timezone__separator {
font-size: 12px;
line-height: 16px;
color: var(--bg-robin-300);
font-weight: 500;
}
@@ -217,6 +228,10 @@
border-radius: 2px;
background: color-mix(in srgb, var(--bg-robin-200) 4%, transparent);
color: var(--l1-foreground);
font-size: 12px;
font-weight: 400;
line-height: 16px;
letter-spacing: -0.06px;
cursor: pointer;
height: 20px;
width: 20px;

View File

@@ -531,7 +531,7 @@ function CustomTimePicker({
// Use setTimeout to wait for React to update the DOM and make input editable
setTimeout(() => {
const inputElement = inputRef.current?.input;
if (inputElement && !document.activeElement?.closest('.timezone-picker')) {
if (inputElement) {
inputElement.focus();
inputElement.select();
}

View File

@@ -21,6 +21,7 @@ $item-spacing: 8px;
.timezone-picker {
width: 532px;
color: var(--l2-foreground);
font-family: $font-family;
&__search {
@include flex-center;
@@ -33,8 +34,34 @@ $item-spacing: 8px;
@include flex-center;
gap: 6px;
width: -webkit-fill-available;
}
--input-hover-border-color: transparent;
&__input {
@include text-style-base;
width: 100%;
background: transparent;
border: none;
border-radius: 0;
box-shadow: none;
outline: none;
height: auto;
color: var(--l1-foreground);
font-size: 14px;
line-height: 20px;
letter-spacing: -0.07px;
padding: 0;
&:focus,
&:focus-visible,
&:hover {
border: none;
box-shadow: none;
outline: none;
}
&::placeholder {
color: var(--l2-foreground);
}
}
&__esc-key {

View File

@@ -65,8 +65,7 @@ function SearchBar({
/>
<Input
type="text"
variant="unstyled"
noFocusRing
className="timezone-picker__input"
placeholder="Search timezones..."
value={value}
onChange={(e): void => onChange(e.target.value)}

View File

@@ -12,4 +12,5 @@
.name {
color: var(--danger-background);
font-weight: var(--font-weight-medium);
}

View File

@@ -1,4 +1,7 @@
.details-header {
// ghost + secondary missing hover bg token in @signozhq/button
--button-ghost-hover-background: var(--l3-background);
box-sizing: border-box;
display: flex;
align-items: center;
@@ -9,6 +12,7 @@
background: var(--l2-background);
&__title {
font-size: 13px;
font-weight: 500;
color: var(--l1-foreground);
flex: 1;

View File

@@ -0,0 +1,17 @@
.drawer {
overflow: hidden;
border-color: var(--l2-border);
background: var(--l2-background);
box-shadow: -4px 10px 16px 2px var(--l1-shadow);
&:focus,
&:focus-visible {
outline: none;
}
}
.body {
display: flex;
flex-direction: column;
height: 100%;
}

View File

@@ -1,46 +1,56 @@
import { ReactNode } from 'react';
import { Drawer } from '@signozhq/ui/drawer';
import { Drawer, DrawerContent } from '@signozhq/ui/drawer';
import cx from 'classnames';
import { AnimatePresence } from 'motion/react';
import styles from './DetailsPanelDrawer.module.scss';
interface DetailsPanelDrawerProps {
isOpen: boolean;
onClose: () => void;
title: string;
children: ReactNode;
headerSuffix?: ReactNode;
loading?: boolean;
children: React.ReactNode;
className?: string;
testId?: string;
}
function DetailsPanelDrawer({
isOpen,
onClose,
title,
children,
headerSuffix,
loading,
className,
testId,
}: DetailsPanelDrawerProps): JSX.Element {
return (
<Drawer
type="inspector"
stack="overlay"
open={isOpen}
onClose={onClose}
title={title}
width="extra-wide"
closePosition="start"
headerSuffix={headerSuffix}
loading={loading}
testId={testId}
onOpenChange={(open): void => {
if (!open) {
onClose();
}
}}
modal={false}
>
{children}
<AnimatePresence>
{isOpen && (
<DrawerContent
forceMount
direction="right"
width="extra-wide"
showOverlay={false}
// Outside presses are left to the page, which knows what counts as inside.
onInteractOutside={(e): void => e.preventDefault()}
className={cx(styles.drawer, className)}
testId={testId}
>
<div className={styles.body}>{children}</div>
</DrawerContent>
)}
</AnimatePresence>
</Drawer>
);
}
DetailsPanelDrawer.defaultProps = {
headerSuffix: undefined,
loading: false,
className: undefined,
testId: undefined,
};

View File

@@ -1,28 +0,0 @@
.dotGrid {
position: relative;
}
.canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
// Read by the snake as its colour on the light page.
color: var(--l1-foreground);
}
// The Snake score line, faint in the grid's bottom-left corner.
.label {
position: absolute;
left: var(--spacing-6);
bottom: var(--spacing-1);
font-family: var(--code-small-400-font-family);
font-size: var(--paragraph-small-400-font-size);
letter-spacing: 0.34em;
text-transform: uppercase;
white-space: nowrap;
color: var(--l3-foreground);
pointer-events: none;
user-select: none;
}

View File

@@ -1,35 +0,0 @@
import { useRef } from 'react';
import cx from 'classnames';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useDotGrid } from './useDotGrid';
import styles from './DotGrid.module.scss';
interface DotGridProps {
/** Sizes and places the grid; it fills whatever box it gets. */
className?: string;
/** Called when a Snake game starts or ends. */
onGameChange?: (isPlaying: boolean) => void;
}
/** Aurora dot grid that drifts on its own and lights up under the cursor. */
export default function DotGrid({
className,
onGameChange,
}: DotGridProps): JSX.Element {
const canvasRef = useRef<HTMLCanvasElement>(null);
const isDarkMode = useIsDarkMode();
const label = useDotGrid(canvasRef, isDarkMode, onGameChange);
return (
<div
className={cx(styles.dotGrid, className)}
data-testid="ai-dot-grid"
aria-hidden
>
<canvas ref={canvasRef} className={styles.canvas} />
{label && <span className={styles.label}>{label}</span>}
</div>
);
}

View File

@@ -1,103 +0,0 @@
import { useRef } from 'react';
import { act, render, screen, userEvent } from 'tests/test-utils';
import DotGrid from '../DotGrid';
import { useDotGrid } from '../useDotGrid';
const KONAMI =
'{ArrowUp}{ArrowUp}{ArrowDown}{ArrowDown}{ArrowLeft}{ArrowRight}{ArrowLeft}{ArrowRight}ba';
function Chat({
onGameChange,
}: {
onGameChange: (isPlaying: boolean) => void;
}): JSX.Element {
return (
<div>
<DotGrid onGameChange={onGameChange} />
<textarea data-testid="chat-textarea" />
</div>
);
}
function ThemedGrid({ isDarkMode }: { isDarkMode: boolean }): JSX.Element {
const canvasRef = useRef<HTMLCanvasElement>(null);
const label = useDotGrid(canvasRef, isDarkMode);
return (
<>
<canvas ref={canvasRef} />
<span data-testid="score-line">{label}</span>
</>
);
}
describe('DotGrid Snake', () => {
beforeEach(() => {
jest.useFakeTimers();
// jsdom has no canvas or layout: a 9 × 7 game grid is enough for a snake.
jest
.spyOn(HTMLCanvasElement.prototype, 'getContext')
.mockReturnValue(
new Proxy({}, { get: () => jest.fn() }) as CanvasRenderingContext2D,
);
jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(120);
jest.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(120);
});
afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
});
it('quits the game on Esc and hands the keyboard back', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const onGameChange = jest.fn();
render(<Chat onGameChange={onGameChange} />);
await user.keyboard(KONAMI);
expect(onGameChange).toHaveBeenLastCalledWith(true);
expect(screen.getByTestId('ai-dot-grid')).toHaveTextContent(
'Snake · score 0 · ↑ ↓ ← → · Esc to quit',
);
await user.keyboard('{Escape}');
expect(onGameChange).toHaveBeenLastCalledWith(false);
expect(screen.getByTestId('ai-dot-grid')).not.toHaveTextContent('Snake');
});
it('leaves arrows in the chat input alone after game over', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const onGameChange = jest.fn();
render(<Chat onGameChange={onGameChange} />);
await user.keyboard(KONAMI);
// Heading right, the snake reaches the wall within a few steps.
act(() => {
jest.advanceTimersByTime(1500);
});
expect(screen.getByTestId('ai-dot-grid')).toHaveTextContent('Game over');
onGameChange.mockClear();
await user.click(screen.getByTestId('chat-textarea'));
await user.keyboard('{ArrowUp}');
expect(onGameChange).not.toHaveBeenCalled();
});
it('drops the score line when the theme changes mid-game', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const { rerender } = render(<ThemedGrid isDarkMode />);
await user.keyboard(KONAMI);
expect(screen.getByTestId('score-line')).toHaveTextContent('Snake · score 0');
rerender(<ThemedGrid isDarkMode={false} />);
expect(screen.getByTestId('score-line')).toBeEmptyDOMElement();
});
});

View File

@@ -1,32 +0,0 @@
import { getSnakeColors } from '../dotGridTheme';
function canvasWithInk(ink: string): HTMLCanvasElement {
const canvas = document.createElement('canvas');
canvas.style.color = ink;
document.body.appendChild(canvas);
return canvas;
}
describe('getSnakeColors', () => {
afterEach(() => {
document.body.innerHTML = '';
});
it('keeps the snake white on the dark page', () => {
expect(getSnakeColors(canvasWithInk('rgb(30, 31, 36)'), true)).toStrictEqual({
head: 'rgba(255,255,255,1)',
body: 'rgba(232,238,245,0.92)',
food: 'rgba(255,255,255,0.97)',
});
});
it('draws the snake in the page ink on the light page', () => {
expect(getSnakeColors(canvasWithInk('rgb(30, 31, 36)'), false)).toStrictEqual(
{
head: 'rgba(30,31,36,1)',
body: 'rgba(30,31,36,0.85)',
food: 'rgba(30,31,36,0.95)',
},
);
});
});

View File

@@ -1,112 +0,0 @@
import { SnakeGame, startSnake, stepSnake } from '../snakeGame';
const COLS = 10;
const ROWS = 6;
function newGame(): SnakeGame {
const game = startSnake(COLS, ROWS);
if (!game) {
throw new Error('a 10 × 6 grid fits a game');
}
return game;
}
describe('snakeGame', () => {
beforeEach(() => {
// Food lands on the first free cell, the top-left corner.
jest.spyOn(Math, 'random').mockReturnValue(0);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('needs at least an 8 × 6 grid', () => {
expect(startSnake(7, 6)).toBeNull();
expect(startSnake(8, 5)).toBeNull();
});
it('starts four cells long in the middle, heading right', () => {
expect(newGame()).toStrictEqual({
body: [
{ c: 5, r: 3 },
{ c: 4, r: 3 },
{ c: 3, r: 3 },
{ c: 2, r: 3 },
],
dir: { c: 1, r: 0 },
nextDir: { c: 1, r: 0 },
food: { c: 0, r: 0 },
score: 0,
});
});
it('moves one cell in its direction', () => {
const next = stepSnake(newGame(), COLS, ROWS);
expect(next?.body).toStrictEqual([
{ c: 6, r: 3 },
{ c: 5, r: 3 },
{ c: 4, r: 3 },
{ c: 3, r: 3 },
]);
expect(next?.score).toBe(0);
});
it('grows and scores when it eats', () => {
const next = stepSnake({ ...newGame(), food: { c: 6, r: 3 } }, COLS, ROWS);
expect(next?.body).toHaveLength(5);
expect(next?.score).toBe(1);
});
it('ends when it hits a wall', () => {
const atEdge: SnakeGame = {
...newGame(),
body: [
{ c: 9, r: 3 },
{ c: 8, r: 3 },
{ c: 7, r: 3 },
{ c: 6, r: 3 },
],
};
expect(stepSnake(atEdge, COLS, ROWS)).toBeNull();
});
it('ends when it runs into itself', () => {
const coiled: SnakeGame = {
...newGame(),
body: [
{ c: 5, r: 3 },
{ c: 5, r: 4 },
{ c: 6, r: 4 },
{ c: 6, r: 3 },
{ c: 7, r: 3 },
],
};
expect(stepSnake(coiled, COLS, ROWS)).toBeNull();
});
it('moves into the cell its tail is leaving', () => {
const up = { c: 0, r: -1 };
const turnedDownThenLeft: SnakeGame = {
...newGame(),
body: [
{ c: 4, r: 4 },
{ c: 5, r: 4 },
{ c: 5, r: 3 },
{ c: 4, r: 3 },
],
nextDir: up,
};
expect(stepSnake(turnedDownThenLeft, COLS, ROWS)?.body).toStrictEqual([
{ c: 4, r: 3 },
{ c: 4, r: 4 },
{ c: 5, r: 4 },
{ c: 5, r: 3 },
]);
});
});

View File

@@ -1,53 +0,0 @@
export const DOT_SPACING = 12;
export const DOT_RADIUS = 1.15;
export const TRAIL_RADIUS = 72;
export const TRAIL_LIFT = 0.24;
export const TRAIL_MAX_POINTS = 18;
export const TRAIL_LIFE_MS = 1000;
export const TRAIL_MIN_STEP = 7;
// Time the field rests at when motion is reduced.
export const STILL_TIME_MS = 12000;
type Rgb = [number, number, number];
// Green, teal, blue, violet and pink, in the order the field drifts through them.
const AURORA: Rgb[] = [
[64, 224, 150],
[48, 200, 210],
[90, 130, 245],
[170, 110, 245],
[235, 110, 200],
];
/** Brightness of the field at a point, between -1 and 1. */
export function auroraBrightness(x: number, y: number, t: number): number {
return (
(Math.sin(x * 0.009 + t * 0.0006) +
Math.sin(y * 0.015 - t * 0.00085 + x * 0.002) +
Math.sin((x + y) * 0.006 + t * 0.0011) +
Math.sin((x - y) * 0.0048 - t * 0.0007)) /
4
);
}
/** Colour of the field at a point, blended along the aurora palette. */
export function auroraColor(x: number, y: number, t: number): Rgb {
const position =
((Math.sin(x * 0.0035 + t * 0.00018) +
Math.sin(y * 0.005 - t * 0.00026) +
Math.sin((x + y) * 0.0028 + t * 0.0002)) /
3 +
1) /
2;
const scaled = position * (AURORA.length - 1);
const from = AURORA[Math.floor(scaled)];
const to = AURORA[Math.min(Math.floor(scaled) + 1, AURORA.length - 1)];
const mix = scaled - Math.floor(scaled);
return [
from[0] + (to[0] - from[0]) * mix,
from[1] + (to[1] - from[1]) * mix,
from[2] + (to[2] - from[2]) * mix,
];
}

View File

@@ -1,34 +0,0 @@
// Colours for the dot grid that depend on the page behind it.
export interface SnakeColors {
head: string;
body: string;
food: string;
}
const DARK_SNAKE: SnakeColors = {
head: 'rgba(255,255,255,1)',
body: 'rgba(232,238,245,0.92)',
food: 'rgba(255,255,255,0.97)',
};
function withAlpha(rgb: string, alpha: number): string {
const channels = rgb.match(/\d+(\.\d+)?/g)?.slice(0, 3) ?? ['0', '0', '0'];
return `rgba(${channels.join(',')},${alpha})`;
}
/** Snake colours: white on the dark page, the canvas's ink (`color`) on the light one. */
export function getSnakeColors(
canvas: HTMLCanvasElement,
isDarkMode: boolean,
): SnakeColors {
if (isDarkMode) {
return DARK_SNAKE;
}
const ink = getComputedStyle(canvas).color;
return {
head: withAlpha(ink, 1),
body: withAlpha(ink, 0.85),
food: withAlpha(ink, 0.95),
};
}

View File

@@ -1,102 +0,0 @@
// Painting for the dot grid: the aurora field with the cursor's glow, and plain dots.
import {
auroraBrightness,
auroraColor,
DOT_RADIUS,
TRAIL_LIFE_MS,
TRAIL_LIFT,
TRAIL_RADIUS,
} from './dotGridField';
// Coloured dots on white read fainter than lit ones on black.
const LIGHT_ALPHA_BOOST = 1.6;
export interface TrailPoint {
x: number;
y: number;
born: number;
}
interface AuroraFrame {
/** Field time; frozen when motion is reduced. */
t: number;
now: number;
height: number;
trail: TrailPoint[];
isGameOn: boolean;
/** Light adds up on the dark page; on the light one colours sit on the paper instead. */
isDarkMode: boolean;
/** Dots below this stay dark. */
cutoffY: number;
}
/** The faint light that washes up from the bottom while the game is on. */
export function gameFloor(y: number, height: number): number {
return 0.07 + 0.16 * (y / height);
}
export function drawDot(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
radius: number,
fill: string,
): void {
ctx.beginPath();
ctx.fillStyle = fill;
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}
/** Paints the aurora dots, brightest at the top and lit along the cursor's trail. */
export function drawAuroraDots(
ctx: CanvasRenderingContext2D,
dots: { x: number; y: number }[],
{ t, now, height, trail, isGameOn, isDarkMode, cutoffY }: AuroraFrame,
): void {
// Overlapping glows add up, as light does.
ctx.globalCompositeOperation = isDarkMode ? 'lighter' : 'source-over';
dots.forEach(({ x, y }) => {
if (y > cutoffY) {
return;
}
// Brightest at the top, fading toward the content below.
const topWeight = 1 - 0.82 * Math.min(1, y / height);
const lum = Math.max(0, auroraBrightness(x, y, t)) ** 1.6;
let intensity = (0.06 + lum * 0.4) * topWeight * (isGameOn ? 0.5 : 1);
if (isGameOn) {
intensity += gameFloor(y, height);
}
let glow = 0;
trail.forEach((point) => {
const distance2 = (x - point.x) ** 2 + (y - point.y) ** 2;
if (distance2 < TRAIL_RADIUS ** 2) {
const life = 1 - (now - point.born) / TRAIL_LIFE_MS;
glow += (1 - distance2 / TRAIL_RADIUS ** 2) ** 3 * life;
}
});
intensity += Math.min(glow, 1.3) * TRAIL_LIFT * topWeight;
if (intensity <= 0.02) {
return;
}
const [red, green, blue] = auroraColor(x, y, t);
// The hottest dots burn toward white on the dark page and deepen on the light one.
const heat = Math.min(1, Math.max(0, intensity - 0.9)) * 0.9;
const toward = isDarkMode ? 255 : 0;
const mix = isDarkMode ? heat : heat * 0.4;
const rgb = `${Math.round(red + (toward - red) * mix)},${Math.round(
green + (toward - green) * mix,
)},${Math.round(blue + (toward - blue) * mix)}`;
const alpha = Math.min(1, intensity * (isDarkMode ? 1 : LIGHT_ALPHA_BOOST));
const radius = DOT_RADIUS + Math.min(intensity, 1.2) * 0.7;
if (intensity > 0.6) {
drawDot(ctx, x, y, radius * 2.6, `rgba(${rgb},${alpha * 0.06})`);
}
drawDot(ctx, x, y, radius, `rgba(${rgb},${alpha})`);
});
ctx.globalCompositeOperation = 'source-over';
}

View File

@@ -1,100 +0,0 @@
// Snake on the dot grid, the easter egg the Konami code unlocks.
interface Cell {
c: number;
r: number;
}
export interface SnakeGame {
body: Cell[];
dir: Cell;
nextDir: Cell;
food: Cell;
score: number;
}
export const SNAKE_STEP_MS = 110;
// Lowercase: keys are lowercased before matching, so B/b and A/a both count.
export const KONAMI_CODE = [
'arrowup',
'arrowup',
'arrowdown',
'arrowdown',
'arrowleft',
'arrowright',
'arrowleft',
'arrowright',
'b',
'a',
];
export const SNAKE_DIRECTIONS: Record<string, Cell> = {
arrowup: { c: 0, r: -1 },
w: { c: 0, r: -1 },
arrowdown: { c: 0, r: 1 },
s: { c: 0, r: 1 },
arrowleft: { c: -1, r: 0 },
a: { c: -1, r: 0 },
arrowright: { c: 1, r: 0 },
d: { c: 1, r: 0 },
};
const isOn = (cells: Cell[], cell: Cell): boolean =>
cells.some(({ c, r }) => c === cell.c && r === cell.r);
/** A free cell for the food, or null when the snake fills the grid. */
function placeFood(body: Cell[], cols: number, rows: number): Cell | null {
const free: Cell[] = [];
for (let r = 0; r < rows; r += 1) {
for (let c = 0; c < cols; c += 1) {
if (!isOn(body, { c, r })) {
free.push({ c, r });
}
}
}
return free.length ? free[Math.floor(Math.random() * free.length)] : null;
}
/** A four-cell snake in the middle heading right, or null when the grid is too small. */
export function startSnake(cols: number, rows: number): SnakeGame | null {
if (cols < 8 || rows < 6) {
return null;
}
const c = Math.floor(cols / 2);
const r = Math.floor(rows / 2);
const body = [0, 1, 2, 3].map((i) => ({ c: c - i, r }));
const food = placeFood(body, cols, rows);
if (!food) {
return null;
}
const right = { c: 1, r: 0 };
return { body, dir: right, nextDir: right, food, score: 0 };
}
/** Moves the snake one cell; null when it hits a wall, itself, or fills the grid. */
export function stepSnake(
game: SnakeGame,
cols: number,
rows: number,
): SnakeGame | null {
const dir = game.nextDir;
const head = { c: game.body[0].c + dir.c, r: game.body[0].r + dir.r };
const ate = head.c === game.food.c && head.r === game.food.r;
const kept = ate ? game.body : game.body.slice(0, -1);
if (
head.c < 0 ||
head.c >= cols ||
head.r < 0 ||
head.r >= rows ||
isOn(kept, head)
) {
return null;
}
const body = [head, ...kept];
const food = ate ? placeFood(body, cols, rows) : game.food;
if (!food) {
return null;
}
return { ...game, body, dir, food, score: game.score + (ate ? 1 : 0) };
}

View File

@@ -1,320 +0,0 @@
import { RefObject, useEffect, useLayoutEffect, useRef, useState } from 'react';
import {
DOT_RADIUS,
DOT_SPACING,
STILL_TIME_MS,
TRAIL_LIFE_MS,
TRAIL_MAX_POINTS,
TRAIL_MIN_STEP,
TRAIL_RADIUS,
} from './dotGridField';
import { drawAuroraDots, drawDot, gameFloor, TrailPoint } from './drawDots';
import {
KONAMI_CODE,
SNAKE_DIRECTIONS,
SNAKE_STEP_MS,
SnakeGame,
startSnake,
stepSnake,
} from './snakeGame';
import { getSnakeColors } from './dotGridTheme';
const GAME_OVER_LABEL_MS = 4000;
const REPLAY_LABEL = '↑ to replay';
const playingLabel = (score: number): string =>
`Snake · score ${score} · ↑ ↓ ← → · Esc to quit`;
// Unlocked once per page load; after that a click on the dots starts a game.
let isSnakeUnlocked = false;
// Room left under the snake's lowest row for the score line, so the two never touch.
const SCORE_LINE_CLEARANCE = 30;
const isField = (target: EventTarget | null): target is HTMLElement =>
target instanceof HTMLElement &&
Boolean(target.closest('input, textarea, select, [contenteditable="true"]'));
/** Draws the aurora dot grid; the Konami code turns it into Snake. Returns the score line. */
export function useDotGrid(
canvasRef: RefObject<HTMLCanvasElement>,
isDarkMode: boolean,
onGameChange?: (isPlaying: boolean) => void,
): string | null {
const [label, setLabel] = useState<string | null>(null);
const onGameChangeRef = useRef(onGameChange);
useLayoutEffect(() => {
onGameChangeRef.current = onGameChange;
});
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext('2d');
if (!canvas || !ctx) {
return undefined;
}
const isStill = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const snakeColors = getSnakeColors(canvas, isDarkMode);
let width = 0;
let height = 0;
let cols = 0;
let rows = 0;
let gameRows = 0;
let left = 0;
let dots: { x: number; y: number }[] = [];
const trail: TrailPoint[] = [];
let frame = 0;
let game: SnakeGame | null = null;
let lastStep = 0;
// With reduced motion the field stands still, so frames repaint only after a change.
let needsDraw = true;
let isScoreLineShown = false;
const showScoreLine = (text: string | null): void => {
isScoreLineShown = text !== null;
needsDraw = true;
setLabel(text);
};
const recentKeys: string[] = [];
let labelTimer = 0;
// An arrow key replays while the game over line is up.
let canReplay = false;
const showPlayCursor = (): void => {
canvas.style.cursor = isSnakeUnlocked && !game ? 'pointer' : '';
};
const cellCenter = (c: number, r: number): { x: number; y: number } => ({
x: left + c * DOT_SPACING,
y: DOT_SPACING + r * DOT_SPACING,
});
const play = (): void => {
game = startSnake(cols, gameRows);
lastStep = performance.now();
canReplay = false;
window.clearTimeout(labelTimer);
showScoreLine(game ? playingLabel(0) : null);
showPlayCursor();
onGameChangeRef.current?.(game !== null);
};
const quit = (): void => {
game = null;
canReplay = false;
window.clearTimeout(labelTimer);
showScoreLine(null);
showPlayCursor();
onGameChangeRef.current?.(false);
};
const endGame = (score: number): void => {
game = null;
canReplay = true;
showScoreLine(`Game over · score ${score} · ${REPLAY_LABEL}`);
showPlayCursor();
onGameChangeRef.current?.(false);
labelTimer = window.setTimeout(() => {
canReplay = false;
showScoreLine(null);
}, GAME_OVER_LABEL_MS);
};
const layout = (): void => {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
width = canvas.clientWidth;
height = canvas.clientHeight;
canvas.width = Math.floor(width * dpr);
canvas.height = Math.floor(height * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
cols = Math.max(0, Math.floor((width - DOT_SPACING) / DOT_SPACING));
rows = Math.max(0, Math.floor((height - DOT_SPACING) / DOT_SPACING));
gameRows = Math.min(
rows,
Math.max(0, Math.floor((height - SCORE_LINE_CLEARANCE) / DOT_SPACING)),
);
left = (width - cols * DOT_SPACING) / 2 + DOT_SPACING / 2;
dots = [];
for (let r = 0; r < rows; r += 1) {
for (let c = 0; c < cols; c += 1) {
dots.push(cellCenter(c, r));
}
}
needsDraw = true;
// A game carries on through a resize unless it no longer fits.
if (
game &&
[...game.body, game.food].some(({ c, r }) => c >= cols || r >= gameRows)
) {
play();
}
};
const onPointer = (event: PointerEvent): void => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
if (
x < -TRAIL_RADIUS ||
y < -TRAIL_RADIUS ||
x > width + TRAIL_RADIUS ||
y > height + TRAIL_RADIUS
) {
return;
}
const head = trail[trail.length - 1];
// Barely moved: keep the head lit instead of stacking points.
if (head && Math.hypot(x - head.x, y - head.y) < TRAIL_MIN_STEP) {
head.born = performance.now();
return;
}
trail.push({ x, y, born: performance.now() });
if (trail.length > TRAIL_MAX_POINTS) {
trail.shift();
}
};
// Keys typed into a field outside this chat belong to that field.
const isOtherField = (target: EventTarget | null): boolean => {
if (!isField(target)) {
return false;
}
let chat = canvas.parentElement;
while (chat && !chat.querySelector('textarea')) {
chat = chat.parentElement;
}
return !chat?.contains(target);
};
const onKeyDown = (event: KeyboardEvent): void => {
if (isOtherField(event.target)) {
return;
}
const key = event.key.toLowerCase();
if (game) {
if (key === 'escape') {
event.preventDefault();
quit();
return;
}
const next = SNAKE_DIRECTIONS[key];
if (next) {
// Steering keys drive the snake, not the input; no turning back onto the neck.
event.preventDefault();
if (next.c !== -game.dir.c || next.r !== -game.dir.r) {
game.nextDir = next;
}
}
return;
}
// Arrows in the chat's input move its caret instead.
if (canReplay && key.startsWith('arrow') && !isField(event.target)) {
event.preventDefault();
play();
return;
}
recentKeys.push(key);
if (recentKeys.length > KONAMI_CODE.length) {
recentKeys.shift();
}
if (recentKeys.join() === KONAMI_CODE.join()) {
recentKeys.length = 0;
isSnakeUnlocked = true;
play();
}
};
const onClick = (): void => {
if (isSnakeUnlocked && !game) {
play();
}
};
// The snake and its food: flat white dots the size of their neighbours.
const stepAndDrawSnake = (now: number): void => {
if (game && now - lastStep >= SNAKE_STEP_MS) {
lastStep = now;
const next = stepSnake(game, cols, gameRows);
if (next) {
if (next.score !== game.score) {
showScoreLine(playingLabel(next.score));
}
game = next;
} else {
endGame(game.score);
}
}
if (game) {
const sizeAt = (y: number): number =>
DOT_RADIUS + Math.min(gameFloor(y, height), 1.2) * 0.7;
const food = cellCenter(game.food.c, game.food.r);
drawDot(ctx, food.x, food.y, sizeAt(food.y), snakeColors.food);
game.body.forEach((cell, i) => {
const { x, y } = cellCenter(cell.c, cell.r);
drawDot(
ctx,
x,
y,
sizeAt(y),
i === 0 ? snakeColors.head : snakeColors.body,
);
});
}
};
const draw = (now: number): void => {
const hadTrail = trail.length > 0;
for (let i = trail.length - 1; i >= 0; i -= 1) {
if (now - trail[i].born >= TRAIL_LIFE_MS) {
trail.splice(i, 1);
}
}
if (isStill && !game && !hadTrail && !needsDraw) {
frame = requestAnimationFrame(draw);
return;
}
needsDraw = false;
const t = isStill ? STILL_TIME_MS : now;
ctx.clearRect(0, 0, width, height);
drawAuroraDots(ctx, dots, {
t,
now,
height,
trail,
isGameOn: game !== null,
isDarkMode,
// Keeps the score line's strip clear of dots.
cutoffY: isScoreLineShown ? gameRows * DOT_SPACING : Infinity,
});
stepAndDrawSnake(now);
frame = requestAnimationFrame(draw);
};
const observer = new ResizeObserver(layout);
observer.observe(canvas);
layout();
window.addEventListener('pointermove', onPointer);
window.addEventListener('pointerdown', onPointer);
window.addEventListener('keydown', onKeyDown);
canvas.addEventListener('click', onClick);
showPlayCursor();
frame = requestAnimationFrame(draw);
return (): void => {
cancelAnimationFrame(frame);
observer.disconnect();
window.clearTimeout(labelTimer);
setLabel(null);
if (game) {
onGameChangeRef.current?.(false);
}
window.removeEventListener('pointermove', onPointer);
window.removeEventListener('pointerdown', onPointer);
window.removeEventListener('keydown', onKeyDown);
canvas.removeEventListener('click', onClick);
};
}, [canvasRef, isDarkMode]);
return label;
}

View File

@@ -68,17 +68,7 @@ export default function DownloadOptionsMenu({
aria-modal="true"
>
<div className="export-format">
<Typography
variant="uppercase"
size="small"
weight="medium"
color="main"
as="p"
marginBottom={4}
textOverflow="wrap"
>
FORMAT
</Typography>
<Typography.Text className="title">FORMAT</Typography.Text>
<RadioGroup
color="primary"
value={exportFormat}
@@ -93,17 +83,7 @@ export default function DownloadOptionsMenu({
<div className="horizontal-line" />
<div className="row-limit">
<Typography
variant="uppercase"
size="small"
weight="medium"
color="main"
as="p"
marginBottom={4}
textOverflow="wrap"
>
Number of Rows
</Typography>
<Typography.Text className="title">Number of Rows</Typography.Text>
<RadioGroup
color="primary"
value={String(rowLimit)}
@@ -121,17 +101,7 @@ export default function DownloadOptionsMenu({
<div className="horizontal-line" />
<div className="columns-scope">
<Typography
variant="uppercase"
size="small"
weight="medium"
color="main"
as="p"
marginBottom={4}
textOverflow="wrap"
>
Columns
</Typography>
<Typography.Text className="title">Columns</Typography.Text>
<RadioGroup
color="primary"
value={columnsScope}

View File

@@ -1,5 +1,6 @@
import { Trash2, X } from '@signozhq/icons';
import { AlertDialog } from '@signozhq/ui/alert-dialog';
import { Button } from '@signozhq/ui/button';
import { DialogWrapper } from '@signozhq/ui/dialog';
import { MemberRow } from 'components/MembersTable/MembersTable';
interface DeleteMemberDialogProps {
@@ -8,7 +9,7 @@ interface DeleteMemberDialogProps {
member: MemberRow | null;
isDeleting: boolean;
onClose: () => void;
onConfirm: () => Promise<void>;
onConfirm: () => void;
}
function DeleteMemberDialog({
@@ -35,20 +36,47 @@ function DeleteMemberDialog({
</>
);
const footer = (
<>
<Button
size="md"
variant="solid"
color="secondary"
onClick={onClose}
prefix={<X size={12} />}
>
Cancel
</Button>
<Button
size="md"
variant="solid"
color="danger"
onClick={onConfirm}
testId="member-delete-confirm-btn"
loading={isDeleting}
prefix={<Trash2 size={12} />}
>
{isDeleting ? 'Processing...' : title}
</Button>
</>
);
return (
<AlertDialog
<DialogWrapper
open={open}
onOpenChange={(isOpen): void => {
if (!isOpen) {
onClose();
}
}}
title={title}
color="danger"
confirmText={isDeleting ? 'Processing...' : title}
confirmIcon={<Trash2 size={12} />}
cancelIcon={<X size={12} />}
onConfirm={onConfirm}
onCancel={onClose}
testId="member-delete"
width="narrow"
showCloseButton={false}
disableOutsideClick={false}
footer={footer}
>
{body}
</AlertDialog>
</DialogWrapper>
);
}

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