Compare commits

..

7 Commits

Author SHA1 Message Date
Naman Verma
8101a79371 Merge branch 'main' into nv/exec-stats 2026-11-16 10:43:03 +05:30
Naman Verma
62d477e920 Merge branch 'main' into nv/exec-stats 2026-11-09 12:20:27 +05:30
Naman Verma
fe45b9dcae Merge branch 'main' into nv/exec-stats 2026-11-06 00:51:46 +05:30
Naman Verma
63ee60a40c fix(querier): stop cache refreshes from inflating exec stats 2026-11-06 00:51:03 +05:30
Naman Verma
29a393e47e Merge branch 'main' into nv/exec-stats 2026-11-05 10:51:11 +05:30
Naman Verma
c58f76f998 Merge branch 'main' into nv/exec-stats 2026-11-03 11:34:10 +05:30
Naman Verma
e39ad9e221 test: check how exec stats fail 2026-11-02 22:24:22 +05:30
697 changed files with 4575 additions and 25254 deletions

View File

@@ -2,50 +2,44 @@ name: e2eci
on:
pull_request:
types:
- opened
- synchronize
- reopened
- labeled
merge_group:
types:
- checks_requested
# Labels other than safe-to-e2e get a group of their own, so they never cancel a running e2e.
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event.action == 'labeled' && github.event.label.name != 'safe-to-e2e' && format('-{0}', github.run_id) || '' }}
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
changes:
if: github.event.action != 'labeled' || github.event.label.name == 'safe-to-e2e'
runs-on: ubuntu-latest
outputs:
e2e: ${{ steps.changes.outputs.e2e }}
steps:
- name: merge-queue-pass
if: github.event_name == 'merge_group'
run: echo "::notice::Merge queue run. E2E already gated the PR, so the required e2e check auto-passes."
- name: changes
id: changes
if: github.event_name == 'pull_request'
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
FORCE: ${{ github.event_name == 'merge_group' || contains(github.event.pull_request.labels.*.name, 'safe-to-e2e') }}
FORCE: ${{ contains(github.event.pull_request.labels.*.name, 'safe-to-e2e') }}
run: |
if [ "$FORCE" = "true" ]; then
echo "e2e=true" >> "$GITHUB_OUTPUT"
exit 0
fi
CHANGED_FILES=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/files" --paginate --jq '.[].filename | select((startswith("tests/integration/") or startswith("frontend/src/api/generated/")) | not)')
PATTERN='^(frontend/|tests/|\.github/workflows/e2eci\.yaml$|cmd/enterprise/Dockerfile\.with-web\.integration$)'
if printf '%s\n' "$CHANGED_FILES" | grep -qE "$PATTERN"; then
if [ "$FORCE" = "true" ]; then
echo "e2e=true" >> "$GITHUB_OUTPUT"
elif printf '%s\n' "$CHANGED_FILES" | grep -qE "$PATTERN"; then
echo "e2e=true" >> "$GITHUB_OUTPUT"
else
echo "e2e=false" >> "$GITHUB_OUTPUT"
fi
fmtlint:
needs: changes
if: github.event_name != 'merge_group' && needs.changes.outputs.e2e == 'true'
if: needs.changes.outputs.e2e == 'true'
runs-on: ubuntu-latest
steps:
- name: checkout
@@ -186,8 +180,6 @@ jobs:
retention-days: 5
# Required status check. Fails when e2e was needed but did not pass.
e2e:
# Runs for other labels must not report as e2e, or their pass would hide the real result.
name: ${{ github.event.action == 'labeled' && github.event.label.name != 'safe-to-e2e' && 'ignored-label' || 'e2e' }}
if: always()
needs: [changes, fmtlint, test]
runs-on: ubuntu-latest

View File

@@ -40,11 +40,11 @@ jobs:
suite:
- alertmanager
- alertmanagerrotation
- auditquerier
- basepath
- callbackauthn
- cloudintegrations
- dashboard
- fileauditor
- ingestionkeys
- inframonitoring
- llmpricingrules
@@ -58,7 +58,6 @@ jobs:
- querierscalar
- queriercommon
- querierai
- querieraudit
- rawexportdata
- promqlconformance
- promapiconformance

View File

@@ -132,26 +132,3 @@ jobs:
run: |
cd frontend && pnpm generate:config:web-settings
git diff --compact-summary --exit-code || (echo; echo "Unexpected difference in generated web settings types. Run pnpm generate:config:web-settings in frontend/ locally and commit."; exit 1)
geo-outlines:
if: |
(github.event_name == 'pull_request' && ! github.event.pull_request.head.repo.fork && github.event.pull_request.user.login != 'dependabot[bot]' && ! contains(github.event.pull_request.labels.*.name, 'safe-to-test')) ||
(github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'safe-to-test'))
runs-on: ubuntu-latest
steps:
- name: self-checkout
uses: actions/checkout@v4
- name: node-install
uses: actions/setup-node@v5
with:
node-version: "22"
- name: install-pnpm
uses: pnpm/action-setup@v6
with:
version: 10
- name: install-frontend
run: cd frontend && pnpm install
- name: generate-geo-outlines
run: |
cd frontend && pnpm build:geo-outlines
git status --short
test -z "$(git status --porcelain)" || (echo; echo "Unexpected difference in geo map outlines. Run pnpm build:geo-outlines in frontend/ locally and commit."; exit 1)

View File

@@ -30,7 +30,7 @@ export default {
],
relations: {
{{- range .Relations }}
{{ .FormattedTypes }}
{{ .Verb }}: [{{ range $i, $t := .Types }}{{ if $i }}, {{ end }}'{{ $t }}'{{ end }}],
{{- end }}
},
},
@@ -38,8 +38,8 @@ export default {
`))
type permissionsTypeRelation struct {
Verb string
FormattedTypes string
Verb string
Types []string
}
type permissionsTypeResource struct {
@@ -77,29 +77,6 @@ func formatAllowedVerbs(verbs []string, indentLevel int, printWidth int) string
return b.String()
}
// formatRelationTypes returns a prettier-compatible formatted `verb: [...]` line, wrapping
// one type per line when it exceeds printWidth (tabWidth assumed to be 1).
func formatRelationTypes(verb string, types []string, indentLevel int, printWidth int) string {
quoted := make([]string, len(types))
for i, t := range types {
quoted[i] = "'" + t + "'"
}
indent := strings.Repeat("\t", indentLevel)
oneLine := indent + verb + ": [" + strings.Join(quoted, ", ") + "],"
if len(oneLine) <= printWidth {
return oneLine
}
var b strings.Builder
b.WriteString(indent + verb + ": [\n")
for _, q := range quoted {
b.WriteString(indent + "\t" + q + ",\n")
}
b.WriteString(indent + "],")
return b.String()
}
func registerGenerateAuthz(parentCmd *cobra.Command) {
authzCmd := &cobra.Command{
Use: "authz",
@@ -129,8 +106,6 @@ func runGenerateAuthz(_ context.Context) error {
coretypes.NewResourceRef(coretypes.ResourceMetaResourceQuickFilter).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceSavedView).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceNotificationChannel).String(): true,
coretypes.NewResourceRef(coretypes.ResourceUser).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceFactorPassword).String(): true,
}
allowedTypes := map[string]bool{}
@@ -179,8 +154,8 @@ func runGenerateAuthz(_ context.Context) error {
types = append(types, t.StringValue())
}
relations = append(relations, permissionsTypeRelation{
Verb: verb.StringValue(),
FormattedTypes: formatRelationTypes(verb.StringValue(), types, 3, 80),
Verb: verb.StringValue(),
Types: types,
})
}

View File

@@ -4318,11 +4318,6 @@ components:
last_6_hr, last_1_day, last_3_days, last_1_week or last_1_month pin a
fixed window.'
type: object
DashboardtypesBubbleRadius:
maximum: 64
minimum: 1
nullable: true
type: integer
DashboardtypesBuilderQuerySpec:
discriminator:
mapping:
@@ -4555,231 +4550,6 @@ components:
minimum: 0
nullable: true
type: number
DashboardtypesGeoMapBubbles:
properties:
maxRadius:
allOf:
- $ref: '#/components/schemas/DashboardtypesBubbleRadius'
description: Radius of the largest circle, in CSS pixels from 1 to 64. Null
means 8 on the points layer, 28 otherwise.
minRadius:
allOf:
- $ref: '#/components/schemas/DashboardtypesBubbleRadius'
description: Radius of the smallest circle, in CSS pixels from 1 to 64.
Null means 2 on the points layer, 3 otherwise.
type: object
DashboardtypesGeoMapChartAppearance:
properties:
bubbles:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapBubbles'
description: The circle radius range of the bubbles and points layers.
colors:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapColors'
description: The color scale applied to the colorBy values.
labels:
description: Shows country and state names once each fits inside its shape.
Null shows them.
nullable: true
type: boolean
type: object
DashboardtypesGeoMapColors:
properties:
fill:
description: The hex color varied in opacity mode. Empty uses the default
fill.
type: string
max:
description: The value mapped to the highest color. Null uses the highest
value in the data.
nullable: true
type: number
min:
description: The value mapped to the lowest color. Null uses the lowest
value in the data. Must not exceed max.
nullable: true
type: number
mode:
allOf:
- $ref: '#/components/schemas/DashboardtypesHeatmapColorMode'
description: 'How values are colored: palette (default) picks a hue from
palette, opacity varies the opacity of fill.'
palette:
allOf:
- $ref: '#/components/schemas/DashboardtypesHeatmapPalette'
description: The named color ramp used in palette mode, such as lava (default),
ice or ember.
scale:
allOf:
- $ref: '#/components/schemas/DashboardtypesHeatmapColorScale'
description: 'How values map onto the color range: log (default), sqrt or
linear.'
steps:
description: The number of distinct color steps, 2 to 128. 0 uses the chart
default.
type: integer
type: object
DashboardtypesGeoMapCountryFormat:
enum:
- auto
- alpha2
- alpha3
- name
type: string
DashboardtypesGeoMapLayer:
enum:
- regions
- bubbles
- points
type: string
DashboardtypesGeoMapLocation:
properties:
country:
description: Group-by key holding the country, for the country and subdivision
modes. Empty detects it by name, such as geo.country.iso_code.
type: string
countryFormat:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapCountryFormat'
description: 'How country values are written: auto (default) detects it,
alpha2, alpha3 or name.'
lat:
description: Group-by key holding the latitude, for the coordinates mode.
Empty detects it by name.
type: string
lon:
description: Group-by key holding the longitude, for the coordinates mode.
Empty detects it by name.
type: string
mode:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapLocationMode'
description: 'How rows are placed: auto (default) detects it from the group-by
keys, country, subdivision or coordinates.'
region:
description: Group-by key holding the ISO 3166-2 region code (e.g. geo.region.iso_code),
for the subdivision mode. Empty detects it by name.
type: string
required:
- mode
- countryFormat
type: object
DashboardtypesGeoMapLocationMode:
enum:
- auto
- country
- subdivision
- coordinates
type: string
DashboardtypesGeoMapPanelSpec:
properties:
chartAppearance:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapChartAppearance'
description: Color scale, bubble size and labels.
formatting:
allOf:
- $ref: '#/components/schemas/DashboardtypesTableFormatting'
description: Per-column units and decimal precision.
legend:
allOf:
- $ref: '#/components/schemas/DashboardtypesLegend'
description: Legend placement.
location:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapLocation'
description: The group-by columns that place each row on the map.
map:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapSettings'
description: Layer, view, projection and the value columns drawn.
thresholds:
description: Rules that recolor a shape, bubble or point when its value
compares to a threshold as specified.
items:
$ref: '#/components/schemas/DashboardtypesGeoMapThreshold'
nullable: true
type: array
visualization:
allOf:
- $ref: '#/components/schemas/DashboardtypesBasicVisualization'
description: The time range the values are computed over.
type: object
DashboardtypesGeoMapProjection:
enum:
- mercator
- equal_earth
- natural_earth
type: string
DashboardtypesGeoMapSettings:
properties:
colorBy:
description: Value column key, as in a Table panel, that sets the color.
Empty uses the first value column.
type: string
layer:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapLayer'
description: 'What is drawn: regions (default) fills each shape, bubbles
draws a circle per region, points a circle per coordinate.'
projection:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapProjection'
description: 'The map projection: mercator (default), equal_earth or natural_earth.'
sizeBy:
description: Value column key, as in a Table panel, that sets the bubble
or point size. Empty uses colorBy.
type: string
view:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapView'
description: 'The area shown: world (default), fit to the data, a continent,
or country with viewCountry.'
viewCountry:
description: Uppercase ISO 3166-1 alpha-2 code of the country the country
view shows.
type: string
required:
- layer
- view
- projection
type: object
DashboardtypesGeoMapThreshold:
properties:
color:
description: 'The CSS color of the shape, bubble or point while the threshold
is active, for example #F1575F; CSS named colors such as red also work.'
type: string
operator:
allOf:
- $ref: '#/components/schemas/DashboardtypesComparisonOperator'
description: 'The comparison that activates the threshold: above (default),
below, above_or_equal, below_or_equal, equal or not_equal.'
unit:
description: The unit id of value, such as ms or percent. Empty means the
colorBy column's unit.
type: string
value:
description: The value compared against, in unit.
format: double
type: number
required:
- value
- color
type: object
DashboardtypesGeoMapView:
enum:
- world
- fit
- africa
- asia
- europe
- north_america
- south_america
- oceania
- country
type: string
DashboardtypesGettableDashboardV2:
properties:
createdAt:
@@ -5517,7 +5287,6 @@ components:
mapping:
signoz/AreaChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec'
signoz/BarChartPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpec'
signoz/GeoMapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
signoz/HeatmapPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
signoz/HistogramPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHistogramPanelSpec'
signoz/ListPanel: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpec'
@@ -5540,7 +5309,6 @@ components:
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
type: object
DashboardtypesPanelPluginKind:
enum:
@@ -5555,7 +5323,6 @@ components:
- signoz/TextPanel
- signoz/HeatmapPanel
- signoz/ScatterPlotPanel
- signoz/GeoMapPanel
type: string
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
properties:
@@ -5587,21 +5354,6 @@ components:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec:
properties:
kind:
description: The panel kind.
enum:
- signoz/GeoMapPanel
type: string
spec:
allOf:
- $ref: '#/components/schemas/DashboardtypesGeoMapPanelSpec'
description: The options for this panel kind. {} accepts every default.
required:
- kind
- spec
type: object
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec:
properties:
kind:
@@ -11992,9 +11744,8 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
type: object
notificationSettings:
allOf:
@@ -12111,9 +11862,8 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
type: object
notificationSettings:
allOf:
@@ -16569,9 +16319,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- org-preference:list
- ADMIN
- tokenizer:
- org-preference:list
- ADMIN
summary: List org preferences
tags:
- preferences
@@ -16634,9 +16384,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- org-preference:read
- ADMIN
- tokenizer:
- org-preference:read
- ADMIN
summary: Get org preference
tags:
- preferences
@@ -16691,9 +16441,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- org-preference:update
- ADMIN
- tokenizer:
- org-preference:update
- ADMIN
summary: Update org preference
tags:
- preferences
@@ -24952,9 +24702,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- organization:read
- ADMIN
- tokenizer:
- organization:read
- ADMIN
summary: Get my organization
tags:
- orgs
@@ -25003,9 +24753,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- organization:update
- ADMIN
- tokenizer:
- organization:update
- ADMIN
summary: Update my organization
tags:
- orgs

View File

@@ -124,11 +124,11 @@ tests/
│ ├── alerts/
│ │ ├── 01_*.py # numbered suite files
│ │ └── conftest.py # optional suite-local fixtures
│ ├── auditquerier/
│ ├── cloudintegrations/
│ ├── dashboard/
│ ├── passwordauthn/
│ ├── querier/
│ ├── querieraudit/
│ └── ...
└── e2e/ # Playwright suite (see docs/contributing/tests/e2e.md)
```

View File

@@ -267,7 +267,9 @@ func (r *AnomalyRule) Eval(ctx context.Context, ts time.Time) (int, error) {
lb := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel)
resultLabels := ruletypes.NewBuilder(smpl.Metric...).Del(ruletypes.MetricNameLabel).Del(ruletypes.TemporalityLabel).Labels()
lb.SetRuleLabels(r.Labels().Map(), expand)
for name, value := range r.Labels().Map() {
lb.Set(name, expand(value))
}
lb.Set(ruletypes.AlertNameLabel, r.Name())
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())

View File

