mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-20 15:21:19 +00:00
Compare commits
29 Commits
issue_nerv
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c47aadb714 | ||
|
|
d317275b36 | ||
|
|
61bc6698d1 | ||
|
|
518def70e0 | ||
|
|
164ff1faec | ||
|
|
f6f7144a80 | ||
|
|
73f02c25e7 | ||
|
|
a01cc1aef9 | ||
|
|
0bd8d52c42 | ||
|
|
e1168108f2 | ||
|
|
7f8a1b283e | ||
|
|
4553c9c9a6 | ||
|
|
a2709c0272 | ||
|
|
d8eda78322 | ||
|
|
a79ff07e77 | ||
|
|
ebc2ba4fee | ||
|
|
edcb9028ce | ||
|
|
d74035f233 | ||
|
|
d41447d4ee | ||
|
|
2e20b154c3 | ||
|
|
bcd7182757 | ||
|
|
b1dbea3eaa | ||
|
|
a30398bf1a | ||
|
|
8b923e88ce | ||
|
|
89c1dfe332 | ||
|
|
0add9cce0d | ||
|
|
4ffa6ac5da | ||
|
|
824315b093 | ||
|
|
1ee097b60a |
@@ -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) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
|
||||
func(_ sqlstore.SQLStore, _ zeus.Zeus, _ organization.Getter, _ analytics.Analytics, _ cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
|
||||
return nooplicensing.NewFactory()
|
||||
},
|
||||
func(_ zeus.Zeus, _ licensing.Licensing) subscription.Subscription {
|
||||
|
||||
@@ -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) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
|
||||
return httplicensing.NewProviderFactory(sqlstore, zeus, orgGetter, analytics)
|
||||
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(zeus zeus.Zeus, licensing licensing.Licensing) subscription.Subscription {
|
||||
return httpsubscription.New(zeus, licensing)
|
||||
|
||||
@@ -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.
|
||||
retention: 120h
|
||||
# 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
|
||||
|
||||
##################### Emailing #####################
|
||||
emailing:
|
||||
|
||||
@@ -4420,7 +4420,8 @@ components:
|
||||
description: The dashboard title and description.
|
||||
duration:
|
||||
description: The default time range, as a Prometheus duration such as 1h
|
||||
or 7d. Stored, but not applied by the UI.
|
||||
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.
|
||||
type: string
|
||||
layouts:
|
||||
description: The Grid layouts that place panels, at most 500. Each panel
|
||||
@@ -11881,7 +11882,7 @@ components:
|
||||
- created_at
|
||||
- name
|
||||
- state
|
||||
- severity
|
||||
- thresholds
|
||||
type: string
|
||||
RuletypesListableRule:
|
||||
properties:
|
||||
@@ -11921,6 +11922,13 @@ components:
|
||||
- $ref: '#/components/schemas/RuletypesAlertState'
|
||||
description: 'The current evaluation state: inactive, pending, recovering,
|
||||
firing, nodata or disabled.'
|
||||
thresholds:
|
||||
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.
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
updatedAt:
|
||||
format: date-time
|
||||
type: string
|
||||
@@ -11932,6 +11940,7 @@ components:
|
||||
- alert
|
||||
- alertType
|
||||
- ruleType
|
||||
- thresholds
|
||||
type: object
|
||||
RuletypesListableRuleViews:
|
||||
properties:
|
||||
@@ -12298,7 +12307,8 @@ components:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesListSort'
|
||||
description: 'The field to sort by: updated_at (the default), created_at,
|
||||
name, state or severity.'
|
||||
name, state or thresholds. Sorting by thresholds ranks each rule by its
|
||||
first threshold name.'
|
||||
states:
|
||||
description: 'Only return rules in these states: firing, pending, recovering,
|
||||
inactive, nodata or disabled. Empty means every state.'
|
||||
@@ -12512,6 +12522,14 @@ components:
|
||||
- schemaVersion
|
||||
- spec
|
||||
type: object
|
||||
ServiceaccounttypesDSLKey:
|
||||
enum:
|
||||
- created_at
|
||||
- email
|
||||
- name
|
||||
- status
|
||||
- updated_at
|
||||
type: string
|
||||
ServiceaccounttypesGettableFactorAPIKey:
|
||||
properties:
|
||||
createdAt:
|
||||
@@ -12548,6 +12566,28 @@ components:
|
||||
- id
|
||||
- key
|
||||
type: object
|
||||
ServiceaccounttypesListableServiceAccount:
|
||||
properties:
|
||||
reservedKeywords:
|
||||
description: The filter keys the query accepts.
|
||||
items:
|
||||
$ref: '#/components/schemas/ServiceaccounttypesDSLKey'
|
||||
type: array
|
||||
serviceAccounts:
|
||||
description: The service accounts on this page.
|
||||
items:
|
||||
$ref: '#/components/schemas/ServiceaccounttypesServiceAccount'
|
||||
type: array
|
||||
total:
|
||||
description: The number of service accounts the filter matches across all
|
||||
pages.
|
||||
format: int64
|
||||
type: integer
|
||||
required:
|
||||
- serviceAccounts
|
||||
- total
|
||||
- reservedKeywords
|
||||
type: object
|
||||
ServiceaccounttypesPostableFactorAPIKey:
|
||||
properties:
|
||||
expiresAt:
|
||||
@@ -12590,17 +12630,30 @@ components:
|
||||
orgId:
|
||||
type: string
|
||||
status:
|
||||
type: string
|
||||
$ref: '#/components/schemas/ServiceaccounttypesServiceAccountStatus'
|
||||
updatedAt:
|
||||
format: date-time
|
||||
type: string
|
||||
required:
|
||||
- id
|
||||
- createdAt
|
||||
- updatedAt
|
||||
- name
|
||||
- email
|
||||
- status
|
||||
- orgId
|
||||
type: object
|
||||
ServiceaccounttypesServiceAccountListOrder:
|
||||
enum:
|
||||
- asc
|
||||
- desc
|
||||
type: string
|
||||
ServiceaccounttypesServiceAccountListSort:
|
||||
enum:
|
||||
- created_at
|
||||
- updated_at
|
||||
- name
|
||||
type: string
|
||||
ServiceaccounttypesServiceAccountRole:
|
||||
properties:
|
||||
createdAt:
|
||||
@@ -12623,6 +12676,11 @@ components:
|
||||
- roleId
|
||||
- role
|
||||
type: object
|
||||
ServiceaccounttypesServiceAccountStatus:
|
||||
enum:
|
||||
- active
|
||||
- deleted
|
||||
type: string
|
||||
ServiceaccounttypesServiceAccountWithRoles:
|
||||
properties:
|
||||
createdAt:
|
||||
@@ -12642,12 +12700,14 @@ components:
|
||||
nullable: true
|
||||
type: array
|
||||
status:
|
||||
type: string
|
||||
$ref: '#/components/schemas/ServiceaccounttypesServiceAccountStatus'
|
||||
updatedAt:
|
||||
format: date-time
|
||||
type: string
|
||||
required:
|
||||
- id
|
||||
- createdAt
|
||||
- updatedAt
|
||||
- name
|
||||
- email
|
||||
- status
|
||||
@@ -13654,6 +13714,7 @@ components:
|
||||
type: string
|
||||
TelemetrytypesSource:
|
||||
enum:
|
||||
- audit
|
||||
- meter
|
||||
- ""
|
||||
type: string
|
||||
@@ -17742,8 +17803,56 @@ paths:
|
||||
/api/v1/service_accounts:
|
||||
get:
|
||||
deprecated: false
|
||||
description: This endpoint lists the service accounts for an organisation
|
||||
description: 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.
|
||||
operationId: ListServiceAccounts
|
||||
parameters:
|
||||
- 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.'
|
||||
in: query
|
||||
name: query
|
||||
schema:
|
||||
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.'
|
||||
type: string
|
||||
- description: 'The sort column: created_at (default), updated_at or name.'
|
||||
in: query
|
||||
name: sort
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/ServiceaccounttypesServiceAccountListSort'
|
||||
description: 'The sort column: created_at (default), updated_at or name.'
|
||||
- description: 'The sort order: asc or desc (default).'
|
||||
in: query
|
||||
name: order
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/ServiceaccounttypesServiceAccountListOrder'
|
||||
description: 'The sort order: asc or desc (default).'
|
||||
- description: The page size; defaults to 20 and is capped at 200.
|
||||
in: query
|
||||
name: limit
|
||||
schema:
|
||||
description: The page size; defaults to 20 and is capped at 200.
|
||||
type: integer
|
||||
- description: The number of service accounts to skip; defaults to 0.
|
||||
in: query
|
||||
name: offset
|
||||
schema:
|
||||
description: The number of service accounts to skip; defaults to 0.
|
||||
type: integer
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
@@ -17751,9 +17860,7 @@ paths:
|
||||
schema:
|
||||
properties:
|
||||
data:
|
||||
items:
|
||||
$ref: '#/components/schemas/ServiceaccounttypesServiceAccount'
|
||||
type: array
|
||||
$ref: '#/components/schemas/ServiceaccounttypesListableServiceAccount'
|
||||
status:
|
||||
type: string
|
||||
required:
|
||||
@@ -17761,6 +17868,12 @@ paths:
|
||||
- data
|
||||
type: object
|
||||
description: OK
|
||||
"400":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Bad Request
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
@@ -32092,7 +32205,7 @@ paths:
|
||||
deprecated: false
|
||||
description: 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`),
|
||||
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
|
||||
@@ -32120,14 +32233,16 @@ paths:
|
||||
type: string
|
||||
type: array
|
||||
- description: 'The field to sort by: updated_at (the default), created_at,
|
||||
name, state or severity.'
|
||||
name, state or thresholds. Sorting by thresholds ranks each rule by its
|
||||
first threshold name.'
|
||||
in: query
|
||||
name: sort
|
||||
schema:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RuletypesListSort'
|
||||
description: 'The field to sort by: updated_at (the default), created_at,
|
||||
name, state or severity.'
|
||||
name, state or thresholds. Sorting by thresholds ranks each rule by its
|
||||
first threshold name.'
|
||||
- description: 'The sort direction: asc or desc (the default).'
|
||||
in: query
|
||||
name: order
|
||||
|
||||
26
ee/licensing/httplicensing/cache.go
Normal file
26
ee/licensing/httplicensing/cache.go
Normal file
@@ -0,0 +1,26 @@
|
||||
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)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ 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"
|
||||
@@ -25,16 +26,17 @@ 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) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
|
||||
func NewProviderFactory(store sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) 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)
|
||||
return New(ctx, providerSettings, config, store, zeus, orgGetter, analytics, cache)
|
||||
})
|
||||
}
|
||||
|
||||
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) {
|
||||
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) {
|
||||
settings := factory.NewScopedProviderSettings(ps, "github.com/SigNoz/signoz/ee/licensing/httplicensing")
|
||||
licensestore := sqllicensingstore.New(sqlstore)
|
||||
return &provider{
|
||||
@@ -45,6 +47,7 @@ func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Conf
|
||||
orgGetter: orgGetter,
|
||||
stopChan: make(chan struct{}),
|
||||
analytics: analytics,
|
||||
cache: cache,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -109,6 +112,7 @@ func (provider *provider) Activate(ctx context.Context, organizationID valuer.UU
|
||||
return nil, err
|
||||
}
|
||||
|
||||
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
|
||||
return license, nil
|
||||
}
|
||||
|
||||
@@ -150,25 +154,38 @@ func (provider *provider) Delete(ctx context.Context, organizationID valuer.UUID
|
||||
return errors.WithAdditionalf(err, "license %s cannot be deleted", licenseID.StringValue())
|
||||
}
|
||||
|
||||
return provider.store.Delete(ctx, organizationID, licenseID)
|
||||
if err := provider.store.Delete(ctx, organizationID, licenseID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
storableLicenses, err := provider.store.GetAll(ctx, organizationID)
|
||||
if err != nil {
|
||||
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) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
activeLicense, err := licensetypes.GetActiveLicenseFromStorableLicenses(storableLicenses, 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()))
|
||||
}
|
||||
|
||||
return activeLicense, nil
|
||||
return activeLicense, err
|
||||
}
|
||||
|
||||
func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUID) error {
|
||||
activeLicense, err := provider.GetActive(ctx, organizationID)
|
||||
activeLicense, err := provider.getActiveFromStore(ctx, organizationID)
|
||||
if err != nil {
|
||||
if errors.Ast(err, errors.TypeNotFound) {
|
||||
return nil
|
||||
@@ -187,6 +204,7 @@ func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUI
|
||||
return err
|
||||
}
|
||||
|
||||
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
@@ -203,6 +221,8 @@ 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{
|
||||
@@ -249,3 +269,30 @@ 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)
|
||||
}
|
||||
|
||||
214
ee/licensing/httplicensing/provider_test.go
Normal file
214
ee/licensing/httplicensing/provider_test.go
Normal file
@@ -0,0 +1,214 @@
|
||||
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())
|
||||
}
|
||||
@@ -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 = f.bunf.AppendIdent(sql, column)
|
||||
sql = append(sql, f.TextToJsonColumn(column)...)
|
||||
sql = append(sql, f.convertJSONPathToPostgresWithMode(path, false)...)
|
||||
sql = append(sql, ") AS "...)
|
||||
sql = f.bunf.AppendIdent(sql, alias)
|
||||
|
||||
@@ -213,28 +213,28 @@ func TestJSONArrayElements(t *testing.T) {
|
||||
column: "data",
|
||||
path: "$",
|
||||
alias: "elem",
|
||||
expected: `jsonb_array_elements("data") AS "elem"`,
|
||||
expected: `jsonb_array_elements("data"::jsonb) AS "elem"`,
|
||||
},
|
||||
{
|
||||
name: "root path empty",
|
||||
column: "data",
|
||||
path: "",
|
||||
alias: "elem",
|
||||
expected: `jsonb_array_elements("data") AS "elem"`,
|
||||
expected: `jsonb_array_elements("data"::jsonb) AS "elem"`,
|
||||
},
|
||||
{
|
||||
name: "nested path",
|
||||
column: "metadata",
|
||||
path: "$.items",
|
||||
alias: "item",
|
||||
expected: `jsonb_array_elements("metadata"->'items') AS "item"`,
|
||||
expected: `jsonb_array_elements("metadata"::jsonb->'items') AS "item"`,
|
||||
},
|
||||
{
|
||||
name: "deeply nested path",
|
||||
column: "json_col",
|
||||
path: "$.user.tags",
|
||||
alias: "tag",
|
||||
expected: `jsonb_array_elements("json_col"->'user'->'tags') AS "tag"`,
|
||||
expected: `jsonb_array_elements("json_col"::jsonb->'user'->'tags') AS "tag"`,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -8,5 +8,5 @@
|
||||
|
||||
.title {
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--font-size-lg);
|
||||
font-size: var(--label-large-400-font-size);
|
||||
}
|
||||
|
||||
@@ -497,7 +497,11 @@
|
||||
// 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-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
|
||||
},
|
||||
"ignorePatterns": [
|
||||
"src/parser/*.ts",
|
||||
|
||||
@@ -40,8 +40,8 @@ const mockAliases = [
|
||||
},
|
||||
{
|
||||
// jest: not replaced, a test asserts on the toast it fires.
|
||||
find: /^@signozhq\/ui\/sonner$/,
|
||||
replacement: `${srcPath}/storybook/mocks/sonner.mock.tsx`,
|
||||
find: /^@signozhq\/ui\/toast$/,
|
||||
replacement: `${srcPath}/storybook/mocks/toast.mock.tsx`,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
<!--
|
||||
`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.
|
||||
Every Google Fonts request the app makes is answered with an empty
|
||||
stylesheet; the local faces stand in for them.
|
||||
-->
|
||||
<link rel="stylesheet" href="storybook-fonts.css" />
|
||||
|
||||
@@ -76,49 +74,3 @@
|
||||
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>
|
||||
|
||||
@@ -147,6 +147,7 @@ const preview: Preview = {
|
||||
'Explorer',
|
||||
['Overview', 'Span Drawer'],
|
||||
'Trace Details',
|
||||
['Overview', 'Thread'],
|
||||
'Funnel Details',
|
||||
],
|
||||
'Metrics',
|
||||
|
||||
@@ -1,22 +1,11 @@
|
||||
/*
|
||||
* The five families the app pulls from Google Fonts, served from the files in
|
||||
* The three 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 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.
|
||||
* 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.
|
||||
*/
|
||||
|
||||
@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');
|
||||
@@ -40,11 +29,3 @@
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -14,9 +14,23 @@ 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: [
|
||||
{
|
||||
|
||||
@@ -191,34 +191,30 @@ 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-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
|
||||
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);
|
||||
}
|
||||
|
||||
// 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
|
||||
.hint {
|
||||
font-size: var(--paragraph-small-400-font-size); // 11px
|
||||
line-height: var(--paragraph-small-400-line-height); // 18px
|
||||
}
|
||||
|
||||
// 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
|
||||
.id {
|
||||
font-family: var(--code-base-400-font-family);
|
||||
font-size: var(--code-base-400-font-size); // 13px
|
||||
}
|
||||
```
|
||||
|
||||
@@ -312,7 +308,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(--periscope-font-size-base);
|
||||
--button-font-size: var(--label-base-400-font-size);
|
||||
}
|
||||
|
||||
// Override Input
|
||||
@@ -342,7 +338,7 @@ Components use data attributes for variants/states. Target them for state-specif
|
||||
|
||||
// Target size
|
||||
.wrapper :global([data-size="sm"]) {
|
||||
--button-font-size: var(--periscope-font-size-small);
|
||||
--button-font-size: var(--label-small-400-font-size);
|
||||
}
|
||||
|
||||
// Target color
|
||||
|
||||
@@ -14,11 +14,6 @@
|
||||
<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>
|
||||
|
||||
@@ -36,6 +36,8 @@ 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',
|
||||
},
|
||||
|
||||
@@ -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.2.1",
|
||||
"@signozhq/design-tokens": "2.8.0",
|
||||
"@signozhq/icons": "0.4.0",
|
||||
"@signozhq/ui": "0.2.0",
|
||||
"@signozhq/ui": "0.4.0-rc.5",
|
||||
"@tanstack/react-table": "8.21.3",
|
||||
"@tanstack/react-virtual": "3.13.22",
|
||||
"@uiw/codemirror-theme-copilot": "4.23.11",
|
||||
|
||||
170
frontend/plugins/__tests__/no-text-css.test.mjs
Normal file
170
frontend/plugins/__tests__/no-text-css.test.mjs
Normal file
@@ -0,0 +1,170 @@
|
||||
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 },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
49
frontend/plugins/__tests__/require-disable-reason.test.mjs
Normal file
49
frontend/plugins/__tests__/require-disable-reason.test.mjs
Normal file
@@ -0,0 +1,49 @@
|
||||
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 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
324
frontend/plugins/rules/no-text-css.mjs
Normal file
324
frontend/plugins/rules/no-text-css.mjs
Normal file
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* 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,
|
||||
};
|
||||
},
|
||||
};
|
||||
38
frontend/plugins/rules/require-disable-reason.mjs
Normal file
38
frontend/plugins/rules/require-disable-reason.mjs
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* 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 \`--\`.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -17,6 +17,8 @@ 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: {
|
||||
@@ -35,5 +37,7 @@ 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,
|
||||
},
|
||||
};
|
||||
|
||||
1189
frontend/pnpm-lock.yaml
generated
1189
frontend/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
@@ -34,10 +34,6 @@
|
||||
"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"
|
||||
|
||||
@@ -34,10 +34,6 @@
|
||||
"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"
|
||||
|
||||
@@ -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`/`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.
|
||||
* 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.
|
||||
* @summary List alert rules (v3)
|
||||
*/
|
||||
export const listRulesV3 = (
|
||||
|
||||
@@ -34,6 +34,7 @@ import type {
|
||||
ListServiceAccountKeys200,
|
||||
ListServiceAccountKeysPathParameters,
|
||||
ListServiceAccounts200,
|
||||
ListServiceAccountsParams,
|
||||
RenderErrorResponseDTO,
|
||||
RevokeServiceAccountKeyPathParameters,
|
||||
ServiceaccounttypesPostableFactorAPIKeyDTO,
|
||||
@@ -334,38 +335,48 @@ export const invalidateGetServiceAccountRole = async (
|
||||
};
|
||||
|
||||
/**
|
||||
* This endpoint lists the service accounts for an organisation
|
||||
* 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.
|
||||
* @summary List service accounts
|
||||
*/
|
||||
export const listServiceAccounts = (signal?: AbortSignal) => {
|
||||
export const listServiceAccounts = (
|
||||
params?: ListServiceAccountsParams,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<ListServiceAccounts200>({
|
||||
url: `/api/v1/service_accounts`,
|
||||
method: 'GET',
|
||||
params,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getListServiceAccountsQueryKey = () => {
|
||||
return [`/api/v1/service_accounts`] as const;
|
||||
export const getListServiceAccountsQueryKey = (
|
||||
params?: ListServiceAccountsParams,
|
||||
) => {
|
||||
return [`/api/v1/service_accounts`, ...(params ? [params] : [])] as const;
|
||||
};
|
||||
|
||||
export const getListServiceAccountsQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof listServiceAccounts>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listServiceAccounts>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
}) => {
|
||||
>(
|
||||
params?: ListServiceAccountsParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listServiceAccounts>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getListServiceAccountsQueryKey();
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getListServiceAccountsQueryKey(params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof listServiceAccounts>>
|
||||
> = ({ signal }) => listServiceAccounts(signal);
|
||||
> = ({ signal }) => listServiceAccounts(params, signal);
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listServiceAccounts>>,
|
||||
@@ -386,14 +397,17 @@ export type ListServiceAccountsQueryError = ErrorType<RenderErrorResponseDTO>;
|
||||
export function useListServiceAccounts<
|
||||
TData = Awaited<ReturnType<typeof listServiceAccounts>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listServiceAccounts>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListServiceAccountsQueryOptions(options);
|
||||
>(
|
||||
params?: ListServiceAccountsParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listServiceAccounts>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListServiceAccountsQueryOptions(params, options);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
@@ -407,10 +421,11 @@ export function useListServiceAccounts<
|
||||
*/
|
||||
export const invalidateListServiceAccounts = async (
|
||||
queryClient: QueryClient,
|
||||
params?: ListServiceAccountsParams,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getListServiceAccountsQueryKey() },
|
||||
{ queryKey: getListServiceAccountsQueryKey(params) },
|
||||
options,
|
||||
);
|
||||
|
||||
|
||||
@@ -5284,6 +5284,7 @@ export interface TelemetrytypesTelemetryFieldKeyDTO {
|
||||
}
|
||||
|
||||
export enum TelemetrytypesSourceDTO {
|
||||
audit = 'audit',
|
||||
meter = 'meter',
|
||||
'' = '',
|
||||
}
|
||||
@@ -8042,7 +8043,7 @@ export interface DashboardtypesDashboardSpecDTO {
|
||||
display: DashboardtypesDisplayDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description The default time range, as a Prometheus duration such as 1h or 7d. Stored, but not applied by the UI.
|
||||
* @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.
|
||||
*/
|
||||
duration?: string;
|
||||
/**
|
||||
@@ -13017,7 +13018,7 @@ export enum RuletypesListSortDTO {
|
||||
created_at = 'created_at',
|
||||
name = 'name',
|
||||
state = 'state',
|
||||
severity = 'severity',
|
||||
thresholds = 'thresholds',
|
||||
}
|
||||
/**
|
||||
* The labels attached to alerts the rule fires.
|
||||
@@ -13076,6 +13077,11 @@ 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
|
||||
@@ -13098,7 +13104,7 @@ export interface RuletypesRuleViewDataDTO {
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @description The field to sort by: updated_at (the default), created_at, name, state or severity.
|
||||
* @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.
|
||||
*/
|
||||
sort?: RuletypesListSortDTO;
|
||||
/**
|
||||
@@ -13611,6 +13617,13 @@ 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
|
||||
@@ -13657,6 +13670,59 @@ 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
|
||||
@@ -13687,39 +13753,15 @@ export interface ServiceaccounttypesPostableServiceAccountRoleDTO {
|
||||
serviceAccountId: string;
|
||||
}
|
||||
|
||||
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 enum ServiceaccounttypesServiceAccountListOrderDTO {
|
||||
asc = 'asc',
|
||||
desc = 'desc',
|
||||
}
|
||||
export enum ServiceaccounttypesServiceAccountListSortDTO {
|
||||
created_at = 'created_at',
|
||||
updated_at = 'updated_at',
|
||||
name = 'name',
|
||||
}
|
||||
|
||||
export interface ServiceaccounttypesServiceAccountRoleDTO {
|
||||
/**
|
||||
* @type string
|
||||
@@ -13751,7 +13793,7 @@ export interface ServiceaccounttypesServiceAccountWithRolesDTO {
|
||||
* @type string
|
||||
* @format date-time
|
||||
*/
|
||||
createdAt?: string;
|
||||
createdAt: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
@@ -13772,15 +13814,12 @@ export interface ServiceaccounttypesServiceAccountWithRolesDTO {
|
||||
* @type array,null
|
||||
*/
|
||||
serviceAccountRoles: ServiceaccounttypesServiceAccountRoleDTO[] | null;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
status: ServiceaccounttypesServiceAccountStatusDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @format date-time
|
||||
*/
|
||||
updatedAt?: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ServiceaccounttypesUpdatableFactorAPIKeyDTO {
|
||||
@@ -15828,11 +15867,34 @@ export type GetServiceAccountRole200 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type ListServiceAccounts200 = {
|
||||
export type ListServiceAccountsParams = {
|
||||
/**
|
||||
* @type array
|
||||
* @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.
|
||||
*/
|
||||
data: ServiceaccounttypesServiceAccountDTO[];
|
||||
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 string
|
||||
*/
|
||||
@@ -17584,7 +17646,7 @@ export type ListRulesV3Params = {
|
||||
*/
|
||||
states?: string[];
|
||||
/**
|
||||
* @description The field to sort by: updated_at (the default), created_at, name, state or severity.
|
||||
* @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.
|
||||
*/
|
||||
sort?: RuletypesListSortDTO;
|
||||
/**
|
||||
|
||||
@@ -12,7 +12,6 @@ export interface MessagingQueueServicePayload {
|
||||
service_name?: string;
|
||||
};
|
||||
detailType?: MessagingQueueServiceDetailType | 'producer' | 'consumer';
|
||||
evalTime?: number;
|
||||
}
|
||||
|
||||
export interface MessagingQueuesPayloadProps {
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
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,
|
||||
};
|
||||
};
|
||||
@@ -1,61 +0,0 @@
|
||||
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);
|
||||
}
|
||||
};
|
||||
@@ -302,6 +302,10 @@ export function createAggregation(
|
||||
reduceTo: haveReduceTo
|
||||
? queryData?.aggregations?.[0]?.reduceTo || queryData?.reduceTo
|
||||
: undefined,
|
||||
...(queryData?.aggregations?.[0]?.comparisonSpaceAggregationParam && {
|
||||
comparisonSpaceAggregationParam:
|
||||
queryData.aggregations[0].comparisonSpaceAggregationParam,
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMutation } from 'react-query';
|
||||
import { Button, Modal } from 'antd';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Dialog } from '@signozhq/ui/dialog';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { createSubscription } from 'api/generated/services/subscriptions';
|
||||
import type { CreateSubscription201 } from 'api/generated/services/sigNoz.schemas';
|
||||
@@ -55,46 +56,51 @@ function AddCreditCardModal({
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
className="add-credit-card-modal"
|
||||
title={<span className="title">Add Credit Card for Chat Support</span>}
|
||||
<Dialog
|
||||
open={open}
|
||||
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}
|
||||
>
|
||||
onClose={onClose}
|
||||
title="Add Credit Card for Chat Support"
|
||||
testId="add-credit-card-modal"
|
||||
footerSuffix={
|
||||
<>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<CreditCard size={16} />}
|
||||
size="middle"
|
||||
loading={isLoadingBilling}
|
||||
disabled={isLoadingBilling}
|
||||
onClick={handleAddCreditCard}
|
||||
className="add-credit-card-btn"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="md"
|
||||
prefix={<X size={16} />}
|
||||
onClick={onClose}
|
||||
testId="add-credit-card-cancel"
|
||||
>
|
||||
Add Credit Card
|
||||
Cancel
|
||||
</Button>
|
||||
</AuthZTooltip>,
|
||||
]}
|
||||
<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>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Typography.Text className="add-credit-card-text">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
You're currently on <span className="highlight-text">Trial plan</span>.
|
||||
Add a credit card to access SigNoz chat support to your workspace.
|
||||
</Typography.Text>
|
||||
</Modal>
|
||||
</Typography>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
.breadcrumb {
|
||||
padding: var(--spacing-4) 16px var(--spacing-2);
|
||||
|
||||
// The antd breadcrumb provides the item spacing.
|
||||
--button-padding: 0;
|
||||
|
||||
ol {
|
||||
align-items: center;
|
||||
}
|
||||
@@ -8,13 +11,4 @@
|
||||
: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;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ function AlertBreadcrumb({
|
||||
items={breadcrumbItems}
|
||||
data-testid={testId}
|
||||
/>
|
||||
{showDivider && <Divider className={styles.divider} />}
|
||||
{showDivider && <Divider spacing="10px 16px" />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
.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);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Copy } from '@signozhq/icons';
|
||||
import { Badge, type BadgeColorType } from '@signozhq/ui/badge';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import cx from 'classnames';
|
||||
import { useLayoutEffect, useRef, useState } from 'react';
|
||||
@@ -15,12 +15,14 @@ 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);
|
||||
@@ -56,11 +58,7 @@ function LabelColumn({
|
||||
const remainingLabels = labels.slice(visibleCount);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={styles.labelColumn}
|
||||
data-testid="label-column"
|
||||
>
|
||||
<div ref={containerRef} className={styles.labelColumn} data-testid={testId}>
|
||||
{labels.map((label, index) => (
|
||||
<LabelTag
|
||||
key={label}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Copy } from '@signozhq/icons';
|
||||
import { Badge, type BadgeColorType } from '@signozhq/ui/badge';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
|
||||
|
||||
@@ -26,8 +26,6 @@
|
||||
}
|
||||
|
||||
.brand-title {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: var(--l1-foreground); // Primary text
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@@ -28,15 +28,29 @@ function AppLoading(): JSX.Element {
|
||||
<div className="brand">
|
||||
<img src={signozBrandLogoUrl} alt="SigNoz" className="brand-logo" />
|
||||
|
||||
<Typography.Title level={2} className="brand-title">
|
||||
<Typography
|
||||
variant="label"
|
||||
size="large"
|
||||
weight="bold"
|
||||
color="main"
|
||||
as="h2"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
SigNoz
|
||||
</Typography.Title>
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="brand-tagline">
|
||||
<Typography.Text>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
OpenTelemetry-Native Logs, Metrics and Traces in a single pane
|
||||
</Typography.Text>
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="loader" />
|
||||
|
||||
9
frontend/src/components/AppToaster/AppToaster.tsx
Normal file
9
frontend/src/components/AppToaster/AppToaster.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
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;
|
||||
@@ -35,7 +35,6 @@
|
||||
&__error-code {
|
||||
color: var(--bg-cherry-100);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
letter-spacing: -0.065px;
|
||||
}
|
||||
@@ -43,8 +42,6 @@
|
||||
&__error-message {
|
||||
color: var(--bg-cherry-300);
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.065px;
|
||||
}
|
||||
|
||||
@@ -75,7 +72,6 @@
|
||||
&__message-item {
|
||||
color: var(--bg-cherry-300);
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
letter-spacing: -0.065px;
|
||||
|
||||
|
||||
@@ -45,9 +45,8 @@
|
||||
}
|
||||
|
||||
.auth-footer-text {
|
||||
font-family: var(--font-family-inter, Inter, sans-serif);
|
||||
font-family: var(--label-small-400-font-family);
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
line-height: 1;
|
||||
color: var(--l2-foreground);
|
||||
text-align: center;
|
||||
@@ -57,7 +56,6 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
text-decoration: none;
|
||||
transition: opacity 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4.9px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.auth-header-logo-icon {
|
||||
@@ -26,7 +25,7 @@
|
||||
}
|
||||
|
||||
.auth-header-logo-text {
|
||||
font-family: Satoshi, var(--font-family-inter, Inter), sans-serif;
|
||||
font-family: Satoshi, var(--label-medium-500-font-family), sans-serif;
|
||||
font-size: 15.4px;
|
||||
font-weight: 500;
|
||||
line-height: 17.5px;
|
||||
|
||||
@@ -17,8 +17,3 @@
|
||||
letter-spacing: -0.01em;
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.divider {
|
||||
--divider-color: var(--l1-border);
|
||||
--divider-margin: 10px 0 16px 0;
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ function BackHeader({
|
||||
</Button>
|
||||
<div className={styles.title}>{title}</div>
|
||||
</div>
|
||||
<Divider className={styles.divider} />
|
||||
<Divider spacing="10px 16px" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { Dispatch, SetStateAction, useState } from 'react';
|
||||
import { Check, Plus, X } from '@signozhq/icons';
|
||||
import { Button, Flex } from 'antd';
|
||||
import { Button } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Pill } from '@signozhq/ui/pill';
|
||||
import Input from 'components/Input';
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { Row, Select, Spin } from 'antd';
|
||||
import { 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 {
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
.ant-table {
|
||||
.ant-table-thead > tr > th {
|
||||
padding: 12px;
|
||||
font-weight: 500;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
|
||||
@@ -31,10 +30,7 @@
|
||||
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;
|
||||
|
||||
@@ -45,7 +41,6 @@
|
||||
|
||||
.ant-table-cell {
|
||||
padding: 12px;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
color: var(--l1-foreground);
|
||||
background: var(--l1-background);
|
||||
@@ -67,12 +62,6 @@
|
||||
.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;
|
||||
}
|
||||
|
||||
@@ -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,10 +40,27 @@ const INITIAL_PAGE_SIZE = 20;
|
||||
|
||||
const showPaginationItem = (total: number, range: number[]): JSX.Element => (
|
||||
<>
|
||||
<Typography.Text className="numbers">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
{range[0]} — {range[1]}
|
||||
</Typography.Text>
|
||||
<Typography.Text className="total"> of {total}</Typography.Text>
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
{' '}
|
||||
of {total}
|
||||
</Typography>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -56,22 +73,15 @@ function ProgressRender(item: string | number): JSX.Element {
|
||||
const percent = Number(Number(item).toFixed(1));
|
||||
return (
|
||||
<div className="progress-container">
|
||||
<Progress
|
||||
percent={percent}
|
||||
strokeLinecap="butt"
|
||||
showInfo
|
||||
strokeColor={((): string => {
|
||||
const cpuPercent = percent;
|
||||
if (cpuPercent >= 90) {
|
||||
return Color.BG_SAKURA_500;
|
||||
<div className="progress-bar">
|
||||
<Progress
|
||||
percent={percent}
|
||||
showInfo
|
||||
color={
|
||||
percent >= 90 ? 'highlight-danger' : percent >= 60 ? 'warning' : 'success'
|
||||
}
|
||||
if (cpuPercent >= 60) {
|
||||
return Color.BG_AMBER_500;
|
||||
}
|
||||
return Color.BG_FOREST_500;
|
||||
})()}
|
||||
className="progress-bar"
|
||||
/>
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -526,7 +536,18 @@ export default function CeleryOverviewTable({
|
||||
),
|
||||
}}
|
||||
locale={{
|
||||
emptyText: isLoading ? null : <Typography.Text>No data</Typography.Text>,
|
||||
emptyText: isLoading ? null : (
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
No data
|
||||
</Typography>
|
||||
),
|
||||
}}
|
||||
scroll={{ x: 'max-content' }}
|
||||
showSorterTooltip
|
||||
|
||||
@@ -24,9 +24,16 @@ function CeleryTaskConfigOptions(): JSX.Element {
|
||||
return (
|
||||
<div className="celery-task-filters">
|
||||
<div className="celery-filters">
|
||||
<Typography.Text style={{ whiteSpace: 'nowrap' }}>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="visible"
|
||||
>
|
||||
Task Name
|
||||
</Typography.Text>
|
||||
</Typography>
|
||||
<Select
|
||||
data-testid="celery-task-name-select"
|
||||
placeholder="Task Name"
|
||||
|
||||
@@ -49,11 +49,7 @@
|
||||
|
||||
.subtitle {
|
||||
color: var(--l2-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 12px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,11 +60,6 @@
|
||||
|
||||
.footer-text {
|
||||
color: var(--l2-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 14px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,15 +65,38 @@ export default function CeleryTaskDetail({
|
||||
width="45%"
|
||||
title={
|
||||
<div>
|
||||
<Typography.Text className="title">{`Details - ${taskData.entity}`}</Typography.Text>
|
||||
<Typography
|
||||
variant="label"
|
||||
size="large"
|
||||
weight="bold"
|
||||
color="main"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>{`Details - ${taskData.entity}`}</Typography>
|
||||
<div>
|
||||
<Typography.Text className="subtitle">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="small"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
{`${formatTimestamp(startTime)} ${
|
||||
endTime ? `- ${formatTimestamp(endTime)}` : ''
|
||||
}`}
|
||||
</Typography.Text>
|
||||
<Divider type="vertical" />
|
||||
<Typography.Text className="subtitle">{taskData.value}</Typography.Text>
|
||||
</Typography>
|
||||
<Divider orientation="vertical" />
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="small"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
{taskData.value}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -88,7 +111,14 @@ export default function CeleryTaskDetail({
|
||||
destroyOnClose
|
||||
closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
|
||||
footer={
|
||||
<Typography.Text className="footer-text">{`Total Task: ${totalTask}`}</Typography.Text>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>{`Total Task: ${totalTask}`}</Typography>
|
||||
}
|
||||
>
|
||||
<CeleryTaskGraph
|
||||
|
||||
@@ -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,6 +33,7 @@ import {
|
||||
celerySlowestTasksTableWidgetData,
|
||||
celerySuccessStateWidgetData,
|
||||
celerySuccessTasksTableWidgetData,
|
||||
getClickedSeries,
|
||||
} from './CeleryTaskGraphUtils';
|
||||
import {
|
||||
CeleryTaskState,
|
||||
@@ -142,24 +143,19 @@ function CeleryTaskBar({
|
||||
data?: {
|
||||
[key: string]: string;
|
||||
},
|
||||
queryData?: { inFocusOrNot: boolean },
|
||||
): void => {
|
||||
const clickedSeries = getClickedSeries(data, queryData);
|
||||
if (!clickedSeries) {
|
||||
return;
|
||||
}
|
||||
const { start, end } = getStartAndEndTimesInMilliseconds(xValue);
|
||||
|
||||
// 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,
|
||||
});
|
||||
}
|
||||
onClick?.({
|
||||
...clickedSeries,
|
||||
timeRange: [start, end],
|
||||
widgetData,
|
||||
});
|
||||
};
|
||||
|
||||
const { getCustomSeries } = useGetGraphCustomSeries({
|
||||
@@ -183,10 +179,11 @@ function CeleryTaskBar({
|
||||
{barState === CeleryTaskState.All && (
|
||||
<GridCard
|
||||
widget={celeryAllStateFilteredData}
|
||||
version={ENTITY_VERSION_V5}
|
||||
headerMenuList={[...ViewMenuAction]}
|
||||
onDragSelect={onDragSelect}
|
||||
isQueryEnabled={queryEnabled}
|
||||
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
|
||||
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
|
||||
onGraphClick(
|
||||
celerySlowestTasksTableWidgetData,
|
||||
xValue,
|
||||
@@ -194,6 +191,7 @@ function CeleryTaskBar({
|
||||
mouseX,
|
||||
mouseY,
|
||||
data,
|
||||
queryData,
|
||||
)
|
||||
}
|
||||
customSeries={getCustomSeries}
|
||||
@@ -203,10 +201,11 @@ function CeleryTaskBar({
|
||||
{barState === CeleryTaskState.Failed && (
|
||||
<GridCard
|
||||
widget={celeryFailedStateFilteredData}
|
||||
version={ENTITY_VERSION_V5}
|
||||
headerMenuList={[...ViewMenuAction]}
|
||||
onDragSelect={onDragSelect}
|
||||
isQueryEnabled={queryEnabled}
|
||||
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
|
||||
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
|
||||
onGraphClick(
|
||||
celeryFailedTasksTableWidgetData,
|
||||
xValue,
|
||||
@@ -214,6 +213,7 @@ function CeleryTaskBar({
|
||||
mouseX,
|
||||
mouseY,
|
||||
data,
|
||||
queryData,
|
||||
)
|
||||
}
|
||||
customSeries={getCustomSeries}
|
||||
@@ -222,10 +222,11 @@ function CeleryTaskBar({
|
||||
{barState === CeleryTaskState.Retry && (
|
||||
<GridCard
|
||||
widget={celeryRetryStateFilteredData}
|
||||
version={ENTITY_VERSION_V5}
|
||||
headerMenuList={[...ViewMenuAction]}
|
||||
onDragSelect={onDragSelect}
|
||||
isQueryEnabled={queryEnabled}
|
||||
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
|
||||
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
|
||||
onGraphClick(
|
||||
celeryRetryTasksTableWidgetData,
|
||||
xValue,
|
||||
@@ -233,6 +234,7 @@ function CeleryTaskBar({
|
||||
mouseX,
|
||||
mouseY,
|
||||
data,
|
||||
queryData,
|
||||
)
|
||||
}
|
||||
customSeries={getCustomSeries}
|
||||
@@ -241,10 +243,11 @@ function CeleryTaskBar({
|
||||
{barState === CeleryTaskState.Successful && (
|
||||
<GridCard
|
||||
widget={celerySuccessStateFilteredData}
|
||||
version={ENTITY_VERSION_V5}
|
||||
headerMenuList={[...ViewMenuAction]}
|
||||
onDragSelect={onDragSelect}
|
||||
isQueryEnabled={queryEnabled}
|
||||
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
|
||||
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
|
||||
onGraphClick(
|
||||
celerySuccessTasksTableWidgetData,
|
||||
xValue,
|
||||
@@ -252,6 +255,7 @@ function CeleryTaskBar({
|
||||
mouseX,
|
||||
mouseY,
|
||||
data,
|
||||
queryData,
|
||||
)
|
||||
}
|
||||
customSeries={getCustomSeries}
|
||||
|
||||
@@ -48,15 +48,11 @@
|
||||
}
|
||||
|
||||
.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 {
|
||||
@@ -148,14 +144,12 @@
|
||||
|
||||
.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(--card) 40%, transparent);
|
||||
background: color-mix(in srgb, var(--surface-2) 40%, transparent);
|
||||
padding: 8px;
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
@@ -217,7 +211,6 @@
|
||||
}
|
||||
|
||||
&__label {
|
||||
font-family: 'Inter';
|
||||
font-size: 14px;
|
||||
color: var(--l2-foreground);
|
||||
line-height: 20px;
|
||||
@@ -225,7 +218,7 @@
|
||||
}
|
||||
|
||||
&__value {
|
||||
font-family: 'Geist Mono';
|
||||
font-family: var(--code-base-400-font-family);
|
||||
font-size: 24px;
|
||||
color: var(--l1-foreground);
|
||||
line-height: 32px;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { QueryParams } from 'constants/query';
|
||||
@@ -22,7 +22,10 @@ import {
|
||||
applyCeleryFilterOnWidgetData,
|
||||
getFiltersFromQueryParams,
|
||||
} from '../CeleryUtils';
|
||||
import { celeryTimeSeriesTablesWidgetData } from './CeleryTaskGraphUtils';
|
||||
import {
|
||||
celeryTimeSeriesTablesWidgetData,
|
||||
getClickedSeries,
|
||||
} from './CeleryTaskGraphUtils';
|
||||
|
||||
function CeleryTaskGraph({
|
||||
widgetData,
|
||||
@@ -102,13 +105,21 @@ function CeleryTaskGraph({
|
||||
widget={applyCeleryTaskFilter ? updatedWidgetData : widgetData}
|
||||
headerMenuList={[...ViewMenuAction]}
|
||||
onDragSelect={onDragSelect}
|
||||
onClickHandler={(xValue, _yValue, _mouseX, _mouseY, data): void => {
|
||||
onClickHandler={(
|
||||
xValue,
|
||||
_yValue,
|
||||
_mouseX,
|
||||
_mouseY,
|
||||
data,
|
||||
queryData,
|
||||
): void => {
|
||||
const clickedSeries = getClickedSeries(data, queryData);
|
||||
if (!clickedSeries) {
|
||||
return;
|
||||
}
|
||||
const { entity, value } = clickedSeries;
|
||||
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,
|
||||
@@ -126,7 +137,7 @@ function CeleryTaskGraph({
|
||||
isQueryEnabled={queryEnabled}
|
||||
openTracesButton={openTracesButton}
|
||||
onOpenTraceBtnClick={onOpenTraceBtnClick}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
customErrorMessage={customErrorMessage}
|
||||
start={start}
|
||||
end={end}
|
||||
|
||||
@@ -104,9 +104,16 @@ export default function CeleryTaskGraphGrid({
|
||||
<CardContainer className="row-card" isDarkMode={isDarkMode}>
|
||||
<div className="row-panel">
|
||||
<div className="row-panel-section">
|
||||
<Typography.Text className="section-title">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Flower Metrics
|
||||
</Typography.Text>
|
||||
</Typography>
|
||||
{collapsedSections.metricBasedGraphs ? (
|
||||
<ChevronDown
|
||||
size={14}
|
||||
@@ -137,17 +144,31 @@ export default function CeleryTaskGraphGrid({
|
||||
/>
|
||||
<Card className="celery-task-graph-worker-count">
|
||||
<div className="worker-count-header">
|
||||
<Typography.Text className="worker-count-header-text">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Worker Online
|
||||
</Typography.Text>
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="worker-count-text-container">
|
||||
<Typography.Text
|
||||
className="celery-task-graph-worker-count-text"
|
||||
data-testid="celery-worker-count"
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
display="inline-block"
|
||||
align="center"
|
||||
textOverflow="wrap"
|
||||
testId="celery-worker-count"
|
||||
>
|
||||
{workerCount ?? '-'}
|
||||
</Typography.Text>
|
||||
</Typography>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
@@ -158,9 +179,16 @@ export default function CeleryTaskGraphGrid({
|
||||
<CardContainer className="row-card" isDarkMode={isDarkMode}>
|
||||
<div className="row-panel">
|
||||
<div className="row-panel-section">
|
||||
<Typography.Text className="section-title">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Span Based Stats
|
||||
</Typography.Text>
|
||||
</Typography>
|
||||
{collapsedSections.traceBasedGraphs ? (
|
||||
<ChevronDown
|
||||
size={14}
|
||||
@@ -179,9 +207,16 @@ export default function CeleryTaskGraphGrid({
|
||||
</CardContainer>
|
||||
<div className="configure-option-Info">
|
||||
{configureOptionComponent}
|
||||
<Typography.Text className="configure-option-Info-text">
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="small"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Click on a graph co-ordinate to see more details
|
||||
</Typography.Text>
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
{!collapsedSections.traceBasedGraphs && (
|
||||
|
||||
@@ -9,9 +9,11 @@ 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';
|
||||
|
||||
@@ -40,6 +42,29 @@ 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,
|
||||
@@ -56,11 +81,12 @@ export const celeryAllStateWidgetData = (
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'count',
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: {
|
||||
items: [],
|
||||
items: [groupByKeyExists('celery.state')],
|
||||
op: 'AND',
|
||||
},
|
||||
functions: [],
|
||||
@@ -108,11 +134,13 @@ export const celeryRetryStateWidgetData = (
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'count',
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: {
|
||||
items: [
|
||||
groupByKeyExists('celery.hostname'),
|
||||
{
|
||||
id: uuidv4(),
|
||||
key: {
|
||||
@@ -168,11 +196,13 @@ export const celeryFailedStateWidgetData = (
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'count',
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: {
|
||||
items: [
|
||||
groupByKeyExists('celery.hostname'),
|
||||
{
|
||||
id: uuidv4(),
|
||||
key: {
|
||||
@@ -228,11 +258,13 @@ export const celerySuccessStateWidgetData = (
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'count',
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: {
|
||||
items: [
|
||||
groupByKeyExists('celery.hostname'),
|
||||
{
|
||||
id: uuidv4(),
|
||||
key: {
|
||||
@@ -287,11 +319,12 @@ export const celeryTasksByWorkerWidgetData = (
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'rate',
|
||||
aggregations: [{ expression: 'rate()' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: {
|
||||
items: [],
|
||||
items: [groupByKeyExists('celery.hostname')],
|
||||
op: 'AND',
|
||||
},
|
||||
functions: [],
|
||||
@@ -331,8 +364,9 @@ export const celeryErrorByWorkerWidgetData = (
|
||||
dataSource: DataSource.TRACES,
|
||||
queryName: 'A',
|
||||
aggregateOperator: 'count_distinct',
|
||||
aggregations: [{ expression: 'count_distinct(span_id)' }],
|
||||
aggregateAttribute: {
|
||||
dataType: 'string',
|
||||
dataType: DataTypes.String,
|
||||
id: 'span_id--string----true',
|
||||
key: 'span_id',
|
||||
type: '',
|
||||
@@ -342,6 +376,7 @@ export const celeryErrorByWorkerWidgetData = (
|
||||
functions: [],
|
||||
filters: {
|
||||
items: [
|
||||
groupByKeyExists('celery.hostname'),
|
||||
{
|
||||
id: uuidv4(),
|
||||
key: {
|
||||
@@ -374,11 +409,12 @@ export const celeryErrorByWorkerWidgetData = (
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
},
|
||||
{
|
||||
dataSource: 'traces',
|
||||
dataSource: DataSource.TRACES,
|
||||
queryName: 'B',
|
||||
aggregateOperator: 'count_distinct',
|
||||
aggregations: [{ expression: 'count_distinct(span_id)' }],
|
||||
aggregateAttribute: {
|
||||
dataType: 'string',
|
||||
dataType: DataTypes.String,
|
||||
id: 'span_id--string----true',
|
||||
key: 'span_id',
|
||||
type: '',
|
||||
@@ -387,7 +423,7 @@ export const celeryErrorByWorkerWidgetData = (
|
||||
spaceAggregation: 'sum',
|
||||
functions: [],
|
||||
filters: {
|
||||
items: [],
|
||||
items: [groupByKeyExists('celery.hostname')],
|
||||
op: 'AND',
|
||||
},
|
||||
expression: 'B',
|
||||
@@ -407,12 +443,14 @@ export const celeryErrorByWorkerWidgetData = (
|
||||
legend: '',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
},
|
||||
],
|
||||
queryFormulas: [
|
||||
{
|
||||
queryName: 'F1',
|
||||
expression: '(A/B)*100',
|
||||
disabled: false,
|
||||
legend: '{{celery.hostname}}',
|
||||
} as any,
|
||||
},
|
||||
],
|
||||
yAxisUnit: 'percent',
|
||||
}),
|
||||
@@ -435,11 +473,12 @@ export const celeryLatencyByWorkerWidgetData = (
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'p99',
|
||||
aggregations: [{ expression: 'p99(duration_nano)' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: {
|
||||
items: [],
|
||||
items: [groupByKeyExists('celery.hostname')],
|
||||
op: 'AND',
|
||||
},
|
||||
functions: [],
|
||||
@@ -532,11 +571,12 @@ export const celeryTaskLatencyWidgetData = (
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: type || 'p99',
|
||||
aggregations: [{ expression: latencyExpression(type) }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: {
|
||||
items: [],
|
||||
items: [groupByKeyExists('celery.task_name')],
|
||||
op: 'AND',
|
||||
},
|
||||
functions: [],
|
||||
@@ -553,7 +593,7 @@ export const celeryTaskLatencyWidgetData = (
|
||||
limit: null,
|
||||
orderBy: [
|
||||
{
|
||||
columnName: '#SIGNOZ_VALUE',
|
||||
columnName: latencyExpression(type),
|
||||
order: 'asc',
|
||||
},
|
||||
],
|
||||
@@ -583,11 +623,12 @@ export const celerySlowestTasksTableWidgetData = getWidgetQueryBuilder(
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'avg',
|
||||
aggregations: [{ expression: 'avg(duration_nano)' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: {
|
||||
items: [],
|
||||
items: [groupByKeyExists('celery.task_name')],
|
||||
op: 'AND',
|
||||
},
|
||||
functions: [],
|
||||
@@ -604,7 +645,7 @@ export const celerySlowestTasksTableWidgetData = getWidgetQueryBuilder(
|
||||
limit: 10,
|
||||
orderBy: [
|
||||
{
|
||||
columnName: '#SIGNOZ_VALUE',
|
||||
columnName: 'avg(duration_nano)',
|
||||
order: 'desc',
|
||||
},
|
||||
],
|
||||
@@ -633,11 +674,13 @@ 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: {
|
||||
@@ -666,7 +709,7 @@ export const celeryRetryTasksTableWidgetData = getWidgetQueryBuilder(
|
||||
limit: 10,
|
||||
orderBy: [
|
||||
{
|
||||
columnName: '#SIGNOZ_VALUE',
|
||||
columnName: 'avg(duration_nano)',
|
||||
order: 'desc',
|
||||
},
|
||||
],
|
||||
@@ -696,11 +739,13 @@ 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: {
|
||||
@@ -729,7 +774,7 @@ export const celeryFailedTasksTableWidgetData = getWidgetQueryBuilder(
|
||||
limit: null,
|
||||
orderBy: [
|
||||
{
|
||||
columnName: '#SIGNOZ_VALUE',
|
||||
columnName: 'avg(duration_nano)',
|
||||
order: 'desc',
|
||||
},
|
||||
],
|
||||
@@ -757,11 +802,13 @@ 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: {
|
||||
@@ -790,7 +837,7 @@ export const celerySuccessTasksTableWidgetData = getWidgetQueryBuilder(
|
||||
limit: null,
|
||||
orderBy: [
|
||||
{
|
||||
columnName: '#SIGNOZ_VALUE',
|
||||
columnName: 'avg(duration_nano)',
|
||||
order: 'desc',
|
||||
},
|
||||
],
|
||||
@@ -824,11 +871,13 @@ 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: {
|
||||
@@ -882,6 +931,7 @@ export const celeryAllStateCountWidgetData = getWidgetQueryBuilder(
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'count_distinct',
|
||||
aggregations: [{ expression: 'count_distinct(span_id)' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
@@ -919,6 +969,7 @@ export const celerySuccessStateCountWidgetData = getWidgetQueryBuilder(
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'count_distinct',
|
||||
aggregations: [{ expression: 'count_distinct(span_id)' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
@@ -968,6 +1019,7 @@ export const celeryFailedStateCountWidgetData = getWidgetQueryBuilder(
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'count_distinct',
|
||||
aggregations: [{ expression: 'count_distinct(span_id)' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
@@ -1017,6 +1069,7 @@ export const celeryRetryStateCountWidgetData = getWidgetQueryBuilder(
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'count_distinct',
|
||||
aggregations: [{ expression: 'count_distinct(span_id)' }],
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { Col, Row } from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
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';
|
||||
@@ -27,7 +29,10 @@ import {
|
||||
getFiltersFromQueryParams,
|
||||
} from '../CeleryUtils';
|
||||
import { useNavigateToExplorer } from '../useNavigateToExplorer';
|
||||
import { celeryTaskLatencyWidgetData } from './CeleryTaskGraphUtils';
|
||||
import {
|
||||
celeryTaskLatencyWidgetData,
|
||||
getClickedSeries,
|
||||
} from './CeleryTaskGraphUtils';
|
||||
|
||||
import './CeleryTaskGraph.style.scss';
|
||||
|
||||
@@ -128,13 +133,12 @@ function CeleryTaskLatencyGraph({
|
||||
|
||||
const onGraphClick = useCallback(
|
||||
(type: string): OnClickPluginOpts['onClick'] =>
|
||||
(xValue, yValue, mouseX, mouseY, data): Promise<void> => {
|
||||
const [firstDataPoint] = Object.entries(data || {});
|
||||
const [entity, value] = firstDataPoint;
|
||||
setEntityData({
|
||||
entity,
|
||||
value,
|
||||
});
|
||||
(xValue, yValue, mouseX, mouseY, data, queryData): Promise<void> => {
|
||||
const clickedSeries = getClickedSeries(data, queryData);
|
||||
if (!clickedSeries) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
setEntityData(clickedSeries);
|
||||
|
||||
return onGraphClickHandler(xValue, yValue, mouseX, mouseY, type);
|
||||
},
|
||||
@@ -198,6 +202,7 @@ function CeleryTaskLatencyGraph({
|
||||
</Button>
|
||||
<GridCard
|
||||
widget={updatedWidgetData}
|
||||
version={ENTITY_VERSION_V5}
|
||||
headerMenuList={[...ViewMenuAction]}
|
||||
onDragSelect={onDragSelect}
|
||||
onClickHandler={onGraphClick('Celery_p99_latency')}
|
||||
@@ -219,6 +224,7 @@ function CeleryTaskLatencyGraph({
|
||||
</Button>
|
||||
<GridCard
|
||||
widget={updatedWidgetData}
|
||||
version={ENTITY_VERSION_V5}
|
||||
headerMenuList={[...ViewMenuAction]}
|
||||
onDragSelect={onDragSelect}
|
||||
onClickHandler={onGraphClick('Celery_p95_latency')}
|
||||
@@ -239,6 +245,7 @@ function CeleryTaskLatencyGraph({
|
||||
</Button>
|
||||
<GridCard
|
||||
widget={updatedWidgetData}
|
||||
version={ENTITY_VERSION_V5}
|
||||
headerMenuList={[...ViewMenuAction]}
|
||||
onDragSelect={onDragSelect}
|
||||
onClickHandler={onGraphClick('Celery_p90_latency')}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Dispatch, SetStateAction, useMemo } from 'react';
|
||||
import { Col, Row } from 'antd';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
@@ -89,7 +90,10 @@ function CeleryTaskStateGraphConfig({
|
||||
>
|
||||
<div className="celery-task-states__label-wrapper">
|
||||
<div className="celery-task-states__label">{tab.label}</div>
|
||||
<div className="celery-task-states__value">
|
||||
<div
|
||||
className="celery-task-states__value"
|
||||
data-testid={`celery-state-value-${tab.key}`}
|
||||
>
|
||||
{isLoading
|
||||
? '-'
|
||||
: isError
|
||||
|
||||
@@ -61,7 +61,13 @@ describe('CeleryTaskGraphGrid worker count', () => {
|
||||
);
|
||||
|
||||
const { minTime, maxTime } = store.getState().globalTime;
|
||||
expect(requests).toStrictEqual([
|
||||
expect(
|
||||
requests.filter((request) =>
|
||||
request.compositeQuery?.queries?.some(
|
||||
(query) => (query.spec as { signal?: string }).signal === 'metrics',
|
||||
),
|
||||
),
|
||||
).toStrictEqual([
|
||||
{
|
||||
schemaVersion: 'v1',
|
||||
start: Math.floor(minTime / 1e6),
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
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',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
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'),
|
||||
],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -2,10 +2,13 @@ import { useCallback } from 'react';
|
||||
import { useQueries } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
|
||||
import { getQueryPayloadFromWidgetsData } from 'pages/Celery/CeleryOverview/CeleryOverviewUtils';
|
||||
import {
|
||||
getQueryPayloadFromWidgetsData,
|
||||
getValueFromScalarResponse,
|
||||
} from 'pages/Celery/CeleryOverview/CeleryOverviewUtils';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { SuccessResponse } from 'types/api';
|
||||
import { Widgets } from 'types/api/widgets/widget';
|
||||
@@ -39,9 +42,9 @@ export const useGetValueFromWidget = (
|
||||
|
||||
const queries = useQueries(
|
||||
queryPayloads().map((payload) => ({
|
||||
queryKey: [...queryKey, payload, ENTITY_VERSION_V4],
|
||||
queryKey: [...queryKey, payload, ENTITY_VERSION_V5],
|
||||
queryFn: (): Promise<SuccessResponse<MetricRangePayloadProps>> =>
|
||||
GetMetricQueryRange(payload, ENTITY_VERSION_V4),
|
||||
GetMetricQueryRange(payload, ENTITY_VERSION_V5),
|
||||
enabled: !!payload,
|
||||
})),
|
||||
);
|
||||
@@ -57,11 +60,7 @@ export const useGetValueFromWidget = (
|
||||
return 'Error';
|
||||
}
|
||||
|
||||
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 getValueFromScalarResponse(query.data);
|
||||
});
|
||||
|
||||
return { values, isLoading, isError };
|
||||
|
||||
@@ -11,9 +11,7 @@
|
||||
justify-content: center;
|
||||
}
|
||||
&__label {
|
||||
font-family: 'Geist Mono';
|
||||
font-size: 12px;
|
||||
line-height: normal;
|
||||
font-family: var(--code-base-400-font-family);
|
||||
}
|
||||
&--positive {
|
||||
.change-percentage-pill {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useMutation } from 'react-query';
|
||||
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
|
||||
import { Button, Flex, Modal } from 'antd';
|
||||
import { Button, Modal } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import updateUserPreference from 'api/v1/user/preferences/name/update';
|
||||
import cx from 'classnames';
|
||||
import { USER_PREFERENCES } from 'constants/userPreferences';
|
||||
@@ -97,6 +98,10 @@ 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')}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
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' },
|
||||
};
|
||||
65
frontend/src/components/ChangelogModal/stories/__story_mockdata__/changelog.ts
generated
Normal file
65
frontend/src/components/ChangelogModal/stories/__story_mockdata__/changelog.ts
generated
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* 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.',
|
||||
};
|
||||
@@ -17,10 +17,6 @@
|
||||
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;
|
||||
|
||||
|
||||
@@ -17,13 +17,13 @@
|
||||
|
||||
pre {
|
||||
color: var(--l2-foreground) !important;
|
||||
font-family: 'Geist Mono' !important;
|
||||
font-family: var(--code-small-400-font-family) !important;
|
||||
font-size: 12px !important;
|
||||
}
|
||||
|
||||
code {
|
||||
color: var(--l1-foreground) !important;
|
||||
font-family: 'Geist Mono' !important;
|
||||
font-family: var(--code-small-400-font-family) !important;
|
||||
font-size: 12px !important;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,3 @@
|
||||
.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;
|
||||
@@ -43,32 +10,11 @@
|
||||
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);
|
||||
@@ -77,22 +23,7 @@
|
||||
}
|
||||
|
||||
&__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;
|
||||
}
|
||||
|
||||
@@ -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 { DialogFooter, DialogWrapper } from '@signozhq/ui/dialog';
|
||||
import { Dialog } from '@signozhq/ui/dialog';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import {
|
||||
invalidateListServiceAccounts,
|
||||
@@ -35,7 +35,7 @@ function CreateServiceAccountModal(): JSX.Element {
|
||||
);
|
||||
const [, setSelectedAccountId] = useQueryState(SA_QUERY_PARAMS.ACCOUNT);
|
||||
|
||||
const { showErrorModal, isErrorModalVisible } = useErrorModal();
|
||||
const { showErrorModal } = useErrorModal();
|
||||
|
||||
const {
|
||||
control,
|
||||
@@ -82,84 +82,75 @@ function CreateServiceAccountModal(): JSX.Element {
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogWrapper
|
||||
<Dialog
|
||||
title="New Service Account"
|
||||
open={isOpen}
|
||||
onOpenChange={(open): void => {
|
||||
if (!open) {
|
||||
handleClose();
|
||||
}
|
||||
}}
|
||||
showCloseButton
|
||||
width="narrow"
|
||||
className="create-sa-modal"
|
||||
disableOutsideClick={isErrorModalVisible}
|
||||
onClose={handleClose}
|
||||
width="base"
|
||||
testId="create-service-account-modal"
|
||||
>
|
||||
<div className="create-sa-modal__content">
|
||||
<AuthZGuardContent
|
||||
checks={[SACreatePermission]}
|
||||
fallbackOnLoading={<Skeleton active paragraph={{ rows: 1 }} />}
|
||||
>
|
||||
<form
|
||||
id="create-sa-form"
|
||||
className="create-sa-form"
|
||||
onSubmit={handleSubmit(handleCreate)}
|
||||
footerSuffix={
|
||||
<>
|
||||
<Button
|
||||
size="md"
|
||||
type="button"
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
onClick={handleClose}
|
||||
testId="create-sa-cancel-btn"
|
||||
prefix={<X size={12} />}
|
||||
>
|
||||
<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>
|
||||
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-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"
|
||||
/>
|
||||
)}
|
||||
</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>
|
||||
/>
|
||||
{errors.name && (
|
||||
<p className="create-sa-form__error">{errors.name.message}</p>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</AuthZGuardContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { toast } from '@signozhq/ui/toast';
|
||||
import {
|
||||
setupAuthzAdmin,
|
||||
setupAuthzDenyAll,
|
||||
@@ -10,9 +10,9 @@ import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import CreateServiceAccountModal from '../CreateServiceAccountModal';
|
||||
|
||||
jest.mock('@signozhq/ui/sonner', () => ({
|
||||
...jest.requireActual('@signozhq/ui/sonner'),
|
||||
toast: { success: jest.fn(), error: jest.fn() },
|
||||
jest.mock('@signozhq/ui/toast', () => ({
|
||||
...jest.requireActual('@signozhq/ui/toast'),
|
||||
toast: { success: jest.fn(), danger: jest.fn() },
|
||||
}));
|
||||
|
||||
const mockToast = jest.mocked(toast);
|
||||
@@ -23,7 +23,6 @@ jest.mock('providers/ErrorModalProvider', () => ({
|
||||
...jest.requireActual('providers/ErrorModalProvider'),
|
||||
useErrorModal: jest.fn(() => ({
|
||||
showErrorModal,
|
||||
isErrorModalVisible: false,
|
||||
})),
|
||||
}));
|
||||
|
||||
@@ -58,7 +57,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');
|
||||
await screen.findByTestId('create-sa-name-input-field');
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('create-sa-submit-btn')).toHaveAttribute(
|
||||
@@ -72,7 +71,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input');
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
const submitBtn = await screen.findByTestId('create-sa-submit-btn');
|
||||
|
||||
await user.type(nameInput, 'test');
|
||||
@@ -90,7 +89,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input');
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
await user.type(nameInput, 'Deploy Bot');
|
||||
|
||||
const submitBtn = screen.getByTestId('create-sa-submit-btn');
|
||||
@@ -128,7 +127,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId<HTMLInputElement>(
|
||||
'create-sa-name-input',
|
||||
'create-sa-name-input-field',
|
||||
);
|
||||
await user.type(nameInput, 'Deploy Bot');
|
||||
const submitBtn = screen.getByTestId('create-sa-submit-btn');
|
||||
@@ -160,7 +159,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input');
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
await user.type(nameInput, 'Dupe Bot');
|
||||
|
||||
const submitBtn = screen.getByTestId('create-sa-submit-btn');
|
||||
@@ -209,7 +208,9 @@ describe('CreateServiceAccountModal', () => {
|
||||
screen.findByText(/is not authorized to perform/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
expect(screen.queryByTestId('create-sa-name-input')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('create-sa-name-input-field'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByTestId('create-service-account-modal'),
|
||||
).toBeInTheDocument();
|
||||
@@ -244,7 +245,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input');
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
await user.type(nameInput, 'Bot');
|
||||
await user.clear(nameInput);
|
||||
|
||||
|
||||
@@ -65,8 +65,6 @@
|
||||
.valid-format-error {
|
||||
margin-top: 4px;
|
||||
color: var(--bg-cherry-400) !important;
|
||||
font-size: 13px !important;
|
||||
font-weight: 400 !important;
|
||||
}
|
||||
|
||||
.info-text {
|
||||
@@ -76,11 +74,6 @@
|
||||
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 {
|
||||
@@ -104,15 +97,11 @@
|
||||
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;
|
||||
}
|
||||
@@ -228,10 +217,6 @@
|
||||
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;
|
||||
|
||||
@@ -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) {
|
||||
if (inputElement && !document.activeElement?.closest('.timezone-picker')) {
|
||||
inputElement.focus();
|
||||
inputElement.select();
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ $item-spacing: 8px;
|
||||
.timezone-picker {
|
||||
width: 532px;
|
||||
color: var(--l2-foreground);
|
||||
font-family: $font-family;
|
||||
|
||||
&__search {
|
||||
@include flex-center;
|
||||
@@ -34,34 +33,8 @@ $item-spacing: 8px;
|
||||
@include flex-center;
|
||||
gap: 6px;
|
||||
width: -webkit-fill-available;
|
||||
}
|
||||
|
||||
&__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);
|
||||
}
|
||||
--input-hover-border-color: transparent;
|
||||
}
|
||||
|
||||
&__esc-key {
|
||||
|
||||
@@ -65,7 +65,8 @@ function SearchBar({
|
||||
/>
|
||||
<Input
|
||||
type="text"
|
||||
className="timezone-picker__input"
|
||||
variant="unstyled"
|
||||
noFocusRing
|
||||
placeholder="Search timezones..."
|
||||
value={value}
|
||||
onChange={(e): void => onChange(e.target.value)}
|
||||
|
||||
@@ -12,5 +12,4 @@
|
||||
|
||||
.name {
|
||||
color: var(--danger-background);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
.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;
|
||||
@@ -12,7 +9,6 @@
|
||||
background: var(--l2-background);
|
||||
|
||||
&__title {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--l1-foreground);
|
||||
flex: 1;
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
.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%;
|
||||
}
|
||||
@@ -1,56 +1,46 @@
|
||||
import { Drawer, DrawerContent } from '@signozhq/ui/drawer';
|
||||
import cx from 'classnames';
|
||||
import { AnimatePresence } from 'motion/react';
|
||||
|
||||
import styles from './DetailsPanelDrawer.module.scss';
|
||||
import { ReactNode } from 'react';
|
||||
import { Drawer } from '@signozhq/ui/drawer';
|
||||
|
||||
interface DetailsPanelDrawerProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
headerSuffix?: ReactNode;
|
||||
loading?: boolean;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
function DetailsPanelDrawer({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
children,
|
||||
className,
|
||||
headerSuffix,
|
||||
loading,
|
||||
testId,
|
||||
}: DetailsPanelDrawerProps): JSX.Element {
|
||||
return (
|
||||
<Drawer
|
||||
type="inspector"
|
||||
stack="overlay"
|
||||
open={isOpen}
|
||||
onOpenChange={(open): void => {
|
||||
if (!open) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
modal={false}
|
||||
onClose={onClose}
|
||||
title={title}
|
||||
width="extra-wide"
|
||||
closePosition="start"
|
||||
headerSuffix={headerSuffix}
|
||||
loading={loading}
|
||||
testId={testId}
|
||||
>
|
||||
<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>
|
||||
{children}
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
DetailsPanelDrawer.defaultProps = {
|
||||
className: undefined,
|
||||
headerSuffix: undefined,
|
||||
loading: false,
|
||||
testId: undefined,
|
||||
};
|
||||
|
||||
|
||||
28
frontend/src/components/DotGrid/DotGrid.module.scss
Normal file
28
frontend/src/components/DotGrid/DotGrid.module.scss
Normal file
@@ -0,0 +1,28 @@
|
||||
.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;
|
||||
}
|
||||
35
frontend/src/components/DotGrid/DotGrid.tsx
Normal file
35
frontend/src/components/DotGrid/DotGrid.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
103
frontend/src/components/DotGrid/__tests__/DotGrid.test.tsx
Normal file
103
frontend/src/components/DotGrid/__tests__/DotGrid.test.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
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)',
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
112
frontend/src/components/DotGrid/__tests__/snakeGame.test.ts
Normal file
112
frontend/src/components/DotGrid/__tests__/snakeGame.test.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
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 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
53
frontend/src/components/DotGrid/dotGridField.ts
Normal file
53
frontend/src/components/DotGrid/dotGridField.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
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,
|
||||
];
|
||||
}
|
||||
34
frontend/src/components/DotGrid/dotGridTheme.ts
Normal file
34
frontend/src/components/DotGrid/dotGridTheme.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
// 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),
|
||||
};
|
||||
}
|
||||
102
frontend/src/components/DotGrid/drawDots.ts
Normal file
102
frontend/src/components/DotGrid/drawDots.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
// 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';
|
||||
}
|
||||
100
frontend/src/components/DotGrid/snakeGame.ts
Normal file
100
frontend/src/components/DotGrid/snakeGame.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
// 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) };
|
||||
}
|
||||
320
frontend/src/components/DotGrid/useDotGrid.ts
Normal file
320
frontend/src/components/DotGrid/useDotGrid.ts
Normal file
@@ -0,0 +1,320 @@
|
||||
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;
|
||||
}
|
||||
@@ -68,7 +68,17 @@ export default function DownloadOptionsMenu({
|
||||
aria-modal="true"
|
||||
>
|
||||
<div className="export-format">
|
||||
<Typography.Text className="title">FORMAT</Typography.Text>
|
||||
<Typography
|
||||
variant="uppercase"
|
||||
size="small"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="p"
|
||||
marginBottom={4}
|
||||
textOverflow="wrap"
|
||||
>
|
||||
FORMAT
|
||||
</Typography>
|
||||
<RadioGroup
|
||||
color="primary"
|
||||
value={exportFormat}
|
||||
@@ -83,7 +93,17 @@ export default function DownloadOptionsMenu({
|
||||
<div className="horizontal-line" />
|
||||
|
||||
<div className="row-limit">
|
||||
<Typography.Text className="title">Number of Rows</Typography.Text>
|
||||
<Typography
|
||||
variant="uppercase"
|
||||
size="small"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="p"
|
||||
marginBottom={4}
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Number of Rows
|
||||
</Typography>
|
||||
<RadioGroup
|
||||
color="primary"
|
||||
value={String(rowLimit)}
|
||||
@@ -101,7 +121,17 @@ export default function DownloadOptionsMenu({
|
||||
<div className="horizontal-line" />
|
||||
|
||||
<div className="columns-scope">
|
||||
<Typography.Text className="title">Columns</Typography.Text>
|
||||
<Typography
|
||||
variant="uppercase"
|
||||
size="small"
|
||||
weight="medium"
|
||||
color="main"
|
||||
as="p"
|
||||
marginBottom={4}
|
||||
textOverflow="wrap"
|
||||
>
|
||||
Columns
|
||||
</Typography>
|
||||
<RadioGroup
|
||||
color="primary"
|
||||
value={columnsScope}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Trash2, X } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { DialogWrapper } from '@signozhq/ui/dialog';
|
||||
import { AlertDialog } from '@signozhq/ui/alert-dialog';
|
||||
import { MemberRow } from 'components/MembersTable/MembersTable';
|
||||
|
||||
interface DeleteMemberDialogProps {
|
||||
@@ -9,7 +8,7 @@ interface DeleteMemberDialogProps {
|
||||
member: MemberRow | null;
|
||||
isDeleting: boolean;
|
||||
onClose: () => void;
|
||||
onConfirm: () => void;
|
||||
onConfirm: () => Promise<void>;
|
||||
}
|
||||
|
||||
function DeleteMemberDialog({
|
||||
@@ -36,47 +35,20 @@ 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 (
|
||||
<DialogWrapper
|
||||
<AlertDialog
|
||||
open={open}
|
||||
onOpenChange={(isOpen): void => {
|
||||
if (!isOpen) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
title={title}
|
||||
width="narrow"
|
||||
showCloseButton={false}
|
||||
disableOutsideClick={false}
|
||||
footer={footer}
|
||||
color="danger"
|
||||
confirmText={isDeleting ? 'Processing...' : title}
|
||||
confirmIcon={<Trash2 size={12} />}
|
||||
cancelIcon={<X size={12} />}
|
||||
onConfirm={onConfirm}
|
||||
onCancel={onClose}
|
||||
testId="member-delete"
|
||||
>
|
||||
{body}
|
||||
</DialogWrapper>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,10 +20,9 @@
|
||||
}
|
||||
|
||||
&__label {
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-normal);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
color: var(--foreground);
|
||||
line-height: var(--line-height-20);
|
||||
line-height: var(--paragraph-base-400-line-height);
|
||||
letter-spacing: -0.07px;
|
||||
cursor: default;
|
||||
}
|
||||
@@ -53,10 +52,8 @@
|
||||
}
|
||||
|
||||
&__email-text {
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
font-weight: var(--paragraph-base-400-font-weight);
|
||||
color: var(--foreground);
|
||||
line-height: var(--line-height-18);
|
||||
line-height: var(--paragraph-small-400-line-height);
|
||||
letter-spacing: -0.07px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
@@ -86,41 +83,26 @@
|
||||
[data-slot='badge'] {
|
||||
padding: var(--padding-1) var(--padding-2);
|
||||
align-items: center;
|
||||
font-size: var(--uppercase-small-500-font-size);
|
||||
font-weight: var(--uppercase-small-500-font-weight);
|
||||
line-height: 100%;
|
||||
letter-spacing: 0.44px;
|
||||
}
|
||||
}
|
||||
|
||||
&__meta-label {
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-medium);
|
||||
font-size: var(--uppercase-small-500-font-size);
|
||||
font-weight: var(--uppercase-small-500-font-weight);
|
||||
color: var(--foreground);
|
||||
line-height: var(--line-height-20);
|
||||
line-height: var(--uppercase-small-500-line-height);
|
||||
letter-spacing: 0.48px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
&__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
&__footer-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
&__footer-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-6);
|
||||
}
|
||||
|
||||
&__footer-divider {
|
||||
width: 1px;
|
||||
height: 21px;
|
||||
@@ -163,14 +145,6 @@
|
||||
}
|
||||
|
||||
.reset-link-dialog {
|
||||
background: var(--l2-background);
|
||||
border: 1px solid var(--l1-border);
|
||||
|
||||
[data-slot='dialog-header'] {
|
||||
border-color: var(--l1-border);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
&__content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -178,8 +152,6 @@
|
||||
}
|
||||
|
||||
&__description {
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
font-weight: var(--paragraph-base-400-font-weight);
|
||||
color: var(--l2-foreground);
|
||||
line-height: var(--paragraph-base-400-line-height);
|
||||
letter-spacing: -0.065px;
|
||||
@@ -193,8 +165,8 @@
|
||||
align-items: center;
|
||||
height: 32px;
|
||||
overflow: hidden;
|
||||
background: var(--l2-background);
|
||||
border: 1px solid var(--l1-border);
|
||||
background: var(--l3-background);
|
||||
border: 1px solid var(--l3-border);
|
||||
border-radius: 2px;
|
||||
padding-right: var(--spacing-4);
|
||||
}
|
||||
@@ -211,10 +183,8 @@
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
padding: 0 var(--padding-2);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
font-weight: var(--paragraph-base-400-font-weight);
|
||||
color: var(--l2-foreground);
|
||||
line-height: var(--line-height-18);
|
||||
line-height: var(--paragraph-small-400-line-height);
|
||||
letter-spacing: -0.07px;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user