@@ -593,19 +593,16 @@
}
},
{
// The react-router allowlist: the facade itself, the route table, the router mount,
// `useSafeNavigate` and the test and story router mounts. Test files are
// The react-router allowlist: the facade itself, the route table, `useSafeNavigate`,
// the history singleton and the test and story router mounts. Test files are
// deliberately absent: they render at a route or use tests/router-mocks.
"files": [
"src/lib/router/**",
"src/AppRoutes/**",
"src/app/AppRouterProvider.tsx",
"src/app/createAppRouter.ts",
"src/hooks/useSafeNavigate.ts",
"src/lib/history.ts",
"src/tests/router.tsx",
"src/tests/router-utils.ts",
"src/storybook/navigation/containment.ts",
"src/storybook/navigation/pageScope.ts",
"src/storybook/providers/StorybookProviders.tsx",
"src/storybook/renderAtRoute.tsx"
],
"rules": {

View File

@@ -8,8 +8,8 @@ const srcPath = resolve(dirname(fileURLToPath(import.meta.url)), '../src');
/**
* Modules replaced for every story. Same idea as `moduleNameMapper` in
* `jest.config.ts`: the app keeps importing its own paths, Storybook resolves
* them to a mock. Regexes so only exact specifiers match: `store` must not
* catch `store/actions`.
* them to a mock. Regexes so only exact specifiers match: `lib/history` must
* not catch `lib/historyUtils`.
*
* Each replacement is typed as the module it stands in for, so drift is a
* compile error rather than a story that fails at render. The `jest` note on
@@ -17,6 +17,11 @@ const srcPath = resolve(dirname(fileURLToPath(import.meta.url)), '../src');
* only diverge where the runner needs them to.
*/
const mockAliases = [
{
// jest: not replaced, jsdom drives a real browser history.
find: /^(?:src\/)?lib\/history$/,
replacement: `${srcPath}/storybook/navigation/history.alias.ts`,
},
{
// jest: src/__tests__/logEventMock.ts
find: /^(?:src\/)?api\/common\/logEvent$/,

View File

@@ -192,7 +192,6 @@ const preview: Preview = {
'Role Details',
'Role Editor',
'Members',
['Overview', 'Authz'],
'Service Accounts',
'Ingestion',
'Single Sign-on',

View File

@@ -56,15 +56,15 @@ const config: Config.InitialOptions = {
transformIgnorePatterns: [
// @chenglou/pretext is ESM-only; @signozhq/ui pulls it in via text-ellipsis.
// Pattern 1: allow .pnpm virtual store through (handled by pattern 2), plus root-level ESM packages.
'node_modules/(?!(\\.pnpm|react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou/pretext|@signozhq/design-tokens|@signozhq|date-fns|d3-interpolate|d3-color|d3-geo|d3-array|internmap|ol|rbush|quickselect|earcut|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|micromark-core-commonmark|micromark-extension-gfm|micromark-extension-gfm-autolink-literal|micromark-extension-gfm-footnote|micromark-extension-gfm-strikethrough|micromark-extension-gfm-table|micromark-extension-gfm-tagfilter|micromark-extension-gfm-task-list-item|micromark-factory-destination|micromark-factory-label|micromark-factory-space|micromark-factory-title|micromark-factory-whitespace|micromark-util-character|micromark-util-chunked|micromark-util-classify-character|micromark-util-combine-extensions|micromark-util-decode-numeric-character-reference|micromark-util-decode-string|micromark-util-encode|micromark-util-html-tag-name|micromark-util-normalize-identifier|micromark-util-resolve-all|micromark-util-sanitize-uri|micromark-util-subtokenize|micromark-util-symbol|micromark-util-types|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)/)',
'node_modules/(?!(\\.pnpm|react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou/pretext|@signozhq/design-tokens|@signozhq|date-fns|d3-interpolate|d3-color|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|micromark-core-commonmark|micromark-extension-gfm|micromark-extension-gfm-autolink-literal|micromark-extension-gfm-footnote|micromark-extension-gfm-strikethrough|micromark-extension-gfm-table|micromark-extension-gfm-tagfilter|micromark-extension-gfm-task-list-item|micromark-factory-destination|micromark-factory-label|micromark-factory-space|micromark-factory-title|micromark-factory-whitespace|micromark-util-character|micromark-util-chunked|micromark-util-classify-character|micromark-util-combine-extensions|micromark-util-decode-numeric-character-reference|micromark-util-decode-string|micromark-util-encode|micromark-util-html-tag-name|micromark-util-normalize-identifier|micromark-util-resolve-all|micromark-util-sanitize-uri|micromark-util-subtokenize|micromark-util-symbol|micromark-util-types|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)/)',
// Pattern 2: pnpm virtual store — ignore everything except ESM-only packages.
// pnpm encodes scoped packages as @scope+name@version, so match on scope prefix.
'node_modules/\\.pnpm/(?!(react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou|@signozhq|date-fns|d3-interpolate|d3-color|d3-geo|d3-array|internmap|ol|rbush|quickselect|earcut|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)[^/]*/node_modules)',
'node_modules/\\.pnpm/(?!(react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou|@signozhq|date-fns|d3-interpolate|d3-color|api|@codemirror|@lezer|@marijn|@grafana|nuqs|uuid|copy-text-to-clipboard|react-markdown|vfile|vfile-message|unist-util-stringify-position|unified|bail|is-plain-obj|trough|remark-parse|remark-gfm|mdast-util-gfm|mdast-util-gfm-autolink-literal|mdast-util-gfm-footnote|mdast-util-gfm-strikethrough|mdast-util-gfm-table|mdast-util-gfm-task-list-item|mdast-util-find-and-replace|mdast-util-phrasing|mdast-util-to-markdown|markdown-table|longest-streak|ccount|escape-string-regexp|mdast-util-from-markdown|mdast-util-to-string|micromark|decode-named-character-reference|remark-rehype|mdast-util-to-hast|unist-util-position|trim-lines|unist-util-visit|unist-util-visit-parents|unist-util-is|unist-util-generated|mdast-util-definitions|property-information|hast-util-whitespace|space-separated-tokens|comma-separated-tokens|rehype-raw|hast-util-raw|hast-util-from-parse5|devlop|hastscript|hast-util-parse-selector|vfile-location|web-namespaces|hast-util-to-parse5|zwitch|html-void-elements)[^/]*/node_modules)',
],
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
testPathIgnorePatterns: ['/node_modules/', '/public/'],
moduleDirectories: ['node_modules', 'src'],
testEnvironment: '<rootDir>/jest.environment.cjs',
testEnvironment: 'jest-environment-jsdom',
coverageThreshold: {
global: {
statements: 80,

View File

@@ -1,22 +0,0 @@
const { TestEnvironment } = require('jest-environment-jsdom');
/**
* jsdom plus the fetch `Request` a data router builds for every navigation,
* which jsdom does not ship. Node's own class is used, except that it keeps the
* `signal` it is handed: the router passes jsdom's `AbortSignal`, and Node's
* `Request` rejects one from another realm.
*/
class JSDOMWithRequestEnvironment extends TestEnvironment {
constructor(config, context) {
super(config, context);
this.global.Request = class extends Request {
constructor(input, { signal, ...init } = {}) {
super(input, init);
Object.defineProperty(this, 'signal', { value: signal ?? super.signal });
}
};
}
}
module.exports = JSDOMWithRequestEnvironment;

View File

@@ -5,8 +5,6 @@
/**
* Adds custom matchers from the react testing library to all tests
*/
import { TextDecoder, TextEncoder } from 'node:util';
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';
import 'jest-styled-components';
@@ -16,14 +14,6 @@ import { server } from './src/mocks-server/server';
import './src/styles.scss';
// Establish API mocking before all tests.
// react-router@7's entry point pulls in its server-runtime cookie signing,
// which builds a TextEncoder at module scope. jsdom ships neither encoder, so
// importing anything from the router throws before a test starts.
Object.assign(globalThis, {
TextEncoder: globalThis.TextEncoder ?? TextEncoder,
TextDecoder: globalThis.TextDecoder ?? TextDecoder,
});
// Mock window.matchMedia
window.matchMedia =
window.matchMedia ||

View File

@@ -30,8 +30,7 @@
"test": "jest",
"test:changedsince": "jest --changedSince=main --coverage --silent",
"generate:api": "orval --config ./orval.config.ts && sh scripts/post-types-generation.sh",
"generate:config:web-settings": "json2ts ./src/schemas/generated/webSettings.schema.json -o src/types/generated/webSettings.ts --style.useTabs --style.tabWidth=1 --style.singleQuote --bannerComment '/* AUTO GENERATED FILE - DO NOT EDIT - GENERATED FROM frontend/src/schemas/generated/webSettings.schema.json */'",
"build:geo-outlines": "node scripts/geo-outlines/build.mjs"
"generate:config:web-settings": "json2ts ./src/schemas/generated/webSettings.schema.json -o src/types/generated/webSettings.ts --style.useTabs --style.tabWidth=1 --style.singleQuote --bannerComment '/* AUTO GENERATED FILE - DO NOT EDIT - GENERATED FROM frontend/src/schemas/generated/webSettings.schema.json */'"
},
"engines": {
"node": ">=22.0.0",
@@ -71,7 +70,7 @@
"antd": "5.11.0",
"antd-table-saveas-excel": "2.2.1",
"antlr4": "4.13.2",
"axios": "1.21.1",
"axios": "1.21.0",
"babel-jest": "^29.6.4",
"chart.js": "3.9.1",
"chartjs-adapter-date-fns": "^2.0.0",
@@ -79,17 +78,17 @@
"classnames": "2.3.2",
"color": "^4.2.1",
"crypto-js": "4.2.0",
"d3-geo": "3.1.1",
"d3-hierarchy": "3.1.2",
"dayjs": "^1.10.7",
"dompurify": "3.4.17",
"event-source-polyfill": "1.0.31",
"eventemitter3": "5.0.1",
"history": "4.10.1",
"html-to-image": "1.11.13",
"http-status-codes": "2.3.0",
"i18next": "^21.6.12",
"i18next-browser-languagedetector": "^6.1.3",
"i18next-http-backend": "^4.0.4",
"i18next-http-backend": "^4.0.0",
"immer": "11.1.3",
"jest": "30.2.0",
"js-base64": "^3.7.2",
@@ -97,7 +96,6 @@
"monaco-editor": "0.55.1",
"motion": "12.4.13",
"nuqs": "2.8.8",
"ol": "10.11.0",
"overlayscrollbars": "^2.16.0",
"overlayscrollbars-react": "^0.5.6",
"papaparse": "5.4.1",
@@ -119,7 +117,8 @@
"react-query": "3.39.3",
"react-redux": "^7.2.2",
"react-rnd": "^10.5.3",
"react-router": "7.18.4",
"react-router-dom": "^5.2.0",
"react-router-dom-v5-compat": "6.30.6",
"react-syntax-highlighter": "15.5.0",
"react-use": "^17.3.2",
"react-virtuoso": "4.0.3",
@@ -131,13 +130,12 @@
"rrule": "2.8.1",
"styled-components": "^5.3.11",
"timestamp-nano": "^1.0.0",
"topojson-client": "3.1.0",
"translation-resilience": "^0.2.0",
"typescript": "5.9.3",
"uplot": "1.6.31",
"uuid": "14.0.1",
"vite": "npm:rolldown-vite@7.3.1",
"zod": "4.6.7",
"zod": "4.3.6",
"zustand": "5.0.11"
},
"browserslist": {
@@ -172,10 +170,9 @@
"@testing-library/user-event": "14.4.3",
"@types/color": "^3.0.3",
"@types/crypto-js": "4.2.2",
"@types/d3-geo": "3.1.1",
"@types/d3-hierarchy": "1.1.11",
"@types/event-source-polyfill": "^1.0.0",
"@types/geojson": "7946.0.16",
"@types/history": "4.7.11",
"@types/jest": "30.0.0",
"@types/lodash-es": "^4.17.4",
"@types/node": "^22.20.5",
@@ -186,12 +183,11 @@
"@types/react-grid-layout": "^1.1.2",
"@types/react-redux": "^7.1.11",
"@types/react-resizable": "3.0.3",
"@types/react-router-dom": "^5.1.6",
"@types/react-syntax-highlighter": "15.5.13",
"@types/redux-mock-store": "1.0.4",
"@types/styled-components": "^5.1.4",
"@types/testing-library__jest-dom": "^5.14.5",
"@types/topojson-client": "3.1.5",
"@types/topojson-specification": "1.0.5",
"@typescript/native-preview": "7.0.0-dev.20260430.1",
"eslint-plugin-sonarjs": "4.0.2",
"husky": "^9.1.7",
@@ -213,8 +209,6 @@
"storybook": "10.6.3",
"stylelint": "17.15.0",
"svgo": "4.1.0",
"topojson-server": "3.0.1",
"topojson-simplify": "3.0.3",
"ts-jest": "29.4.15",
"typescript-plugin-css-modules": "5.3.0",
"use-sync-external-store": "1.6.0",

View File

@@ -1,6 +1,7 @@
import { ruleTester } from './rule-tester.mjs';
const FACADE = 'src/lib/router facade';
const HISTORY = 'lib/history singleton';
const MOCK = 'tests/router-mocks helpers';
await ruleTester({
@@ -10,6 +11,11 @@ await ruleTester({
name: 'facade import',
code: "import { useAppNavigate } from 'lib/router/useAppNavigate';",
},
{
name:
'the history package itself is a version-bump concern, not a facade one',
code: "import { createBrowserHistory } from 'history';",
},
{
name: 'unrelated module whose name contains history',
code: "import { useHistoryPanel } from 'container/HistoryPanel';",
@@ -43,8 +49,13 @@ await ruleTester({
errors: [{ message: MOCK }],
},
{
name: 'jest.doMock of react-router',
code: "jest.doMock('react-router');",
name: 'jest.mock of lib/history',
code: "jest.mock('lib/history');",
errors: [{ message: MOCK }],
},
{
name: 'jest.doMock of react-router-dom-v5-compat',
code: "jest.doMock('react-router-dom-v5-compat');",
errors: [{ message: MOCK }],
},
{
@@ -63,14 +74,29 @@ await ruleTester({
errors: [{ message: FACADE }],
},
{
name: 'react-router-dom is flagged as the v7 re-export shim',
code: "import { Outlet } from 'react-router-dom';",
errors: [{ message: 'only a re-export shim' }],
name: 'react-router-dom-v5-compat',
code: "import { useNavigate } from 'react-router-dom-v5-compat';",
errors: [{ message: 'compat package is an implementation detail' }],
},
{
name: 'require',
code: "const router = require('react-router');",
errors: [{ message: FACADE }],
name: 'lib/history default import',
code: "import history from 'lib/history';",
errors: [{ message: HISTORY }],
},
{
name: 'lib/history through the @/ alias',
code: "import history from '@/lib/history';",
errors: [{ message: HISTORY }],
},
{
name: 'jest.mock of lib/history through the @/ alias',
code: "jest.mock('@/lib/history');",
errors: [{ message: MOCK }],
},
{
name: 'lib/history require',
code: "const history = require('lib/history').default;",
errors: [{ message: HISTORY }],
},
{
name: 'dynamic import',
@@ -90,10 +116,10 @@ await ruleTester({
{
name: 'one report per import statement',
code:
"import { Link } from 'react-router';\nimport { Outlet } from 'react-router';",
"import { Link } from 'react-router-dom';\nimport history from 'lib/history';",
errors: [
{ message: FACADE, line: 1 },
{ message: FACADE, line: 2 },
{ message: HISTORY, line: 2 },
],
},
],

View File

@@ -5,14 +5,18 @@
* upgrade is a change to one directory instead of ~300 call sites. This rule
* keeps new call sites, and test mocks, from reaching past it.
*
* `react-router-dom` is still flagged even though the package is gone: on v7 it is a
* re-export shim over `react-router`, so reinstalling it would split the tree again.
* `history` (the package) is deliberately not flagged: it is a transitive concern of
* the version bump, not something the facade replaces.
*
* The allowlist (the facade itself, the route table, the router mount,
* `useSafeNavigate` and the test and story router mounts) is applied via overrides
* in .oxlintrc.json, not here, so the file list stays visible next to the severity.
* The allowlist (the facade itself, the route table, `useSafeNavigate`, the history
* singleton and the test and story router mounts) is applied via overrides in
* .oxlintrc.json, not here, so the file list stays visible next to the severity.
*/
import path from 'node:path';
const HISTORY_MODULE_SUFFIX = path.join('src', 'lib', 'history');
const JEST_MODULE_METHODS = new Set([
'mock',
'doMock',
@@ -25,12 +29,30 @@ const JEST_MODULE_METHODS = new Set([
]);
const MESSAGE_IDS = {
'react-router': 'router',
'react-router-dom': 'routerDom',
'react-router': 'v5Router',
'react-router-dom': 'v5Router',
'react-router-dom-v5-compat': 'v6Compat',
'lib/history': 'historySingleton',
'@/lib/history': 'historySingleton',
};
function messageIdFor(specifier) {
return MESSAGE_IDS[specifier] ?? null;
/** Resolves `./history` / `../history` so files inside src/lib count too. */
function isHistoryModule(specifier, filename) {
if (!specifier.startsWith('.') || !filename) {
return false;
}
const resolved = path.resolve(path.dirname(filename), specifier);
return (
resolved.endsWith(HISTORY_MODULE_SUFFIX) ||
resolved.endsWith(`${HISTORY_MODULE_SUFFIX}.ts`)
);
}
function messageIdFor(specifier, filename) {
if (MESSAGE_IDS[specifier] !== undefined) {
return MESSAGE_IDS[specifier];
}
return isHistoryModule(specifier, filename) ? 'historySingleton' : null;
}
export default {
@@ -38,15 +60,17 @@ export default {
type: 'suggestion',
docs: {
description:
'Disallow direct react-router imports; import from src/lib/router instead',
'Disallow direct react-router / lib/history imports; import from src/lib/router instead',
category: 'React Router migration',
},
schema: [],
messages: {
router:
'Do not import react-router directly. Use the src/lib/router facade (useAppNavigate, useAppLocation, useAppParams, AppLink, Redirect, matchRoute) so a router upgrade stays contained.',
routerDom:
'Do not import react-router-dom. The app is on react-router; on v7 react-router-dom is only a re-export shim, and installing it puts two copies of the router in the tree. Use the src/lib/router facade.',
v5Router:
'Do not import react-router-dom directly. Use the src/lib/router facade (useAppNavigate, useAppLocation, useAppParams, AppLink, Redirect, matchRoute) so a router upgrade stays contained.',
v6Compat:
'Do not import react-router-dom-v5-compat directly. Use the src/lib/router facade instead; the compat package is an implementation detail of the migration and disappears with it.',
historySingleton:
'Do not import the lib/history singleton. Use the helpers in src/lib/router/navigation.ts, or useAppNavigate() to follow the nearest router. history loses basename handling once the router owns it.',
mock:
'Do not mock the router directly. Render at a route with tests/test-utils, or spy on the facade with the tests/router-mocks helpers.',
},
@@ -61,7 +85,7 @@ export default {
) {
return;
}
const messageId = messageIdFor(sourceNode.value);
const messageId = messageIdFor(sourceNode.value, context.filename);
if (messageId !== null) {
context.report({
node: sourceNode,

438
frontend/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -45,17 +45,14 @@ overrides:
# orval >=8.20.0 and ts-jest >=29.4.11 already fixed on their side
esbuild@>=0.27.3 <0.28.1: '>=0.28.1 <0.29.0'
# via: @commitlint/cli > @commitlint/config-validator > ajv@8 (fast-uri ^3.0.1)
# remove: blocked — ajv@8 caps fast-uri at ^3, and only 3.1.9 carries the fix
fast-uri@<3.1.9: '>=3.1.9 <4'
# remove: blocked — ajv@8 caps fast-uri at ^3, and only 3.1.6 carries the fix
fast-uri@<3.1.6: '>=3.1.6 <4'
# via: direct dep posthog-js@1.298.0 (fflate ^0.4.8)
# remove: blocked, posthog-js 1.430.2 (latest) is still on ^0.4.8
fflate@<0.4.9: '>=0.4.9 <0.5'
# via: direct devDep sass@1.97.3 (immutable ^5.0.2)
# remove: blocked — plain sass bumps stay within ^5, so the floor is what pulls 5.1.8
immutable@<5.1.8: '>=5.1.8 <6'
# via: @storybook/test-runner > jest-process-manager > wait-on@7.2.0 (joi ^17.11.0)
# remove: blocked, the range is open, so the floor is what pulls the fix
joi@<17.13.9: '>=17.13.9 <18'
# via: react-use@17.5.1 (direct, js-cookie ^2.2.1); @grafana/data > react-use@17.6.0
# remove: bump react-use to >=17.6.1 (js-cookie ^3); @grafana/data side blocked
js-cookie@<=3.0.5: '>=3.0.7 <4'
@@ -63,12 +60,6 @@ overrides:
# @commitlint/cli > @commitlint/load > cosmiconfig@9 (^4.1.0)
# remove: blocked, both consumers cap js-yaml at ^4 and only 4.3.2 carries the fix
'js-yaml@>=4.0.0 <4.3.2': '>=4.3.2 <5'
# via: orval > typedoc@0.28.19 (markdown-it ^14.1.1)
# remove: blocked, typedoc 0.28.20 (latest) only widens to ^14.3.0, still vulnerable
markdown-it@<14.3.3: '>=14.3.3 <15'
# via: @grafana/data@11.6.15 (moment 2.30.1 exact)
# remove: bump @grafana/data to >=13, which drops the exact moment pin
moment@<2.31.0: '>=2.31.0 <3'
# via: react-syntax-highlighter@15.5.0 (prismjs ^1.27.0 + refractor@3 ~1.27.0 tilde-pinned)
# remove: bump react-syntax-highlighter to >=16.1.1 (prismjs ^1.30.0, refractor@5)
prismjs@<1.30.0: '>=1.30.0 <2'
@@ -76,13 +67,14 @@ overrides:
# (postcss-selector-parser ^7.0.0)
# remove: blocked, 4.2.0 is latest and the range is open, so the floor is what pulls the fix
postcss-selector-parser@>=7.1.0 <7.1.3: '>=7.1.3 <8'
# via: @signozhq/ui > nuqs@2 (react-router ^6.4.0 || ^7)
# remove: blocked. GHSA-wrjc-x8rr-h8h6 and the deserializeErrors advisory are patched
# only in 7.18.0. Do NOT open the cap: react-router >=7 requires React 19 and breaks
# the app-wide CompatRouter, so those two moderates stay until the app moves to React 19
react-router@>=6.7.0 <6.30.6: '>=6.30.6 <7'
# via: msw@1.3.2 (devDep) > inquirer@8 > external-editor@3.1.0 (tmp ^0.0.33)
# remove: upgrade msw to >=2 (drops the inquirer/external-editor chain)
tmp@<0.2.6: '>=0.2.6 <0.3.0'
# via: @storybook/test-runner (uuid ^8.3.2)
# remove: blocked, test-runner (latest) still depends on uuid ^8.3.2. Forces a
# major: 11.x keeps the CJS build and the v4 export the runner imports
uuid@<11.1.1: '>=11.1.1 <12'
# via: jest > babel-plugin-macros > cosmiconfig@7 (yaml ^1.10.0);
# typescript-plugin-css-modules > postcss-load-config@3 (^1.10.2)
# remove: blocked — babel-plugin-macros 3.1.0 (latest) still uses cosmiconfig@7

View File

@@ -1,210 +0,0 @@
// Builds the Geo Map outlines assets: Natural Earth 50m admin-0 countries, and
// 10m admin-1 states/provinces for every country with at least two of them.
// Run by hand when bumping Natural Earth or editing regions/aliases; the output is committed.
// Usage: pnpm build:geo-outlines
//
// Nothing is written until every invariant in validate.mjs holds. The assets
// are built in a staging folder and swapped in whole, so a failed run leaves
// the committed ones as they were.
import {
existsSync,
mkdirSync,
readdirSync,
renameSync,
rmSync,
writeFileSync,
} from 'node:fs';
import { join } from 'node:path';
import { setTimeout as sleep } from 'node:timers/promises';
import { gzipSync } from 'node:zlib';
import {
ASSETS_DIR,
COUNTRIES_URL,
SUBDIVISION_LIST_FILE,
SUBDIVISIONS_URL,
} from './config.mjs';
import { buildCountries } from './countries.mjs';
import { buildSubdivisions } from './subdivisions.mjs';
import { validate } from './validate.mjs';
const DOWNLOAD_TIMEOUT_MS = 120_000;
const DOWNLOAD_ATTEMPTS = 3;
const STAGING_DIR = `${ASSETS_DIR}.staging`;
const PREVIOUS_DIR = `${ASSETS_DIR}.previous`;
// Everything in the assets folder is generated; anything else would be lost
// in the swap, so its presence stops the build.
const GENERATED_ENTRIES = new Set([
'countries-50m.json',
'lookups.json',
'subdivisions',
]);
const kb = (bytes) => `${(bytes / 1024).toFixed(0)} KB`;
const sizeOf = (json) =>
`${kb(Buffer.byteLength(json))} raw / ${kb(gzipSync(json).length)} gzip`;
async function downloadFeatures(url) {
for (let attempt = 1; ; attempt += 1) {
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const body = await response.json();
if (
body?.type !== 'FeatureCollection' ||
!Array.isArray(body.features) ||
body.features.length === 0
) {
throw new Error('response is not a non-empty GeoJSON FeatureCollection');
}
return body;
} catch (error) {
if (attempt === DOWNLOAD_ATTEMPTS) {
throw new Error(
`download failed after ${attempt} attempts: ${url}\n ${error.message}`,
);
}
await sleep(attempt * 2_000);
}
}
}
function subdivisionListSource(countries) {
return `// Generated by scripts/geo-outlines/build.mjs; do not edit.
export const SUBDIVISION_COUNTRY_CODES = [
${countries.map((country) => `\t'${country}',`).join('\n')}
] as const;
`;
}
// A run that died mid-swap leaves the assets in the previous folder.
function recoverInterruptedSwap() {
if (!existsSync(ASSETS_DIR) && existsSync(PREVIOUS_DIR)) {
renameSync(PREVIOUS_DIR, ASSETS_DIR);
}
rmSync(STAGING_DIR, { recursive: true, force: true });
rmSync(PREVIOUS_DIR, { recursive: true, force: true });
}
function assertOnlyGeneratedEntries() {
if (!existsSync(ASSETS_DIR)) {
return;
}
const foreign = readdirSync(ASSETS_DIR).filter(
(entry) => !GENERATED_ENTRIES.has(entry),
);
if (foreign.length > 0) {
throw new Error(
`${ASSETS_DIR} holds files this build doesn't generate: ${foreign.join(', ')}`,
);
}
}
/** Writes every output under the staging folder; returns the sizes report. */
function stage(outputs) {
const subdivisionDir = join(STAGING_DIR, 'subdivisions');
mkdirSync(subdivisionDir, { recursive: true });
writeFileSync(join(STAGING_DIR, 'countries-50m.json'), outputs.countriesJson);
writeFileSync(join(STAGING_DIR, 'lookups.json'), outputs.lookupsJson);
const sizes = [];
for (const [country, file] of outputs.subdivisionFiles) {
const json = JSON.stringify(file);
writeFileSync(join(subdivisionDir, `${country}.json`), json);
sizes.push({
country,
shapes: file.objects.subdivisions.geometries.length,
gzip: gzipSync(json).length,
});
}
writeFileSync(`${SUBDIVISION_LIST_FILE}.staging`, outputs.subdivisionList);
return sizes;
}
/** Swaps the staged assets in; puts the previous ones back if that fails. */
function commitStaged() {
const hadAssets = existsSync(ASSETS_DIR);
if (hadAssets) {
renameSync(ASSETS_DIR, PREVIOUS_DIR);
}
try {
renameSync(STAGING_DIR, ASSETS_DIR);
// A failed rename leaves the previous list in place.
renameSync(`${SUBDIVISION_LIST_FILE}.staging`, SUBDIVISION_LIST_FILE);
} catch (error) {
rmSync(ASSETS_DIR, { recursive: true, force: true });
if (hadAssets) {
renameSync(PREVIOUS_DIR, ASSETS_DIR);
}
throw error;
}
rmSync(PREVIOUS_DIR, { recursive: true, force: true });
}
function cleanUpStaging() {
rmSync(STAGING_DIR, { recursive: true, force: true });
rmSync(`${SUBDIVISION_LIST_FILE}.staging`, { force: true });
}
function report(countries, subdivisions, outputs, sizes) {
const totalGzip = sizes.reduce((sum, { gzip }) => sum + gzip, 0);
return {
countries: {
...countries.report,
sizes: {
'countries-50m.json': sizeOf(outputs.countriesJson),
'lookups.json': sizeOf(outputs.lookupsJson),
},
},
subdivisions: {
...subdivisions.report,
countries: sizes.length,
totalGzip: kb(totalGzip),
largest: [...sizes]
.sort((a, b) => b.gzip - a.gzip)
.slice(0, 10)
.map(
({ country, shapes, gzip }) =>
`${country}: ${shapes} shapes, ${kb(gzip)} gzip`,
),
},
};
}
async function main() {
recoverInterruptedSwap();
assertOnlyGeneratedEntries();
const [countrySource, subdivisionSource] = await Promise.all([
downloadFeatures(COUNTRIES_URL),
downloadFeatures(SUBDIVISIONS_URL),
]);
const countries = buildCountries(countrySource);
const subdivisions = buildSubdivisions(subdivisionSource);
validate(countries, subdivisions);
const outputs = {
countriesJson: JSON.stringify(countries.topology),
lookupsJson: JSON.stringify(countries.lookups),
subdivisionFiles: subdivisions.files,
subdivisionList: subdivisionListSource([...subdivisions.files.keys()]),
};
try {
const sizes = stage(outputs);
commitStaged();
process.stdout.write(
`${JSON.stringify(report(countries, subdivisions, outputs, sizes), null, 2)}\n`,
);
} finally {
cleanUpStaging();
}
}
main().catch((error) => {
process.stderr.write(`Geo outlines build failed: ${error.message}\n`);
process.exitCode = 1;
});

View File

@@ -1,181 +0,0 @@
// Inputs and tuning for the Geo Map outlines build. Tables only; no logic.
// Read by every other module here; not run on its own.
//
// Edit this file to bump Natural Earth (the pinned version below), retune
// simplification, or fix a region, alias or merge; then run
// pnpm build:geo-outlines and commit the rebuilt assets.
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const NATURAL_EARTH_BASE =
'https://raw.githubusercontent.com/nvkelso/natural-earth-vector/v5.1.2/geojson';
export const COUNTRIES_URL = `${NATURAL_EARTH_BASE}/ne_50m_admin_0_countries.geojson`;
export const SUBDIVISIONS_URL = `${NATURAL_EARTH_BASE}/ne_10m_admin_1_states_provinces.geojson`;
const GEO_MAP_DIR = join(
dirname(fileURLToPath(import.meta.url)),
'../../src/lib/visualization/charts/GeoMap',
);
export const ASSETS_DIR = join(GEO_MAP_DIR, 'assets');
export const SUBDIVISION_LIST_FILE = join(
GEO_MAP_DIR,
'geo/subdivisionCountries.ts',
);
export const COUNTRY_QUANTIZATION = 1e5;
// Simplification drops every point whose triangle with its neighbours is
// smaller than this, in square degrees. A fixed size, unlike a share of all
// points, still leaves a small island a few points of its own.
export const COUNTRY_MIN_WEIGHT = 3e-3;
// 10m is street-level detail; a country view needs far less.
export const SUBDIVISION_QUANTIZATION = 1e4;
export const SUBDIVISION_MIN_WEIGHT = 1e-3;
// A shape this many times the minimum weight or smaller could lose every polygon.
export const PROTECTED_SHAPE_FACTOR = 10;
// A country view needs at least this many coded states to be worth drawing.
export const MIN_SUBDIVISIONS = 2;
// ISO 3166-2 codes that changed after Natural Earth v5.1.2, or older spellings
// still in GeoIP data, mapped to the code the shape carries.
export const SUBDIVISION_ALIASES = {
IN: {
'IN-CG': 'IN-CT',
'IN-UK': 'IN-UT',
'IN-TS': 'IN-TG',
'IN-OD': 'IN-OR',
'IN-DD': 'IN-DH',
'IN-DN': 'IN-DH',
},
// Natural Earth carries Metro Manila under its retired code.
PH: { 'PH-00': 'PH-MNL' },
};
// Shapes Natural Earth still splits along retired lines, merged into the codes
// GeoIP reports now; the retired codes become aliases. Northern Ireland's 26
// districts became 11 councils in 2015, each a union of old districts.
// Current code → [current name, retired codes].
export const SUBDIVISION_MERGES = {
GB: {
'GB-ANN': ['Antrim and Newtownabbey', ['GB-ANT', 'GB-NTA']],
'GB-AND': ['Ards and North Down', ['GB-ARD', 'GB-NDN']],
'GB-ABC': [
'Armagh City, Banbridge and Craigavon',
['GB-ARM', 'GB-BNB', 'GB-CGV'],
],
'GB-BFS': ['Belfast', ['GB-BFS']],
'GB-CCG': [
'Causeway Coast and Glens',
['GB-BLY', 'GB-CLR', 'GB-LMV', 'GB-MYL'],
],
'GB-DRS': ['Derry City and Strabane', ['GB-DRY', 'GB-STB']],
'GB-FMO': ['Fermanagh and Omagh', ['GB-FER', 'GB-OMH']],
'GB-LBC': ['Lisburn and Castlereagh', ['GB-LSB', 'GB-CSR']],
'GB-MEA': ['Mid and East Antrim', ['GB-BLA', 'GB-CKF', 'GB-LRN']],
'GB-MUL': ['Mid Ulster', ['GB-CKT', 'GB-DGN', 'GB-MFT']],
'GB-NMD': ['Newry, Mourne and Down', ['GB-NYM', 'GB-DOW']],
},
};
// Natural Earth puts these islands in "Seven seas (open ocean)".
export const OPEN_OCEAN_REGION = {
Africa: 'africa',
Asia: 'asia',
Americas: 'south_america',
};
export const CONTINENT_REGION = {
Africa: 'africa',
Asia: 'asia',
Europe: 'europe',
'North America': 'north_america',
'South America': 'south_america',
Oceania: 'oceania',
};
// Transcontinental countries belong to every region they span.
export const EXTRA_REGIONS = {
RU: ['asia'],
TR: ['europe'],
KZ: ['europe'],
GE: ['europe'],
AM: ['europe'],
AZ: ['europe'],
CY: ['europe'],
EG: ['asia'],
};
// ISO codes GeoIP emits for places Natural Earth draws inside another country.
export const COUNTRY_ALIASES = {
GF: 'FR',
GP: 'FR',
MQ: 'FR',
RE: 'FR',
YT: 'FR',
BQ: 'NL',
SJ: 'NO',
BV: 'NO',
CX: 'AU',
CC: 'AU',
HM: 'AU',
UM: 'US',
TK: 'NZ',
AC: 'SH',
TA: 'SH',
DG: 'IO',
CP: 'FR',
FX: 'FR',
EA: 'ES',
IC: 'ES',
CQ: 'GB',
GI: 'GB',
// Retired or reserved codes still seen in older data.
UK: 'GB',
SU: 'RU',
YU: 'RS',
CS: 'RS',
TP: 'TL',
BU: 'MM',
ZR: 'CD',
DD: 'DE',
VD: 'VN',
YD: 'YE',
RH: 'ZW',
NH: 'VU',
HV: 'BF',
DY: 'BJ',
AN: 'CW',
};
export const COUNTRY_NAME_ALIASES = {
usa: 'US',
'united states of america': 'US',
america: 'US',
uk: 'GB',
'great britain': 'GB',
britain: 'GB',
england: 'GB',
russia: 'RU',
'south korea': 'KR',
'north korea': 'KP',
czechia: 'CZ',
'czech republic': 'CZ',
'ivory coast': 'CI',
turkiye: 'TR',
türkiye: 'TR',
burma: 'MM',
'cape verde': 'CV',
swaziland: 'SZ',
macedonia: 'MK',
'east timor': 'TL',
vatican: 'VA',
};
// Alpha-2 codes Intl names that aren't countries, so none needs a shape.
export const NON_COUNTRY_CODES = new Set([
'EU',
'EZ',
'UN',
'ZZ',
'QO',
'XA',
'XB',
'AQ',
]);

View File

@@ -1,190 +0,0 @@
// Natural Earth admin-0 → the countries topology and the lookup tables.
// Called by build.mjs; not run on its own.
//
// Merges each country's parts into one shape by ISO alpha-2, drops Antarctica,
// assigns view regions and builds the alpha-3/name/alias lookups
// normalizeCountry reads. Returns the topology, the lookups and a report.
import { geoArea, geoBounds } from 'd3-geo';
import { feature } from 'topojson-client';
import {
CONTINENT_REGION,
COUNTRY_ALIASES,
COUNTRY_MIN_WEIGHT,
COUNTRY_NAME_ALIASES,
COUNTRY_QUANTIZATION,
EXTRA_REGIONS,
NON_COUNTRY_CODES,
OPEN_OCEAN_REGION,
} from './config.mjs';
import {
polygonsOf,
round,
roundBounds,
simplifyAndQuantize,
} from './geometry.mjs';
export const isCountryCode = (value) => /^[A-Z]{2}$/.test(value ?? '');
function regionsOf(props, iso2) {
const base = props.CONTINENT.startsWith('Seven seas')
? OPEN_OCEAN_REGION[props.REGION_UN]
: CONTINENT_REGION[props.CONTINENT];
return [...new Set([base, ...(EXTRA_REGIONS[iso2] ?? [])].filter(Boolean))];
}
// Group features by code so a country's overseas parts (Australia's Indian
// Ocean territories) become one shape that one data row colours.
function groupByCode(sourceFeatures, report) {
const groups = new Map();
for (const f of sourceFeatures) {
const p = f.properties;
if (p.CONTINENT === 'Antarctica') {
report.dropped.push(p.NAME);
continue;
}
const iso2 = isCountryCode(p.ISO_A2_EH) ? p.ISO_A2_EH : null;
const key = iso2 ?? `uncoded:${p.NAME}`;
if (!iso2) {
report.uncoded.push(p.NAME);
}
if (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(f);
}
return groups;
}
function toCountryFeature(key, members, report) {
// The sovereign part carries the name, label point and region.
const primary =
members.find((f) => f.properties.ISO_A2 === f.properties.ISO_A2_EH) ??
members.reduce((a, b) => (geoArea(a) >= geoArea(b) ? a : b));
const p = primary.properties;
const iso2 = key.startsWith('uncoded:') ? null : key;
if (members.length > 1) {
report.merged.push(
`${iso2}: ${members.map((f) => f.properties.NAME).join(' + ')}`,
);
}
const polygons = members.flatMap((f) => polygonsOf(f.geometry));
const geometry = { type: 'MultiPolygon', coordinates: polygons };
const mainland = polygons
.map((coordinates) => ({ type: 'Polygon', coordinates }))
.reduce((a, b) => (geoArea(a) >= geoArea(b) ? a : b));
return {
type: 'Feature',
id: iso2 ?? p.NAME,
properties: {
code: iso2,
iso3: /^[A-Z]{3}$/.test(p.ISO_A3_EH) ? p.ISO_A3_EH : null,
name: p.NAME,
label: [round(p.LABEL_X), round(p.LABEL_Y)],
mainland: roundBounds(geoBounds(mainland)),
bounds: roundBounds(geoBounds(geometry)),
regions: regionsOf(p, iso2 ?? ''),
},
geometry,
};
}
/** Alpha-3 codes and English names → alpha-2, for normalising data. */
function buildLookups(sourceFeatures) {
const alpha3 = {};
const names = { ...COUNTRY_NAME_ALIASES };
for (const { properties: p } of sourceFeatures) {
if (!isCountryCode(p.ISO_A2_EH) || p.CONTINENT === 'Antarctica') {
continue;
}
if (/^[A-Z]{3}$/.test(p.ISO_A3_EH)) {
alpha3[p.ISO_A3_EH] = p.ISO_A2_EH;
}
for (const name of [
p.NAME,
p.NAME_LONG,
p.ADMIN,
p.NAME_EN,
p.BRK_NAME,
p.NAME_SORT,
p.NAME_CIAWF,
]) {
if (name) {
names[name.toLowerCase()] ??= p.ISO_A2_EH;
}
}
}
return { alpha3, names, aliases: COUNTRY_ALIASES };
}
/** ISO alpha-2 codes Intl knows that neither a shape nor an alias covers. */
function findUncoveredCodes(drawn) {
const display = new Intl.DisplayNames(['en'], {
type: 'region',
fallback: 'none',
});
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const uncovered = [];
for (const a of letters) {
for (const b of letters) {
const code = a + b;
const name = display.of(code);
if (
name &&
!NON_COUNTRY_CODES.has(code) &&
!drawn.has(code) &&
!COUNTRY_ALIASES[code]
) {
uncovered.push(`${code} ${name}`);
}
}
}
return uncovered;
}
/** Natural Earth admin-0 GeoJSON → `{ topology, lookups, report }`. */
export function buildCountries(source) {
const report = { dropped: [], uncoded: [], merged: [] };
const features = [...groupByCode(source.features, report)]
.map(([key, members]) => toCountryFeature(key, members, report))
.sort((a, b) => String(a.id).localeCompare(String(b.id)));
const { topo, flipped, collapsed, emptied } = simplifyAndQuantize(
'countries',
features,
COUNTRY_MIN_WEIGHT,
COUNTRY_QUANTIZATION,
);
const drawn = new Set(features.map((f) => f.properties.code).filter(Boolean));
// Lets data be checked against the drawn codes without decoding the outlines.
const lookups = { codes: [...drawn].sort(), ...buildLookups(source.features) };
const regionCounts = {};
for (const f of features) {
for (const region of f.properties.regions) {
regionCounts[region] = (regionCounts[region] ?? 0) + 1;
}
}
return {
topology: topo,
lookups,
report: {
features: features.length,
decodedFeatures: feature(topo, topo.objects.countries).features.length,
droppedFlippedIslands: flipped,
droppedCollapsedPolygons: collapsed,
emptied: emptied.join(' '),
regionCounts,
...report,
lookupCounts: {
alpha3: Object.keys(lookups.alpha3).length,
names: Object.keys(lookups.names).length,
aliases: Object.keys(lookups.aliases).length,
},
uncoveredIsoCodes: findUncoveredCodes(drawn),
},
};
}

View File

@@ -1,118 +0,0 @@
// Geometry helpers and the simplification shared by countries and states.
// Used by countries.mjs and subdivisions.mjs; not run on its own.
//
// Simplification protects small shapes so islands keep an outline, and drops
// polygons that collapse to slivers or flip inside out after quantizing.
import { geoArea } from 'd3-geo';
import { topology } from 'topojson-server';
import { presimplify, simplify } from 'topojson-simplify';
import { feature, quantize } from 'topojson-client';
import { PROTECTED_SHAPE_FACTOR } from './config.mjs';
export const round = (n) => Math.round(n * 1e3) / 1e3;
export const roundBounds = (bounds) =>
bounds.map(([x, y]) => [round(x), round(y)]);
export function polygonsOf(geometry) {
if (geometry.type === 'Polygon') {
return [geometry.coordinates];
}
if (geometry.type === 'MultiPolygon') {
return geometry.coordinates;
}
return [];
}
/** Area of a lon/lat ring in square degrees, the unit of the simplify weights. */
function planarRingArea(ring) {
let twice = 0;
ring.forEach(([x, y], i) => {
const [nx, ny] = ring[(i + 1) % ring.length];
twice += x * ny - nx * y;
});
return Math.abs(twice) / 2;
}
// Weights every point of a small shape's largest outline as Infinity, which
// simplify never removes, so a city-state or city-sized province (Monaco, a
// London borough) still has an outline to colour. Neighbours share those arcs,
// so their common border stays in step.
function protectSmallShapes(topo, objectName, features, minWeight) {
topo.objects[objectName].geometries.forEach((geometry, i) => {
const polygons = polygonsOf(features[i].geometry);
const areas = polygons.map(([outer]) => planarRingArea(outer));
const total = areas.reduce((sum, area) => sum + area, 0);
if (polygons.length === 0 || total > minWeight * PROTECTED_SHAPE_FACTOR) {
return;
}
const largest = areas.indexOf(Math.max(...areas));
const rings =
geometry.type === 'Polygon' ? geometry.arcs : geometry.arcs[largest];
rings[0].forEach((index) => {
topo.arcs[index < 0 ? ~index : index].forEach((point) => {
point[2] = Infinity;
});
});
});
}
const isCollapsed = ([outer]) =>
new Set(outer.map((point) => point.join())).size < 3;
// Simplifying can collapse a tiny island until its ring runs the other way; d3
// then reads it as "the whole globe except this island" and floods the map.
const isInverted = (coordinates) =>
geoArea({ type: 'Polygon', coordinates }) > 2 * Math.PI;
/**
* One feature collection to a simplified, quantized topology under
* `objectName`. Polygons that collapse to a sliver or flip inside out are
* dropped and the topology rebuilt without them.
*/
export function simplifyAndQuantize(
objectName,
features,
minWeight,
quantization,
) {
let topo = presimplify(
topology({ [objectName]: { type: 'FeatureCollection', features } }),
);
protectSmallShapes(topo, objectName, features, minWeight);
topo = simplify(topo, minWeight);
// presimplify stores each point's weight as a third coordinate and simplify
// keeps it, so it is dropped before quantizing (which would carry it through).
topo = { ...topo, arcs: topo.arcs.map((arc) => arc.map(([x, y]) => [x, y])) };
topo = quantize(topo, quantization);
let flipped = 0;
let collapsed = 0;
const cleaned = feature(topo, topo.objects[objectName]).features.map((f) => {
const kept = polygonsOf(f.geometry).filter((coordinates) => {
if (isCollapsed(coordinates)) {
collapsed += 1;
return false;
}
if (isInverted(coordinates)) {
flipped += 1;
return false;
}
return true;
});
return { ...f, geometry: { type: 'MultiPolygon', coordinates: kept } };
});
const emptied = cleaned
.filter((f) => f.geometry.coordinates.length === 0)
.map((f) => f.properties.code ?? f.properties.name);
if (flipped > 0 || collapsed > 0) {
topo = quantize(
topology({
[objectName]: { type: 'FeatureCollection', features: cleaned },
}),
quantization,
);
}
return { topo, flipped, collapsed, emptied };
}

View File

@@ -1,202 +0,0 @@
// Natural Earth admin-1 → one states/provinces topology per country.
// Called by build.mjs; not run on its own.
//
// Skips countries with fewer than MIN_SUBDIVISIONS coded states, merges shapes
// split along retired lines, and records aliases for renamed codes. Returns one
// file per country and a report of what was skipped, merged or dropped.
import { geoArea } from 'd3-geo';
import { topology } from 'topojson-server';
import { merge } from 'topojson-client';
import {
MIN_SUBDIVISIONS,
SUBDIVISION_ALIASES,
SUBDIVISION_MERGES,
SUBDIVISION_MIN_WEIGHT,
SUBDIVISION_QUANTIZATION,
} from './config.mjs';
import { isCountryCode } from './countries.mjs';
import { round, simplifyAndQuantize } from './geometry.mjs';
const SUBDIVISION_CODE = /^[A-Z]{2}-[A-Z0-9]{1,3}$/;
/** Retired code → `[current code, current name]`, from `SUBDIVISION_MERGES`. */
const RECODES = new Map(
Object.values(SUBDIVISION_MERGES).flatMap((merges) =>
Object.entries(merges).flatMap(([code, [name, retired]]) =>
retired.map((old) => [old, [code, name]]),
),
),
);
/** A country's aliases: the hand-written ones, then each merge's retired codes. */
function aliasesOf(country) {
const aliases = { ...SUBDIVISION_ALIASES[country] };
for (const [code, [, retired]] of Object.entries(
SUBDIVISION_MERGES[country] ?? {},
)) {
for (const old of retired) {
if (old !== code) {
aliases[old] = code;
}
}
}
return aliases;
}
// Shapes without an ISO 3166-2 code can't be matched to data, and a code under
// another country's prefix (Puerto Rico's `US-PR`) belongs to that country's
// file. Retired codes are rewritten to the current ones here, so the merge
// below dissolves them.
function groupByCountry(sourceFeatures) {
const byCountry = new Map();
const uncoded = {};
const recoded = new Set();
for (const f of sourceFeatures) {
const country = f.properties.iso_a2;
if (!isCountryCode(country)) {
continue;
}
const code = f.properties.iso_3166_2;
if (!SUBDIVISION_CODE.test(code ?? '') || !code.startsWith(`${country}-`)) {
uncoded[country] = (uncoded[country] ?? 0) + 1;
continue;
}
if (!byCountry.has(country)) {
byCountry.set(country, []);
}
const recode = RECODES.get(code);
if (recode) {
recoded.add(code);
}
byCountry.get(country).push(
recode
? {
...f,
properties: {
...f.properties,
iso_3166_2: recode[0],
name: recode[1],
},
}
: f,
);
}
return { byCountry, uncoded, recoded };
}
// Natural Earth splits some codes across shapes (Dublin's four councils are all
// `IE-D`). Merging them through a topology drops the borders between the parts,
// so one code is one shape with one outline.
function mergeByCode(features) {
const byCode = new Map();
for (const f of features) {
const code = f.properties.iso_3166_2;
if (!byCode.has(code)) {
byCode.set(code, []);
}
byCode.get(code).push(f);
}
const topo = topology({ parts: { type: 'FeatureCollection', features } });
const { geometries } = topo.objects.parts;
let merged = 0;
const shapes = [...byCode].map(([code, members]) => {
// The largest part carries the name and label point.
const primary = members.reduce((a, b) => (geoArea(a) >= geoArea(b) ? a : b));
let geometry = primary.geometry;
if (members.length > 1) {
merged += members.length - 1;
geometry = merge(
topo,
geometries.filter((_, i) => features[i].properties.iso_3166_2 === code),
);
}
return {
type: 'Feature',
id: code,
properties: {
code,
name: primary.properties.name,
label: [
round(primary.properties.longitude),
round(primary.properties.latitude),
],
},
geometry,
};
});
return { shapes: shapes.sort((a, b) => a.id.localeCompare(b.id)), merged };
}
/**
* Lower-cased English names → code, for data that names a state. A main name
* outranks a neighbour's alternate spelling of it.
*/
function namesOf(members) {
const names = {};
const mainNames = new Set();
for (const { properties: p } of members) {
const main = p.name?.toLowerCase();
if (main && !mainNames.has(main)) {
mainNames.add(main);
names[main] = p.iso_3166_2;
}
for (const name of [p.name_en, p.gn_name, p.woe_name]) {
if (name) {
names[name.toLowerCase()] ??= p.iso_3166_2;
}
}
}
return names;
}
/**
* Natural Earth admin-1 GeoJSON → `{ files, report }`, where `files` maps each
* country with enough coded states to its outlines file, in code order.
*/
export function buildSubdivisions(source) {
const { byCountry, uncoded, recoded } = groupByCountry(source.features);
const files = new Map();
const report = {
skippedUnderMinimum: [],
mergedParts: {},
uncodedShapes: uncoded,
droppedFlippedIslands: {},
droppedCollapsedPolygons: 0,
emptiedShapes: [],
// Merge entries whose retired code Natural Earth no longer has.
unmatchedRetiredCodes: [...RECODES.keys()].filter(
(code) => !recoded.has(code),
),
};
const countries = [...byCountry.keys()].sort((a, b) => a.localeCompare(b));
for (const country of countries) {
const members = byCountry.get(country);
const { shapes, merged } = mergeByCode(members);
if (shapes.length < MIN_SUBDIVISIONS) {
report.skippedUnderMinimum.push(country);
continue;
}
if (merged) {
report.mergedParts[country] = merged;
}
const { topo, flipped, collapsed, emptied } = simplifyAndQuantize(
'subdivisions',
shapes,
SUBDIVISION_MIN_WEIGHT,
SUBDIVISION_QUANTIZATION,
);
if (flipped) {
report.droppedFlippedIslands[country] = flipped;
}
report.droppedCollapsedPolygons += collapsed;
report.emptiedShapes.push(...emptied);
files.set(country, {
...topo,
aliases: aliasesOf(country),
names: namesOf(members),
});
}
return { files, report };
}

View File

@@ -1,114 +0,0 @@
// Invariants the chart relies on, checked before anything is written. A
// failure names every problem; the committed assets are left untouched.
// Called by build.mjs; not run on its own.
//
// Checks shape counts, that no shape is emptied or drawn twice, and that every
// code, alias and name resolves to a drawn shape.
import { feature } from 'topojson-client';
import { MIN_SUBDIVISIONS } from './config.mjs';
// Natural Earth v5.1.2 yields 239 countries and 198 countries with states. A
// drop below these means a changed or truncated download, not real geography.
const MIN_COUNTRIES = 230;
const MIN_SUBDIVISION_COUNTRIES = 190;
function duplicatesOf(values) {
const seen = new Set();
return values.filter((value) => seen.has(value) || !seen.add(value));
}
function checkCountries({ topology, lookups, report }, problems) {
const shapes = feature(topology, topology.objects.countries).features;
const codes = shapes.map((shape) => shape.properties.code).filter(Boolean);
const drawn = new Set(codes);
if (shapes.length < MIN_COUNTRIES) {
problems.push(
`only ${shapes.length} countries (expected ≥ ${MIN_COUNTRIES})`,
);
}
if (report.emptied) {
problems.push(`countries left with no outline: ${report.emptied}`);
}
for (const code of duplicatesOf(codes)) {
problems.push(`country code ${code} is drawn twice`);
}
if (lookups.codes.join() !== [...drawn].sort().join()) {
problems.push('lookups.codes differs from the drawn country codes');
}
for (const [alias, target] of Object.entries(lookups.aliases)) {
if (!drawn.has(target)) {
problems.push(`country alias ${alias} → ${target}, which has no shape`);
}
}
for (const [alpha3, target] of Object.entries(lookups.alpha3)) {
if (!drawn.has(target)) {
problems.push(`alpha-3 ${alpha3} → ${target}, which has no shape`);
}
}
}
function checkSubdivisionFile(country, file, problems) {
const codes = file.objects.subdivisions.geometries.map(
(geometry) => geometry.properties.code,
);
const known = new Set(codes);
if (codes.length < MIN_SUBDIVISIONS) {
problems.push(
`${country}: ${codes.length} states (expected ≥ ${MIN_SUBDIVISIONS})`,
);
}
for (const code of duplicatesOf(codes)) {
problems.push(`${country}: state code ${code} is drawn twice`);
}
for (const code of codes) {
if (!code?.startsWith(`${country}-`)) {
problems.push(`${country}: state code ${code} is outside the country`);
}
}
for (const [alias, target] of Object.entries(file.aliases)) {
if (!known.has(target)) {
problems.push(`${country}: alias ${alias} → ${target}, which has no shape`);
}
}
for (const [name, code] of Object.entries(file.names)) {
if (!known.has(code)) {
problems.push(`${country}: name "${name}" → ${code}, which has no shape`);
}
}
}
function checkSubdivisions({ files, report }, problems) {
if (files.size < MIN_SUBDIVISION_COUNTRIES) {
problems.push(
`only ${files.size} countries with states (expected ≥ ${MIN_SUBDIVISION_COUNTRIES})`,
);
}
if (report.emptiedShapes.length > 0) {
problems.push(
`states left with no outline: ${report.emptiedShapes.join(' ')}`,
);
}
if (report.unmatchedRetiredCodes.length > 0) {
problems.push(
`merge codes not found in Natural Earth: ${report.unmatchedRetiredCodes.join(' ')}`,
);
}
for (const [country, file] of files) {
checkSubdivisionFile(country, file, problems);
}
}
/** Throws one error listing every broken invariant. */
export function validate(countries, subdivisions) {
const problems = [];
checkCountries(countries, problems);
checkSubdivisions(subdivisions, problems);
if (problems.length > 0) {
throw new Error(
`${problems.length} problem(s) in the generated outlines:\n- ${problems.join('\n- ')}`,
);
}
}

View File

@@ -1,4 +1,5 @@
import { ReactChild, useCallback, useMemo } from 'react';
import { matchPath, Redirect, useLocation } from 'react-router-dom';
import getLocalStorageApi from 'api/browser/localstorage/get';
import setLocalStorageApi from 'api/browser/localstorage/set';
import { useListUsers } from 'api/generated/services/users';
@@ -8,14 +9,10 @@ import ROUTES from 'constants/routes';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { isEmpty } from 'lodash-es';
import { matchRoute } from 'lib/router/matchRoute';
import { Redirect } from 'lib/router/Redirect';
import { useAppLocation } from 'lib/router/useAppLocation';
import { useAppContext } from 'providers/App/App';
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
import { OrgPreference } from 'types/api/preferences/preference';
import { USER_ROLES } from 'types/roles';
import { isSignozAdminEmail } from 'utils/app';
import {
routePermission,
routeWithInitialAuthZSupport,
@@ -28,12 +25,10 @@ import routes, {
ROUTES_NOT_TO_BE_OVERRIDEN,
SUPPORT_ROUTE,
} from './routes';
import { useAuthZ } from '@/lib/authz/hooks/useAuthZ/useAuthZ';
import { UserListPermission } from '@/lib/authz/hooks/useAuthZ/permissions/user.permissions';
// eslint-disable-next-line sonarjs/cognitive-complexity
function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const location = useAppLocation();
const location = useLocation();
const { pathname } = location;
const {
org,
@@ -52,11 +47,10 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
() =>
new Map(
[...routes, LIST_LICENSES, SUPPORT_ROUTE].map((e) => {
const patterns = Array.isArray(e.path) ? e.path : [e.path];
const matches = patterns.some(
(pattern) => matchRoute(pathname, pattern) !== null,
);
return [matches ? 'current' : null, e];
const currentPath = matchPath(pathname, {
path: e.path,
});
return [currentPath === null ? null : 'current', e];
}),
),
[pathname],
@@ -71,16 +65,9 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
return undefined;
}, [org]);
const { permissions: authzPermission } = useAuthZ([UserListPermission], {
enabled: isLoggedInState,
});
const canListUsers = authzPermission?.[UserListPermission]?.isGranted ?? false;
// Without `list:user` the list isn't fetched, so the onboarding redirect is skipped.
const { data: usersData, isFetching: isFetchingUsers } = useListUsers({
query: {
enabled: !isEmpty(orgData) && canListUsers,
enabled: !isEmpty(orgData) && user.role === 'ADMIN',
},
});
@@ -88,7 +75,7 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const users = usersData?.data || [];
const remainingUsers = (Array.isArray(users) ? users : []).filter(
(u) => !isSignozAdminEmail(u.email),
(user) => user.email !== 'admin@signoz.cloud',
);
return remainingUsers.length === 1;
@@ -174,9 +161,10 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const isRouteEnabledForWorkspaceBlockedState =
pathname === ROUTES.SETTINGS ||
pathname === ROUTES.BILLING ||
pathname === ROUTES.MEMBERS_SETTINGS ||
(isAdmin &&
(pathname === ROUTES.ORG_SETTINGS || pathname === ROUTES.MY_SETTINGS));
(pathname === ROUTES.ORG_SETTINGS ||
pathname === ROUTES.MEMBERS_SETTINGS ||
pathname === ROUTES.MY_SETTINGS));
if (
pathname !== ROUTES.WORKSPACE_LOCKED &&
@@ -215,7 +203,6 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const isFirstUser = checkFirstTimeUser();
if (
isFirstUser &&
!isSignozAdminEmail(user.email) &&
!isOnboardingComplete &&
!ROUTES_NOT_TO_BE_OVERRIDEN.includes(pathname) &&
pathname !== ROUTES.ONBOARDING

View File

@@ -1,29 +0,0 @@
import type { ComponentType } from 'react';
import { useOutletContext } from 'react-router';
import NotFound from 'components/NotFound';
import type { AppRoutes } from './routes';
/**
* The routes the plan, the license and the feature flags enable. The root
* layout computes it and hands it down as outlet context.
*/
export type EnabledRouteKeys = ReadonlySet<AppRoutes['key']>;
interface RouteGateProps {
routeKey: AppRoutes['key'];
component: ComponentType;
}
/**
* The table is created once, so a route the session may not use is still in
* it. It renders the not-found page instead, which is what the old dynamic
* `<Switch>` fell through to.
*/
export function RouteGate({
routeKey,
component: Component,
}: RouteGateProps): JSX.Element {
const enabledRouteKeys = useOutletContext<EnabledRouteKeys>();
return enabledRouteKeys.has(routeKey) ? <Component /> : <NotFound />;
}

View File

@@ -1,25 +1,10 @@
import { ReactElement } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import {
MemoryRouter,
Route,
Routes,
useLocation,
useNavigationType,
} from 'react-router';
import { MemoryRouter, Route, Switch, useLocation } from 'react-router-dom';
import { act, render, screen, waitFor } from '@testing-library/react';
import { useListUsers } from 'api/generated/services/users';
import { SIGNOZ_ADMIN_EMAIL } from 'constants/app';
import { LOCALSTORAGE } from 'constants/localStorage';
import { ORG_PREFERENCES } from 'constants/orgPreferences';
import ROUTES from 'constants/routes';
import { UserListPermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import {
AUTHZ_CHECK_URL,
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { rest, server } from 'mocks-server/server';
import { AppContext } from 'providers/App/App';
import { IAppContext, IUser } from 'providers/App/types';
import {
@@ -88,13 +73,11 @@ const queryClient = new QueryClient({
// Component to capture current location for assertions
function LocationDisplay(): ReactElement {
const location = useLocation();
const navigationType = useNavigationType();
return (
<>
<div data-testid="location-display">{location.pathname}</div>
<div data-testid="location-search">{location.search}</div>
<div data-testid="location-hash">{location.hash}</div>
<div data-testid="navigation-type">{navigationType}</div>
</>
);
}
@@ -254,17 +237,12 @@ function buildPrivateRouteTree(
<MemoryRouter initialEntries={[initialRoute]}>
<AppContext.Provider value={contextValue}>
<PrivateRoute>
<Routes>
<Route
path="*"
element={
<>
<div data-testid="children-rendered">Content</div>
<LocationDisplay />
</>
}
/>
</Routes>
<Switch>
<Route path="*">
<div data-testid="children-rendered">Content</div>
<LocationDisplay />
</Route>
</Switch>
</PrivateRoute>
</AppContext.Provider>
</MemoryRouter>
@@ -527,19 +505,6 @@ describe('PrivateRoute', () => {
await assertRedirectsTo(ROUTES.ALL_DASHBOARD);
});
it('should replace the login entry when redirecting to the saved route', async () => {
mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT] =
ROUTES.ALL_DASHBOARD;
renderPrivateRoute({
initialRoute: ROUTES.LOGIN,
appContext: { isLoggedIn: true },
});
await assertRedirectsTo(ROUTES.ALL_DASHBOARD);
expect(screen.getByTestId('navigation-type')).toHaveTextContent('REPLACE');
});
it('should clear localStorage after redirecting to saved route', async () => {
mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT] = ROUTES.HOME;
@@ -664,19 +629,6 @@ describe('PrivateRoute', () => {
expect(mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT]).toBe('');
});
});
it('should replace the unknown route entry when redirecting to the saved route', async () => {
mockLocalStorage[LOCALSTORAGE.UNAUTHENTICATED_ROUTE_HIT] =
ROUTES.ALL_DASHBOARD;
renderPrivateRoute({
initialRoute: '/unknown-route-that-does-not-exist',
appContext: { isLoggedIn: true },
});
await assertRedirectsTo(ROUTES.ALL_DASHBOARD);
expect(screen.getByTestId('navigation-type')).toHaveTextContent('REPLACE');
});
});
describe('Workspace Blocked - Trial Expired (Cloud Users)', () => {
@@ -824,7 +776,7 @@ describe('PrivateRoute', () => {
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should allow VIEWER to access members settings when workspace is blocked', () => {
it('should redirect VIEWER to workspace locked when trying to access members settings', async () => {
renderPrivateRoute({
initialRoute: ROUTES.MEMBERS_SETTINGS,
appContext: {
@@ -837,7 +789,7 @@ describe('PrivateRoute', () => {
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.MEMBERS_SETTINGS);
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should redirect VIEWER to workspace locked when trying to access my-settings', async () => {
@@ -1137,99 +1089,6 @@ describe('PrivateRoute', () => {
await assertRedirectsTo(ROUTES.ONBOARDING);
});
it('should not redirect the signoz admin to onboarding while the first user has not completed it', async () => {
mockUsersData = [
{ email: 'test@example.com' },
{ email: SIGNOZ_ADMIN_EMAIL },
];
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
isFetchingOrgPreferences: false,
orgPreferences: createMockOrgPreferences(false),
user: createMockUser({
role: USER_ROLES.ADMIN as ROLES,
email: SIGNOZ_ADMIN_EMAIL,
}),
},
isCloudUser: true,
});
await act(async () => {
await Promise.resolve();
});
assertStaysOnRoute(ROUTES.HOME);
});
it('fetches the user list for a non-admin role that has list:user', async () => {
server.use(setupAuthzAdmin());
jest.mocked(useListUsers).mockClear();
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.VIEWER as ROLES }),
},
isCloudUser: true,
});
await waitFor(() =>
expect(useListUsers).toHaveBeenLastCalledWith({
query: { enabled: true },
}),
);
});
it('does not check list:user while logged out', async () => {
const authzCheck = jest.fn();
server.use(
rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => {
authzCheck();
return res(ctx.status(401));
}),
);
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: { isLoggedIn: false },
isCloudUser: true,
});
await act(async () => {
await new Promise((resolve) => {
setTimeout(resolve, 50);
});
});
expect(authzCheck).not.toHaveBeenCalled();
});
it('does not fetch the user list for an admin without list:user', async () => {
server.use(setupAuthzDeny(UserListPermission));
jest.mocked(useListUsers).mockClear();
renderPrivateRoute({
initialRoute: ROUTES.HOME,
appContext: {
isLoggedIn: true,
user: createMockUser({ role: USER_ROLES.ADMIN as ROLES }),
},
isCloudUser: true,
});
await act(async () => {
await Promise.resolve();
});
expect(useListUsers).not.toHaveBeenCalledWith({
query: { enabled: true },
});
});
it('should not redirect to onboarding when org preferences are still fetching', () => {
renderPrivateRoute({
initialRoute: ROUTES.HOME,

View File

@@ -1,85 +0,0 @@
import { lazy, Suspense, useState } from 'react';
import {
createBrowserRouter,
type DataRouter,
Outlet,
RouterProvider,
} from 'react-router';
import { act, render, screen } from '@testing-library/react';
import ROUTES from 'constants/routes';
import { resetTestRoute } from 'tests/router-utils';
import type { EnabledRouteKeys } from '../RouteGate';
import { createGatedRoutes } from '../routeTable';
import type { AppRoutes } from '../routes';
let mounts = 0;
function Page(): JSX.Element {
const [mount] = useState(() => {
mounts += 1;
return mounts;
});
return <div data-testid="page">mount {mount}</div>;
}
// Two lazy wrappers of one module, like the logs explorer and pipelines routes.
const Explorer = lazy(async () => ({ default: Page }));
const Pipelines = lazy(async () => ({ default: Page }));
const routes: AppRoutes[] = [
{ path: ROUTES.LOGS, component: Explorer, key: 'LOGS', isPrivate: true },
{
path: [ROUTES.LOGS_PIPELINES, ROUTES.LOGS_INDEX_FIELDS],
component: Pipelines,
key: 'LOGS_PIPELINES',
isPrivate: true,
},
];
const enabledRouteKeys: EnabledRouteKeys = new Set(['LOGS', 'LOGS_PIPELINES']);
function renderRoutes(): DataRouter {
window.history.replaceState(null, '', ROUTES.LOGS);
const router = createBrowserRouter([
{
element: (
<Suspense fallback={<div data-testid="fallback" />}>
<Outlet context={enabledRouteKeys} />
</Suspense>
),
children: createGatedRoutes(routes),
},
]);
render(<RouterProvider router={router} useTransitions={false} />);
return router;
}
describe('createGatedRoutes', () => {
beforeEach(() => {
mounts = 0;
});
afterEach(() => {
resetTestRoute();
});
it('remounts the page when another route entry resolves to the same component', async () => {
const router = renderRoutes();
await expect(screen.findByText('mount 1')).resolves.toBeInTheDocument();
await act(() => router.navigate(ROUTES.LOGS_PIPELINES));
await expect(screen.findByText('mount 2')).resolves.toBeInTheDocument();
});
it('keeps the page mounted across the patterns of one route entry', async () => {
const router = renderRoutes();
await act(() => router.navigate(ROUTES.LOGS_PIPELINES));
await expect(screen.findByText('mount 2')).resolves.toBeInTheDocument();
await act(() => router.navigate(ROUTES.LOGS_INDEX_FIELDS));
expect(screen.getByTestId('page')).toHaveTextContent('mount 2');
});
});

View File

@@ -2,9 +2,9 @@ import type { ErrorEvent, StackFrame } from '@sentry/react';
import { AxiosError, AxiosHeaders } from 'axios';
import {
isInjectedScriptError,
hasNoAppFrames,
isExpectedRequestFailure,
isThirdPartyScriptError,
isExternalIntegrationError,
SENTRY_IGNORE_ERRORS,
} from '../sentryFilters';
@@ -27,7 +27,7 @@ function eventWithFrames(...filenames: string[]): ErrorEvent {
};
}
describe('isThirdPartyScriptError', () => {
describe('isExternalIntegrationError', () => {
it.each([
[
'PostHog recorder',
@@ -39,12 +39,14 @@ describe('isThirdPartyScriptError', () => {
],
['Appcues', 'https://fast.appcues.com/123456.js'],
])('drops an error with a %s frame', (_, url) => {
expect(isThirdPartyScriptError(eventWithFrames(APP_BUNDLE, url))).toBe(true);
expect(isExternalIntegrationError(eventWithFrames(APP_BUNDLE, url))).toBe(
true,
);
});
it('drops it when the top frame is our bundle', () => {
expect(
isThirdPartyScriptError(
isExternalIntegrationError(
eventWithFrames(
'https://us-assets.i.posthog.com/static/posthog-recorder.js?v=1.298.0',
'<anonymous>',
@@ -56,13 +58,13 @@ describe('isThirdPartyScriptError', () => {
it('keeps an error from our bundle only', () => {
expect(
isThirdPartyScriptError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
isExternalIntegrationError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
).toBe(false);
});
it('keeps an error from a host that only contains an integration name', () => {
expect(
isThirdPartyScriptError(
isExternalIntegrationError(
eventWithFrames(
'https://posthog.example.com/app.js',
'https://notusepylon.com/widget.js',
@@ -72,11 +74,11 @@ describe('isThirdPartyScriptError', () => {
});
it('keeps an error without a stack trace', () => {
expect(isThirdPartyScriptError({ type: undefined })).toBe(false);
expect(isExternalIntegrationError({ type: undefined })).toBe(false);
});
});
describe('isInjectedScriptError', () => {
describe('hasNoAppFrames', () => {
const PAGE_URL = 'https://example.us.signoz.cloud/dashboard/01a081e1';
function eventWithStackFrames(frames: StackFrame[]): ErrorEvent {
@@ -90,7 +92,7 @@ describe('isInjectedScriptError', () => {
it('drops a script appended to the page', () => {
expect(
isInjectedScriptError(
hasNoAppFrames(
eventWithStackFrames([
{ filename: PAGE_URL, lineno: 1, colno: 30, function: 'global code' },
{ filename: '[native code]', function: 'eval' },
@@ -102,7 +104,7 @@ describe('isInjectedScriptError', () => {
it('drops a browser extension error', () => {
expect(
isInjectedScriptError(
hasNoAppFrames(
eventWithStackFrames([
{ filename: 'chrome-extension://abc/content.js', lineno: 4, colno: 12 },
]),
@@ -110,46 +112,21 @@ describe('isInjectedScriptError', () => {
).toBe(true);
});
it('drops an error thrown from injected code behind the Sentry wrapper', () => {
expect(
isInjectedScriptError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
).toBe(true);
});
it('keeps an error thrown from our bundle after an anonymous frame', () => {
expect(
isInjectedScriptError(eventWithFrames('<anonymous>', APP_BUNDLE)),
).toBe(false);
});
it('keeps an error with a frame from our bundle', () => {
expect(isInjectedScriptError(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(
false,
);
expect(hasNoAppFrames(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(false);
});
it('keeps an error without a stack trace', () => {
expect(isInjectedScriptError({ type: undefined })).toBe(false);
expect(hasNoAppFrames({ type: undefined })).toBe(false);
});
it('keeps an error whose frames have no position', () => {
expect(
isInjectedScriptError(
hasNoAppFrames(
eventWithStackFrames([{ filename: '[native code]', function: 'eval' }]),
),
).toBe(false);
});
it('keeps an error a builtin threw for our bundle', () => {
expect(
isInjectedScriptError(
eventWithStackFrames([
{ filename: APP_BUNDLE, lineno: 1, colno: 1 },
{ filename: '<anonymous>', function: 'JSON.parse' },
]),
),
).toBe(false);
});
});
describe('SENTRY_IGNORE_ERRORS', () => {

View File

@@ -1,12 +1,6 @@
import {
ReactNode,
Suspense,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import { Outlet } from 'react-router';
import { ReactNode, Suspense, useCallback, useEffect, useState } from 'react';
import { Route, Router, Switch } from 'react-router-dom';
import { CompatRouter } from 'react-router-dom-v5-compat';
import * as Sentry from '@sentry/react';
import getLocalStorageApi from 'api/browser/localstorage/get';
import setLocalStorageApi from 'api/browser/localstorage/set';
@@ -15,6 +9,7 @@ import AppPageProviders from 'app/AppPageProviders';
import AppShell from 'app/AppShell';
import AppLoading from 'components/AppLoading/AppLoading';
import { CmdKPalette } from 'components/cmdKPalette/cmdKPalette';
import NotFound from 'components/NotFound';
import { ShiftHoldOverlayController } from 'components/ShiftOverlay/ShiftHoldOverlayController';
import Spinner from 'components/Spinner';
import { LOCALSTORAGE } from 'constants/localStorage';
@@ -28,7 +23,7 @@ import { useIsDarkMode } from 'hooks/useDarkMode';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { StatusCodes } from 'http-status-codes';
import { IS_PROD } from 'lib/env';
import { getCurrentLocation, navigate, subscribe } from 'lib/router/navigation';
import history from 'lib/history';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import posthog from 'posthog-js';
import { useAppContext } from 'providers/App/App';
@@ -36,20 +31,26 @@ import { IUser } from 'providers/App/types';
import { LicenseStatus } from 'types/api/licensesV3/getActive';
import { extractDomain } from 'utils/app';
import { Home } from './pageComponents';
import PrivateRoute from './Private';
import defaultRoutes, {
AppRoutes,
LIST_LICENSES,
SUPPORT_ROUTE,
} from './routes';
import type { EnabledRouteKeys } from './RouteGate';
import {
isInjectedScriptError,
hasNoAppFrames,
isExpectedRequestFailure,
isThirdPartyScriptError,
isExternalIntegrationError,
SENTRY_IGNORE_ERRORS,
} from './sentryFilters';
const appRouter = (children: ReactNode): ReactNode => (
<Router history={history}>
<CompatRouter>{children}</CompatRouter>
</Router>
);
const appLayout = (children: ReactNode): ReactNode => (
<AppLayout>{children}</AppLayout>
);
@@ -70,24 +71,18 @@ function App(): JSX.Element {
isPreflightLoading,
} = useAppContext();
const [routes, setRoutes] = useState<AppRoutes[]>(defaultRoutes);
const enabledRouteKeys = useMemo<EnabledRouteKeys>(
() => new Set(routes.map(({ key }) => key)),
[routes],
);
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const chatSupport = useChatSupport();
const { hostname } = window.location;
// Through the facade, not the raw history: the router owns the base path
// now, so `history.location.pathname` would still carry it.
const [pathname, setPathname] = useState(getCurrentLocation().pathname);
const [pathname, setPathname] = useState(history.location.pathname);
const { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
const [isSentryInitialized, setIsSentryInitialized] = useState(false);
useEffect(() => {
return subscribe(({ location }) => {
return history.listen((location) => {
setPathname(location.pathname);
});
}, []);
@@ -360,12 +355,12 @@ function App(): JSX.Element {
return null;
}
if (isThirdPartyScriptError(event)) {
if (isExternalIntegrationError(event)) {
return null;
}
// Dev serves source from /src/, so every frame would look foreign there.
if (IS_PROD && isInjectedScriptError(event)) {
if (IS_PROD && hasNoAppFrames(event)) {
return null;
}
@@ -407,7 +402,7 @@ function App(): JSX.Element {
// this needs to be on top of data missing error because if there is an error, data will never be loaded and it will
// move to indefinitive loading
if (userFetchError && pathname !== ROUTES.SOMETHING_WENT_WRONG) {
navigate(ROUTES.SOMETHING_WENT_WRONG, { replace: true });
history.replace(ROUTES.SOMETHING_WENT_WRONG);
}
// if all of the data is not set then return a spinner, this is required because there is some gap between loading states and data setting
@@ -423,6 +418,7 @@ function App(): JSX.Element {
return (
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
<AppShell
router={appRouter}
overlays={
isLoggedInState && (
<>
@@ -435,7 +431,18 @@ function App(): JSX.Element {
<PrivateRoute>
<AppPageProviders layout={appLayout}>
<Suspense fallback={<Spinner size="large" tip="Loading..." />}>
<Outlet context={enabledRouteKeys} />
<Switch>
{routes.map(({ path, component, exact }) => (
<Route
key={`${path}`}
exact={exact}
path={path}
component={component}
/>
))}
<Route exact path="/" component={Home} />
<Route path="*" component={NotFound} />
</Switch>
</Suspense>
</AppPageProviders>
</PrivateRoute>

View File

@@ -1,46 +0,0 @@
import type { ReactNode } from 'react';
import type { RouteObject } from 'react-router';
import NotFound from 'components/NotFound';
import { RethrowRouteError } from 'lib/router/RethrowRouteError';
import { Home } from './pageComponents';
import { RouteGate } from './RouteGate';
import routes, { AppRoutes, LIST_LICENSES, SUPPORT_ROUTE } from './routes';
/**
* The gate is keyed by its route entry. The outlet renders the match unkeyed,
* so every route would otherwise reuse the previous route's gate, and a lazy
* page that resolves to the same component would keep its instance. The
* patterns of one entry share the key.
*/
export function createGatedRoutes(appRoutes: AppRoutes[]): RouteObject[] {
return appRoutes.flatMap(({ path, component, nested, key }) =>
(Array.isArray(path) ? path : [path]).map((pattern) => ({
path: nested ? `${pattern}/*` : pattern,
element: <RouteGate key={key} routeKey={key} component={component} />,
})),
);
}
const gatedRoutes = createGatedRoutes([
...routes,
LIST_LICENSES,
SUPPORT_ROUTE,
]);
/** `root` is the layout every route renders in; it has to render an `<Outlet>`. */
export function createRouteTable(root: ReactNode): RouteObject[] {
return [
{
element: root,
// An error above `Sentry.ErrorBoundary` in the root layout crashes the
// root and reaches Sentry, as it did before the data router.
errorElement: <RethrowRouteError />,
children: [
...gatedRoutes,
{ path: '/', element: <Home /> },
{ path: '*', element: <NotFound /> },
],
},
];
}

View File

@@ -1,4 +1,4 @@
import type { ComponentType } from 'react';
import { RouteProps } from 'react-router-dom';
import ROUTES from 'constants/routes';
import {
@@ -58,25 +58,27 @@ const routes: AppRoutes[] = [
{
component: SignupPage,
path: ROUTES.SIGN_UP,
exact: true,
isPrivate: false,
key: 'SIGN_UP',
},
{
path: ROUTES.GET_STARTED_WITH_CLOUD,
nested: true,
exact: false,
component: OnboardingV2,
isPrivate: true,
key: 'GET_STARTED_WITH_CLOUD',
},
{
path: ROUTES.HOME,
exact: true,
component: Home,
isPrivate: true,
key: 'HOME',
},
{
path: ROUTES.ONBOARDING,
nested: true,
exact: false,
component: OrgOnboarding,
isPrivate: true,
key: 'ONBOARDING',
@@ -84,23 +86,27 @@ const routes: AppRoutes[] = [
{
component: LogsIndexToFields,
path: ROUTES.LOGS_INDEX_FIELDS,
exact: true,
isPrivate: true,
key: 'LOGS_INDEX_FIELDS',
},
{
component: ServicesTablePage,
path: ROUTES.APPLICATION,
exact: true,
isPrivate: true,
key: 'APPLICATION',
},
{
path: ROUTES.SERVICE_METRICS,
exact: true,
component: ServiceMetricsPage,
isPrivate: true,
key: 'SERVICE_METRICS',
},
{
path: ROUTES.SERVICE_TOP_LEVEL_OPERATIONS,
exact: true,
component: ServiceTopLevelOperationsPage,
isPrivate: true,
key: 'SERVICE_TOP_LEVEL_OPERATIONS',
@@ -109,252 +115,292 @@ const routes: AppRoutes[] = [
path: ROUTES.SERVICE_MAP,
component: ServiceMapPage,
isPrivate: true,
exact: true,
key: 'SERVICE_MAP',
},
{
path: ROUTES.TRACE_DETAIL,
exact: true,
component: TraceDetailV3,
isPrivate: true,
key: 'TRACE_DETAIL',
},
{
path: ROUTES.SETTINGS,
nested: true,
exact: false,
component: SettingsPage,
isPrivate: true,
key: 'SETTINGS',
},
{
path: ROUTES.USAGE_EXPLORER,
exact: true,
component: UsageExplorerPage,
isPrivate: true,
key: 'USAGE_EXPLORER',
},
{
path: ROUTES.ALL_DASHBOARD,
exact: true,
component: DashboardsListPage,
isPrivate: true,
key: 'ALL_DASHBOARD',
},
{
path: ROUTES.DASHBOARD,
exact: true,
component: DashboardPage,
isPrivate: true,
key: 'DASHBOARD',
},
{
path: ROUTES.PUBLIC_DASHBOARD,
nested: true,
exact: false,
component: PublicDashboardPage,
isPrivate: false,
key: 'PUBLIC_DASHBOARD',
},
{
path: ROUTES.DASHBOARD_PANEL_EDITOR,
exact: true,
component: DashboardPanelEditorPage,
isPrivate: true,
key: 'DASHBOARD_PANEL_EDITOR',
},
{
path: ROUTES.EDIT_ALERTS,
exact: true,
component: EditRulesPage,
isPrivate: true,
key: 'EDIT_ALERTS',
},
{
path: ROUTES.LIST_ALL_ALERT,
exact: true,
component: ListAllALertsPage,
isPrivate: true,
key: 'LIST_ALL_ALERT',
},
{
path: ROUTES.ALERTS_NEW,
exact: true,
component: CreateNewAlerts,
isPrivate: true,
key: 'ALERTS_NEW',
},
{
path: ROUTES.ALERT_HISTORY,
exact: true,
component: AlertHistory,
isPrivate: true,
key: 'ALERT_HISTORY',
},
{
path: ROUTES.ALERT_OVERVIEW,
exact: true,
component: AlertOverview,
isPrivate: true,
key: 'ALERT_OVERVIEW',
},
{
path: ROUTES.TRACES_EXPLORER,
exact: true,
component: TracesExplorer,
isPrivate: true,
key: 'TRACES_EXPLORER',
},
{
path: ROUTES.TRACES_FUNNELS,
exact: true,
component: TracesFunnels,
isPrivate: true,
key: 'TRACES_FUNNELS',
},
{
path: ROUTES.TRACES_FUNNELS_DETAIL,
exact: true,
component: TracesFunnelDetails,
isPrivate: true,
key: 'TRACES_FUNNELS_DETAIL',
},
{
path: ROUTES.CHANNELS_NEW,
exact: true,
component: ChannelsNew,
isPrivate: true,
key: 'CHANNELS_NEW',
},
{
path: ROUTES.CHANNELS_EDIT,
exact: true,
component: ChannelsEdit,
isPrivate: true,
key: 'CHANNELS_EDIT',
},
{
path: ROUTES.ALL_ERROR,
exact: true,
isPrivate: true,
component: AllErrors,
key: 'ALL_ERROR',
},
{
path: ROUTES.ERROR_DETAIL,
exact: true,
component: ErrorDetails,
isPrivate: true,
key: 'ERROR_DETAIL',
},
{
path: ROUTES.VERSION,
exact: true,
component: StatusPage,
isPrivate: true,
key: 'VERSION',
},
{
path: ROUTES.LOGS,
exact: true,
component: Logs,
key: 'LOGS',
isPrivate: true,
},
{
path: ROUTES.LOGS_PIPELINES,
exact: true,
component: PipelinePage,
key: 'LOGS_PIPELINES',
isPrivate: true,
},
{
path: ROUTES.LOGIN,
exact: true,
component: Login,
isPrivate: false,
key: 'LOGIN',
},
{
path: ROUTES.FORGOT_PASSWORD,
exact: true,
component: ForgotPassword,
isPrivate: false,
key: 'FORGOT_PASSWORD',
},
{
path: ROUTES.UN_AUTHORIZED,
exact: true,
component: UnAuthorized,
key: 'UN_AUTHORIZED',
isPrivate: true,
},
{
path: ROUTES.PASSWORD_RESET,
exact: true,
component: PasswordReset,
key: 'PASSWORD_RESET',
isPrivate: false,
},
{
path: ROUTES.SOMETHING_WENT_WRONG,
exact: true,
component: SomethingWentWrong,
key: 'SOMETHING_WENT_WRONG',
isPrivate: false,
},
{
path: ROUTES.WORKSPACE_LOCKED,
exact: true,
component: WorkspaceBlocked,
isPrivate: true,
key: 'WORKSPACE_LOCKED',
},
{
path: ROUTES.WORKSPACE_SUSPENDED,
exact: true,
component: WorkspaceSuspended,
isPrivate: true,
key: 'WORKSPACE_SUSPENDED',
},
{
path: ROUTES.WORKSPACE_ACCESS_RESTRICTED,
exact: true,
component: WorkspaceAccessRestricted,
isPrivate: true,
key: 'WORKSPACE_ACCESS_RESTRICTED',
},
{
path: ROUTES.INTEGRATIONS_DETAIL,
exact: true,
component: IntegrationsDetailsPage,
isPrivate: true,
key: 'INTEGRATIONS_DETAIL',
},
{
path: ROUTES.INTEGRATIONS,
exact: true,
component: Integrations,
isPrivate: true,
key: 'INTEGRATIONS',
},
{
path: ROUTES.MESSAGING_QUEUES_KAFKA,
exact: true,
component: MessagingQueuesMainPage,
key: 'MESSAGING_QUEUES_KAFKA',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_CELERY_TASK,
exact: true,
component: MessagingQueuesMainPage,
key: 'MESSAGING_QUEUES_CELERY_TASK',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_OVERVIEW,
exact: true,
component: MessagingQueuesMainPage,
key: 'MESSAGING_QUEUES_OVERVIEW',
isPrivate: true,
},
{
path: ROUTES.MESSAGING_QUEUES_KAFKA_DETAIL,
exact: true,
component: MessagingQueuesMainPage,
key: 'MESSAGING_QUEUES_KAFKA_DETAIL',
isPrivate: true,
},
{
path: ROUTES.INFRASTRUCTURE_MONITORING_HOSTS,
exact: true,
component: InfrastructureMonitoring,
key: 'INFRASTRUCTURE_MONITORING_HOSTS',
isPrivate: true,
},
{
path: ROUTES.INFRASTRUCTURE_MONITORING_KUBERNETES,
exact: true,
component: InfrastructureMonitoring,
key: 'INFRASTRUCTURE_MONITORING_KUBERNETES',
isPrivate: true,
},
{
path: ROUTES.METRICS_EXPLORER,
exact: true,
component: MetricsExplorer,
key: 'METRICS_EXPLORER',
isPrivate: true,
},
{
path: ROUTES.METRICS_EXPLORER_EXPLORER,
exact: true,
component: MetricsExplorer,
key: 'METRICS_EXPLORER_EXPLORER',
isPrivate: true,
},
{
path: ROUTES.METRICS_EXPLORER_VOLUME_CONTROL,
exact: true,
component: MetricsExplorer,
key: 'METRICS_EXPLORER_VOLUME_CONTROL',
isPrivate: true,
@@ -362,48 +408,56 @@ const routes: AppRoutes[] = [
{
path: ROUTES.METER,
exact: true,
component: MeterExplorerPage,
key: 'METER',
isPrivate: true,
},
{
path: ROUTES.METER_EXPLORER,
exact: true,
component: MeterExplorerPage,
key: 'METER_EXPLORER',
isPrivate: true,
},
{
path: ROUTES.API_MONITORING,
exact: true,
component: ApiMonitoring,
key: 'API_MONITORING',
isPrivate: true,
},
{
path: [ROUTES.AI_ASSISTANT_BASE, ROUTES.AI_ASSISTANT],
exact: true,
component: AIAssistantPage,
key: 'AI_ASSISTANT',
isPrivate: true,
},
{
path: ROUTES.AI_OBSERVABILITY_ATTRIBUTE_MAPPING,
exact: true,
component: LLMObservabilityPage,
key: 'AI_OBSERVABILITY_ATTRIBUTE_MAPPING',
isPrivate: true,
},
{
path: ROUTES.AI_OBSERVABILITY_OVERVIEW,
exact: true,
component: LLMObservabilityPage,
key: 'AI_OBSERVABILITY_OVERVIEW',
isPrivate: true,
},
{
path: ROUTES.AI_OBSERVABILITY_EXPLORER,
exact: true,
component: LLMObservabilityPage,
key: 'AI_OBSERVABILITY_EXPLORER',
isPrivate: true,
},
{
path: ROUTES.AI_OBSERVABILITY_CONFIGURATION,
exact: true,
component: LLMObservabilityPage,
key: 'AI_OBSERVABILITY_CONFIGURATION',
isPrivate: true,
@@ -412,6 +466,7 @@ const routes: AppRoutes[] = [
export const SUPPORT_ROUTE: AppRoutes = {
path: ROUTES.SUPPORT,
exact: true,
component: SupportPage,
key: 'SUPPORT',
isPrivate: true,
@@ -419,6 +474,7 @@ export const SUPPORT_ROUTE: AppRoutes = {
export const LIST_LICENSES: AppRoutes = {
path: ROUTES.LIST_LICENSES,
exact: true,
component: LicensePage,
isPrivate: true,
key: 'LIST_LICENSES',
@@ -450,15 +506,9 @@ export const ROUTES_NOT_TO_BE_OVERRIDEN: string[] = [
];
export interface AppRoutes {
component: ComponentType;
/** An array registers the same component under each pattern. */
path: string | string[];
/**
* The route renders its own child routes, so it matches as a prefix. v6
* matches the whole path by default, so the mount appends a `/*` splat for
* these and nothing for the rest.
*/
nested?: boolean;
component: RouteProps['component'];
path: RouteProps['path'];
exact: RouteProps['exact'];
isPrivate: boolean;
key: keyof typeof ROUTES;
}

View File

@@ -28,15 +28,10 @@ export function isExpectedRequestFailure(error: unknown): boolean {
}
const APP_ASSETS_PATH = '/assets/';
const ANONYMOUS_FILENAME = '<anonymous>';
// Frames without a position are `[native code]` or a browser builtin such as
// `JSON.parse (<anonymous>)`, which say nothing about the script that threw.
// A positioned `<anonymous>` throwing (last) frame is code loaded without a
// URL: the DevTools console, CDP, or an extension's `executeScript`. Sentry's
// own timer wrapper is bundled with the app, so checking for any app frame
// alone misses it.
export function isInjectedScriptError(event: ErrorEvent): boolean {
// Frames without a position are `[native code]`, which says nothing about the
// script that threw.
export function hasNoAppFrames(event: ErrorEvent): boolean {
const frames = (event.exception?.values ?? [])
.flatMap((exception) => exception.stacktrace?.frames ?? [])
.filter(
@@ -45,13 +40,12 @@ export function isInjectedScriptError(event: ErrorEvent): boolean {
return (
frames.length > 0 &&
(frames[frames.length - 1].filename === ANONYMOUS_FILENAME ||
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH)))
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH))
);
}
// PostHog's lazy recorder, the Pylon widget and Appcues.
const THIRD_PARTY_SCRIPT_URLS = [
const EXTERNAL_SCRIPT_URLS = [
/^https?:\/\/[^/]+\.posthog\.com\//,
/^https?:\/\/(?:[^/]+\.)?usepylon\.com\//,
/^https?:\/\/(?:[^/]+\.)?appcues\.(?:com|net)\//,
@@ -59,10 +53,10 @@ const THIRD_PARTY_SCRIPT_URLS = [
// Checks every frame, not only the top one: a failed fetch from the recorder
// tops out in Sentry's own fetch wrapper, which is bundled with the app.
export function isThirdPartyScriptError(event: ErrorEvent): boolean {
export function isExternalIntegrationError(event: ErrorEvent): boolean {
return (event.exception?.values ?? []).some((exception) =>
(exception.stacktrace?.frames ?? []).some((frame) =>
THIRD_PARTY_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
EXTERNAL_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
),
);
}

View File

@@ -5660,13 +5660,6 @@ export interface DashboardtypesBasicVisualizationDTO {
timePreference?: DashboardtypesTimePreferenceDTO;
}
/**
* @minimum 1
* @maximum 64
* @nullable
*/
export type DashboardtypesBubbleRadiusDTO = number | null;
export interface Querybuildertypesv5LogAggregationDTO {
/**
* @type string
@@ -6950,246 +6943,6 @@ export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDa
spec: DashboardtypesScatterPlotPanelSpecDTO;
}
/**
* The panel kind.
*/
export enum DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTOKind {
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
}
/**
* Radius of the largest circle, in CSS pixels from 1 to 64. Null means 8 on the points layer, 28 otherwise.
*/
export type DashboardtypesGeoMapBubblesDTOMaxRadius = DashboardtypesBubbleRadiusDTO | null;
/**
* Radius of the smallest circle, in CSS pixels from 1 to 64. Null means 2 on the points layer, 3 otherwise.
*/
export type DashboardtypesGeoMapBubblesDTOMinRadius = DashboardtypesBubbleRadiusDTO | null;
export interface DashboardtypesGeoMapBubblesDTO {
/**
* @description Radius of the largest circle, in CSS pixels from 1 to 64. Null means 8 on the points layer, 28 otherwise.
*/
maxRadius?: DashboardtypesGeoMapBubblesDTOMaxRadius;
/**
* @description Radius of the smallest circle, in CSS pixels from 1 to 64. Null means 2 on the points layer, 3 otherwise.
*/
minRadius?: DashboardtypesGeoMapBubblesDTOMinRadius;
}
export interface DashboardtypesGeoMapColorsDTO {
/**
* @type string
* @description The hex color varied in opacity mode. Empty uses the default fill.
*/
fill?: string;
/**
* @type number,null
* @description The value mapped to the highest color. Null uses the highest value in the data.
*/
max?: number | null;
/**
* @type number,null
* @description The value mapped to the lowest color. Null uses the lowest value in the data. Must not exceed max.
*/
min?: number | null;
/**
* @description How values are colored: palette (default) picks a hue from palette, opacity varies the opacity of fill.
*/
mode?: DashboardtypesHeatmapColorModeDTO;
/**
* @description The named color ramp used in palette mode, such as lava (default), ice or ember.
*/
palette?: DashboardtypesHeatmapPaletteDTO;
/**
* @description How values map onto the color range: log (default), sqrt or linear.
*/
scale?: DashboardtypesHeatmapColorScaleDTO;
/**
* @type integer
* @description The number of distinct color steps, 2 to 128. 0 uses the chart default.
*/
steps?: number;
}
export interface DashboardtypesGeoMapChartAppearanceDTO {
/**
* @description The circle radius range of the bubbles and points layers.
*/
bubbles?: DashboardtypesGeoMapBubblesDTO;
/**
* @description The color scale applied to the colorBy values.
*/
colors?: DashboardtypesGeoMapColorsDTO;
/**
* @type boolean,null
* @description Shows country and state names once each fits inside its shape. Null shows them.
*/
labels?: boolean | null;
}
export enum DashboardtypesGeoMapCountryFormatDTO {
auto = 'auto',
alpha2 = 'alpha2',
alpha3 = 'alpha3',
name = 'name',
}
export enum DashboardtypesGeoMapLocationModeDTO {
auto = 'auto',
country = 'country',
subdivision = 'subdivision',
coordinates = 'coordinates',
}
export interface DashboardtypesGeoMapLocationDTO {
/**
* @type string
* @description Group-by key holding the country, for the country and subdivision modes. Empty detects it by name, such as geo.country.iso_code.
*/
country?: string;
/**
* @description How country values are written: auto (default) detects it, alpha2, alpha3 or name.
*/
countryFormat: DashboardtypesGeoMapCountryFormatDTO;
/**
* @type string
* @description Group-by key holding the latitude, for the coordinates mode. Empty detects it by name.
*/
lat?: string;
/**
* @type string
* @description Group-by key holding the longitude, for the coordinates mode. Empty detects it by name.
*/
lon?: string;
/**
* @description How rows are placed: auto (default) detects it from the group-by keys, country, subdivision or coordinates.
*/
mode: DashboardtypesGeoMapLocationModeDTO;
/**
* @type string
* @description Group-by key holding the ISO 3166-2 region code (e.g. geo.region.iso_code), for the subdivision mode. Empty detects it by name.
*/
region?: string;
}
export enum DashboardtypesGeoMapLayerDTO {
regions = 'regions',
bubbles = 'bubbles',
points = 'points',
}
export enum DashboardtypesGeoMapProjectionDTO {
mercator = 'mercator',
equal_earth = 'equal_earth',
natural_earth = 'natural_earth',
}
export enum DashboardtypesGeoMapViewDTO {
world = 'world',
fit = 'fit',
africa = 'africa',
asia = 'asia',
europe = 'europe',
north_america = 'north_america',
south_america = 'south_america',
oceania = 'oceania',
country = 'country',
}
export interface DashboardtypesGeoMapSettingsDTO {
/**
* @type string
* @description Value column key, as in a Table panel, that sets the color. Empty uses the first value column.
*/
colorBy?: string;
/**
* @description What is drawn: regions (default) fills each shape, bubbles draws a circle per region, points a circle per coordinate.
*/
layer: DashboardtypesGeoMapLayerDTO;
/**
* @description The map projection: mercator (default), equal_earth or natural_earth.
*/
projection: DashboardtypesGeoMapProjectionDTO;
/**
* @type string
* @description Value column key, as in a Table panel, that sets the bubble or point size. Empty uses colorBy.
*/
sizeBy?: string;
/**
* @description The area shown: world (default), fit to the data, a continent, or country with viewCountry.
*/
view: DashboardtypesGeoMapViewDTO;
/**
* @type string
* @description Uppercase ISO 3166-1 alpha-2 code of the country the country view shows.
*/
viewCountry?: string;
}
export interface DashboardtypesGeoMapThresholdDTO {
/**
* @type string
* @description The CSS color of the shape, bubble or point while the threshold is active, for example #F1575F; CSS named colors such as red also work.
*/
color: string;
/**
* @description The comparison that activates the threshold: above (default), below, above_or_equal, below_or_equal, equal or not_equal.
*/
operator?: DashboardtypesComparisonOperatorDTO;
/**
* @type string
* @description The unit id of value, such as ms or percent. Empty means the colorBy column's unit.
*/
unit?: string;
/**
* @type number
* @format double
* @description The value compared against, in unit.
*/
value: number;
}
export interface DashboardtypesGeoMapPanelSpecDTO {
/**
* @description Color scale, bubble size and labels.
*/
chartAppearance?: DashboardtypesGeoMapChartAppearanceDTO;
/**
* @description Per-column units and decimal precision.
*/
formatting?: DashboardtypesTableFormattingDTO;
/**
* @description Legend placement.
*/
legend?: DashboardtypesLegendDTO;
/**
* @description The group-by columns that place each row on the map.
*/
location?: DashboardtypesGeoMapLocationDTO;
/**
* @description Layer, view, projection and the value columns drawn.
*/
map?: DashboardtypesGeoMapSettingsDTO;
/**
* @type array,null
* @description Rules that recolor a shape, bubble or point when its value compares to a threshold as specified.
*/
thresholds?: DashboardtypesGeoMapThresholdDTO[] | null;
/**
* @description The time range the values are computed over.
*/
visualization?: DashboardtypesBasicVisualizationDTO;
}
export interface DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO {
/**
* @enum signoz/GeoMapPanel
* @type string
* @description The panel kind.
*/
kind: DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTOKind;
/**
* @description The options for this panel kind. {} accepts every default.
*/
spec: DashboardtypesGeoMapPanelSpecDTO;
}
export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTO
@@ -7201,8 +6954,7 @@ export type DashboardtypesPanelPluginDTO =
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO;
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO;
export enum Querybuildertypesv5RequestTypeDTO {
scalar = 'scalar',
@@ -8489,7 +8241,6 @@ export enum DashboardtypesPanelPluginKindDTO {
'signoz/TextPanel' = 'signoz/TextPanel',
'signoz/HeatmapPanel' = 'signoz/HeatmapPanel',
'signoz/ScatterPlotPanel' = 'signoz/ScatterPlotPanel',
'signoz/GeoMapPanel' = 'signoz/GeoMapPanel',
}
/**
* The RFC 6902 operations, applied in order against the dashboard's postable shape.
@@ -13156,7 +12907,7 @@ export interface RuletypesNotificationSettingsDTO {
export type RuletypesPostableRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
@@ -13273,7 +13024,7 @@ export interface RuletypesPostableRuleDTO {
evaluation: RuletypesEvaluationEnvelopeDTO;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
labels?: RuletypesPostableRuleDTOLabels;
/**
@@ -13306,7 +13057,7 @@ export interface RuletypesPostableRuleViewDTO {
export type RuletypesRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
export type RuletypesRuleDTOLabels = { [key: string]: string };
@@ -13365,7 +13116,7 @@ export interface RuletypesRuleDTO {
id: string;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
labels?: RuletypesRuleDTOLabels;
/**

View File

@@ -54,7 +54,6 @@ export function mapPanelTypeToRequestType(panelType: PANEL_TYPES): RequestType {
case PANEL_TYPES.SCATTER:
case PANEL_TYPES.PIE:
case PANEL_TYPES.VALUE:
case PANEL_TYPES.GEO_MAP:
return 'scalar';
case PANEL_TYPES.TRACE:
return 'trace';
@@ -278,8 +277,7 @@ export function createAggregation(
(panelType === PANEL_TYPES.TABLE ||
panelType === PANEL_TYPES.SCATTER ||
panelType === PANEL_TYPES.PIE ||
panelType === PANEL_TYPES.VALUE ||
panelType === PANEL_TYPES.GEO_MAP);
panelType === PANEL_TYPES.VALUE);
if (queryData.dataSource === DataSource.METRICS) {
return [

View File

@@ -27,10 +27,6 @@ export interface AppProvidersProps {
* A new provider belongs here only if it holds process-wide state that does not
* depend on the user, the license or the route. One that fetches on mount would
* fire unauthenticated from here; put it in `AppShell` or lower.
*
* The whole stack is the root route's element, so it renders inside the data
* router: `searchParams` (nuqs) reads the router's `useNavigate` /
* `useSearchParams`, and the boot spinner renders at a route too.
*/
function AppProviders({
children,

View File

@@ -1,17 +0,0 @@
import { type DataRouter, RouterProvider } from 'react-router';
interface AppRouterProviderProps {
router: DataRouter;
}
/**
* Transitions are off on purpose: under one React keeps the previous screen up
* instead of committing the Suspense fallback, so a route whose chunk is not
* cached yet renders no loader at all. Pending UI under transitions needs
* route `lazy` and `useNavigation()`.
*/
export function AppRouterProvider({
router,
}: AppRouterProviderProps): JSX.Element {
return <RouterProvider router={router} useTransitions={false} />;
}

View File

@@ -5,8 +5,11 @@ import { NotificationProvider } from 'hooks/useNotifications';
import { CmdKProvider } from 'providers/cmdKProvider';
import { ErrorModalProvider } from 'providers/ErrorModalProvider';
import { AppLayer } from './types';
export interface AppShellProps {
children: ReactNode;
router: AppLayer;
/** Mounted beside the routed content: the command palette and its siblings. */
overlays?: ReactNode;
}
@@ -16,26 +19,28 @@ export interface AppShellProps {
* fetches settle, above `PrivateRoute`, so it also covers the redirects and the
* not-found route, and it survives every navigation.
*
* A new provider belongs here if it needs the user and has to outlive the page:
* a global overlay, a shortcut host, anything one route opens and the next one
* keeps. The router itself is higher up, in `AppProviders`.
* A new provider belongs here if it needs the router or the user and has to
* outlive the page: a global overlay, a shortcut host, anything one route opens
* and the next one keeps.
*
* `ConfigProvider` reads `useThemeConfig`, which needs `ThemeProvider` above it,
* so the antd theme is settled here instead of by the caller.
*/
function AppShell({ children, overlays }: AppShellProps): JSX.Element {
function AppShell({ children, router, overlays }: AppShellProps): JSX.Element {
const themeConfig = useThemeConfig();
return (
<ConfigProvider theme={themeConfig}>
<CmdKProvider>
<NotificationProvider>
<ErrorModalProvider>
{overlays}
{children}
</ErrorModalProvider>
</NotificationProvider>
</CmdKProvider>
{router(
<CmdKProvider>
<NotificationProvider>
<ErrorModalProvider>
{overlays}
{children}
</ErrorModalProvider>
</NotificationProvider>
</CmdKProvider>,
)}
</ConfigProvider>
);
}

View File

@@ -1,19 +0,0 @@
import type { ReactNode } from 'react';
import { createBrowserRouter, type DataRouter } from 'react-router';
import { createRouteTable } from 'AppRoutes/routeTable';
import { attachRouter } from 'lib/router/navigation';
import { getBasePath } from 'utils/basePath';
/**
* Creates the app's data router and attaches it to `lib/router/navigation`, so
* code outside a component navigates through it. `root` is the layout route:
* every provider the pages need, `nuqs/adapters/react-router/v7` included,
* renders inside it, because a data router owns everything below it.
*/
export function createAppRouter(root: ReactNode): DataRouter {
const router = createBrowserRouter(createRouteTable(root), {
basename: getBasePath(),
});
attachRouter(router);
return router;
}

View File

@@ -1,6 +1,5 @@
import { useCallback, useMemo, useState } from 'react';
import { Row, Select, Spin } from 'antd';
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import {
@@ -18,7 +17,6 @@ export interface SelectOptionConfig {
placeholder: string;
queryParam: QueryParams;
filterType: string | string[];
fieldContext?: TelemetrytypesFieldContextDTO;
shouldSetQueryParams?: boolean;
onChange?: (value: string | string[]) => void;
values?: string | string[];
@@ -29,16 +27,13 @@ export function FilterSelect({
placeholder,
queryParam,
filterType,
fieldContext,
values,
shouldSetQueryParams,
onChange,
isMultiple,
}: SelectOptionConfig): JSX.Element {
const { handleSearch, isFetching, options } = useCeleryFilterOptions(
filterType,
fieldContext,
);
const { handleSearch, isFetching, options } =
useCeleryFilterOptions(filterType);
const urlQuery = useUrlQuery();
const location = useAppLocation();
@@ -123,7 +118,6 @@ export function FilterSelect({
}
FilterSelect.defaultProps = {
fieldContext: undefined,
shouldSetQueryParams: true,
onChange: (): void => {},
values: [],
@@ -135,14 +129,12 @@ function CeleryOverviewConfigOptions(): JSX.Element {
{
placeholder: 'Service Name',
queryParam: QueryParams.service,
filterType: 'service.name',
fieldContext: TelemetrytypesFieldContextDTO.resource,
filterType: 'serviceName',
},
{
placeholder: 'Span Name',
queryParam: QueryParams.spanName,
filterType: 'name',
fieldContext: TelemetrytypesFieldContextDTO.span,
},
{
placeholder: 'Msg System',
@@ -170,7 +162,6 @@ function CeleryOverviewConfigOptions(): JSX.Element {
placeholder={config.placeholder}
queryParam={config.queryParam}
filterType={config.filterType}
fieldContext={config.fieldContext}
/>
))}
</Row>

View File

@@ -1,37 +0,0 @@
import type { GetFieldsValues200 } from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import { render, waitFor } from 'tests/test-utils';
import CeleryOverviewConfigOptions from '../CeleryOverviewConfigOptions';
const emptyValues: GetFieldsValues200 = {
status: 'success',
data: { complete: true, values: { stringValues: [] } },
};
describe('CeleryOverviewConfigOptions', () => {
it('scopes the service and span name lookups to their field context', async () => {
const contextByKey = new Map<string, string | null>();
server.use(
rest.get('*/api/v1/fields/values', (req, res, ctx) => {
contextByKey.set(
req.url.searchParams.get('name') ?? '',
req.url.searchParams.get('fieldContext'),
);
return res(ctx.status(200), ctx.json(emptyValues));
}),
);
render(<CeleryOverviewConfigOptions />);
await waitFor(() => expect(contextByKey.size).toBe(6));
expect(Object.fromEntries(contextByKey)).toStrictEqual({
'service.name': 'resource',
name: 'span',
'messaging.system': null,
'messaging.destination.name': null,
'messaging.destination': null,
kind_string: null,
});
});
});

View File

@@ -1,21 +1,23 @@
import { useQuery } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import type { DefaultOptionType } from 'antd/es/select';
import type { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import { getFieldValueSuggestions } from 'api/querySuggestions/getFieldValueSuggestions';
import { FIELD_API_CACHE_TIME } from 'constants/queryCacheTime';
import { getAttributesValues } from 'api/queryBuilder/getAttributesValues';
import { DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { toFieldValues } from 'hooks/querySuggestions/useFieldValuesSuggestion';
import { AppState } from 'store/reducers';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { DATA_SOURCE_TO_SIGNAL, DataSource } from 'types/common/queryBuilder';
import { getValuesForDataType } from 'utils/fieldValues';
import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
export interface Filters {
searchText: string;
attributeKey: string | string[];
aggregateOperator?: string;
dataSource?: DataSource;
metricName?: string;
aggregateAttribute?: string;
filterAttributeKeyDataType?: DataTypes;
fieldContext?: TelemetrytypesFieldContextDTO;
tagType?: string;
}
export interface GetAllFiltersResponse {
@@ -27,41 +29,54 @@ export function useGetAllFilters(props: Filters): GetAllFiltersResponse {
const {
searchText,
attributeKey,
aggregateOperator,
dataSource,
metricName,
aggregateAttribute,
filterAttributeKeyDataType,
fieldContext,
tagType,
} = props;
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
const { data, isLoading } = useQuery(
[
REACT_QUERY_KEY.GET_ATTRIBUTE_VALUES,
dataSource,
metricName,
attributeKey,
fieldContext,
searchText,
minTime,
maxTime,
],
async () => {
const keys = Array.isArray(attributeKey) ? attributeKey : [attributeKey];
const responses = await Promise.all(
keys.map((key) =>
getFieldValueSuggestions({
signal: DATA_SOURCE_TO_SIGNAL[dataSource || DataSource.TRACES],
name: key,
fieldContext,
getAttributesValues({
aggregateOperator: aggregateOperator || 'noop',
dataSource: dataSource || DataSource.TRACES,
aggregateAttribute: aggregateAttribute || '',
attributeKey: key,
searchText: searchText ?? '',
metricName,
filterAttributeKeyDataType:
filterAttributeKeyDataType || DataTypes.String,
tagType: tagType || 'tag',
}),
),
);
const uniqueValues = [
...new Set(
responses.flatMap((response) =>
getValuesForDataType(toFieldValues(response), filterAttributeKeyDataType),
),
responses.flatMap(({ payload }) => {
if (!payload) {
return [];
}
const dataType = filterAttributeKeyDataType || DataTypes.String;
const key = DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY[dataType];
return key ? payload[key] || [] : [];
}),
),
];
@@ -70,7 +85,6 @@ export function useGetAllFilters(props: Filters): GetAllFiltersResponse {
value: val,
}));
},
{ staleTime: FIELD_API_CACHE_TIME },
);
return { options: data ?? [], isFetching: isLoading };

View File

@@ -8,9 +8,12 @@ import { CardContainer } from 'container/WidgetCard/styles';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { ChevronDown, ChevronUp } from '@signozhq/icons';
import { AppState } from 'store/reducers';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
import { CaptureDataProps } from '../CeleryTaskDetail/CeleryTaskDetail';
import { useCeleryFilterOptions } from '../useCeleryFilterOptions';
import CeleryTaskBar from './CeleryTaskBar';
import CeleryTaskGraph from './CeleryTaskGraph';
import {
@@ -20,7 +23,6 @@ import {
celeryTasksByWorkerWidgetData,
} from './CeleryTaskGraphUtils';
import CeleryTaskLatencyGraph from './CeleryTaskLatencyGraph';
import { useCeleryWorkerCount } from './useCeleryWorkerCount';
import './CeleryTaskGraph.style.scss';
@@ -69,7 +71,14 @@ export default function CeleryTaskGraphGrid({
'Latency by worker',
];
const { data: workerCount } = useCeleryWorkerCount();
const { options } = useCeleryFilterOptions(
'worker',
'rate',
DataSource.METRICS,
'flower_task_runtime_seconds_sum',
DataTypes.String,
'tag',
);
const isDarkMode = useIsDarkMode();
const [collapsedSections, setCollapsedSections] = useState<{
@@ -142,11 +151,8 @@ export default function CeleryTaskGraphGrid({
</Typography.Text>
</div>
<div className="worker-count-text-container">
<Typography.Text
className="celery-task-graph-worker-count-text"
data-testid="celery-worker-count"
>
{workerCount ?? '-'}
<Typography.Text className="celery-task-graph-worker-count-text">
{options.filter((option) => option.value).length}
</Typography.Text>
</div>
</Card>

View File

@@ -1,12 +1,3 @@
import {
MetrictypesSpaceAggregationDTO,
MetrictypesTimeAggregationDTO,
Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
type Querybuildertypesv5QueryRangeRequestDTO,
Querybuildertypesv5ReduceToDTO,
Querybuildertypesv5RequestTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
import { getWidgetQuery } from 'pages/MessagingQueues/MQDetails/MetricPage/MetricPageUtil';
@@ -1051,34 +1042,3 @@ export const celeryRetryStateCountWidgetData = getWidgetQueryBuilder(
],
}),
);
// One row per worker that reported in the range; the card counts the rows.
export const getCeleryWorkerCountRequest = (
startTime: number,
endTime: number,
): Querybuildertypesv5QueryRangeRequestDTO => ({
schemaVersion: 'v1',
start: Math.floor(startTime / 1e6),
end: Math.floor(endTime / 1e6),
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
compositeQuery: {
queries: [
{
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,
spec: {
name: 'A',
signal: MetricSignal.metrics,
aggregations: [
{
metricName: 'flower_task_runtime_seconds_sum',
timeAggregation: MetrictypesTimeAggregationDTO.count,
spaceAggregation: MetrictypesSpaceAggregationDTO.sum,
reduceTo: Querybuildertypesv5ReduceToDTO.sum,
},
],
groupBy: [{ name: 'worker' }],
},
},
],
},
});

View File

@@ -1,93 +0,0 @@
import {
Querybuildertypesv5ColumnTypeDTO,
type Querybuildertypesv5QueryRangeRequestDTO,
Querybuildertypesv5RequestTypeDTO,
type QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import store from 'store';
import { render, screen, waitFor } from 'tests/test-utils';
import CeleryTaskGraphGrid from '../CeleryTaskGraphGrid';
const workerCountResponse = (workers: string[]): QueryRangeV5200 => ({
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.scalar,
data: {
results: [
{
columns: [
{
name: 'worker',
queryName: 'A',
columnType: Querybuildertypesv5ColumnTypeDTO.group,
},
{
name: '__result_0',
queryName: 'A',
aggregationIndex: 0,
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
},
],
data: workers.map((worker) => [worker, 4]),
},
],
},
},
});
describe('CeleryTaskGraphGrid worker count', () => {
let requests: Querybuildertypesv5QueryRangeRequestDTO[];
beforeEach(() => {
requests = [];
server.use(
rest.post('*/api/v5/query_range', async (req, res, ctx) => {
requests.push(await req.json());
return res(
ctx.status(200),
ctx.json(workerCountResponse(['worker-a', 'worker-b', ''])),
);
}),
);
});
it('counts the workers that reported in the selected range', async () => {
render(<CeleryTaskGraphGrid onClick={jest.fn()} queryEnabled={false} />);
await waitFor(() =>
expect(screen.getByTestId('celery-worker-count')).toHaveTextContent('2'),
);
const { minTime, maxTime } = store.getState().globalTime;
expect(requests).toStrictEqual([
{
schemaVersion: 'v1',
start: Math.floor(minTime / 1e6),
end: Math.floor(maxTime / 1e6),
requestType: 'scalar',
compositeQuery: {
queries: [
{
type: 'builder_query',
spec: {
name: 'A',
signal: 'metrics',
aggregations: [
{
metricName: 'flower_task_runtime_seconds_sum',
timeAggregation: 'count',
spaceAggregation: 'sum',
reduceTo: 'sum',
},
],
groupBy: [{ name: 'worker' }],
},
},
],
},
},
]);
});
});

View File

@@ -1,31 +0,0 @@
import { useMemo } from 'react';
import { useQuery, UseQueryResult } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { queryRangeV5 } from 'api/generated/services/querier';
import type { QueryRangeV5200 } from 'api/generated/services/sigNoz.schemas';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { getScalarResults } from 'pages/DashboardPage/DashboardContainer/queryV5/v5ResponseData';
import { AppState } from 'store/reducers';
import { GlobalReducer } from 'types/reducer/globalTime';
import { getCeleryWorkerCountRequest } from './CeleryTaskGraphUtils';
export function useCeleryWorkerCount(): UseQueryResult<number, Error> {
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
const request = useMemo(
() => getCeleryWorkerCountRequest(minTime, maxTime),
[minTime, maxTime],
);
return useQuery<QueryRangeV5200, Error, number>({
queryKey: [REACT_QUERY_KEY.GET_CELERY_WORKER_COUNT, request],
queryFn: ({ signal }) => queryRangeV5(request, signal),
select: (response) =>
(getScalarResults(response)[0]?.data ?? []).filter(([worker]) => worker)
.length,
});
}

View File

@@ -1,13 +1,18 @@
import { useState } from 'react';
import type { DefaultOptionType } from 'antd/es/select';
import type { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import useDebouncedFn from 'hooks/useDebouncedFunction';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { DataSource } from 'types/common/queryBuilder';
import { useGetAllFilters } from './CeleryTaskConfigOptions/useGetCeleryFilters';
export const useCeleryFilterOptions = (
type: string | string[],
fieldContext?: TelemetrytypesFieldContextDTO,
aggregateOperator?: string,
dataSource?: DataSource,
aggregateAttribute?: string,
filterAttributeKeyDataType?: DataTypes,
tagType?: string,
): {
searchText: string;
handleSearch: (value: string) => void;
@@ -18,7 +23,11 @@ export const useCeleryFilterOptions = (
const { isFetching, options } = useGetAllFilters({
attributeKey: type,
searchText,
fieldContext,
aggregateOperator,
dataSource,
aggregateAttribute,
filterAttributeKeyDataType,
tagType,
});
const handleDebouncedSearch = useDebouncedFn((searchText): void => {
setSearchText(searchText as string);

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCopyToClipboard } from 'react-use';
import { LockKeyhole, RefreshCw, Trash2, X } from '@signozhq/icons';
import { Badge } from '@signozhq/ui/badge';
@@ -39,17 +39,6 @@ import DeleteMemberDialog from './DeleteMemberDialog';
import ResetLinkDialog from './ResetLinkDialog';
import './EditMemberDrawer.styles.scss';
import { AuthZGuardContent } from '@/lib/authz/components/AuthZGuard/AuthZGuardContent';
import {
buildResetPasswordPermission,
buildUserDeletePermission,
buildUserReadPermission,
buildUserUpdatePermission,
PasswordListPermission,
} from '@/lib/authz/hooks/useAuthZ/permissions/user.permissions';
import AuthZButton from '@/lib/authz/components/AuthZButton/AuthZButton';
import { useAuthZ } from '@/lib/authz/hooks/useAuthZ/useAuthZ';
import AuthZTooltip from '@/lib/authz/components/AuthZTooltip/AuthZTooltip';
const ROOT_USER_TOOLTIP = 'This operation is not supported for the root user';
const SELF_DELETE_TOOLTIP =
@@ -70,7 +59,6 @@ function getDeleteTooltip(
function getInviteButtonLabel(
isLoading: boolean,
canListPassword: boolean,
existingToken: { expiresAt?: string } | undefined,
isExpired: boolean,
notFound: boolean,
@@ -78,9 +66,6 @@ function getInviteButtonLabel(
if (isLoading) {
return 'Checking invite...';
}
if (!canListPassword) {
return 'Invite Link Unavailable';
}
if (existingToken && !isExpired) {
return 'Copy Invite Link';
}
@@ -102,6 +87,7 @@ function toSaveApiError(err: unknown): APIError {
export interface EditMemberDrawerProps {
member: MemberRow | null;
open: boolean;
onClose: () => void;
onComplete: () => void;
}
@@ -109,6 +95,7 @@ export interface EditMemberDrawerProps {
// eslint-disable-next-line sonarjs/cognitive-complexity
function EditMemberDrawer({
member,
open,
onClose,
onComplete,
}: EditMemberDrawerProps): JSX.Element {
@@ -132,47 +119,16 @@ function EditMemberDrawer({
const isDeleted = member?.status === MemberStatus.Deleted;
const isSelf = !!member?.id && member.id === currentUser?.id;
const requestPermission = useMemo(() => {
if (member) {
return isInvited
? [buildUserReadPermission(member.id), PasswordListPermission]
: [buildUserReadPermission(member.id)];
}
return [];
}, [member, isInvited]);
const {
permissions: authZPermission,
error: authZError,
isLoading: isLoadingAuthZ,
} = useAuthZ(requestPermission);
const canReadUser = member
? !!authZError ||
(authZPermission?.[buildUserReadPermission(member.id)]?.isGranted ?? false)
: false;
const canListPassword =
!!authZError ||
(authZPermission?.[PasswordListPermission]?.isGranted ?? false);
const resetLinkChecks = useMemo(() => {
if (!member) {
return [];
}
if (isInvited && !canListPassword) {
return [PasswordListPermission];
}
return buildResetPasswordPermission(member.id);
}, [member, isInvited, canListPassword]);
const { showErrorModal } = useErrorModal();
const {
data: fetchedUser,
isLoading: isFetchingUser,
refetch: refetchUser,
} = useGetUser({ id: member?.id ?? '' }, { query: { enabled: canReadUser } });
} = useGetUser(
{ id: member?.id ?? '' },
{ query: { enabled: open && !!member?.id } },
);
const isRootUser = !!fetchedUser?.data?.isRoot;
@@ -188,7 +144,7 @@ function EditMemberDrawer({
currentRoles: currentMemberRoles,
isLoading: isMemberRolesLoading,
applyDiff,
} = useMemberRoleManager(member?.id ?? '', canReadUser);
} = useMemberRoleManager(member?.id ?? '', open && !!member?.id);
// Token status query for invited users
const {
@@ -197,7 +153,7 @@ function EditMemberDrawer({
isError: tokenNotFound,
} = useGetResetPasswordToken(
{ id: member?.id ?? '' },
{ query: { enabled: !!member?.id && isInvited && canListPassword } },
{ query: { enabled: open && !!member?.id && isInvited } },
);
const existingToken = tokenQueryData?.data;
@@ -231,17 +187,13 @@ function EditMemberDrawer({
useEffect(() => {
if (!member?.id) {
roleSessionRef.current = null;
} else if (
canReadUser &&
member.id !== roleSessionRef.current &&
!isMemberRolesLoading
) {
} else if (member.id !== roleSessionRef.current && !isMemberRolesLoading) {
setLocalRoles(
currentMemberRoles.map((r) => r.id).filter(Boolean) as string[],
);
roleSessionRef.current = member.id;
}
}, [member?.id, canReadUser, currentMemberRoles, isMemberRolesLoading]);
}, [member?.id, currentMemberRoles, isMemberRolesLoading]);
const isDirty =
member !== null &&
@@ -511,31 +463,6 @@ function EditMemberDrawer({
[formatTimezoneAdjustedTimestamp],
);
const inviteLinkAndResetPasswordText = useMemo(() => {
if (isGeneratingLink) {
return 'Generating...';
}
if (isInvited) {
return getInviteButtonLabel(
isLoadingTokenStatus || isLoadingAuthZ,
canListPassword,
existingToken,
isTokenExpired,
tokenNotFound,
);
}
return 'Generate Password Reset Link';
}, [
isGeneratingLink,
isInvited,
isLoadingTokenStatus,
isLoadingAuthZ,
canListPassword,
existingToken,
isTokenExpired,
tokenNotFound,
]);
const drawerBody = isFetchingUser ? (
<Skeleton active paragraph={{ rows: 6 }} />
) : (
@@ -544,11 +471,7 @@ function EditMemberDrawer({
<label className="edit-member-drawer__label" htmlFor="member-name">
Name
</label>
<AuthZTooltip
checks={member && !isSelf ? [buildUserUpdatePermission(member.id)] : []}
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : undefined}
>
<Tooltip title={isRootUser ? ROOT_USER_TOOLTIP : undefined}>
<Input
id="member-name"
value={localDisplayName}
@@ -561,7 +484,7 @@ function EditMemberDrawer({
placeholder="Enter name"
disabled={isRootUser || isDeleted}
/>
</AuthZTooltip>
</Tooltip>
</div>
<div className="edit-member-drawer__field">
@@ -580,12 +503,17 @@ function EditMemberDrawer({
<label className="edit-member-drawer__label" htmlFor="member-role">
Roles
</label>
{isRootUser || isDeleted ? (
<Tooltip title={isRootUser ? ROOT_USER_TOOLTIP : undefined}>
<div
className="edit-member-drawer__input-wrapper edit-member-drawer__input-wrapper--disabled"
data-testid="member-roles-locked"
>
{isSelf || isRootUser || isDeleted ? (
<Tooltip
title={
isRootUser
? ROOT_USER_TOOLTIP
: isDeleted
? undefined
: 'You cannot modify your own role'
}
>
<div className="edit-member-drawer__input-wrapper edit-member-drawer__input-wrapper--disabled">
<div className="edit-member-drawer__disabled-roles">
{localRoles.length > 0 ? (
localRoles.map((roleId) => {
@@ -692,33 +620,42 @@ function EditMemberDrawer({
{!isDeleted && (
<>
<div className="edit-member-drawer__footer-left">
<AuthZButton
<Button
disabledTooltip={getDeleteTooltip(isRootUser, isSelf)}
size="md"
onClick={(): void => setShowDeleteConfirm(true)}
testId="member-delete-btn"
disabled={isRootUser || isSelf}
variant="link"
color="danger"
checks={member ? [buildUserDeletePermission(member.id)] : []}
prefix={<Trash2 size={12} />}
>
{isInvited ? 'Revoke Invite' : 'Delete Member'}
</AuthZButton>
</Button>
<div className="edit-member-drawer__footer-divider" />
<AuthZButton
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : undefined}
<Button
disabledTooltip={ROOT_USER_TOOLTIP}
size="md"
onClick={handleGenerateResetLink}
testId="member-reset-link-btn"
disabled={isRootUser}
loading={isGeneratingLink || isLoadingTokenStatus}
variant="link"
color="warning"
checks={resetLinkChecks}
prefix={<RefreshCw size={12} />}
>
{inviteLinkAndResetPasswordText}
</AuthZButton>
{isGeneratingLink
? 'Generating...'
: isInvited
? getInviteButtonLabel(
isLoadingTokenStatus,
existingToken,
isTokenExpired,
tokenNotFound,
)
: 'Generate Password Reset Link'}
</Button>
</div>
<div className="edit-member-drawer__footer-right">
@@ -732,25 +669,18 @@ function EditMemberDrawer({
Cancel
</Button>
<AuthZButton
disabledTooltip={
isRootUser
? ROOT_USER_TOOLTIP
: !isDirty
? 'No changes to save'
: undefined
}
<Button
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : 'No changes to save'}
size="md"
variant="solid"
color="primary"
disabled={!isDirty || isRootUser}
onClick={handleSave}
checks={[]}
testId="member-save-btn"
loading={isSaving}
>
{isSaving ? 'Saving...' : 'Save Member Details'}
</AuthZButton>
</Button>
</div>
</>
)}
@@ -760,7 +690,7 @@ function EditMemberDrawer({
return (
<>
<DrawerWrapper
open={member !== null}
open={open}
onOpenChange={(isOpen): void => {
if (!isOpen) {
handleClose();
@@ -773,12 +703,7 @@ function EditMemberDrawer({
footer={footer}
width="wide"
>
<AuthZGuardContent
checks={member ? [buildUserReadPermission(member?.id)] : []}
fallbackOnLoading={<Skeleton active paragraph={{ rows: 6 }} />}
>
{drawerContent}
</AuthZGuardContent>
{drawerContent}
</DrawerWrapper>
<ResetLinkDialog

View File

@@ -17,16 +17,6 @@ import {
managedRoles,
} from 'mocks-server/__mockdata__/roles';
import { rest, server } from 'mocks-server/server';
import {
buildUserUpdatePermission,
PasswordListPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import {
AUTHZ_CHECK_URL,
setupAuthzAdmin,
setupAuthzDeny,
setupAuthzDenyAll,
} from 'lib/authz/utils/authz-test-utils';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import EditMemberDrawer, { EditMemberDrawerProps } from '../EditMemberDrawer';
@@ -178,6 +168,7 @@ function renderDrawer(
return render(
<EditMemberDrawer
member={activeMember}
open
onClose={jest.fn()}
onComplete={jest.fn()}
{...props}
@@ -185,16 +176,6 @@ function renderDrawer(
);
}
async function clickDeleteButton(
user: ReturnType<typeof userEvent.setup>,
): Promise<void> {
const deleteBtn = await screen.findByTestId('member-delete-btn');
await waitFor(() =>
expect(deleteBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
await user.click(deleteBtn);
}
describe('EditMemberDrawer', () => {
beforeEach(() => {
jest.clearAllMocks();
@@ -205,7 +186,6 @@ describe('EditMemberDrawer', () => {
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
),
setupAuthzAdmin(),
);
(useGetUser as jest.Mock).mockReturnValue({
data: mockFetchedUser,
@@ -263,33 +243,15 @@ describe('EditMemberDrawer', () => {
server.resetHandlers();
});
it('renders active member details and disables Save when form is not dirty', async () => {
it('renders active member details and disables Save when form is not dirty', () => {
renderDrawer();
await expect(
screen.findByDisplayValue('Alice Smith'),
).resolves.toBeInTheDocument();
expect(screen.getByDisplayValue('Alice Smith')).toBeInTheDocument();
expect(screen.getByText('alice@signoz.io')).toBeInTheDocument();
expect(screen.getByText('ACTIVE')).toBeInTheDocument();
await waitFor(() =>
expect(screen.getByTestId('member-save-btn')).toHaveAttribute(
'aria-disabled',
'true',
),
);
});
it('still fetches the member when the permission check fails', async () => {
server.use(rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => res(ctx.status(500))));
renderDrawer();
await waitFor(() =>
expect(useGetUser).toHaveBeenLastCalledWith(
{ id: 'user-1' },
{ query: { enabled: true } },
),
);
expect(
screen.getByRole('button', { name: /save member details/i }),
).toHaveAttribute('aria-disabled', 'true');
});
it('enables Save after editing name and calls updateUser on confirm', async () => {
@@ -304,8 +266,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() => expect(nameInput).toBeEnabled());
const nameInput = screen.getByDisplayValue('Alice Smith');
await user.clear(nameInput);
await user.type(nameInput, 'Alice Updated');
@@ -331,8 +292,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onClose });
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() => expect(nameInput).toBeEnabled());
const nameInput = screen.getByDisplayValue('Alice Smith');
await user.clear(nameInput);
await user.type(nameInput, 'Alice Updated');
@@ -363,7 +323,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
// signoz-admin is already selected; add signoz-editor on top
await user.click(await screen.findByLabelText('Roles'));
await user.click(screen.getByLabelText('Roles'));
await user.click(await screen.findByTitle('signoz-editor'));
const saveBtn = screen.getByRole('button', { name: /save member details/i });
@@ -421,7 +381,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ onComplete });
await clickDeleteButton(user);
await user.click(screen.getByRole('button', { name: /delete member/i }));
await expect(
screen.findByText(/are you sure you want to delete/i),
@@ -438,11 +398,9 @@ describe('EditMemberDrawer', () => {
});
});
it('shows revoke invite and copy invite link for invited members; hides Last Modified', async () => {
it('shows revoke invite and copy invite link for invited members; hides Last Modified', () => {
renderDrawer({ member: invitedMember });
await screen.findByText('Invited On');
expect(
screen.getByRole('button', { name: /revoke invite/i }),
).toBeInTheDocument();
@@ -456,7 +414,7 @@ describe('EditMemberDrawer', () => {
expect(screen.queryByText('Last Modified')).not.toBeInTheDocument();
});
it('shows "Regenerate Invite Link" when token is expired', async () => {
it('shows "Regenerate Invite Link" when token is expired', () => {
(useGetResetPasswordToken as jest.Mock).mockReturnValue({
data: {
data: {
@@ -471,12 +429,12 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember });
await expect(
screen.findByRole('button', { name: /regenerate invite link/i }),
).resolves.toBeInTheDocument();
expect(
screen.getByRole('button', { name: /regenerate invite link/i }),
).toBeInTheDocument();
});
it('shows "Generate Invite Link" when no token exists', async () => {
it('shows "Generate Invite Link" when no token exists', () => {
(useGetResetPasswordToken as jest.Mock).mockReturnValue({
data: undefined,
isLoading: false,
@@ -485,88 +443,9 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember });
await expect(
screen.findByRole('button', { name: /generate invite link/i }),
).resolves.toBeInTheDocument();
});
it('looks up the invite link when factor-password list is granted', async () => {
renderDrawer({ member: invitedMember });
await waitFor(() =>
expect(useGetResetPasswordToken).toHaveBeenLastCalledWith(
{ id: invitedMember.id },
{ query: { enabled: true } },
),
);
await waitFor(() =>
expect(screen.getByTestId('member-reset-link-btn')).not.toHaveAttribute(
'aria-disabled',
'true',
),
);
});
it('skips the invite link lookup and disables the button without factor-password list', async () => {
server.use(setupAuthzDeny(PasswordListPermission));
renderDrawer({ member: invitedMember });
await waitFor(() =>
expect(screen.getByTestId('member-reset-link-btn')).toHaveAttribute(
'data-denied-permissions',
PasswordListPermission,
),
);
expect(screen.getByTestId('member-reset-link-btn')).toHaveAttribute(
'aria-disabled',
'true',
);
expect(screen.getByTestId('member-reset-link-btn')).toHaveTextContent(
'Invite Link Unavailable',
);
expect(useGetResetPasswordToken).toHaveBeenLastCalledWith(
{ id: invitedMember.id },
{ query: { enabled: false } },
);
});
it('reports only factor-password list for an invited member who lacks every permission', async () => {
server.use(setupAuthzDenyAll());
renderDrawer({ member: invitedMember });
await waitFor(() =>
expect(screen.getByTestId('member-reset-link-btn')).toHaveAttribute(
'data-denied-permissions',
PasswordListPermission,
),
);
});
it('still looks up the invite link when the permission check fails', async () => {
server.use(rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => res(ctx.status(500))));
renderDrawer({ member: invitedMember });
await waitFor(() =>
expect(useGetResetPasswordToken).toHaveBeenLastCalledWith(
{ id: invitedMember.id },
{ query: { enabled: true } },
),
);
});
it('keeps the reset link enabled for an active member without factor-password list', async () => {
server.use(setupAuthzDeny(PasswordListPermission));
renderDrawer();
await screen.findByDisplayValue('Alice Smith');
expect(screen.getByTestId('member-reset-link-btn')).not.toHaveAttribute(
'aria-disabled',
'true',
);
expect(
screen.getByRole('button', { name: /generate invite link/i }),
).toBeInTheDocument();
});
it('calls deleteUser after confirming revoke invite for invited members', async () => {
@@ -582,7 +461,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember, onComplete });
await clickDeleteButton(user);
await user.click(screen.getByRole('button', { name: /revoke invite/i }));
await expect(
screen.findByText(/Are you sure you want to revoke the invite/i),
@@ -629,8 +508,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: { ...invitedMember, name: 'Bob' }, onComplete });
const nameInput = await screen.findByDisplayValue('Bob');
await waitFor(() => expect(nameInput).toBeEnabled());
const nameInput = screen.getByDisplayValue('Bob');
await user.clear(nameInput);
await user.type(nameInput, 'Bob Updated');
@@ -668,8 +546,7 @@ describe('EditMemberDrawer', () => {
renderDrawer();
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() => expect(nameInput).toBeEnabled());
const nameInput = screen.getByDisplayValue('Alice Smith');
await user.clear(nameInput);
await user.type(nameInput, 'Alice Updated');
@@ -698,7 +575,7 @@ describe('EditMemberDrawer', () => {
renderDrawer();
await clickDeleteButton(user);
await user.click(screen.getByRole('button', { name: /delete member/i }));
const confirmBtns = screen.getAllByRole('button', {
name: /delete member/i,
});
@@ -729,7 +606,7 @@ describe('EditMemberDrawer', () => {
renderDrawer({ member: invitedMember });
await clickDeleteButton(user);
await user.click(screen.getByRole('button', { name: /revoke invite/i }));
const confirmBtns = screen.getAllByRole('button', {
name: /revoke invite/i,
});
@@ -768,86 +645,16 @@ describe('EditMemberDrawer', () => {
).not.toBeInTheDocument();
});
it('keeps name input enabled when viewing own profile', async () => {
it('keeps name input enabled when viewing own profile', () => {
renderDrawer({ member: selfMember });
await expect(
screen.findByDisplayValue('Alice Smith'),
).resolves.not.toBeDisabled();
expect(screen.getByDisplayValue('Alice Smith')).not.toBeDisabled();
});
it('keeps Reset Link button enabled when viewing own profile', async () => {
it('keeps Reset Link button enabled when viewing own profile', () => {
renderDrawer({ member: selfMember });
const resetBtn = await screen.findByTestId('member-reset-link-btn');
await waitFor(() =>
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
});
});
describe('self user roles', () => {
it('keeps roles editable', async () => {
renderDrawer({ member: selfMember });
await expect(screen.findByText('Select roles')).resolves.toBeInTheDocument();
expect(screen.queryByTestId('member-roles-locked')).not.toBeInTheDocument();
});
});
describe('deleted member', () => {
const deletedMember = { ...activeMember, status: MemberStatus.Deleted };
it('is read-only with no footer actions', async () => {
renderDrawer({ member: deletedMember });
const nameInput = await screen.findByDisplayValue('Alice Smith');
await waitFor(() =>
expect(nameInput).not.toHaveStyle({ cursor: 'not-allowed' }),
);
expect(nameInput).toBeDisabled();
expect(screen.getByTestId('member-roles-locked')).toBeInTheDocument();
expect(
screen.queryByPlaceholderText('Select roles'),
).not.toBeInTheDocument();
expect(screen.queryByTestId('member-save-btn')).not.toBeInTheDocument();
expect(screen.queryByTestId('member-delete-btn')).not.toBeInTheDocument();
expect(
screen.queryByTestId('member-reset-link-btn'),
).not.toBeInTheDocument();
});
});
describe('self user name update', () => {
it('saves through the me API without update:user', async () => {
const updateMyUser = jest.fn().mockResolvedValue({});
(useUpdateMyUserV2 as jest.Mock).mockReturnValue({
mutateAsync: updateMyUser,
isLoading: false,
});
server.use(setupAuthzDeny(buildUserUpdatePermission(selfMember.id)));
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer({ member: selfMember });
const input = await screen.findByDisplayValue('Alice Smith');
await user.clear(input);
await user.type(input, 'Alice Cooper');
await user.click(screen.getByTestId('member-save-btn'));
await waitFor(() =>
expect(updateMyUser).toHaveBeenCalledWith({
data: { displayName: 'Alice Cooper' },
}),
);
});
it('does not gate Save on permissions', async () => {
server.use(setupAuthzDenyAll());
renderDrawer({ member: selfMember });
await screen.findByText(/is not authorized/);
expect(screen.getByTestId('member-save-btn')).not.toHaveAttribute(
'data-denied-permissions',
);
screen.getByRole('button', { name: /generate password reset link/i }),
).not.toHaveAttribute('aria-disabled', 'true');
});
});
@@ -860,11 +667,9 @@ describe('EditMemberDrawer', () => {
});
});
it('disables name input for root user', async () => {
it('disables name input for root user', () => {
renderDrawer();
await expect(
screen.findByDisplayValue('Alice Smith'),
).resolves.toBeDisabled();
expect(screen.getByDisplayValue('Alice Smith')).toBeDisabled();
});
it('disables Delete button for root user', () => {
@@ -921,11 +726,9 @@ describe('EditMemberDrawer', () => {
renderDrawer();
const resetBtn = await screen.findByTestId('member-reset-link-btn');
await waitFor(() =>
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
await user.click(
screen.getByRole('button', { name: /generate password reset link/i }),
);
await user.click(resetBtn);
const dialog = await screen.findByRole('dialog', {
name: /password reset link/i,
@@ -944,11 +747,9 @@ describe('EditMemberDrawer', () => {
renderDrawer();
const resetBtn = await screen.findByTestId('member-reset-link-btn');
await waitFor(() =>
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
await user.click(
screen.getByRole('button', { name: /generate password reset link/i }),
);
await user.click(resetBtn);
const dialog = await screen.findByRole('dialog', {
name: /password reset link/i,

View File

@@ -105,3 +105,8 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.error {
font-size: var(--font-size-xs);
color: var(--danger-foreground);
}

View File

@@ -20,7 +20,7 @@ interface Props {
query: string;
grammar: DslGrammar;
// Ids: `${testIdPrefix}-search-zone`, `-list-search*`, `-filter-zone`,
// `-filter-clear`, `-filter-created-by`, `-filter-updated`.
// `-filter-clear`, `-filter-created-by`, `-filter-updated`, `-query-error`.
testIdPrefix: string;
creatorOptions: CreatorOption[];
source: SuggestionSource;
@@ -35,6 +35,8 @@ interface Props {
hasExtraFilters?: boolean;
// Called by Clear after it empties the query.
onClearAll?: () => void;
// Shown under the search row.
error?: string;
// Wraps the search box and the filter controls (e.g. in an authz tooltip).
wrapControl?: (node: ReactElement) => ReactElement;
onSubmitted?: (hasQuery: boolean) => void;
@@ -63,6 +65,7 @@ function FilterZone({
extraFilters,
hasExtraFilters = false,
onClearAll,
error,
wrapControl = identity,
onSubmitted,
onFilterApplied,
@@ -112,6 +115,14 @@ function FilterZone({
)}
{rightSlot}
</div>
{error && (
<Typography.Text
className={styles.error}
testId={`${testIdPrefix}-query-error`}
>
{error}
</Typography.Text>
)}
<div className={styles.filtersRow}>
<Typography.Text className={styles.filtersLabel}>Filters</Typography.Text>
{wrapControl(

View File

@@ -1,49 +0,0 @@
.wrapper {
display: flex;
flex-direction: column;
height: 320px;
margin-top: 16px;
padding: 105px 141px;
gap: 4px;
justify-content: center;
align-items: flex-start;
border-radius: 6px;
border: 1px dashed var(--l1-border);
}
.img {
max-width: 100%;
}
.text {
font-family: Inter;
font-size: var(--font-size-sm);
font-style: normal;
line-height: 18px;
letter-spacing: -0.07px;
}
.title {
composes: text;
color: var(--l1-foreground);
font-weight: var(--font-weight-medium);
}
.detail {
composes: text;
color: var(--l2-foreground);
font-weight: var(--font-weight-normal);
}
.actionButtons {
display: flex;
gap: 24px;
align-items: center;
margin-top: 20px;
}
.learnMoreArrow {
margin-left: -20px;
color: var(--bg-robin-400);
cursor: pointer;
}

View File

@@ -1,64 +0,0 @@
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import { ArrowUpRight } from '@signozhq/icons';
import { handleContactSupport } from 'container/Integrations/utils';
import awwSnapUrl from '@/assets/Icons/awwSnap.svg';
import { formatQueryErrorMessage } from './utils';
import styles from './InvalidQueryState.module.scss';
interface Props {
/** The backend's parse error for the list's DSL filter. */
errorMessage?: string;
isCloudUser: boolean;
testIdPrefix: string;
/** Runs before support opens, for analytics. */
onContactSupport?: () => void;
}
const INVALID_QUERY_FALLBACK = 'Please review the syntax and try again.';
function InvalidQueryState({
errorMessage,
isCloudUser,
testIdPrefix,
onContactSupport,
}: Props): JSX.Element {
const handleContactSupportClick = (): void => {
onContactSupport?.();
handleContactSupport(isCloudUser);
};
return (
<div className={styles.wrapper} data-testid={`${testIdPrefix}-invalid-query`}>
<img src={awwSnapUrl} alt="something went wrong" className={styles.img} />
<Typography.Text
className={styles.title}
data-testid={`${testIdPrefix}-invalid-query-title`}
>
Invalid query
</Typography.Text>
<Typography.Text
className={styles.detail}
data-testid={`${testIdPrefix}-invalid-query-detail`}
>
{formatQueryErrorMessage(errorMessage) || INVALID_QUERY_FALLBACK}
</Typography.Text>
<section className={styles.actionButtons}>
<Button
size="md"
variant="link"
color="primary"
onClick={handleContactSupportClick}
testId={`${testIdPrefix}-contact-support`}
>
Contact Support
</Button>
<ArrowUpRight size={16} className={styles.learnMoreArrow} />
</section>
</div>
);
}
export default InvalidQueryState;

View File

@@ -1,53 +0,0 @@
import { handleContactSupport } from 'container/Integrations/utils';
import { render, screen, userEvent } from 'tests/test-utils';
import InvalidQueryState from '../InvalidQueryState';
jest.mock('container/Integrations/utils', () => ({
handleContactSupport: jest.fn(),
}));
describe('InvalidQueryState', () => {
it('shows the backend message without its prefix and with quoted hints', () => {
render(
<InvalidQueryState
errorMessage="invalid filter query: unknown field `nme`"
isCloudUser={false}
testIdPrefix="list"
/>,
);
expect(screen.getByTestId('list-invalid-query-title')).toHaveTextContent(
'Invalid query',
);
expect(screen.getByTestId('list-invalid-query-detail')).toHaveTextContent(
/^unknown field "nme"$/,
);
});
it('falls back to a syntax hint without a message', () => {
render(<InvalidQueryState isCloudUser={false} testIdPrefix="list" />);
expect(screen.getByTestId('list-invalid-query-detail')).toHaveTextContent(
'Please review the syntax and try again.',
);
});
it('runs the callback, then opens support', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onContactSupport = jest.fn();
render(
<InvalidQueryState
errorMessage="bad"
isCloudUser
testIdPrefix="list"
onContactSupport={onContactSupport}
/>,
);
await user.click(screen.getByTestId('list-contact-support'));
expect(onContactSupport).toHaveBeenCalledTimes(1);
expect(jest.mocked(handleContactSupport)).toHaveBeenCalledWith(true);
});
});

View File

@@ -1,13 +0,0 @@
// Normalize BE query-parse error messages for display:
// - Drop the "invalid filter query:" prefix (the UI already says "Invalid query").
// - Backticks → double quotes for the format hint that follows the em-dash.
// - Trim surrounding whitespace.
export const formatQueryErrorMessage = (raw: string | undefined): string => {
if (!raw) {
return '';
}
return raw
.replace(/^invalid filter query:\s*/i, '')
.replace(/`([^`]+)`/g, '"$1"')
.trim();
};

View File

@@ -1,68 +0,0 @@
import { useListUsers } from 'api/generated/services/users';
import { UserListPermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import {
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { server } from 'mocks-server/server';
import { AllTheProviders, renderHook, waitFor } from 'tests/test-utils';
import { useCreatorOptions } from '../useCreatorOptions';
jest.mock('api/generated/services/users', () => ({
...jest.requireActual('api/generated/services/users'),
useListUsers: jest.fn(),
}));
const ARGS = {
currentUserEmail: 'me@signoz.io',
fallbackEmails: ['author@signoz.io'],
};
function mockUsers(users: { email: string; displayName: string }[]): void {
jest.mocked(useListUsers).mockReturnValue({
data: { data: users },
} as ReturnType<typeof useListUsers>);
}
describe('useCreatorOptions', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('lists the org users with their display names when list:user is granted', async () => {
server.use(setupAuthzAdmin());
mockUsers([{ email: 'alice@signoz.io', displayName: 'Alice' }]);
const { result } = renderHook(() => useCreatorOptions(ARGS), {
wrapper: AllTheProviders,
});
await waitFor(() =>
expect(useListUsers).toHaveBeenLastCalledWith({ query: { enabled: true } }),
);
expect(result.current).toStrictEqual([
{ email: 'alice@signoz.io', label: 'Alice (alice@signoz.io)' },
{ email: 'me@signoz.io', label: 'me@signoz.io (me)' },
]);
});
it('does not fetch users without list:user and falls back to me and the page authors', async () => {
server.use(setupAuthzDeny(UserListPermission));
jest.mocked(useListUsers).mockReturnValue({
data: undefined,
} as ReturnType<typeof useListUsers>);
const { result } = renderHook(() => useCreatorOptions(ARGS), {
wrapper: AllTheProviders,
});
await waitFor(() => expect(useListUsers).toHaveBeenCalled());
expect(useListUsers).not.toHaveBeenCalledWith({ query: { enabled: true } });
expect(useListUsers).toHaveBeenLastCalledWith({ query: { enabled: false } });
expect(result.current).toStrictEqual([
{ email: 'author@signoz.io', label: 'author@signoz.io' },
{ email: 'me@signoz.io', label: 'me@signoz.io (me)' },
]);
});
});

View File

@@ -1,7 +1,5 @@
import { useMemo } from 'react';
import { useListUsers } from 'api/generated/services/users';
import { UserListPermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import type { CreatorOption } from './types';
@@ -17,12 +15,7 @@ export function useCreatorOptions({
currentUserEmail,
fallbackEmails,
}: Args): CreatorOption[] {
const { permissions } = useAuthZ([UserListPermission]);
const canListUsers = permissions?.[UserListPermission]?.isGranted ?? false;
// Without `list:user` the list isn't fetched: options shrink to "me" and the
// page's authors, with bare emails instead of display names.
const { data } = useListUsers({ query: { enabled: canListUsers } });
const { data } = useListUsers();
return useMemo<CreatorOption[]>(() => {
const users = data?.data ?? [];

View File

@@ -121,7 +121,6 @@ exports[`Not Found page test should render Not Found page without errors 1`] = `
</div>
<a
class="c3"
data-discover="true"
href="/home"
tabindex="0"
>

View File

@@ -1,4 +1,4 @@
import { ReactNode, useCallback, useEffect, useRef } from 'react';
import { ReactNode, useEffect, useRef } from 'react';
import { parseAsString, useQueryState } from 'nuqs';
import { useStore } from 'zustand';
@@ -61,37 +61,34 @@ export function QuerySearchV2Provider({
);
}, [urlExpression, initialExpression, store]);
// The URL owns the expression. Reads the browser's URL: after a write, nuqs
// can briefly report the value it replaced.
const followBrowserUrl = useCallback((): void => {
isInitialized.current = true;
const urlValue = new URLSearchParams(window.location.search).get(
queryParamKey,
);
const expression = urlValue
? getUserExpressionFromCombined(initialExpression, urlValue)
: '';
// Another param changed; keep any text typed but not run.
if (expression === store.getState().committedExpression) {
return;
}
// Already in the URL, so the write below must not run for it.
lastCommittedRef.current = expression;
if (expression) {
store.getState().initializeFromUrl(expression);
} else {
store.getState().resetExpression();
}
// Back and Forward. Reads the browser's URL: after a write, nuqs can briefly
// report the value it replaced.
useEffect(() => {
const onPopState = (): void => {
isInitialized.current = true;
const urlValue = new URLSearchParams(window.location.search).get(
queryParamKey,
);
const expression = urlValue
? getUserExpressionFromCombined(initialExpression, urlValue)
: '';
// Another param changed; keep any text typed but not run.
if (expression === store.getState().committedExpression) {
return;
}
// Already in the URL, so the write below must not run for it.
lastCommittedRef.current = expression;
if (expression) {
store.getState().initializeFromUrl(expression);
} else {
store.getState().resetExpression();
}
};
window.addEventListener('popstate', onPopState);
return (): void => window.removeEventListener('popstate', onPopState);
}, [queryParamKey, initialExpression, store]);
// Back and Forward.
useEffect(() => {
window.addEventListener('popstate', followBrowserUrl);
return (): void => window.removeEventListener('popstate', followBrowserUrl);
}, [followBrowserUrl]);
// Write only when the committed filter changes, never in reply to a URL change.
// Declared before the effect below, which can reset the filter this render holds.
useEffect(() => {
if (committedExpression === lastCommittedRef.current) {
return;
@@ -105,24 +102,6 @@ export function QuerySearchV2Provider({
void setUrlExpression(next);
}, [committedExpression, urlExpression, setUrlExpression]);
// Any other navigation. A provider can outlive the navigation away from its
// page (a route-driven tab keeps the leaving pane mounted until its animation
// ends), so a param that disappeared is followed, not restored.
const previousUrlExpression = useRef(urlExpression);
useEffect(() => {
if (urlExpression === previousUrlExpression.current) {
return;
}
previousUrlExpression.current = urlExpression;
const browserValue = new URLSearchParams(window.location.search).get(
queryParamKey,
);
if (urlExpression !== browserValue) {
return;
}
followBrowserUrl();
}, [urlExpression, queryParamKey, followBrowserUrl]);
useEffect(() => {
return (): void => {
if (!persistOnUnmount) {

View File

@@ -1,4 +1,4 @@
import { ReactNode, useEffect, useRef } from 'react';
import { ReactNode } from 'react';
import { act, renderHook } from 'tests/test-utils';
import {
@@ -215,83 +215,6 @@ describe('QuerySearchExpressionProvider', () => {
expect(result.current.userExpression).toBe('status = 404');
});
it('should follow the URL when the param is dropped', () => {
mockUrlValue = 'status = 500';
const { result, rerender } = renderHook(() => useTestHooks(), {
wrapper: createWrapper(),
});
expect(result.current.expression).toBe('status = 500');
mockSetQueryState.mockClear();
mockUrlValue = null;
rerender();
expect(result.current.expression).toBe('');
expect(mockSetQueryState).not.toHaveBeenCalledWith('status = 500');
});
it('should keep an expression a child runs on mount', () => {
function RunOnMount(): null {
const onRun = useQuerySearchOnRun();
useEffect(() => {
onRun('service = "api"');
}, [onRun]);
return null;
}
const Wrapper = createWrapper();
const { result } = renderHook(() => useTestHooks(), {
wrapper: ({ children }: { children: ReactNode }) => (
<Wrapper>
<RunOnMount />
{children}
</Wrapper>
),
});
expect(result.current.userExpression).toBe('service = "api"');
expect(mockSetQueryState).toHaveBeenCalledWith('service = "api"');
});
it('should keep an expression a child runs when the initial expression changes', () => {
mockUrlValue = "k8s.pod.name = 'pod-1'";
let initialExpression = "k8s.cluster.name = 'a'";
let runExpression = "k8s.pod.name = 'pod-1'";
// Runs once per initial expression, as the K8s carry-over does.
function RunOnce(): null {
const onRun = useQuerySearchOnRun();
const hasRun = useRef(false);
useEffect(() => {
if (!hasRun.current) {
hasRun.current = true;
onRun(runExpression);
}
}, [onRun]);
return null;
}
const { result, rerender } = renderHook(() => useTestHooks(), {
wrapper: ({ children }: { children: ReactNode }) => (
<QuerySearchV2Provider
queryParamKey="testExpression"
initialExpression={initialExpression}
>
<RunOnce key={initialExpression} />
{children}
</QuerySearchV2Provider>
),
});
expect(result.current.userExpression).toBe("k8s.pod.name = 'pod-1'");
initialExpression = "k8s.node.name = 'b'";
runExpression = '';
rerender();
expect(result.current.userExpression).toBe('');
expect(mockSetQueryState).toHaveBeenLastCalledWith(null);
});
it('should throw error when used outside provider', () => {
expect(() => {
renderHook(() => useExpression());

View File

@@ -6,7 +6,6 @@ const SCALAR_PANEL_TYPES: ReadonlySet<string> = new Set<string>([
PANEL_TYPES.SCATTER,
PANEL_TYPES.PIE,
PANEL_TYPES.VALUE,
PANEL_TYPES.GEO_MAP,
]);
export function isScalarPanelType(panelType?: string | null): boolean {

View File

@@ -1,5 +1,5 @@
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
import { fieldContextToAttributeType } from 'utils/fieldContext';
import { fieldDataTypeToDataType } from 'utils/fieldDataType';
import { FiltersType, IQuickFiltersConfig } from './types';
@@ -14,6 +14,19 @@ const FILTER_TYPE_MAP: Record<string, FiltersType> = {
duration_nano: FiltersType.DURATION,
};
// The map below exists only for the old v3 attribute-values fetch
// (useCheckboxFilterValues), the sole reader of attributeKey.dataType/type.
// Once the values fetch moves to fields/values, remove this and reduce
// attributeKey to { id, key }.
const FIELD_CONTEXT_TO_ATTRIBUTE_TYPE: Record<string, string> = {
[TelemetrytypesFieldContextDTO.attribute]: 'tag',
[TelemetrytypesFieldContextDTO.resource]: 'resource',
};
const mapFieldContext = (fieldContext?: string): string =>
(fieldContext && FIELD_CONTEXT_TO_ATTRIBUTE_TYPE[fieldContext]) || '';
const getFilterName = (str: string): string => {
if (FILTER_TITLE_MAP[str]) {
return FILTER_TITLE_MAP[str];
@@ -48,15 +61,11 @@ export const getFilterConfig = (
({
type: getFilterType(att),
title: getFilterName(att.name),
// The type mapping below exists only for the old v3 attribute-values fetch
// (useCheckboxFilterValues), the sole reader of attributeKey.dataType/type.
// Once the values fetch moves to fields/values, remove this and reduce
// attributeKey to { id, key }.
attributeKey: {
id: att.name,
key: att.name,
dataType: fieldDataTypeToDataType(att.fieldDataType),
type: fieldContextToAttributeType(att.fieldContext),
type: mapFieldContext(att.fieldContext),
},
defaultOpen: index < 2,
}) as IQuickFiltersConfig,

View File

@@ -15,5 +15,3 @@ export const DASHBOARD_TIME_IN_DURATION = 'refreshInterval';
export const DEFAULT_ENTITY_VERSION = 'v3';
export const ENTITY_VERSION_V4 = 'v4';
export const ENTITY_VERSION_V5 = 'v5';
export const SIGNOZ_ADMIN_EMAIL = 'admin@signoz.cloud';

View File

@@ -34,7 +34,6 @@ export const getComponentForPanelType = (
[PANEL_TYPES.HISTOGRAM]: Uplot,
// V2-only kind; it renders through the V2 panel registry.
[PANEL_TYPES.HEATMAP]: null,
[PANEL_TYPES.GEO_MAP]: null,
// Dashboards v2 renders this kind; nothing reaches the V1 chart map for it.
[PANEL_TYPES.TEXT]: null,
[PANEL_TYPES.SCATTER]: null,

View File

@@ -340,7 +340,6 @@ export enum PANEL_TYPES {
PIE = 'pie',
HISTOGRAM = 'histogram',
HEATMAP = 'heatmap',
GEO_MAP = 'geo_map',
TEXT = 'text',
EMPTY_WIDGET = 'EMPTY_WIDGET',
}

View File

@@ -109,9 +109,6 @@ export const REACT_QUERY_KEY = {
// Field Values Suggestion Query Keys
FIELD_VALUES_SUGGESTION: 'FIELD_VALUES_SUGGESTION',
// Celery Query Keys
GET_CELERY_WORKER_COUNT: 'GET_CELERY_WORKER_COUNT',
// AI Assistant Query Keys
AI_ASSISTANT_EMPTY_STATE_CHIPS: 'AI_ASSISTANT_EMPTY_STATE_CHIPS',
} as const;

View File

@@ -5,7 +5,6 @@ import { useIsDarkMode } from 'hooks/useDarkMode';
import { useAppLocation } from 'lib/router/useAppLocation';
import { navigate } from 'lib/router/navigation';
import { ArrowRight } from '@signozhq/icons';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import TopContributorsContent from './TopContributorsContent';
import { TopContributorsCardProps } from './types';
@@ -28,15 +27,23 @@ function TopContributorsCard({
const isDarkMode = useIsDarkMode();
const toggleViewAllDrawer = (): void => {
const params = getUnstableCurrentSearchParams();
if (isViewAllVisible) {
params.delete('viewAllTopContributors');
const toggleViewAllParam = (isOpen: boolean): void => {
if (isOpen) {
searchParams.set('viewAllTopContributors', 'true');
} else {
params.set('viewAllTopContributors', 'true');
searchParams.delete('viewAllTopContributors');
}
setIsViewAllVisible(!isViewAllVisible);
navigate({ search: params.toString() });
};
const toggleViewAllDrawer = (): void => {
setIsViewAllVisible((prev) => {
const newState = !prev;
toggleViewAllParam(newState);
return newState;
});
navigate({ search: searchParams.toString() });
};
return (

View File

@@ -6,6 +6,7 @@ import Uplot from 'components/Uplot';
import { QueryParams } from 'constants/query';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useResizeObserver } from 'hooks/useDimensions';
import useUrlQuery from 'hooks/useUrlQuery';
import { navigate } from 'lib/router/navigation';
import heatmapPlugin from 'lib/uPlotLib/plugins/heatmapPlugin';
import timelinePlugin from 'lib/uPlotLib/plugins/timelinePlugin';
@@ -14,7 +15,6 @@ import { useTimezone } from 'providers/Timezone';
import { UpdateTimeInterval } from 'store/actions';
import { AlertRuleTimelineGraphResponse } from 'types/api/alerts/def';
import uPlot, { AlignedData } from 'uplot';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import { ALERT_STATUS, TIMELINE_OPTIONS } from './constants';
@@ -49,6 +49,7 @@ function HorizontalTimelineGraph({
return [timestamps, states];
}, [data]);
const urlQuery = useUrlQuery();
const dispatch = useDispatch();
const { timezone } = useTimezone();
@@ -88,7 +89,6 @@ function HorizontalTimelineGraph({
const diff = endTime - startTime;
if (diff > 0) {
const urlQuery = getUnstableCurrentSearchParams();
if (urlQuery.has(QueryParams.relativeTime)) {
urlQuery.delete(QueryParams.relativeTime);
}
@@ -125,7 +125,14 @@ function HorizontalTimelineGraph({
tzDate: (timestamp: number): Date =>
uPlot.tzDate(new Date(timestamp * 1e3), timezone.value),
}),
[width, isDarkMode, transformedData.length, dispatch, timezone.value],
[
width,
isDarkMode,
transformedData.length,
urlQuery,
dispatch,
timezone.value,
],
);
return <Uplot data={transformedData} options={options} />;
}

View File

@@ -5,7 +5,6 @@ import { useAppLocation } from 'lib/router/useAppLocation';
import { navigate } from 'lib/router/navigation';
import { Info } from '@signozhq/icons';
import Tabs2 from 'periscope/components/Tabs2';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import './TabsAndFilters.styles.scss';
@@ -52,9 +51,8 @@ function TimelineFilters(): JSX.Element {
);
const handleFilter = (value: TimelineFilter): void => {
const params = getUnstableCurrentSearchParams();
params.set('timelineFilter', value);
navigate({ search: params.toString() });
searchParams.set('timelineFilter', value);
navigate({ search: searchParams.toString() });
};
const tabs = [

View File

@@ -1,149 +0,0 @@
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
import ROUTES from 'constants/routes';
import { parseAsString, useQueryState } from 'nuqs';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
import type uPlot from 'uplot';
import TopContributorsCard from '../Statistics/TopContributorsCard/TopContributorsCard';
import Graph from '../Timeline/Graph/Graph';
import { ALERT_HISTORY_EXPRESSION_KEY } from '../Timeline/Table/Table';
import TabsAndFilters from '../Timeline/TabsAndFilters/TabsAndFilters';
import { TimelineFilter } from '../types';
const mockUplot: { options?: uPlot.Options } = {};
jest.mock('components/Uplot', () => ({
__esModule: true,
default: ({ options }: { options: uPlot.Options }): null => {
mockUplot.options = options;
return null;
},
}));
jest.mock('lib/uPlotLib/plugins/timelinePlugin', () => ({
__esModule: true,
default: (): object => ({}),
}));
const EXPRESSION = "service.name = 'frontend'";
// Writes the expression the way the search box does: a shallow nuqs write that
// reaches the address bar but not the router's location.
function Expression(): JSX.Element {
const [expression, setExpression] = useQueryState(
ALERT_HISTORY_EXPRESSION_KEY,
parseAsString,
);
return (
<>
<button
type="button"
aria-label="Run expression"
data-testid="run-expression"
onClick={(): void => {
void setExpression(EXPRESSION);
}}
/>
<output data-testid="expression">{expression ?? ''}</output>
</>
);
}
function getUrlParam(key: string): string | null {
return new URLSearchParams(window.location.search).get(key);
}
async function runExpression(): Promise<void> {
await userEvent.click(screen.getByTestId('run-expression'));
await waitFor(() =>
expect(getUrlParam(ALERT_HISTORY_EXPRESSION_KEY)).toBe(EXPRESSION),
);
}
function expectExpressionKept(): void {
expect(getUrlParam(ALERT_HISTORY_EXPRESSION_KEY)).toBe(EXPRESSION);
expect(screen.getByTestId('expression')).toHaveTextContent(EXPRESSION);
}
const initialRoute = `${ROUTES.ALERT_HISTORY}?ruleId=1`;
describe('Alert history navigations keep the expression', () => {
it('keeps it when a state tab is clicked', async () => {
render(
<>
<Expression />
<TabsAndFilters />
</>,
undefined,
{ initialRoute },
);
await runExpression();
await userEvent.click(screen.getByTestId('timeline-filter-fired'));
await waitFor(() =>
expect(getUrlParam('timelineFilter')).toBe(TimelineFilter.FIRED),
);
expectExpressionKept();
});
it('keeps it when the top contributors drawer opens', async () => {
const topContributorsData = [1, 2, 3, 4].map((fingerprint) => ({
fingerprint,
labels: { service: `service-${fingerprint}` },
count: fingerprint,
relatedLogsLink: '',
relatedTracesLink: '',
}));
render(
<>
<Expression />
<TopContributorsCard
topContributorsData={topContributorsData}
totalCurrentTriggers={10}
/>
</>,
undefined,
{ initialRoute },
);
await runExpression();
await userEvent.click(screen.getByTestId('top-contributors-view-all'));
await waitFor(() =>
expect(getUrlParam('viewAllTopContributors')).toBe('true'),
);
expectExpressionKept();
});
it('keeps it when a range is selected on the graph', async () => {
render(
<>
<Expression />
<Graph
type="horizontal"
data={[
{
start: 1_700_000_000_000,
end: 1_700_000_600_000,
state: RuletypesAlertStateDTO.firing,
},
]}
/>
</>,
undefined,
{ initialRoute },
);
await runExpression();
const self = {
select: { left: 10, width: 20 },
posToVal: (pos: number): number => 1_700_000_000 + pos,
} as unknown as uPlot;
act(() => {
mockUplot.options?.hooks?.setSelect?.[0]?.(self);
});
await waitFor(() => expect(getUrlParam('startTime')).toBe('1700000010000'));
expectExpressionKept();
});
});

View File

@@ -20,7 +20,8 @@ export const SlackInitialConfig: Partial<AlertmanagertypesChannelSlackConfigDTO>
*Summary:* {{ .Annotations.summary }}
*Description:* {{ .Annotations.description }}
{{ template "signoz.relatedLinks.slack" . }}
*RelatedLogs:* {{ if gt (len .Annotations.related_logs) 0 -}} View in <{{ .Annotations.related_logs }}|logs explorer> {{- end}}
*RelatedTraces:* {{ if gt (len .Annotations.related_traces) 0 -}} View in <{{ .Annotations.related_traces }}|traces explorer> {{- end}}
*Details:*
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
@@ -140,7 +141,11 @@ export const JsmOpsInitialConfig: Partial<AlertmanagertypesChannelJSMOpsConfigDT
{{ end }}{{ if .GeneratorURL }}[View in SigNoz]({{ .GeneratorURL }})
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ end }}`,
{{ end }}{{ if .Annotations.related_logs }}[View related logs]({{ .Annotations.related_logs }})
{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})
{{ end }}{{ end }}`,
priority:
'{{ if eq (index .Alerts 0).Labels.severity "critical" }}P1{{ else if eq (index .Alerts 0).Labels.severity "warning" }}P2{{ else if eq (index .Alerts 0).Labels.severity "info" }}P3{{ else }}P4{{ end }}',
tags: 'signoz-alert',
@@ -163,7 +168,11 @@ export const IncidentIOInitialConfig: Partial<AlertmanagertypesChannelIncidentIO
{{ end }}{{ if .GeneratorURL }}[View in SigNoz]({{ .GeneratorURL }})
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ end }}`,
{{ end }}{{ if .Annotations.related_logs }}[View related logs]({{ .Annotations.related_logs }})
{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})
{{ end }}{{ end }}`,
};
export const EmailInitialConfig: Partial<AlertmanagertypesChannelEmailConfigDTO> =

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Button, Tooltip } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
@@ -17,10 +17,10 @@ import {
QuickFilterChangeEventData,
QuickFiltersSource,
} from 'components/QuickFilters/types';
import { initialQueriesMap } from 'constants/queryBuilder';
import K8sBaseDetails, {
K8sDetailsFilters,
} from 'container/InfraMonitoringK8sV2/Base/K8sBaseDetails';
import { DefaultQueryRedirect } from 'container/InfraMonitoringK8sV2/Base/DefaultQueryRedirect';
import { K8sBaseList } from 'container/InfraMonitoringK8sV2/Base/K8sBaseList';
import StatusFilter from 'container/InfraMonitoringHostsV2/StatusFilter';
import { K8sBaseFilters } from 'container/InfraMonitoringK8sV2/Base/types';
@@ -28,6 +28,9 @@ import {
InfraMonitoringEntity,
METRIC_NAMESPACE_BY_ENTITY,
} from 'container/InfraMonitoringK8sV2/constants';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { DataSource } from 'types/common/queryBuilder';
import {
getHostMetricsQueryPayload,
@@ -57,6 +60,10 @@ import {
function Hosts(): JSX.Element {
const [showFilters, setShowFilters] = useState(true);
const compositeQuery = useGetCompositeQueryParam();
const { redirectWithQueryBuilderData } = useQueryBuilder();
const isInitialized = useRef(false);
const selectedTime = useGlobalTimeStore((state) => state.selectedTime);
const getMinMaxTime = useGlobalTimeStore((state) => state.getMinMaxTime);
const { startUnixMilli, endUnixMilli } = useMemo(() => {
@@ -68,6 +75,28 @@ function Hosts(): JSX.Element {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedTime, getMinMaxTime]);
useEffect(() => {
if (isInitialized.current) {
return;
}
isInitialized.current = true;
if (!compositeQuery) {
const defaultQuery = initialQueriesMap[DataSource.METRICS];
redirectWithQueryBuilderData({
...defaultQuery,
builder: {
...defaultQuery.builder,
queryData: defaultQuery.builder.queryData.map((query) => ({
...query,
filter: { expression: '' },
filters: { items: [], op: 'AND' as const },
})),
},
});
}
}, [compositeQuery, redirectWithQueryBuilderData]);
const handleFilterVisibilityChange = (): void => {
setShowFilters(!showFilters);
};
@@ -197,7 +226,6 @@ function Hosts(): JSX.Element {
return (
<>
<DefaultQueryRedirect />
<div className={styles.infraMonitoringContainer}>
<div className={styles.infraContentRow}>
{showFilters && (

View File

@@ -1,42 +0,0 @@
import { useEffect, useRef } from 'react';
import { initialQueriesMap } from 'constants/queryBuilder';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { DataSource } from 'types/common/queryBuilder';
/**
* Puts the default query in the URL when the page mounts without one.
*
* Render it before the list: React runs sibling effects in tree order, and this
* navigation drops the nuqs writes still queued, such as the page size the list
* writes on mount.
*/
export function DefaultQueryRedirect(): null {
const compositeQuery = useGetCompositeQueryParam();
const { redirectWithQueryBuilderData } = useQueryBuilder();
const isInitialized = useRef(false);
useEffect(() => {
if (isInitialized.current) {
return;
}
isInitialized.current = true;
if (!compositeQuery) {
const defaultQuery = initialQueriesMap[DataSource.METRICS];
redirectWithQueryBuilderData({
...defaultQuery,
builder: {
...defaultQuery.builder,
queryData: defaultQuery.builder.queryData.map((query) => ({
...query,
filter: { expression: '' },
filters: { items: [], op: 'AND' as const },
})),
},
});
}
}, [compositeQuery, redirectWithQueryBuilderData]);
return null;
}

View File

@@ -60,6 +60,7 @@ function K8sHeader({
const currentExpression =
currentQuery.builder.queryData[0]?.filter?.expression || '';
const finalExpression = newExpression ?? currentExpression;
void setCurrentPage(1);
const updatedQuery = {
...currentQuery,
@@ -86,8 +87,6 @@ function K8sHeader({
);
safeNavigate(`${location.pathname}?${newUrlQuery.toString()}`);
// After the navigation: a navigation drops the nuqs writes still queued.
void setCurrentPage(1);
void invalidateQueries();
if (finalExpression?.trim()) {

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import * as Sentry from '@sentry/react';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
@@ -9,12 +9,14 @@ import {
QuickFilterCheckboxUseFieldApis,
QuickFiltersSource,
} from 'components/QuickFilters/types';
import { initialQueriesMap } from 'constants/queryBuilder';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { ArrowUpToLine, Filter } from '@signozhq/icons';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import { DataSource } from 'types/common/queryBuilder';
import { CategoryIcon } from './Base/categoryIcons';
import { DefaultQueryRedirect } from './Base/DefaultQueryRedirect';
import { K8sDynamicList } from './Base/K8sDynamicList';
import EntityStatusFilter from './Base/components/EntityStatusFilter/EntityStatusFilter';
import {
@@ -64,7 +66,9 @@ export default function InfraMonitoringK8s(): JSX.Element {
const [, setNodeReadinessFilter] = useInfraMonitoringNodeReadinessFilter();
const [, setContainerStatusFilter] = useInfraMonitoringContainerStatusFilter();
const compositeQuery = useGetCompositeQueryParam();
const { currentQuery, redirectWithQueryBuilderData } = useQueryBuilder();
const isInitialized = useRef(false);
const selectedTime = useGlobalTimeStore((state) => state.selectedTime);
const getMinMaxTime = useGlobalTimeStore((state) => state.getMinMaxTime);
@@ -91,6 +95,28 @@ export default function InfraMonitoringK8s(): JSX.Element {
[getUseFieldApis, selectedCategory],
);
useEffect(() => {
if (isInitialized.current) {
return;
}
isInitialized.current = true;
if (!compositeQuery) {
const defaultQuery = initialQueriesMap[DataSource.METRICS];
redirectWithQueryBuilderData({
...defaultQuery,
builder: {
...defaultQuery.builder,
queryData: defaultQuery.builder.queryData.map((query) => ({
...query,
filter: { expression: '' },
filters: { items: [], op: 'AND' as const },
})),
},
});
}
}, [compositeQuery, redirectWithQueryBuilderData]);
useEffect(() => {
// The category query param is a plain string; entities are validated by
// getEntityConfig before rendering
@@ -186,7 +212,14 @@ export default function InfraMonitoringK8s(): JSX.Element {
const handleCategorySelect = (key: string): void => {
if (key !== selectedCategory) {
// Navigate first: a navigation drops the nuqs writes still queued.
void setSelectedCategory(key as string);
void setOrderBy(null);
void setGroupBy(null);
void setCurrentPage(null);
setSelectedItemParams(null);
void setPodStatusFilter(null);
void setNodeReadinessFilter(null);
void setContainerStatusFilter(null);
redirectWithQueryBuilderData({
...currentQuery,
builder: {
@@ -200,14 +233,6 @@ export default function InfraMonitoringK8s(): JSX.Element {
],
},
});
void setSelectedCategory(key as string);
void setOrderBy(null);
void setGroupBy(null);
void setCurrentPage(null);
setSelectedItemParams(null);
void setPodStatusFilter(null);
void setNodeReadinessFilter(null);
void setContainerStatusFilter(null);
}
};
@@ -237,7 +262,6 @@ export default function InfraMonitoringK8s(): JSX.Element {
return (
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
<DefaultQueryRedirect />
<div className={styles.infraMonitoringContainer}>
<div className={styles.infraContentRow}>
{showFilters && (

View File

@@ -1,211 +0,0 @@
import { usePreferredPageSizeStore } from 'components/TanStackTableView/usePreferredPageSize.store';
import { initialQueriesMap } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import { DataSource } from 'types/common/queryBuilder';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import K8sHeader from '../Base/K8sHeader';
import EntityDateTimeSelector from '../EntityDetailsUtils/EntityDateTimeSelector/EntityDateTimeSelector';
import {
InfraMonitoringEntity,
INFRA_MONITORING_K8S_PARAMS_KEYS,
K8sCategories,
} from '../constants';
import {
useInfraMonitoringCategory,
useInfraMonitoringSelectedItemParams,
} from '../hooks';
import InfraMonitoringK8s from '../InfraMonitoringK8s';
// The real hook: a navigation made while a nuqs write is queued drops that write,
// which is what these tests guard. The extension slips past jest.config.ts's mock.
jest.mock('hooks/useSafeNavigate', () =>
jest.requireActual('../../../hooks/useSafeNavigate.ts'),
);
jest.mock('components/QuickFilters/QuickFilters', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="quick-filters" />,
}));
// Keeps the list's own URL write on mount: the page size.
jest.mock('../Base/K8sDynamicList', () => {
const { useTableParams } = jest.requireActual<
typeof import('components/TanStackTableView')
>('components/TanStackTableView');
function K8sDynamicList(): JSX.Element {
useTableParams(
{ page: 'page', limit: 'pageSize' },
{ page: 1, limit: 10, storageKey: 'k8s-containers' },
);
return <div data-testid="k8s-dynamic-list" />;
}
return { __esModule: true, K8sDynamicList, default: K8sDynamicList };
});
jest.mock('components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch', () => ({
__esModule: true,
default: ({ onRun }: { onRun: (expression: string) => void }): JSX.Element => (
<button
type="button"
aria-label="Run filter"
data-testid="run-filter"
onClick={(): void => onRun("k8s.pod.name = 'pod-1'")}
/>
),
}));
jest.mock('lib/navigation', () => ({
getNavigationReferrer: (): string => 'direct',
}));
const route = ROUTES.INFRASTRUCTURE_MONITORING_KUBERNETES;
function DrawerHarness(): JSX.Element {
const [, setCategory] = useInfraMonitoringCategory();
const [selectedItemParams, setSelectedItemParams] =
useInfraMonitoringSelectedItemParams();
return (
<>
<button
type="button"
aria-label="Select category"
data-testid="select-category"
onClick={(): void => {
void setCategory(K8sCategories.PODS);
}}
/>
<button
type="button"
aria-label="Open row"
data-testid="open-row"
onClick={(): void =>
setSelectedItemParams({
selectedItem: 'pod-1',
clusterName: null,
namespaceName: null,
})
}
/>
{selectedItemParams.selectedItem && (
<div data-testid="drawer">
<EntityDateTimeSelector category={InfraMonitoringEntity.PODS} />
</div>
)}
</>
);
}
function getUrlParam(key: string): string | null {
return new URLSearchParams(window.location.search).get(key);
}
describe('K8s URL writes queued by nuqs', () => {
afterEach(() => {
usePreferredPageSizeStore
.getState()
.setPreferredPageSize('k8s-containers', null);
});
it('opens the drawer on the first click after an earlier shallow write', async () => {
render(<DrawerHarness />, undefined, {
initialRoute: `${route}?relativeTime=15m`,
});
await userEvent.click(screen.getByTestId('select-category'));
await waitFor(() =>
expect(getUrlParam(INFRA_MONITORING_K8S_PARAMS_KEYS.CATEGORY)).toBe(
K8sCategories.PODS,
),
);
await userEvent.click(screen.getByTestId('open-row'));
await waitFor(() =>
expect(getUrlParam(INFRA_MONITORING_K8S_PARAMS_KEYS.SELECTED_ITEM)).toBe(
'pod-1',
),
);
expect(screen.getByTestId('drawer')).toBeInTheDocument();
});
it('switches category on the first click while a filter is applied', async () => {
const query = initialQueriesMap[DataSource.METRICS];
const filteredQuery = {
...query,
builder: {
...query.builder,
queryData: [
{
...query.builder.queryData[0],
filter: { expression: "k8s.pod.name = 'pod-1'" },
},
],
},
};
const params = new URLSearchParams({
[INFRA_MONITORING_K8S_PARAMS_KEYS.CATEGORY]: K8sCategories.PODS,
compositeQuery: encodeURIComponent(JSON.stringify(filteredQuery)),
});
render(<InfraMonitoringK8s />, undefined, {
initialRoute: `${route}?${params.toString()}`,
});
await userEvent.click(
await screen.findByTestId(`category-${K8sCategories.CONTAINERS}`),
);
await waitFor(() => {
const compositeQuery = JSON.parse(
decodeURIComponent(getUrlParam('compositeQuery') ?? ''),
);
expect(compositeQuery.builder.queryData[0].filter.expression).toBe('');
});
await waitFor(() =>
expect(getUrlParam(INFRA_MONITORING_K8S_PARAMS_KEYS.CATEGORY)).toBe(
K8sCategories.CONTAINERS,
),
);
});
it('goes back to the first page when a filter runs', async () => {
render(
<K8sHeader
entity={InfraMonitoringEntity.PODS}
showAutoRefresh={false}
cancelQuery={jest.fn()}
/>,
undefined,
{ initialRoute: `${route}?relativeTime=30m&page=3` },
);
await userEvent.click(screen.getByTestId('run-filter'));
await waitFor(() => {
const compositeQuery = JSON.parse(
decodeURIComponent(getUrlParam('compositeQuery') ?? ''),
);
expect(compositeQuery.builder.queryData[0].filter.expression).toBe(
"k8s.pod.name = 'pod-1'",
);
});
await waitFor(() =>
expect(getUrlParam(INFRA_MONITORING_K8S_PARAMS_KEYS.PAGE)).toBe('1'),
);
});
it('keeps the page size the list writes while the default query loads', async () => {
usePreferredPageSizeStore
.getState()
.setPreferredPageSize('k8s-containers', 25);
render(<InfraMonitoringK8s />, undefined, { initialRoute: route });
await waitFor(() => expect(getUrlParam('compositeQuery')).not.toBeNull());
await waitFor(() =>
expect(getUrlParam(INFRA_MONITORING_K8S_PARAMS_KEYS.PAGE_SIZE)).toBe('25'),
);
});
});

View File

@@ -194,7 +194,7 @@ describe('ListAlertRules — search', () => {
});
it.each(['rule_list_filter_invalid', 'rule_list_invalid'])(
'shows the invalid query state with the backend message for %s',
'shows the backend message and no-results state for %s',
async (code) => {
const user = userEvent.setup({ delay: null });
server.use(
@@ -219,11 +219,12 @@ describe('ListAlertRules — search', () => {
await runSearchQuery(user, "nme = 'x'");
await expect(
screen.findByTestId('alert-rules-invalid-query-detail'),
screen.findByTestId('alert-rules-query-error'),
).resolves.toHaveTextContent('unknown field "nme"');
expect(
screen.queryByTestId('no-results-empty-state'),
).not.toBeInTheDocument();
const empty = screen.getByTestId('no-results-empty-state');
expect(within(empty).getByTestId('no-results-subtitle')).toHaveTextContent(
'The filter query is invalid. Fix it or clear the search.',
);
expect(screen.queryByTestId('error-empty-state')).not.toBeInTheDocument();
expect(screen.queryByText('High CPU Alert')).not.toBeInTheDocument();
},

View File

@@ -10,6 +10,7 @@ interface Props {
states: string[];
creatorOptions: CreatorOption[];
source: SuggestionSource;
error: string | null;
onQueryChange: (query: string) => void;
onStatesChange: (states: string[]) => void;
}
@@ -19,6 +20,7 @@ function AlertRulesFilterZone({
states,
creatorOptions,
source,
error,
onQueryChange,
onStatesChange,
}: Props): JSX.Element {
@@ -34,6 +36,7 @@ function AlertRulesFilterZone({
extraFilters={<RuleStatesFilter states={states} onChange={onStatesChange} />}
hasExtraFilters={states.length > 0}
onClearAll={(): void => onStatesChange([])}
error={error ?? undefined}
/>
);
}

View File

@@ -1,7 +1,6 @@
import { useCallback, useMemo } from 'react';
import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
import NoResultsEmptyState from 'components/Alerts/NoResultsEmptyState';
import InvalidQueryState from 'components/ListFilter/InvalidQueryState/InvalidQueryState';
import ListCommandHeader from 'components/ListViews/ListCommandHeader/ListCommandHeader';
import ListStatusBar from 'components/ListViews/ListStatusBar/ListStatusBar';
import ViewsRail from 'components/ListViews/ViewsRail/ViewsRail';
@@ -9,7 +8,6 @@ import TanStackTable from 'components/TanStackTableView';
import { useCalculatedPageSize } from 'components/TanStackTableView/useCalculatedPageSize';
import { useTableParams } from 'components/TanStackTableView/useTableParams';
import useComponentPermission from 'hooks/useComponentPermission';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useAppContext } from 'providers/App/App';
import { useTimezone } from 'providers/Timezone';
@@ -40,7 +38,6 @@ const DEFAULT_LIMIT = 10;
function ListAlertRules(): JSX.Element {
const { user } = useAppContext();
const { isCloudUser } = useGetTenantLicense();
const [addNewAlert, action] = useComponentPermission(
['add_new_alert', 'action'],
user.role,
@@ -202,6 +199,7 @@ function ListAlertRules(): JSX.Element {
states={filter.states}
creatorOptions={creatorOptions}
source={source}
error={queryError}
onQueryChange={submitQuery}
onStatesChange={changeStates}
/>
@@ -211,16 +209,14 @@ function ListAlertRules(): JSX.Element {
<div ref={containerRef} className={styles.tableContainer}>
{isError ? (
<ErrorEmptyState title="Failed to load alert rules" onRefresh={refetch} />
) : isEmptyDueToFilters && queryError ? (
<InvalidQueryState
errorMessage={queryError}
isCloudUser={!!isCloudUser}
testIdPrefix="alert-rules"
/>
) : isEmptyDueToFilters ? (
<NoResultsEmptyState
title="No matching alert rules"
subtitle="No alert rules match your search. Try adjusting your search criteria."
subtitle={
queryError
? 'The filter query is invalid. Fix it or clear the search.'
: 'No alert rules match your search. Try adjusting your search criteria.'
}
onClear={handleClearFilters}
clearButtonText="Clear Search"
/>

View File

@@ -991,15 +991,6 @@ describe('Login Component', () => {
describe('Enter key submission', () => {
const EMAIL_PASSWORD_ENDPOINT = '*/api/v2/sessions/email_password';
const originalLocation = window.location;
afterEach(() => {
Object.defineProperty(window, 'location', {
value: originalLocation,
writable: true,
configurable: true,
});
});
async function typeEmail(
user: ReturnType<typeof userEvent.setup>,
@@ -1166,15 +1157,8 @@ describe('Login Component', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
Object.defineProperty(window, 'location', {
value: {
href: 'http://localhost/',
origin: 'http://localhost',
pathname: '/',
search: '',
hash: '',
},
value: { href: 'http://localhost/' },
writable: true,
configurable: true,
});
server.use(

View File

@@ -47,10 +47,6 @@
flex: 1;
min-width: 0;
}
&__search-trigger {
width: 100%;
}
}
.members-filter-trigger__chevron {

View File

@@ -6,25 +6,15 @@ import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
import { Input } from '@signozhq/ui/input';
import { useListUsers } from 'api/generated/services/users';
import EditMemberDrawer from 'components/EditMemberDrawer/EditMemberDrawer';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import InviteMembersModal from 'container/MembersSettings/components/InviteMembersModal/InviteMembersModal';
import MembersTable, { MemberRow } from 'components/MembersTable/MembersTable';
import useUrlQuery from 'hooks/useUrlQuery';
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import {
UserCreatePermission,
UserListPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { parseAsBoolean, useQueryState } from 'nuqs';
import { toISOString } from 'utils/app';
import { toAPIError } from 'utils/errorUtils';
import { FilterMode, MemberStatus, toMemberStatus } from './utils';
import './MembersSettings.styles.scss';
import AuthZButton from '@/lib/authz/components/AuthZButton/AuthZButton';
const PAGE_SIZE = 20;
@@ -33,12 +23,6 @@ function MembersSettings(): JSX.Element {
const pageParam = parseInt(urlQuery.get('page') ?? '1', 10);
const currentPage = Number.isNaN(pageParam) || pageParam < 1 ? 1 : pageParam;
const {
permissions: authzPermissions,
isLoading: isAuthZLoading,
error: authzError,
} = useAuthZ([UserListPermission]);
// TODO(nuqs): Replace with nuqs once the nuqs setup and integration is done - for search
const [searchQuery, setSearchQuery] = useState('');
const [filterMode, setFilterMode] = useState<FilterMode>(FilterMode.All);
@@ -48,18 +32,7 @@ function MembersSettings(): JSX.Element {
);
const [selectedMember, setSelectedMember] = useState<MemberRow | null>(null);
const canListUsers =
!!authzError || (authzPermissions?.[UserListPermission]?.isGranted ?? false);
const {
data: usersData,
isLoading,
refetch: refetchUsers,
isError,
error,
} = useListUsers({ query: { enabled: canListUsers } });
const controlsDisabled = !canListUsers || isAuthZLoading;
const { data: usersData, isLoading, refetch: refetchUsers } = useListUsers();
const allMembers = useMemo(
(): MemberRow[] =>
@@ -203,89 +176,57 @@ function MembersSettings(): JSX.Element {
</div>
<div className="members-settings__controls">
<AuthZTooltip checks={[UserListPermission]}>
<span>
<Dropdown
disabled={controlsDisabled}
disabledTooltip={undefined}
items={filterMenuItems}
nativeButton
align="end"
side="bottom"
>
<Button
size="md"
variant="solid"
color="secondary"
loading={isAuthZLoading}
disabled={!canListUsers}
disabledTooltip={undefined}
suffix={
<ChevronDown size={12} className="members-filter-trigger__chevron" />
}
testId="members-filter-trigger"
>
<span>{filterLabel}</span>
</Button>
</Dropdown>
</span>
</AuthZTooltip>
<Dropdown items={filterMenuItems} nativeButton align="end" side="bottom">
<Button
size="md"
variant="solid"
color="secondary"
suffix={
<ChevronDown size={12} className="members-filter-trigger__chevron" />
}
testId="members-filter-trigger"
>
<span>{filterLabel}</span>
</Button>
</Dropdown>
<div className="members-settings__search">
<AuthZTooltip
checks={[UserListPermission]}
triggerClassName="members-settings__search-trigger"
>
<Input
type="search"
placeholder="Search by name or email..."
value={searchQuery}
onChange={(e): void => {
setSearchQuery(e.target.value);
setPage(1);
}}
className="members-search-input"
name="members-search"
testId="members-search-input"
disabled={controlsDisabled}
/>
</AuthZTooltip>
<Input
type="search"
placeholder="Search by name or email..."
value={searchQuery}
onChange={(e): void => {
setSearchQuery(e.target.value);
setPage(1);
}}
className="members-search-input"
name="members-search"
testId="members-search-input"
/>
</div>
<AuthZButton
<Button
size="md"
variant="solid"
color="primary"
checks={[UserCreatePermission]}
onClick={(): void => void setIsInviteModalOpen(true)}
prefix={<Plus size={12} />}
testId="invite-member-btn"
>
Invite member
</AuthZButton>
</Button>
</div>
</div>
<AuthZGuardContent checks={[UserListPermission]}>
{isError ? (
<ErrorInPlace
error={toAPIError(
error,
'An unexpected error occurred while fetching members.',
)}
/>
) : (
<MembersTable
data={filteredMembers}
loading={isLoading}
total={filteredMembers.length}
currentPage={currentPage}
pageSize={PAGE_SIZE}
searchQuery={searchQuery}
onPageChange={setPage}
onRowClick={handleRowClick}
/>
)}
</AuthZGuardContent>
<MembersTable
data={filteredMembers}
loading={isLoading}
total={filteredMembers.length}
currentPage={currentPage}
pageSize={PAGE_SIZE}
searchQuery={searchQuery}
onPageChange={setPage}
onRowClick={handleRowClick}
/>
<InviteMembersModal
open={isInviteModalOpen}
@@ -295,6 +236,7 @@ function MembersSettings(): JSX.Element {
<EditMemberDrawer
member={selectedMember}
open={selectedMember !== null}
onClose={handleDrawerClose}
onComplete={handleMemberEditComplete}
/>

View File

@@ -1,11 +1,7 @@
import type { TypesUserDTO } from 'api/generated/services/sigNoz.schemas';
import userEvent from '@testing-library/user-event';
import { rest, server } from 'mocks-server/server';
import {
AUTHZ_CHECK_URL,
setupAuthzAdmin,
} from 'lib/authz/utils/authz-test-utils';
import { fireEvent, render, screen, waitFor } from 'tests/test-utils';
import { fireEvent, render, screen } from 'tests/test-utils';
import MembersSettings from '../MembersSettings';
@@ -61,7 +57,6 @@ describe('MembersSettings (integration)', () => {
rest.get(USERS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: mockUsers })),
),
setupAuthzAdmin(),
);
});
@@ -128,22 +123,10 @@ describe('MembersSettings (integration)', () => {
expect(screen.queryByText('Member Details')).toBeInTheDocument();
});
it('still lists members when the permission check fails', async () => {
server.use(rest.post(AUTHZ_CHECK_URL, (_, res, ctx) => res(ctx.status(500))));
render(<MembersSettings />);
await expect(screen.findByText('Alice Smith')).resolves.toBeInTheDocument();
});
it('opens InviteMembersModal when "Invite member" button is clicked', async () => {
render(<MembersSettings />);
const inviteBtn = await screen.findByTestId('invite-member-btn');
await waitFor(() =>
expect(inviteBtn).not.toHaveAttribute('aria-disabled', 'true'),
);
await userEvent.click(inviteBtn);
fireEvent.click(screen.getByRole('button', { name: /invite member/i }));
await expect(
screen.findAllByPlaceholderText('e.g. john@signoz.io'),

View File

@@ -4,8 +4,6 @@ import { Button } from '@signozhq/ui/button';
import { DialogWrapper } from '@signozhq/ui/dialog';
import { toast } from '@signozhq/ui/sonner';
import InviteMembers from 'components/InviteMembers/InviteMembers';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import './InviteMembersModal.styles.scss';
@@ -60,21 +58,18 @@ function InviteMembersModal({
Cancel
</Button>
<AuthZButton
<Button
size="md"
variant="solid"
color="primary"
onClick={submit}
disabled={!canSubmit}
disabledTooltip={
canSubmit ? undefined : 'Add at least one team member to invite'
}
checks={[UserCreatePermission]}
disabledTooltip="Add at least one team member to invite"
loading={isSubmitting}
testId="invite-submit-btn"
>
{isSubmitting ? 'Inviting...' : 'Invite Team Members'}
</AuthZButton>
</Button>
</div>
)}
/>

View File

@@ -1,11 +1,5 @@
import { toast } from '@signozhq/ui/sonner';
import {
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { render, screen, userEvent } from 'tests/test-utils';
import InviteMembersModal from '../InviteMembersModal';
@@ -61,7 +55,6 @@ describe('InviteMembersModal', () => {
beforeEach(() => {
jest.clearAllMocks();
mockInviteMembersProps = null;
server.use(setupAuthzAdmin());
});
describe('rendering', () => {
@@ -141,7 +134,7 @@ describe('InviteMembersModal', () => {
const { unmount } = renderComponent();
unmount();
const { getByTestId } = render(
const { getByRole } = render(
mockInviteMembersProps?.renderFooter({
submit: mockSubmit,
canSubmit: true,
@@ -149,27 +142,10 @@ describe('InviteMembersModal', () => {
}) as JSX.Element,
);
const submit = getByTestId('invite-submit-btn');
await waitFor(() =>
expect(submit).not.toHaveAttribute('aria-disabled', 'true'),
);
await user.click(submit);
await user.click(getByRole('button', { name: /invite team members/i }));
expect(mockSubmit).toHaveBeenCalledTimes(1);
});
it('disables the Invite button without create permission', async () => {
server.use(setupAuthzDeny(UserCreatePermission));
renderComponent();
await waitFor(() =>
expect(screen.getByTestId('invite-submit-btn')).toHaveAttribute(
'aria-disabled',
'true',
),
);
});
});
describe('handleSuccess callback', () => {

View File

@@ -58,6 +58,22 @@
line-height: 20px; /* 142.857% */
letter-spacing: -0.07px;
}
.user-role {
display: flex;
align-items: center;
gap: 8px;
text-transform: capitalize;
color: var(--l2-foreground);
font-family: Inter;
font-size: 13px;
font-style: normal;
font-weight: 400;
line-height: 20px; /* 142.857% */
letter-spacing: -0.07px;
}
}
}

View File

@@ -8,7 +8,7 @@ import {
useUpdateMyUserV2,
} from 'api/generated/services/users';
import { toast } from '@signozhq/ui/sonner';
import { Check, FileTerminal, Mail } from '@signozhq/icons';
import { Check, FileTerminal, Mail, User } from '@signozhq/icons';
import { useAppContext } from 'providers/App/App';
import { useErrorModal } from 'providers/ErrorModalProvider';
import APIError from 'types/api/error';
@@ -129,9 +129,13 @@ function UserInfo(): JSX.Element {
</div>
<div className="user-info-subsection">
<div className="user-email" data-testid="user-info-email">
<div className="user-email">
<Mail size={16} /> {user.email}
</div>
<div className="user-role">
<User size={16} /> {user.role.toLowerCase()}
</div>
</div>
</div>

View File

@@ -168,13 +168,6 @@ describe('MySettings Flows', () => {
expect(modalUpdateNameButton).toBeInTheDocument();
});
it('Should show the email and not the role', () => {
expect(screen.getByTestId('user-info-email')).toHaveTextContent(
'does-not-matter@signoz.io',
);
expect(screen.queryByText('admin')).not.toBeInTheDocument();
});
it('Should update the name on clicking Update button', async () => {
// Open the Update name modal first
const updateNameButton = screen.getByText(UPDATE_NAME_BUTTON_TEXT);
@@ -471,34 +464,3 @@ describe('MySettings Flows', () => {
});
});
});
describe('MySettings name update and app context', () => {
beforeEach(() => {
jest.clearAllMocks();
editUserFn.mockResolvedValue({});
mockUseActiveLicenseKey.mockReturnValue({
licenseKey: 'test-key',
isLoading: false,
});
});
it('updates the user in the app context with the new name', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const updateUser = jest.fn();
render(<MySettingsContainer />, undefined, {
appContextOverrides: { updateUser },
});
await user.click(screen.getByTestId('update-name-open-btn'));
const nameInput = screen.getByTestId('update-name-input');
await user.clear(nameInput);
await user.type(nameInput, 'New Name');
await user.click(screen.getByTestId(UPDATE_NAME_BUTTON_TEST_ID));
await waitFor(() =>
expect(updateUser).toHaveBeenCalledWith(
expect.objectContaining({ displayName: 'New Name' }),
),
);
});
});

View File

@@ -6,8 +6,6 @@ import InviteMembers from 'components/InviteMembers/InviteMembers';
import { InviteMemberRow, InviteResult } from 'components/InviteMembers/types';
import { useRoles } from 'components/RolesSelect/RolesSelect';
import { useNotifications } from 'hooks/useNotifications';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { getBaseUrl } from 'utils/basePath';
import { OnboardingQuestionHeader } from '../OnboardingQuestionHeader';
@@ -120,22 +118,20 @@ function InviteTeamMembers({
return (
<div className="onboarding-buttons-container">
<AuthZButton
<Button
size="md"
variant="solid"
color="primary"
width="100%"
onClick={submit}
loading={isButtonDisabled}
disabledTooltip={
canSubmit ? undefined : 'Add at least one team member to invite'
}
checks={[UserCreatePermission]}
disabled={!canSubmit}
disabledTooltip="Add at least one team member to invite"
testId="send-invites-button"
suffix={<ArrowRight size={12} />}
>
Send Invites
</AuthZButton>
</Button>
<Button
size="md"
variant="ghost"

View File

@@ -1,78 +0,0 @@
import { InviteMembersProps } from 'components/InviteMembers/types';
import type { useRoles } from 'components/RolesSelect/RolesSelect';
import type { useNotifications } from 'hooks/useNotifications';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import {
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { server } from 'mocks-server/server';
import { render, screen, waitFor } from 'tests/test-utils';
import InviteTeamMembers from '../InviteTeamMembers';
jest.mock('hooks/useNotifications', () => ({
useNotifications: (): ReturnType<typeof useNotifications> => ({
notifications: {
success: jest.fn(),
error: jest.fn(),
info: jest.fn(),
warning: jest.fn(),
open: jest.fn(),
destroy: jest.fn(),
},
}),
}));
jest.mock('components/RolesSelect/RolesSelect', () => ({
useRoles: (): ReturnType<typeof useRoles> => ({
roles: [],
isLoading: false,
isError: false,
error: undefined,
refetch: jest.fn(),
}),
}));
jest.mock('components/InviteMembers/InviteMembers', () => {
return function MockInviteMembers(props: InviteMembersProps): JSX.Element {
return (
<div>
{props.renderFooter?.({
submit: jest.fn().mockResolvedValue([]),
reset: jest.fn(),
canSubmit: true,
isSubmitting: false,
touchedCount: 1,
})}
</div>
);
};
});
describe('InviteTeamMembers authz', () => {
it('enables Send Invites with create:user', async () => {
server.use(setupAuthzAdmin());
render(<InviteTeamMembers isLoading={false} onNext={jest.fn()} />);
const button = screen.getByTestId('send-invites-button');
await waitFor(() => expect(button).not.toHaveAttribute('aria-busy', 'true'));
expect(button).not.toHaveAttribute('aria-disabled', 'true');
});
it('disables Send Invites without create:user', async () => {
server.use(setupAuthzDeny(UserCreatePermission));
render(<InviteTeamMembers isLoading={false} onNext={jest.fn()} />);
await waitFor(() =>
expect(screen.getByTestId('send-invites-button')).toHaveAttribute(
'data-denied-permissions',
UserCreatePermission,
),
);
expect(screen.getByTestId('send-invites-button')).toHaveAttribute(
'aria-disabled',
'true',
);
});
});

View File

@@ -22,8 +22,6 @@ import { useGetGlobalConfig } from 'api/generated/services/global';
import useDebouncedFn from 'hooks/useDebouncedFunction';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { isEmpty } from 'lodash-es';
import { useAppContext } from 'providers/App/App';
import { isModifierKeyPressed } from 'utils/app';
@@ -713,7 +711,6 @@ function OnboardingAddDataSource(): JSX.Element {
<Button
type="default"
className="periscope-btn invite-teammate-btn outlined"
data-testid="invite-teammate-btn"
onClick={handleShowInviteTeamMembersModal}
icon={<UserPlus size={16} />}
>
@@ -1188,7 +1185,7 @@ function OnboardingAddDataSource(): JSX.Element {
>
Cancel
</SignozButton>
<AuthZButton
<SignozButton
size="md"
color="primary"
variant="solid"
@@ -1199,16 +1196,13 @@ function OnboardingAddDataSource(): JSX.Element {
);
void submit();
}}
disabledTooltip={
canSubmit ? undefined : 'Add at least one team member to invite'
}
checks={[UserCreatePermission]}
disabled={!canSubmit}
disabledTooltip="Add at least one team member to invite"
loading={isSubmitting}
suffix={<ArrowRight size={14} />}
testId="onboarding-send-invites-btn"
>
Send Invites
</AuthZButton>
</SignozButton>
</div>
)}
/>

View File

@@ -1,61 +0,0 @@
import { InviteMembersProps } from 'components/InviteMembers/types';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import {
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import OnboardingAddDataSource from '../AddDataSource';
jest.mock('components/LaunchChatSupport/LaunchChatSupport', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('components/InviteMembers/InviteMembers', () => {
return function MockInviteMembers(props: InviteMembersProps): JSX.Element {
return (
<div>
{props.renderFooter?.({
submit: jest.fn().mockResolvedValue([]),
reset: jest.fn(),
canSubmit: true,
isSubmitting: false,
touchedCount: 1,
})}
</div>
);
};
});
async function openInviteModal(): Promise<HTMLElement> {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<OnboardingAddDataSource />);
await user.click(screen.getByTestId('invite-teammate-btn'));
return screen.findByTestId('onboarding-send-invites-btn');
}
describe('OnboardingAddDataSource invite modal authz', () => {
it('enables Send Invites with create:user', async () => {
server.use(setupAuthzAdmin());
const button = await openInviteModal();
await waitFor(() => expect(button).not.toHaveAttribute('aria-busy', 'true'));
expect(button).not.toHaveAttribute('aria-disabled', 'true');
});
it('disables Send Invites without create:user', async () => {
server.use(setupAuthzDeny(UserCreatePermission));
const button = await openInviteModal();
await waitFor(() =>
expect(button).toHaveAttribute(
'data-denied-permissions',
UserCreatePermission,
),
);
expect(button).toHaveAttribute('aria-disabled', 'true');
});
});

View File

@@ -1,88 +0,0 @@
import { Form } from 'antd';
import QueryBuilderSearchV2 from 'container/QueryBuilder/filters/QueryBuilderSearchV2/QueryBuilderSearchV2';
import { server } from 'mocks-server/server';
import { act, render, waitFor } from 'tests/test-utils';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import type { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import type {
BaseBuilderQuery,
QueryRangePayloadV5,
} from 'types/api/v5/queryRange';
import { pipelineFields } from '../../../../config';
import { queryRangeV5Handler } from '../../../../Preview/__tests__/fixtures';
import FilterInput from '..';
jest.mock(
'container/QueryBuilder/filters/QueryBuilderSearchV2/QueryBuilderSearchV2',
() => ({ __esModule: true, default: jest.fn(() => null) }),
);
const filterField = pipelineFields.find((field) => field.name === 'filter');
const v5Filter: TagFilter = {
op: 'AND',
items: [
{
id: 'attribute-pill',
key: { key: 'http.method', dataType: DataTypes.String, type: 'attribute' },
op: '=',
value: 'GET',
},
{
id: 'log-pill',
key: { key: 'severity_text', dataType: DataTypes.String, type: 'log' },
op: '=',
value: 'ERROR',
},
],
};
describe('Pipeline FilterInput', () => {
it('saves the filter with the legacy key types the pipeline builders read', () => {
const onValuesChange = jest.fn() as jest.MockedFunction<
(changedValues: { filter: TagFilter }) => void
>;
render(
<Form onValuesChange={onValuesChange}>
{filterField && <FilterInput fieldData={filterField} />}
</Form>,
);
const { onChange } = jest.mocked(QueryBuilderSearchV2).mock.calls[0][0];
act(() => onChange(v5Filter));
expect(
onValuesChange.mock.lastCall?.[0].filter.items.map((item) => [
item.key?.key,
item.key?.type,
]),
).toStrictEqual([
['http.method', 'tag'],
['severity_text', ''],
]);
});
it('previews sample logs for the picked filter', async () => {
const requests: QueryRangePayloadV5[] = [];
server.use(queryRangeV5Handler({ rows: [], count: 0, requests }));
render(<Form>{filterField && <FilterInput fieldData={filterField} />}</Form>);
const { onChange } = jest.mocked(QueryBuilderSearchV2).mock.calls[0][0];
act(() => onChange(v5Filter));
await waitFor(() =>
expect(
requests
.filter((request) => request.requestType === 'raw')
.map(
(request) =>
(request.compositeQuery.queries[0].spec as BaseBuilderQuery).filter
?.expression,
),
).toContain("http.method = 'GET' AND severity_text = 'ERROR'"),
);
});
});

View File

@@ -4,7 +4,6 @@ import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
import QueryBuilderSearchV2 from 'container/QueryBuilder/filters/QueryBuilderSearchV2/QueryBuilderSearchV2';
import isEqual from 'lodash-es/isEqual';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { toLegacyLogsFilter } from 'utils/fieldContext';
import { ProcessorFormField } from '../../../AddNewProcessor/config';
import { formValidationRules } from '../../../config';
@@ -23,10 +22,9 @@ function TagFilterInput({
}
const onQueryChange = (newValue: TagFilter): void => {
const legacyValue = toLegacyLogsFilter(newValue);
// Avoid unnecessary onChange calls
if (!isEqual(legacyValue, query.filters)) {
onChange(legacyValue);
if (!isEqual(newValue, query.filters)) {
onChange(newValue);
}
};

View File

@@ -1,64 +0,0 @@
import { server } from 'mocks-server/server';
import { render, screen } from 'tests/test-utils';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { BaseBuilderQuery, QueryRangePayloadV5 } from 'types/api/v5/queryRange';
import { queryRangeV5Handler } from '../../__tests__/fixtures';
import LogsFilterPreview from '../index';
const filter: TagFilter = {
op: 'AND',
items: [
{
id: 'code-function',
key: { key: 'code.function', dataType: DataTypes.String, type: 'tag' },
op: '=',
value: 'PlaceOrder',
},
],
};
describe('LogsFilterPreview', () => {
it('loads the sample logs and the match count from query_range v5', async () => {
const requests: QueryRangePayloadV5[] = [];
server.use(
queryRangeV5Handler({
rows: [
{
timestamp: '2026-11-16T10:00:02Z',
data: { id: 'log-2', body: 'order placed' },
},
{
timestamp: '2026-11-16T10:00:01Z',
data: { id: 'log-1', body: 'payment charged' },
},
],
count: 4213,
requests,
}),
);
render(<LogsFilterPreview filter={filter} />);
await expect(
screen.findByTestId('pipeline-filter-preview-count'),
).resolves.toHaveTextContent('4213 matches in');
await expect(
screen.findAllByTestId('pipeline-preview-log'),
).resolves.toHaveLength(2);
const specOf = (requestType: string): BaseBuilderQuery | undefined =>
requests.find((request) => request.requestType === requestType)
?.compositeQuery.queries[0].spec as BaseBuilderQuery | undefined;
expect(specOf('raw')).toMatchObject({
filter: { expression: "code.function = 'PlaceOrder'" },
limit: 5,
order: [{ key: { name: 'timestamp' }, direction: 'desc' }],
});
expect(specOf('scalar')?.filter?.expression).toBe(
"code.function = 'PlaceOrder'",
);
});
});

View File

@@ -1,54 +0,0 @@
import { PipelineSimulationRequest } from 'api/pipeline/preview';
import { pipelineMockData } from 'container/PipelinePage/mocks/pipeline';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { queryRangeV5Handler } from '../../__tests__/fixtures';
import PipelineProcessingPreview from '../index';
describe('PipelineProcessingPreview', () => {
it('sends object bodies to the simulation as JSON strings', async () => {
const simulations: PipelineSimulationRequest[] = [];
server.use(
queryRangeV5Handler({
rows: [
{
timestamp: '2026-11-16T10:00:02Z',
data: {
id: 'log-2',
body: { order: { id: 'o-1' }, message: 'order placed' },
},
},
{
timestamp: '2026-11-16T10:00:01Z',
data: { id: 'log-1', body: 'payment charged' },
},
],
count: 2,
}),
rest.post('*/api/v1/logs/pipelines/preview', async (req, res, ctx) => {
const body: PipelineSimulationRequest = await req.json();
simulations.push(body);
return res(
ctx.status(200),
ctx.json({ status: 'success', data: { logs: body.logs } }),
);
}),
);
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<PipelineProcessingPreview pipeline={pipelineMockData[0]} />);
await expect(
screen.findAllByTestId('pipeline-preview-log'),
).resolves.toHaveLength(2);
await user.click(screen.getByTestId('pipeline-simulate-processing'));
await waitFor(() => expect(simulations).toHaveLength(1));
expect(simulations[0].logs.map((log) => log.body)).toStrictEqual([
'{"order":{"id":"o-1"},"message":"order placed"}',
'payment charged',
]);
});
});

View File

@@ -19,7 +19,6 @@ function LogsProcessingSimulator({
disabled={(inputLogs?.length || 0) < 1}
type="primary"
onClick={simulate}
data-testid="pipeline-simulate-processing"
>
Simulate Processing
</Button>

View File

@@ -1,63 +0,0 @@
import {
Querybuildertypesv5ColumnTypeDTO,
Querybuildertypesv5RequestTypeDTO,
type QueryRangeV5200,
type Querybuildertypesv5RawDataDTO,
type Querybuildertypesv5RawRowDTO,
type Querybuildertypesv5ScalarDataDTO,
} from 'api/generated/services/sigNoz.schemas';
import { rest, RestHandler } from 'msw';
import { QueryRangePayloadV5 } from 'types/api/v5/queryRange';
function countResponse(count: number): QueryRangeV5200 {
const result: Querybuildertypesv5ScalarDataDTO = {
columns: [
{
name: '__result_0',
queryName: 'A',
aggregationIndex: 0,
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
},
],
data: [[count]],
};
return {
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.scalar,
data: { results: [result] },
},
};
}
function rowsResponse(rows: Querybuildertypesv5RawRowDTO[]): QueryRangeV5200 {
const result: Querybuildertypesv5RawDataDTO = { queryName: 'A', rows };
return {
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.raw,
data: { results: [result] },
},
};
}
export function queryRangeV5Handler({
rows,
count,
requests,
}: {
rows: Querybuildertypesv5RawRowDTO[];
count: number;
requests?: QueryRangePayloadV5[];
}): RestHandler {
return rest.post('*/api/v5/query_range', async (req, res, ctx) => {
const body: QueryRangePayloadV5 = await req.json();
requests?.push(body);
return res(
ctx.status(200),
ctx.json(
body.requestType === 'scalar' ? countResponse(count) : rowsResponse(rows),
),
);
});
}

View File

@@ -1,5 +1,5 @@
import { useMemo } from 'react';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import {
initialFilters,
initialQueriesMap,
@@ -34,26 +34,18 @@ function LogsCountInInterval({
selectedTime: 'GLOBAL_TIME',
globalSelectedInterval: timeInterval,
},
ENTITY_VERSION_V5,
DEFAULT_ENTITY_VERSION,
);
const count = useMemo(() => {
const table = result.data?.payload?.data?.result?.[0]?.table;
const countColumn = table?.columns.find((column) => column.isValueColumn);
return (
countColumn && table?.rows[0]?.data[countColumn.id || countColumn.name]
);
}, [result.data]);
if (!result.isFetched) {
return null;
}
const count =
result?.data?.payload?.data?.newResult?.data?.result?.[0]?.series?.[0]
?.values?.[0]?.value;
return (
<div
className="logs-filter-preview-matched-logs-count"
data-testid="pipeline-filter-preview-count"
>
<div className="logs-filter-preview-matched-logs-count">
{count} matches in
</div>
);

View File

@@ -4,7 +4,6 @@ import simulatePipelineProcessing, {
} from 'api/pipeline/preview';
import { AxiosError } from 'axios';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { getBodyDisplay } from 'lib/logs/logBody';
import { ILog } from 'types/api/logs/log';
import { PipelineData } from 'types/api/pipeline/def';
@@ -30,8 +29,6 @@ const usePipelinePreview = ({
...l,
// log timestamps in query service API are unix nanos
timestamp: new Date(l.timestamp).getTime() * 10 ** 6,
// the preview API only accepts a string body
body: getBodyDisplay(l.body),
}));
const response = useQuery<PipelineSimulationResponse, AxiosError>({

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