mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-17 22:00:42 +00:00
Compare commits
30 Commits
nv/exec-st
...
feat/servi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
043cb3f64d | ||
|
|
2e7b42e734 | ||
|
|
934866ab9d | ||
|
|
91900ea04e | ||
|
|
7ccc4bff6b | ||
|
|
11f6f7b0e1 | ||
|
|
5c2c814e8a | ||
|
|
2a96645af6 | ||
|
|
0c1560514d | ||
|
|
47e2486639 | ||
|
|
fdd4d8d078 | ||
|
|
079ce982c6 | ||
|
|
900796a573 | ||
|
|
2175611902 | ||
|
|
29d4f7fb8d | ||
|
|
b2991101af | ||
|
|
7a52290c0c | ||
|
|
d5a8c64f1f | ||
|
|
de1edd1f2d | ||
|
|
6429c7a3ea | ||
|
|
f0cde4f37d | ||
|
|
82d7243ad9 | ||
|
|
1efbbcfc5e | ||
|
|
7cef7e48ea | ||
|
|
7189736cea | ||
|
|
8e089a8bd8 | ||
|
|
5b2027ad81 | ||
|
|
ce78251920 | ||
|
|
879b6e4e69 | ||
|
|
f7e78384ed |
28
.github/workflows/e2eci.yaml
vendored
28
.github/workflows/e2eci.yaml
vendored
@@ -2,44 +2,50 @@ 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 }}
|
||||
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) || '' }}
|
||||
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: ${{ contains(github.event.pull_request.labels.*.name, 'safe-to-e2e') }}
|
||||
FORCE: ${{ github.event_name == 'merge_group' || 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 [ "$FORCE" = "true" ]; then
|
||||
echo "e2e=true" >> "$GITHUB_OUTPUT"
|
||||
elif printf '%s\n' "$CHANGED_FILES" | grep -qE "$PATTERN"; then
|
||||
if 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: needs.changes.outputs.e2e == 'true'
|
||||
if: github.event_name != 'merge_group' && needs.changes.outputs.e2e == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
@@ -180,6 +186,8 @@ 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
|
||||
|
||||
3
.github/workflows/integrationci.yaml
vendored
3
.github/workflows/integrationci.yaml
vendored
@@ -40,11 +40,11 @@ jobs:
|
||||
suite:
|
||||
- alertmanager
|
||||
- alertmanagerrotation
|
||||
- auditquerier
|
||||
- basepath
|
||||
- callbackauthn
|
||||
- cloudintegrations
|
||||
- dashboard
|
||||
- fileauditor
|
||||
- ingestionkeys
|
||||
- inframonitoring
|
||||
- llmpricingrules
|
||||
@@ -58,6 +58,7 @@ jobs:
|
||||
- querierscalar
|
||||
- queriercommon
|
||||
- querierai
|
||||
- querieraudit
|
||||
- rawexportdata
|
||||
- promqlconformance
|
||||
- promapiconformance
|
||||
|
||||
23
.github/workflows/jsci.yaml
vendored
23
.github/workflows/jsci.yaml
vendored
@@ -132,3 +132,26 @@ 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)
|
||||
|
||||
35
cmd/authz.go
35
cmd/authz.go
@@ -30,7 +30,7 @@ export default {
|
||||
],
|
||||
relations: {
|
||||
{{- range .Relations }}
|
||||
{{ .Verb }}: [{{ range $i, $t := .Types }}{{ if $i }}, {{ end }}'{{ $t }}'{{ end }}],
|
||||
{{ .FormattedTypes }}
|
||||
{{- end }}
|
||||
},
|
||||
},
|
||||
@@ -38,8 +38,8 @@ export default {
|
||||
`))
|
||||
|
||||
type permissionsTypeRelation struct {
|
||||
Verb string
|
||||
Types []string
|
||||
Verb string
|
||||
FormattedTypes string
|
||||
}
|
||||
|
||||
type permissionsTypeResource struct {
|
||||
@@ -77,6 +77,29 @@ 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",
|
||||
@@ -106,6 +129,8 @@ 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{}
|
||||
@@ -154,8 +179,8 @@ func runGenerateAuthz(_ context.Context) error {
|
||||
types = append(types, t.StringValue())
|
||||
}
|
||||
relations = append(relations, permissionsTypeRelation{
|
||||
Verb: verb.StringValue(),
|
||||
Types: types,
|
||||
Verb: verb.StringValue(),
|
||||
FormattedTypes: formatRelationTypes(verb.StringValue(), types, 3, 80),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -4318,6 +4318,11 @@ 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:
|
||||
@@ -4550,6 +4555,231 @@ 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:
|
||||
@@ -5287,6 +5517,7 @@ 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'
|
||||
@@ -5309,6 +5540,7 @@ components:
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpec'
|
||||
- $ref: '#/components/schemas/DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpec'
|
||||
type: object
|
||||
DashboardtypesPanelPluginKind:
|
||||
enum:
|
||||
@@ -5323,6 +5555,7 @@ components:
|
||||
- signoz/TextPanel
|
||||
- signoz/HeatmapPanel
|
||||
- signoz/ScatterPlotPanel
|
||||
- signoz/GeoMapPanel
|
||||
type: string
|
||||
DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesAreaChartPanelSpec:
|
||||
properties:
|
||||
@@ -5354,6 +5587,21 @@ 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:
|
||||
@@ -11744,8 +11992,9 @@ 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}}. severity
|
||||
is the conventional routing label.
|
||||
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.
|
||||
type: object
|
||||
notificationSettings:
|
||||
allOf:
|
||||
@@ -11862,8 +12111,9 @@ 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}}. severity
|
||||
is the conventional routing label.
|
||||
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.
|
||||
type: object
|
||||
notificationSettings:
|
||||
allOf:
|
||||
@@ -16319,9 +16569,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- org-preference:list
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- org-preference:list
|
||||
summary: List org preferences
|
||||
tags:
|
||||
- preferences
|
||||
@@ -16384,9 +16634,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- org-preference:read
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- org-preference:read
|
||||
summary: Get org preference
|
||||
tags:
|
||||
- preferences
|
||||
@@ -16441,9 +16691,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- org-preference:update
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- org-preference:update
|
||||
summary: Update org preference
|
||||
tags:
|
||||
- preferences
|
||||
@@ -24702,9 +24952,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- organization:read
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- organization:read
|
||||
summary: Get my organization
|
||||
tags:
|
||||
- orgs
|
||||
@@ -24753,9 +25003,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- organization:update
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- organization:update
|
||||
summary: Update my organization
|
||||
tags:
|
||||
- orgs
|
||||
|
||||
@@ -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)
|
||||
```
|
||||
|
||||
@@ -267,9 +267,7 @@ 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()
|
||||
|
||||
for name, value := range r.Labels().Map() {
|
||||
lb.Set(name, expand(value))
|
||||
}
|
||||
lb.SetRuleLabels(r.Labels().Map(), expand)
|
||||
|
||||
lb.Set(ruletypes.AlertNameLabel, r.Name())
|
||||
lb.Set(ruletypes.AlertRuleIDLabel, r.ID())
|
||||
|
||||
@@ -593,16 +593,19 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
// The react-router allowlist: the facade itself, the route table, `useSafeNavigate`,
|
||||
// the history singleton and the test and story router mounts. Test files are
|
||||
// The react-router allowlist: the facade itself, the route table, the router mount,
|
||||
// `useSafeNavigate` 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/storybook/providers/StorybookProviders.tsx",
|
||||
"src/tests/router-utils.ts",
|
||||
"src/storybook/navigation/containment.ts",
|
||||
"src/storybook/navigation/pageScope.ts",
|
||||
"src/storybook/renderAtRoute.tsx"
|
||||
],
|
||||
"rules": {
|
||||
|
||||
@@ -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: `lib/history` must
|
||||
* not catch `lib/historyUtils`.
|
||||
* them to a mock. Regexes so only exact specifiers match: `store` must not
|
||||
* catch `store/actions`.
|
||||
*
|
||||
* 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,11 +17,6 @@ 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$/,
|
||||
|
||||
@@ -192,6 +192,7 @@ const preview: Preview = {
|
||||
'Role Details',
|
||||
'Role Editor',
|
||||
'Members',
|
||||
['Overview', 'Authz'],
|
||||
'Service Accounts',
|
||||
'Ingestion',
|
||||
'Single Sign-on',
|
||||
|
||||
@@ -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|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|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)/)',
|
||||
// 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|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|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)',
|
||||
],
|
||||
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
|
||||
testPathIgnorePatterns: ['/node_modules/', '/public/'],
|
||||
moduleDirectories: ['node_modules', 'src'],
|
||||
testEnvironment: 'jest-environment-jsdom',
|
||||
testEnvironment: '<rootDir>/jest.environment.cjs',
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
statements: 80,
|
||||
|
||||
22
frontend/jest.environment.cjs
Normal file
22
frontend/jest.environment.cjs
Normal file
@@ -0,0 +1,22 @@
|
||||
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;
|
||||
@@ -5,6 +5,8 @@
|
||||
/**
|
||||
* 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';
|
||||
@@ -14,6 +16,14 @@ 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 ||
|
||||
|
||||
@@ -30,7 +30,8 @@
|
||||
"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 */'"
|
||||
"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"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0",
|
||||
@@ -70,7 +71,7 @@
|
||||
"antd": "5.11.0",
|
||||
"antd-table-saveas-excel": "2.2.1",
|
||||
"antlr4": "4.13.2",
|
||||
"axios": "1.21.0",
|
||||
"axios": "1.21.1",
|
||||
"babel-jest": "^29.6.4",
|
||||
"chart.js": "3.9.1",
|
||||
"chartjs-adapter-date-fns": "^2.0.0",
|
||||
@@ -78,17 +79,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.0",
|
||||
"i18next-http-backend": "^4.0.4",
|
||||
"immer": "11.1.3",
|
||||
"jest": "30.2.0",
|
||||
"js-base64": "^3.7.2",
|
||||
@@ -96,6 +97,7 @@
|
||||
"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",
|
||||
@@ -117,8 +119,7 @@
|
||||
"react-query": "3.39.3",
|
||||
"react-redux": "^7.2.2",
|
||||
"react-rnd": "^10.5.3",
|
||||
"react-router-dom": "^5.2.0",
|
||||
"react-router-dom-v5-compat": "6.30.6",
|
||||
"react-router": "7.18.4",
|
||||
"react-syntax-highlighter": "15.5.0",
|
||||
"react-use": "^17.3.2",
|
||||
"react-virtuoso": "4.0.3",
|
||||
@@ -130,12 +131,13 @@
|
||||
"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.3.6",
|
||||
"zod": "4.6.7",
|
||||
"zustand": "5.0.11"
|
||||
},
|
||||
"browserslist": {
|
||||
@@ -170,9 +172,10 @@
|
||||
"@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/history": "4.7.11",
|
||||
"@types/geojson": "7946.0.16",
|
||||
"@types/jest": "30.0.0",
|
||||
"@types/lodash-es": "^4.17.4",
|
||||
"@types/node": "^22.20.5",
|
||||
@@ -183,11 +186,12 @@
|
||||
"@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",
|
||||
@@ -209,6 +213,8 @@
|
||||
"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",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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({
|
||||
@@ -11,11 +10,6 @@ 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';",
|
||||
@@ -49,13 +43,8 @@ await ruleTester({
|
||||
errors: [{ message: MOCK }],
|
||||
},
|
||||
{
|
||||
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');",
|
||||
name: 'jest.doMock of react-router',
|
||||
code: "jest.doMock('react-router');",
|
||||
errors: [{ message: MOCK }],
|
||||
},
|
||||
{
|
||||
@@ -74,29 +63,14 @@ await ruleTester({
|
||||
errors: [{ message: FACADE }],
|
||||
},
|
||||
{
|
||||
name: 'react-router-dom-v5-compat',
|
||||
code: "import { useNavigate } from 'react-router-dom-v5-compat';",
|
||||
errors: [{ message: 'compat package is an implementation detail' }],
|
||||
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: '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: 'require',
|
||||
code: "const router = require('react-router');",
|
||||
errors: [{ message: FACADE }],
|
||||
},
|
||||
{
|
||||
name: 'dynamic import',
|
||||
@@ -116,10 +90,10 @@ await ruleTester({
|
||||
{
|
||||
name: 'one report per import statement',
|
||||
code:
|
||||
"import { Link } from 'react-router-dom';\nimport history from 'lib/history';",
|
||||
"import { Link } from 'react-router';\nimport { Outlet } from 'react-router';",
|
||||
errors: [
|
||||
{ message: FACADE, line: 1 },
|
||||
{ message: HISTORY, line: 2 },
|
||||
{ message: FACADE, line: 2 },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -5,18 +5,14 @@
|
||||
* 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.
|
||||
*
|
||||
* `history` (the package) is deliberately not flagged: it is a transitive concern of
|
||||
* the version bump, not something the facade replaces.
|
||||
* `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.
|
||||
*
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import path from 'node:path';
|
||||
|
||||
const HISTORY_MODULE_SUFFIX = path.join('src', 'lib', 'history');
|
||||
|
||||
const JEST_MODULE_METHODS = new Set([
|
||||
'mock',
|
||||
'doMock',
|
||||
@@ -29,30 +25,12 @@ const JEST_MODULE_METHODS = new Set([
|
||||
]);
|
||||
|
||||
const MESSAGE_IDS = {
|
||||
'react-router': 'v5Router',
|
||||
'react-router-dom': 'v5Router',
|
||||
'react-router-dom-v5-compat': 'v6Compat',
|
||||
'lib/history': 'historySingleton',
|
||||
'@/lib/history': 'historySingleton',
|
||||
'react-router': 'router',
|
||||
'react-router-dom': 'routerDom',
|
||||
};
|
||||
|
||||
/** 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;
|
||||
function messageIdFor(specifier) {
|
||||
return MESSAGE_IDS[specifier] ?? null;
|
||||
}
|
||||
|
||||
export default {
|
||||
@@ -60,17 +38,15 @@ export default {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description:
|
||||
'Disallow direct react-router / lib/history imports; import from src/lib/router instead',
|
||||
'Disallow direct react-router imports; import from src/lib/router instead',
|
||||
category: 'React Router migration',
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
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.',
|
||||
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.',
|
||||
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.',
|
||||
},
|
||||
@@ -85,7 +61,7 @@ export default {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const messageId = messageIdFor(sourceNode.value, context.filename);
|
||||
const messageId = messageIdFor(sourceNode.value);
|
||||
if (messageId !== null) {
|
||||
context.report({
|
||||
node: sourceNode,
|
||||
|
||||
438
frontend/pnpm-lock.yaml
generated
438
frontend/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -45,14 +45,17 @@ 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.6 carries the fix
|
||||
fast-uri@<3.1.6: '>=3.1.6 <4'
|
||||
# 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'
|
||||
# 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'
|
||||
@@ -60,6 +63,12 @@ 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'
|
||||
@@ -67,14 +76,13 @@ 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
|
||||
|
||||
210
frontend/scripts/geo-outlines/build.mjs
Normal file
210
frontend/scripts/geo-outlines/build.mjs
Normal file
@@ -0,0 +1,210 @@
|
||||
// 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;
|
||||
});
|
||||
181
frontend/scripts/geo-outlines/config.mjs
Normal file
181
frontend/scripts/geo-outlines/config.mjs
Normal file
@@ -0,0 +1,181 @@
|
||||
// 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',
|
||||
]);
|
||||
190
frontend/scripts/geo-outlines/countries.mjs
Normal file
190
frontend/scripts/geo-outlines/countries.mjs
Normal file
@@ -0,0 +1,190 @@
|
||||
// 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),
|
||||
},
|
||||
};
|
||||
}
|
||||
118
frontend/scripts/geo-outlines/geometry.mjs
Normal file
118
frontend/scripts/geo-outlines/geometry.mjs
Normal file
@@ -0,0 +1,118 @@
|
||||
// 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 };
|
||||
}
|
||||
202
frontend/scripts/geo-outlines/subdivisions.mjs
Normal file
202
frontend/scripts/geo-outlines/subdivisions.mjs
Normal file
@@ -0,0 +1,202 @@
|
||||
// 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 };
|
||||
}
|
||||
114
frontend/scripts/geo-outlines/validate.mjs
Normal file
114
frontend/scripts/geo-outlines/validate.mjs
Normal file
@@ -0,0 +1,114 @@
|
||||
// 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- ')}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
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';
|
||||
@@ -9,10 +8,14 @@ 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,
|
||||
@@ -25,10 +28,12 @@ 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 = useLocation();
|
||||
const location = useAppLocation();
|
||||
const { pathname } = location;
|
||||
const {
|
||||
org,
|
||||
@@ -47,10 +52,11 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
() =>
|
||||
new Map(
|
||||
[...routes, LIST_LICENSES, SUPPORT_ROUTE].map((e) => {
|
||||
const currentPath = matchPath(pathname, {
|
||||
path: e.path,
|
||||
});
|
||||
return [currentPath === null ? null : 'current', 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];
|
||||
}),
|
||||
),
|
||||
[pathname],
|
||||
@@ -65,9 +71,16 @@ 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) && user.role === 'ADMIN',
|
||||
enabled: !isEmpty(orgData) && canListUsers,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -75,7 +88,7 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
const users = usersData?.data || [];
|
||||
|
||||
const remainingUsers = (Array.isArray(users) ? users : []).filter(
|
||||
(user) => user.email !== 'admin@signoz.cloud',
|
||||
(u) => !isSignozAdminEmail(u.email),
|
||||
);
|
||||
|
||||
return remainingUsers.length === 1;
|
||||
@@ -161,10 +174,9 @@ 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.MEMBERS_SETTINGS ||
|
||||
pathname === ROUTES.MY_SETTINGS));
|
||||
(pathname === ROUTES.ORG_SETTINGS || pathname === ROUTES.MY_SETTINGS));
|
||||
|
||||
if (
|
||||
pathname !== ROUTES.WORKSPACE_LOCKED &&
|
||||
@@ -203,6 +215,7 @@ 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
|
||||
|
||||
29
frontend/src/AppRoutes/RouteGate.tsx
Normal file
29
frontend/src/AppRoutes/RouteGate.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
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 />;
|
||||
}
|
||||
@@ -1,10 +1,25 @@
|
||||
import { ReactElement } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import { MemoryRouter, Route, Switch, useLocation } from 'react-router-dom';
|
||||
import {
|
||||
MemoryRouter,
|
||||
Route,
|
||||
Routes,
|
||||
useLocation,
|
||||
useNavigationType,
|
||||
} from 'react-router';
|
||||
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 {
|
||||
@@ -73,11 +88,13 @@ 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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -237,12 +254,17 @@ function buildPrivateRouteTree(
|
||||
<MemoryRouter initialEntries={[initialRoute]}>
|
||||
<AppContext.Provider value={contextValue}>
|
||||
<PrivateRoute>
|
||||
<Switch>
|
||||
<Route path="*">
|
||||
<div data-testid="children-rendered">Content</div>
|
||||
<LocationDisplay />
|
||||
</Route>
|
||||
</Switch>
|
||||
<Routes>
|
||||
<Route
|
||||
path="*"
|
||||
element={
|
||||
<>
|
||||
<div data-testid="children-rendered">Content</div>
|
||||
<LocationDisplay />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</PrivateRoute>
|
||||
</AppContext.Provider>
|
||||
</MemoryRouter>
|
||||
@@ -505,6 +527,19 @@ 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;
|
||||
|
||||
@@ -629,6 +664,19 @@ 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)', () => {
|
||||
@@ -776,7 +824,7 @@ describe('PrivateRoute', () => {
|
||||
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
|
||||
});
|
||||
|
||||
it('should redirect VIEWER to workspace locked when trying to access members settings', async () => {
|
||||
it('should allow VIEWER to access members settings when workspace is blocked', () => {
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.MEMBERS_SETTINGS,
|
||||
appContext: {
|
||||
@@ -789,7 +837,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertStaysOnRoute(ROUTES.MEMBERS_SETTINGS);
|
||||
});
|
||||
|
||||
it('should redirect VIEWER to workspace locked when trying to access my-settings', async () => {
|
||||
@@ -1089,6 +1137,99 @@ 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,
|
||||
|
||||
85
frontend/src/AppRoutes/__tests__/routeTable.test.tsx
Normal file
85
frontend/src/AppRoutes/__tests__/routeTable.test.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -2,9 +2,9 @@ import type { ErrorEvent, StackFrame } from '@sentry/react';
|
||||
import { AxiosError, AxiosHeaders } from 'axios';
|
||||
|
||||
import {
|
||||
hasNoAppFrames,
|
||||
isInjectedScriptError,
|
||||
isExpectedRequestFailure,
|
||||
isExternalIntegrationError,
|
||||
isThirdPartyScriptError,
|
||||
SENTRY_IGNORE_ERRORS,
|
||||
} from '../sentryFilters';
|
||||
|
||||
@@ -27,7 +27,7 @@ function eventWithFrames(...filenames: string[]): ErrorEvent {
|
||||
};
|
||||
}
|
||||
|
||||
describe('isExternalIntegrationError', () => {
|
||||
describe('isThirdPartyScriptError', () => {
|
||||
it.each([
|
||||
[
|
||||
'PostHog recorder',
|
||||
@@ -39,14 +39,12 @@ describe('isExternalIntegrationError', () => {
|
||||
],
|
||||
['Appcues', 'https://fast.appcues.com/123456.js'],
|
||||
])('drops an error with a %s frame', (_, url) => {
|
||||
expect(isExternalIntegrationError(eventWithFrames(APP_BUNDLE, url))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isThirdPartyScriptError(eventWithFrames(APP_BUNDLE, url))).toBe(true);
|
||||
});
|
||||
|
||||
it('drops it when the top frame is our bundle', () => {
|
||||
expect(
|
||||
isExternalIntegrationError(
|
||||
isThirdPartyScriptError(
|
||||
eventWithFrames(
|
||||
'https://us-assets.i.posthog.com/static/posthog-recorder.js?v=1.298.0',
|
||||
'<anonymous>',
|
||||
@@ -58,13 +56,13 @@ describe('isExternalIntegrationError', () => {
|
||||
|
||||
it('keeps an error from our bundle only', () => {
|
||||
expect(
|
||||
isExternalIntegrationError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
|
||||
isThirdPartyScriptError(eventWithFrames(APP_BUNDLE, '<anonymous>')),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps an error from a host that only contains an integration name', () => {
|
||||
expect(
|
||||
isExternalIntegrationError(
|
||||
isThirdPartyScriptError(
|
||||
eventWithFrames(
|
||||
'https://posthog.example.com/app.js',
|
||||
'https://notusepylon.com/widget.js',
|
||||
@@ -74,11 +72,11 @@ describe('isExternalIntegrationError', () => {
|
||||
});
|
||||
|
||||
it('keeps an error without a stack trace', () => {
|
||||
expect(isExternalIntegrationError({ type: undefined })).toBe(false);
|
||||
expect(isThirdPartyScriptError({ type: undefined })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasNoAppFrames', () => {
|
||||
describe('isInjectedScriptError', () => {
|
||||
const PAGE_URL = 'https://example.us.signoz.cloud/dashboard/01a081e1';
|
||||
|
||||
function eventWithStackFrames(frames: StackFrame[]): ErrorEvent {
|
||||
@@ -92,7 +90,7 @@ describe('hasNoAppFrames', () => {
|
||||
|
||||
it('drops a script appended to the page', () => {
|
||||
expect(
|
||||
hasNoAppFrames(
|
||||
isInjectedScriptError(
|
||||
eventWithStackFrames([
|
||||
{ filename: PAGE_URL, lineno: 1, colno: 30, function: 'global code' },
|
||||
{ filename: '[native code]', function: 'eval' },
|
||||
@@ -104,7 +102,7 @@ describe('hasNoAppFrames', () => {
|
||||
|
||||
it('drops a browser extension error', () => {
|
||||
expect(
|
||||
hasNoAppFrames(
|
||||
isInjectedScriptError(
|
||||
eventWithStackFrames([
|
||||
{ filename: 'chrome-extension://abc/content.js', lineno: 4, colno: 12 },
|
||||
]),
|
||||
@@ -112,21 +110,46 @@ describe('hasNoAppFrames', () => {
|
||||
).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(hasNoAppFrames(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(false);
|
||||
expect(isInjectedScriptError(eventWithFrames(PAGE_URL, APP_BUNDLE))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps an error without a stack trace', () => {
|
||||
expect(hasNoAppFrames({ type: undefined })).toBe(false);
|
||||
expect(isInjectedScriptError({ type: undefined })).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps an error whose frames have no position', () => {
|
||||
expect(
|
||||
hasNoAppFrames(
|
||||
isInjectedScriptError(
|
||||
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', () => {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
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 {
|
||||
ReactNode,
|
||||
Suspense,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { Outlet } from 'react-router';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import getLocalStorageApi from 'api/browser/localstorage/get';
|
||||
import setLocalStorageApi from 'api/browser/localstorage/set';
|
||||
@@ -9,7 +15,6 @@ 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';
|
||||
@@ -23,7 +28,7 @@ import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
import { IS_PROD } from 'lib/env';
|
||||
import history from 'lib/history';
|
||||
import { getCurrentLocation, navigate, subscribe } from 'lib/router/navigation';
|
||||
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
|
||||
import posthog from 'posthog-js';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
@@ -31,26 +36,20 @@ 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 {
|
||||
hasNoAppFrames,
|
||||
isInjectedScriptError,
|
||||
isExpectedRequestFailure,
|
||||
isExternalIntegrationError,
|
||||
isThirdPartyScriptError,
|
||||
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>
|
||||
);
|
||||
@@ -71,18 +70,24 @@ 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;
|
||||
const [pathname, setPathname] = useState(history.location.pathname);
|
||||
// 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 { isCloudUser, isEnterpriseSelfHostedUser } = useGetTenantLicense();
|
||||
|
||||
const [isSentryInitialized, setIsSentryInitialized] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
return history.listen((location) => {
|
||||
return subscribe(({ location }) => {
|
||||
setPathname(location.pathname);
|
||||
});
|
||||
}, []);
|
||||
@@ -355,12 +360,12 @@ function App(): JSX.Element {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isExternalIntegrationError(event)) {
|
||||
if (isThirdPartyScriptError(event)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Dev serves source from /src/, so every frame would look foreign there.
|
||||
if (IS_PROD && hasNoAppFrames(event)) {
|
||||
if (IS_PROD && isInjectedScriptError(event)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -402,7 +407,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) {
|
||||
history.replace(ROUTES.SOMETHING_WENT_WRONG);
|
||||
navigate(ROUTES.SOMETHING_WENT_WRONG, { replace: true });
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -418,7 +423,6 @@ function App(): JSX.Element {
|
||||
return (
|
||||
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
|
||||
<AppShell
|
||||
router={appRouter}
|
||||
overlays={
|
||||
isLoggedInState && (
|
||||
<>
|
||||
@@ -431,18 +435,7 @@ function App(): JSX.Element {
|
||||
<PrivateRoute>
|
||||
<AppPageProviders layout={appLayout}>
|
||||
<Suspense fallback={<Spinner size="large" tip="Loading..." />}>
|
||||
<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>
|
||||
<Outlet context={enabledRouteKeys} />
|
||||
</Suspense>
|
||||
</AppPageProviders>
|
||||
</PrivateRoute>
|
||||
|
||||
46
frontend/src/AppRoutes/routeTable.tsx
Normal file
46
frontend/src/AppRoutes/routeTable.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
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 /> },
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { RouteProps } from 'react-router-dom';
|
||||
import type { ComponentType } from 'react';
|
||||
import ROUTES from 'constants/routes';
|
||||
|
||||
import {
|
||||
@@ -58,27 +58,25 @@ const routes: AppRoutes[] = [
|
||||
{
|
||||
component: SignupPage,
|
||||
path: ROUTES.SIGN_UP,
|
||||
exact: true,
|
||||
isPrivate: false,
|
||||
key: 'SIGN_UP',
|
||||
},
|
||||
{
|
||||
path: ROUTES.GET_STARTED_WITH_CLOUD,
|
||||
exact: false,
|
||||
nested: true,
|
||||
component: OnboardingV2,
|
||||
isPrivate: true,
|
||||
key: 'GET_STARTED_WITH_CLOUD',
|
||||
},
|
||||
{
|
||||
path: ROUTES.HOME,
|
||||
exact: true,
|
||||
component: Home,
|
||||
isPrivate: true,
|
||||
key: 'HOME',
|
||||
},
|
||||
{
|
||||
path: ROUTES.ONBOARDING,
|
||||
exact: false,
|
||||
nested: true,
|
||||
component: OrgOnboarding,
|
||||
isPrivate: true,
|
||||
key: 'ONBOARDING',
|
||||
@@ -86,27 +84,23 @@ 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',
|
||||
@@ -115,292 +109,252 @@ 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,
|
||||
exact: false,
|
||||
nested: true,
|
||||
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,
|
||||
exact: false,
|
||||
nested: true,
|
||||
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,
|
||||
@@ -408,56 +362,48 @@ 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,
|
||||
@@ -466,7 +412,6 @@ const routes: AppRoutes[] = [
|
||||
|
||||
export const SUPPORT_ROUTE: AppRoutes = {
|
||||
path: ROUTES.SUPPORT,
|
||||
exact: true,
|
||||
component: SupportPage,
|
||||
key: 'SUPPORT',
|
||||
isPrivate: true,
|
||||
@@ -474,7 +419,6 @@ export const SUPPORT_ROUTE: AppRoutes = {
|
||||
|
||||
export const LIST_LICENSES: AppRoutes = {
|
||||
path: ROUTES.LIST_LICENSES,
|
||||
exact: true,
|
||||
component: LicensePage,
|
||||
isPrivate: true,
|
||||
key: 'LIST_LICENSES',
|
||||
@@ -506,9 +450,15 @@ export const ROUTES_NOT_TO_BE_OVERRIDEN: string[] = [
|
||||
];
|
||||
|
||||
export interface AppRoutes {
|
||||
component: RouteProps['component'];
|
||||
path: RouteProps['path'];
|
||||
exact: RouteProps['exact'];
|
||||
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;
|
||||
isPrivate: boolean;
|
||||
key: keyof typeof ROUTES;
|
||||
}
|
||||
|
||||
@@ -28,10 +28,15 @@ export function isExpectedRequestFailure(error: unknown): boolean {
|
||||
}
|
||||
|
||||
const APP_ASSETS_PATH = '/assets/';
|
||||
const ANONYMOUS_FILENAME = '<anonymous>';
|
||||
|
||||
// Frames without a position are `[native code]`, which says nothing about the
|
||||
// script that threw.
|
||||
export function hasNoAppFrames(event: ErrorEvent): boolean {
|
||||
// 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 {
|
||||
const frames = (event.exception?.values ?? [])
|
||||
.flatMap((exception) => exception.stacktrace?.frames ?? [])
|
||||
.filter(
|
||||
@@ -40,12 +45,13 @@ export function hasNoAppFrames(event: ErrorEvent): boolean {
|
||||
|
||||
return (
|
||||
frames.length > 0 &&
|
||||
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH))
|
||||
(frames[frames.length - 1].filename === ANONYMOUS_FILENAME ||
|
||||
!frames.some((frame) => frame.filename?.includes(APP_ASSETS_PATH)))
|
||||
);
|
||||
}
|
||||
|
||||
// PostHog's lazy recorder, the Pylon widget and Appcues.
|
||||
const EXTERNAL_SCRIPT_URLS = [
|
||||
const THIRD_PARTY_SCRIPT_URLS = [
|
||||
/^https?:\/\/[^/]+\.posthog\.com\//,
|
||||
/^https?:\/\/(?:[^/]+\.)?usepylon\.com\//,
|
||||
/^https?:\/\/(?:[^/]+\.)?appcues\.(?:com|net)\//,
|
||||
@@ -53,10 +59,10 @@ const EXTERNAL_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 isExternalIntegrationError(event: ErrorEvent): boolean {
|
||||
export function isThirdPartyScriptError(event: ErrorEvent): boolean {
|
||||
return (event.exception?.values ?? []).some((exception) =>
|
||||
(exception.stacktrace?.frames ?? []).some((frame) =>
|
||||
EXTERNAL_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
|
||||
THIRD_PARTY_SCRIPT_URLS.some((url) => url.test(frame.filename ?? '')),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5660,6 +5660,13 @@ export interface DashboardtypesBasicVisualizationDTO {
|
||||
timePreference?: DashboardtypesTimePreferenceDTO;
|
||||
}
|
||||
|
||||
/**
|
||||
* @minimum 1
|
||||
* @maximum 64
|
||||
* @nullable
|
||||
*/
|
||||
export type DashboardtypesBubbleRadiusDTO = number | null;
|
||||
|
||||
export interface Querybuildertypesv5LogAggregationDTO {
|
||||
/**
|
||||
* @type string
|
||||
@@ -6943,6 +6950,246 @@ 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
|
||||
@@ -6954,7 +7201,8 @@ export type DashboardtypesPanelPluginDTO =
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTextPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesHeatmapPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO;
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesScatterPlotPanelSpecDTO
|
||||
| DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesGeoMapPanelSpecDTO;
|
||||
|
||||
export enum Querybuildertypesv5RequestTypeDTO {
|
||||
scalar = 'scalar',
|
||||
@@ -8241,6 +8489,7 @@ 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.
|
||||
@@ -12907,7 +13156,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}}. severity is the conventional routing label.
|
||||
* 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.
|
||||
*/
|
||||
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
|
||||
|
||||
@@ -13024,7 +13273,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}}. severity is the conventional routing label.
|
||||
* @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.
|
||||
*/
|
||||
labels?: RuletypesPostableRuleDTOLabels;
|
||||
/**
|
||||
@@ -13057,7 +13306,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}}. severity is the conventional routing label.
|
||||
* 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.
|
||||
*/
|
||||
export type RuletypesRuleDTOLabels = { [key: string]: string };
|
||||
|
||||
@@ -13116,7 +13365,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}}. severity is the conventional routing label.
|
||||
* @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.
|
||||
*/
|
||||
labels?: RuletypesRuleDTOLabels;
|
||||
/**
|
||||
|
||||
@@ -54,6 +54,7 @@ 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';
|
||||
@@ -277,7 +278,8 @@ export function createAggregation(
|
||||
(panelType === PANEL_TYPES.TABLE ||
|
||||
panelType === PANEL_TYPES.SCATTER ||
|
||||
panelType === PANEL_TYPES.PIE ||
|
||||
panelType === PANEL_TYPES.VALUE);
|
||||
panelType === PANEL_TYPES.VALUE ||
|
||||
panelType === PANEL_TYPES.GEO_MAP);
|
||||
|
||||
if (queryData.dataSource === DataSource.METRICS) {
|
||||
return [
|
||||
@@ -297,6 +299,10 @@ export function createAggregation(
|
||||
reduceTo: haveReduceTo
|
||||
? queryData?.aggregations?.[0]?.reduceTo || queryData?.reduceTo
|
||||
: undefined,
|
||||
...(queryData?.aggregations?.[0]?.comparisonSpaceAggregationParam && {
|
||||
comparisonSpaceAggregationParam:
|
||||
queryData.aggregations[0].comparisonSpaceAggregationParam,
|
||||
}),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -27,6 +27,10 @@ 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,
|
||||
|
||||
17
frontend/src/app/AppRouterProvider.tsx
Normal file
17
frontend/src/app/AppRouterProvider.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
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} />;
|
||||
}
|
||||
@@ -5,11 +5,8 @@ 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;
|
||||
}
|
||||
@@ -19,28 +16,26 @@ 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 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.
|
||||
* 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`.
|
||||
*
|
||||
* `ConfigProvider` reads `useThemeConfig`, which needs `ThemeProvider` above it,
|
||||
* so the antd theme is settled here instead of by the caller.
|
||||
*/
|
||||
function AppShell({ children, router, overlays }: AppShellProps): JSX.Element {
|
||||
function AppShell({ children, overlays }: AppShellProps): JSX.Element {
|
||||
const themeConfig = useThemeConfig();
|
||||
|
||||
return (
|
||||
<ConfigProvider theme={themeConfig}>
|
||||
{router(
|
||||
<CmdKProvider>
|
||||
<NotificationProvider>
|
||||
<ErrorModalProvider>
|
||||
{overlays}
|
||||
{children}
|
||||
</ErrorModalProvider>
|
||||
</NotificationProvider>
|
||||
</CmdKProvider>,
|
||||
)}
|
||||
<CmdKProvider>
|
||||
<NotificationProvider>
|
||||
<ErrorModalProvider>
|
||||
{overlays}
|
||||
{children}
|
||||
</ErrorModalProvider>
|
||||
</NotificationProvider>
|
||||
</CmdKProvider>
|
||||
</ConfigProvider>
|
||||
);
|
||||
}
|
||||
|
||||
19
frontend/src/app/createAppRouter.ts
Normal file
19
frontend/src/app/createAppRouter.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
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 {
|
||||
@@ -17,6 +18,7 @@ export interface SelectOptionConfig {
|
||||
placeholder: string;
|
||||
queryParam: QueryParams;
|
||||
filterType: string | string[];
|
||||
fieldContext?: TelemetrytypesFieldContextDTO;
|
||||
shouldSetQueryParams?: boolean;
|
||||
onChange?: (value: string | string[]) => void;
|
||||
values?: string | string[];
|
||||
@@ -27,13 +29,16 @@ export function FilterSelect({
|
||||
placeholder,
|
||||
queryParam,
|
||||
filterType,
|
||||
fieldContext,
|
||||
values,
|
||||
shouldSetQueryParams,
|
||||
onChange,
|
||||
isMultiple,
|
||||
}: SelectOptionConfig): JSX.Element {
|
||||
const { handleSearch, isFetching, options } =
|
||||
useCeleryFilterOptions(filterType);
|
||||
const { handleSearch, isFetching, options } = useCeleryFilterOptions(
|
||||
filterType,
|
||||
fieldContext,
|
||||
);
|
||||
|
||||
const urlQuery = useUrlQuery();
|
||||
const location = useAppLocation();
|
||||
@@ -118,6 +123,7 @@ export function FilterSelect({
|
||||
}
|
||||
|
||||
FilterSelect.defaultProps = {
|
||||
fieldContext: undefined,
|
||||
shouldSetQueryParams: true,
|
||||
onChange: (): void => {},
|
||||
values: [],
|
||||
@@ -129,12 +135,14 @@ function CeleryOverviewConfigOptions(): JSX.Element {
|
||||
{
|
||||
placeholder: 'Service Name',
|
||||
queryParam: QueryParams.service,
|
||||
filterType: 'serviceName',
|
||||
filterType: 'service.name',
|
||||
fieldContext: TelemetrytypesFieldContextDTO.resource,
|
||||
},
|
||||
{
|
||||
placeholder: 'Span Name',
|
||||
queryParam: QueryParams.spanName,
|
||||
filterType: 'name',
|
||||
fieldContext: TelemetrytypesFieldContextDTO.span,
|
||||
},
|
||||
{
|
||||
placeholder: 'Msg System',
|
||||
@@ -162,6 +170,7 @@ function CeleryOverviewConfigOptions(): JSX.Element {
|
||||
placeholder={config.placeholder}
|
||||
queryParam={config.queryParam}
|
||||
filterType={config.filterType}
|
||||
fieldContext={config.fieldContext}
|
||||
/>
|
||||
))}
|
||||
</Row>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,23 +1,21 @@
|
||||
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 { getAttributesValues } from 'api/queryBuilder/getAttributesValues';
|
||||
import { DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY } from 'constants/queryBuilder';
|
||||
import type { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { getFieldValueSuggestions } from 'api/querySuggestions/getFieldValueSuggestions';
|
||||
import { FIELD_API_CACHE_TIME } from 'constants/queryCacheTime';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { toFieldValues } from 'hooks/querySuggestions/useFieldValuesSuggestion';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
import { DATA_SOURCE_TO_SIGNAL, DataSource } from 'types/common/queryBuilder';
|
||||
import { getValuesForDataType } from 'utils/fieldValues';
|
||||
|
||||
export interface Filters {
|
||||
searchText: string;
|
||||
attributeKey: string | string[];
|
||||
aggregateOperator?: string;
|
||||
dataSource?: DataSource;
|
||||
aggregateAttribute?: string;
|
||||
metricName?: string;
|
||||
filterAttributeKeyDataType?: DataTypes;
|
||||
tagType?: string;
|
||||
fieldContext?: TelemetrytypesFieldContextDTO;
|
||||
}
|
||||
|
||||
export interface GetAllFiltersResponse {
|
||||
@@ -29,54 +27,41 @@ export function useGetAllFilters(props: Filters): GetAllFiltersResponse {
|
||||
const {
|
||||
searchText,
|
||||
attributeKey,
|
||||
aggregateOperator,
|
||||
dataSource,
|
||||
aggregateAttribute,
|
||||
metricName,
|
||||
filterAttributeKeyDataType,
|
||||
tagType,
|
||||
fieldContext,
|
||||
} = 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) =>
|
||||
getAttributesValues({
|
||||
aggregateOperator: aggregateOperator || 'noop',
|
||||
dataSource: dataSource || DataSource.TRACES,
|
||||
aggregateAttribute: aggregateAttribute || '',
|
||||
attributeKey: key,
|
||||
getFieldValueSuggestions({
|
||||
signal: DATA_SOURCE_TO_SIGNAL[dataSource || DataSource.TRACES],
|
||||
name: key,
|
||||
fieldContext,
|
||||
searchText: searchText ?? '',
|
||||
filterAttributeKeyDataType:
|
||||
filterAttributeKeyDataType || DataTypes.String,
|
||||
tagType: tagType || 'tag',
|
||||
metricName,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const uniqueValues = [
|
||||
...new Set(
|
||||
responses.flatMap(({ payload }) => {
|
||||
if (!payload) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const dataType = filterAttributeKeyDataType || DataTypes.String;
|
||||
const key = DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY[dataType];
|
||||
return key ? payload[key] || [] : [];
|
||||
}),
|
||||
responses.flatMap((response) =>
|
||||
getValuesForDataType(toFieldValues(response), filterAttributeKeyDataType),
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
@@ -85,6 +70,7 @@ export function useGetAllFilters(props: Filters): GetAllFiltersResponse {
|
||||
value: val,
|
||||
}));
|
||||
},
|
||||
{ staleTime: FIELD_API_CACHE_TIME },
|
||||
);
|
||||
|
||||
return { options: data ?? [], isFetching: isLoading };
|
||||
|
||||
@@ -8,12 +8,9 @@ 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 {
|
||||
@@ -23,6 +20,7 @@ import {
|
||||
celeryTasksByWorkerWidgetData,
|
||||
} from './CeleryTaskGraphUtils';
|
||||
import CeleryTaskLatencyGraph from './CeleryTaskLatencyGraph';
|
||||
import { useCeleryWorkerCount } from './useCeleryWorkerCount';
|
||||
|
||||
import './CeleryTaskGraph.style.scss';
|
||||
|
||||
@@ -71,14 +69,7 @@ export default function CeleryTaskGraphGrid({
|
||||
'Latency by worker',
|
||||
];
|
||||
|
||||
const { options } = useCeleryFilterOptions(
|
||||
'worker',
|
||||
'rate',
|
||||
DataSource.METRICS,
|
||||
'flower_task_runtime_seconds_sum',
|
||||
DataTypes.String,
|
||||
'tag',
|
||||
);
|
||||
const { data: workerCount } = useCeleryWorkerCount();
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
const [collapsedSections, setCollapsedSections] = useState<{
|
||||
@@ -151,8 +142,11 @@ export default function CeleryTaskGraphGrid({
|
||||
</Typography.Text>
|
||||
</div>
|
||||
<div className="worker-count-text-container">
|
||||
<Typography.Text className="celery-task-graph-worker-count-text">
|
||||
{options.filter((option) => option.value).length}
|
||||
<Typography.Text
|
||||
className="celery-task-graph-worker-count-text"
|
||||
data-testid="celery-worker-count"
|
||||
>
|
||||
{workerCount ?? '-'}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
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';
|
||||
@@ -1042,3 +1051,34 @@ 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' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
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' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -1,18 +1,13 @@
|
||||
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[],
|
||||
aggregateOperator?: string,
|
||||
dataSource?: DataSource,
|
||||
aggregateAttribute?: string,
|
||||
filterAttributeKeyDataType?: DataTypes,
|
||||
tagType?: string,
|
||||
fieldContext?: TelemetrytypesFieldContextDTO,
|
||||
): {
|
||||
searchText: string;
|
||||
handleSearch: (value: string) => void;
|
||||
@@ -23,11 +18,7 @@ export const useCeleryFilterOptions = (
|
||||
const { isFetching, options } = useGetAllFilters({
|
||||
attributeKey: type,
|
||||
searchText,
|
||||
aggregateOperator,
|
||||
dataSource,
|
||||
aggregateAttribute,
|
||||
filterAttributeKeyDataType,
|
||||
tagType,
|
||||
fieldContext,
|
||||
});
|
||||
const handleDebouncedSearch = useDebouncedFn((searchText): void => {
|
||||
setSearchText(searchText as string);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import { LockKeyhole, RefreshCw, Trash2, X } from '@signozhq/icons';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
@@ -39,6 +39,17 @@ 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 =
|
||||
@@ -59,6 +70,7 @@ function getDeleteTooltip(
|
||||
|
||||
function getInviteButtonLabel(
|
||||
isLoading: boolean,
|
||||
canListPassword: boolean,
|
||||
existingToken: { expiresAt?: string } | undefined,
|
||||
isExpired: boolean,
|
||||
notFound: boolean,
|
||||
@@ -66,6 +78,9 @@ function getInviteButtonLabel(
|
||||
if (isLoading) {
|
||||
return 'Checking invite...';
|
||||
}
|
||||
if (!canListPassword) {
|
||||
return 'Invite Link Unavailable';
|
||||
}
|
||||
if (existingToken && !isExpired) {
|
||||
return 'Copy Invite Link';
|
||||
}
|
||||
@@ -87,7 +102,6 @@ function toSaveApiError(err: unknown): APIError {
|
||||
|
||||
export interface EditMemberDrawerProps {
|
||||
member: MemberRow | null;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onComplete: () => void;
|
||||
}
|
||||
@@ -95,7 +109,6 @@ export interface EditMemberDrawerProps {
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
function EditMemberDrawer({
|
||||
member,
|
||||
open,
|
||||
onClose,
|
||||
onComplete,
|
||||
}: EditMemberDrawerProps): JSX.Element {
|
||||
@@ -119,16 +132,47 @@ 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: open && !!member?.id } },
|
||||
);
|
||||
} = useGetUser({ id: member?.id ?? '' }, { query: { enabled: canReadUser } });
|
||||
|
||||
const isRootUser = !!fetchedUser?.data?.isRoot;
|
||||
|
||||
@@ -144,7 +188,7 @@ function EditMemberDrawer({
|
||||
currentRoles: currentMemberRoles,
|
||||
isLoading: isMemberRolesLoading,
|
||||
applyDiff,
|
||||
} = useMemberRoleManager(member?.id ?? '', open && !!member?.id);
|
||||
} = useMemberRoleManager(member?.id ?? '', canReadUser);
|
||||
|
||||
// Token status query for invited users
|
||||
const {
|
||||
@@ -153,7 +197,7 @@ function EditMemberDrawer({
|
||||
isError: tokenNotFound,
|
||||
} = useGetResetPasswordToken(
|
||||
{ id: member?.id ?? '' },
|
||||
{ query: { enabled: open && !!member?.id && isInvited } },
|
||||
{ query: { enabled: !!member?.id && isInvited && canListPassword } },
|
||||
);
|
||||
|
||||
const existingToken = tokenQueryData?.data;
|
||||
@@ -187,13 +231,17 @@ function EditMemberDrawer({
|
||||
useEffect(() => {
|
||||
if (!member?.id) {
|
||||
roleSessionRef.current = null;
|
||||
} else if (member.id !== roleSessionRef.current && !isMemberRolesLoading) {
|
||||
} else if (
|
||||
canReadUser &&
|
||||
member.id !== roleSessionRef.current &&
|
||||
!isMemberRolesLoading
|
||||
) {
|
||||
setLocalRoles(
|
||||
currentMemberRoles.map((r) => r.id).filter(Boolean) as string[],
|
||||
);
|
||||
roleSessionRef.current = member.id;
|
||||
}
|
||||
}, [member?.id, currentMemberRoles, isMemberRolesLoading]);
|
||||
}, [member?.id, canReadUser, currentMemberRoles, isMemberRolesLoading]);
|
||||
|
||||
const isDirty =
|
||||
member !== null &&
|
||||
@@ -463,6 +511,31 @@ 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 }} />
|
||||
) : (
|
||||
@@ -471,7 +544,11 @@ function EditMemberDrawer({
|
||||
<label className="edit-member-drawer__label" htmlFor="member-name">
|
||||
Name
|
||||
</label>
|
||||
<Tooltip title={isRootUser ? ROOT_USER_TOOLTIP : undefined}>
|
||||
|
||||
<AuthZTooltip
|
||||
checks={member && !isSelf ? [buildUserUpdatePermission(member.id)] : []}
|
||||
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : undefined}
|
||||
>
|
||||
<Input
|
||||
id="member-name"
|
||||
value={localDisplayName}
|
||||
@@ -484,7 +561,7 @@ function EditMemberDrawer({
|
||||
placeholder="Enter name"
|
||||
disabled={isRootUser || isDeleted}
|
||||
/>
|
||||
</Tooltip>
|
||||
</AuthZTooltip>
|
||||
</div>
|
||||
|
||||
<div className="edit-member-drawer__field">
|
||||
@@ -503,17 +580,12 @@ function EditMemberDrawer({
|
||||
<label className="edit-member-drawer__label" htmlFor="member-role">
|
||||
Roles
|
||||
</label>
|
||||
{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">
|
||||
{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"
|
||||
>
|
||||
<div className="edit-member-drawer__disabled-roles">
|
||||
{localRoles.length > 0 ? (
|
||||
localRoles.map((roleId) => {
|
||||
@@ -620,42 +692,33 @@ function EditMemberDrawer({
|
||||
{!isDeleted && (
|
||||
<>
|
||||
<div className="edit-member-drawer__footer-left">
|
||||
<Button
|
||||
<AuthZButton
|
||||
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'}
|
||||
</Button>
|
||||
</AuthZButton>
|
||||
|
||||
<div className="edit-member-drawer__footer-divider" />
|
||||
<Button
|
||||
disabledTooltip={ROOT_USER_TOOLTIP}
|
||||
<AuthZButton
|
||||
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : undefined}
|
||||
size="md"
|
||||
onClick={handleGenerateResetLink}
|
||||
testId="member-reset-link-btn"
|
||||
disabled={isRootUser}
|
||||
loading={isGeneratingLink || isLoadingTokenStatus}
|
||||
variant="link"
|
||||
color="warning"
|
||||
checks={resetLinkChecks}
|
||||
prefix={<RefreshCw size={12} />}
|
||||
>
|
||||
{isGeneratingLink
|
||||
? 'Generating...'
|
||||
: isInvited
|
||||
? getInviteButtonLabel(
|
||||
isLoadingTokenStatus,
|
||||
existingToken,
|
||||
isTokenExpired,
|
||||
tokenNotFound,
|
||||
)
|
||||
: 'Generate Password Reset Link'}
|
||||
</Button>
|
||||
{inviteLinkAndResetPasswordText}
|
||||
</AuthZButton>
|
||||
</div>
|
||||
|
||||
<div className="edit-member-drawer__footer-right">
|
||||
@@ -669,18 +732,25 @@ function EditMemberDrawer({
|
||||
Cancel
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
disabledTooltip={isRootUser ? ROOT_USER_TOOLTIP : 'No changes to save'}
|
||||
<AuthZButton
|
||||
disabledTooltip={
|
||||
isRootUser
|
||||
? ROOT_USER_TOOLTIP
|
||||
: !isDirty
|
||||
? 'No changes to save'
|
||||
: undefined
|
||||
}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
disabled={!isDirty || isRootUser}
|
||||
onClick={handleSave}
|
||||
checks={[]}
|
||||
testId="member-save-btn"
|
||||
loading={isSaving}
|
||||
>
|
||||
{isSaving ? 'Saving...' : 'Save Member Details'}
|
||||
</Button>
|
||||
</AuthZButton>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
@@ -690,7 +760,7 @@ function EditMemberDrawer({
|
||||
return (
|
||||
<>
|
||||
<DrawerWrapper
|
||||
open={open}
|
||||
open={member !== null}
|
||||
onOpenChange={(isOpen): void => {
|
||||
if (!isOpen) {
|
||||
handleClose();
|
||||
@@ -703,7 +773,12 @@ function EditMemberDrawer({
|
||||
footer={footer}
|
||||
width="wide"
|
||||
>
|
||||
{drawerContent}
|
||||
<AuthZGuardContent
|
||||
checks={member ? [buildUserReadPermission(member?.id)] : []}
|
||||
fallbackOnLoading={<Skeleton active paragraph={{ rows: 6 }} />}
|
||||
>
|
||||
{drawerContent}
|
||||
</AuthZGuardContent>
|
||||
</DrawerWrapper>
|
||||
|
||||
<ResetLinkDialog
|
||||
|
||||
@@ -17,6 +17,16 @@ 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';
|
||||
@@ -168,7 +178,6 @@ function renderDrawer(
|
||||
return render(
|
||||
<EditMemberDrawer
|
||||
member={activeMember}
|
||||
open
|
||||
onClose={jest.fn()}
|
||||
onComplete={jest.fn()}
|
||||
{...props}
|
||||
@@ -176,6 +185,16 @@ 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();
|
||||
@@ -186,6 +205,7 @@ describe('EditMemberDrawer', () => {
|
||||
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
|
||||
),
|
||||
setupAuthzAdmin(),
|
||||
);
|
||||
(useGetUser as jest.Mock).mockReturnValue({
|
||||
data: mockFetchedUser,
|
||||
@@ -243,15 +263,33 @@ describe('EditMemberDrawer', () => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('renders active member details and disables Save when form is not dirty', () => {
|
||||
it('renders active member details and disables Save when form is not dirty', async () => {
|
||||
renderDrawer();
|
||||
|
||||
expect(screen.getByDisplayValue('Alice Smith')).toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByDisplayValue('Alice Smith'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText('alice@signoz.io')).toBeInTheDocument();
|
||||
expect(screen.getByText('ACTIVE')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: /save member details/i }),
|
||||
).toHaveAttribute('aria-disabled', 'true');
|
||||
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 } },
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('enables Save after editing name and calls updateUser on confirm', async () => {
|
||||
@@ -266,7 +304,8 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ onComplete });
|
||||
|
||||
const nameInput = screen.getByDisplayValue('Alice Smith');
|
||||
const nameInput = await screen.findByDisplayValue('Alice Smith');
|
||||
await waitFor(() => expect(nameInput).toBeEnabled());
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Alice Updated');
|
||||
|
||||
@@ -292,7 +331,8 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ onClose });
|
||||
|
||||
const nameInput = screen.getByDisplayValue('Alice Smith');
|
||||
const nameInput = await screen.findByDisplayValue('Alice Smith');
|
||||
await waitFor(() => expect(nameInput).toBeEnabled());
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Alice Updated');
|
||||
|
||||
@@ -323,7 +363,7 @@ describe('EditMemberDrawer', () => {
|
||||
renderDrawer({ onComplete });
|
||||
|
||||
// signoz-admin is already selected; add signoz-editor on top
|
||||
await user.click(screen.getByLabelText('Roles'));
|
||||
await user.click(await screen.findByLabelText('Roles'));
|
||||
await user.click(await screen.findByTitle('signoz-editor'));
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /save member details/i });
|
||||
@@ -381,7 +421,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ onComplete });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /delete member/i }));
|
||||
await clickDeleteButton(user);
|
||||
|
||||
await expect(
|
||||
screen.findByText(/are you sure you want to delete/i),
|
||||
@@ -398,9 +438,11 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('shows revoke invite and copy invite link for invited members; hides Last Modified', () => {
|
||||
it('shows revoke invite and copy invite link for invited members; hides Last Modified', async () => {
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
await screen.findByText('Invited On');
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /revoke invite/i }),
|
||||
).toBeInTheDocument();
|
||||
@@ -414,7 +456,7 @@ describe('EditMemberDrawer', () => {
|
||||
expect(screen.queryByText('Last Modified')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "Regenerate Invite Link" when token is expired', () => {
|
||||
it('shows "Regenerate Invite Link" when token is expired', async () => {
|
||||
(useGetResetPasswordToken as jest.Mock).mockReturnValue({
|
||||
data: {
|
||||
data: {
|
||||
@@ -429,12 +471,12 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /regenerate invite link/i }),
|
||||
).toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByRole('button', { name: /regenerate invite link/i }),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "Generate Invite Link" when no token exists', () => {
|
||||
it('shows "Generate Invite Link" when no token exists', async () => {
|
||||
(useGetResetPasswordToken as jest.Mock).mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
@@ -443,9 +485,88 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /generate invite link/i }),
|
||||
).toBeInTheDocument();
|
||||
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',
|
||||
);
|
||||
});
|
||||
|
||||
it('calls deleteUser after confirming revoke invite for invited members', async () => {
|
||||
@@ -461,7 +582,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ member: invitedMember, onComplete });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /revoke invite/i }));
|
||||
await clickDeleteButton(user);
|
||||
|
||||
await expect(
|
||||
screen.findByText(/Are you sure you want to revoke the invite/i),
|
||||
@@ -508,7 +629,8 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ member: { ...invitedMember, name: 'Bob' }, onComplete });
|
||||
|
||||
const nameInput = screen.getByDisplayValue('Bob');
|
||||
const nameInput = await screen.findByDisplayValue('Bob');
|
||||
await waitFor(() => expect(nameInput).toBeEnabled());
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Bob Updated');
|
||||
|
||||
@@ -546,7 +668,8 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer();
|
||||
|
||||
const nameInput = screen.getByDisplayValue('Alice Smith');
|
||||
const nameInput = await screen.findByDisplayValue('Alice Smith');
|
||||
await waitFor(() => expect(nameInput).toBeEnabled());
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Alice Updated');
|
||||
|
||||
@@ -575,7 +698,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /delete member/i }));
|
||||
await clickDeleteButton(user);
|
||||
const confirmBtns = screen.getAllByRole('button', {
|
||||
name: /delete member/i,
|
||||
});
|
||||
@@ -606,7 +729,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer({ member: invitedMember });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /revoke invite/i }));
|
||||
await clickDeleteButton(user);
|
||||
const confirmBtns = screen.getAllByRole('button', {
|
||||
name: /revoke invite/i,
|
||||
});
|
||||
@@ -645,16 +768,86 @@ describe('EditMemberDrawer', () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps name input enabled when viewing own profile', () => {
|
||||
it('keeps name input enabled when viewing own profile', async () => {
|
||||
renderDrawer({ member: selfMember });
|
||||
expect(screen.getByDisplayValue('Alice Smith')).not.toBeDisabled();
|
||||
await expect(
|
||||
screen.findByDisplayValue('Alice Smith'),
|
||||
).resolves.not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('keeps Reset Link button enabled when viewing own profile', () => {
|
||||
it('keeps Reset Link button enabled when viewing own profile', async () => {
|
||||
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.getByRole('button', { name: /generate password reset link/i }),
|
||||
).not.toHaveAttribute('aria-disabled', 'true');
|
||||
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',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -667,9 +860,11 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('disables name input for root user', () => {
|
||||
it('disables name input for root user', async () => {
|
||||
renderDrawer();
|
||||
expect(screen.getByDisplayValue('Alice Smith')).toBeDisabled();
|
||||
await expect(
|
||||
screen.findByDisplayValue('Alice Smith'),
|
||||
).resolves.toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables Delete button for root user', () => {
|
||||
@@ -726,9 +921,11 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer();
|
||||
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: /generate password reset link/i }),
|
||||
const resetBtn = await screen.findByTestId('member-reset-link-btn');
|
||||
await waitFor(() =>
|
||||
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
await user.click(resetBtn);
|
||||
|
||||
const dialog = await screen.findByRole('dialog', {
|
||||
name: /password reset link/i,
|
||||
@@ -747,9 +944,11 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
renderDrawer();
|
||||
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: /generate password reset link/i }),
|
||||
const resetBtn = await screen.findByTestId('member-reset-link-btn');
|
||||
await waitFor(() =>
|
||||
expect(resetBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
await user.click(resetBtn);
|
||||
|
||||
const dialog = await screen.findByRole('dialog', {
|
||||
name: /password reset link/i,
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
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)' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
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';
|
||||
|
||||
@@ -15,7 +17,12 @@ export function useCreatorOptions({
|
||||
currentUserEmail,
|
||||
fallbackEmails,
|
||||
}: Args): CreatorOption[] {
|
||||
const { data } = useListUsers();
|
||||
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 } });
|
||||
|
||||
return useMemo<CreatorOption[]>(() => {
|
||||
const users = data?.data ?? [];
|
||||
|
||||
@@ -121,6 +121,7 @@ exports[`Not Found page test should render Not Found page without errors 1`] = `
|
||||
</div>
|
||||
<a
|
||||
class="c3"
|
||||
data-discover="true"
|
||||
href="/home"
|
||||
tabindex="0"
|
||||
>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ReactNode, useEffect, useRef } from 'react';
|
||||
import { ReactNode, useCallback, useEffect, useRef } from 'react';
|
||||
import { parseAsString, useQueryState } from 'nuqs';
|
||||
import { useStore } from 'zustand';
|
||||
|
||||
@@ -61,34 +61,37 @@ export function QuerySearchV2Provider({
|
||||
);
|
||||
}, [urlExpression, initialExpression, store]);
|
||||
|
||||
// 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);
|
||||
// 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();
|
||||
}
|
||||
}, [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;
|
||||
@@ -102,6 +105,24 @@ 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) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { ReactNode, useEffect, useRef } from 'react';
|
||||
import { act, renderHook } from 'tests/test-utils';
|
||||
|
||||
import {
|
||||
@@ -215,6 +215,83 @@ 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());
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 {
|
||||
|
||||
@@ -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,19 +14,6 @@ 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];
|
||||
@@ -61,11 +48,15 @@ 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: mapFieldContext(att.fieldContext),
|
||||
type: fieldContextToAttributeType(att.fieldContext),
|
||||
},
|
||||
defaultOpen: index < 2,
|
||||
}) as IQuickFiltersConfig,
|
||||
|
||||
@@ -15,3 +15,5 @@ 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';
|
||||
|
||||
@@ -34,6 +34,7 @@ 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,
|
||||
|
||||
@@ -340,6 +340,7 @@ export enum PANEL_TYPES {
|
||||
PIE = 'pie',
|
||||
HISTOGRAM = 'histogram',
|
||||
HEATMAP = 'heatmap',
|
||||
GEO_MAP = 'geo_map',
|
||||
TEXT = 'text',
|
||||
EMPTY_WIDGET = 'EMPTY_WIDGET',
|
||||
}
|
||||
|
||||
@@ -109,6 +109,9 @@ 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;
|
||||
|
||||
@@ -5,6 +5,7 @@ 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';
|
||||
@@ -27,23 +28,15 @@ function TopContributorsCard({
|
||||
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
const toggleViewAllParam = (isOpen: boolean): void => {
|
||||
if (isOpen) {
|
||||
searchParams.set('viewAllTopContributors', 'true');
|
||||
} else {
|
||||
searchParams.delete('viewAllTopContributors');
|
||||
}
|
||||
};
|
||||
|
||||
const toggleViewAllDrawer = (): void => {
|
||||
setIsViewAllVisible((prev) => {
|
||||
const newState = !prev;
|
||||
|
||||
toggleViewAllParam(newState);
|
||||
|
||||
return newState;
|
||||
});
|
||||
navigate({ search: searchParams.toString() });
|
||||
const params = getUnstableCurrentSearchParams();
|
||||
if (isViewAllVisible) {
|
||||
params.delete('viewAllTopContributors');
|
||||
} else {
|
||||
params.set('viewAllTopContributors', 'true');
|
||||
}
|
||||
setIsViewAllVisible(!isViewAllVisible);
|
||||
navigate({ search: params.toString() });
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -6,7 +6,6 @@ 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';
|
||||
@@ -15,6 +14,7 @@ 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,7 +49,6 @@ function HorizontalTimelineGraph({
|
||||
return [timestamps, states];
|
||||
}, [data]);
|
||||
|
||||
const urlQuery = useUrlQuery();
|
||||
const dispatch = useDispatch();
|
||||
const { timezone } = useTimezone();
|
||||
|
||||
@@ -89,6 +88,7 @@ function HorizontalTimelineGraph({
|
||||
const diff = endTime - startTime;
|
||||
|
||||
if (diff > 0) {
|
||||
const urlQuery = getUnstableCurrentSearchParams();
|
||||
if (urlQuery.has(QueryParams.relativeTime)) {
|
||||
urlQuery.delete(QueryParams.relativeTime);
|
||||
}
|
||||
@@ -125,14 +125,7 @@ function HorizontalTimelineGraph({
|
||||
tzDate: (timestamp: number): Date =>
|
||||
uPlot.tzDate(new Date(timestamp * 1e3), timezone.value),
|
||||
}),
|
||||
[
|
||||
width,
|
||||
isDarkMode,
|
||||
transformedData.length,
|
||||
urlQuery,
|
||||
dispatch,
|
||||
timezone.value,
|
||||
],
|
||||
[width, isDarkMode, transformedData.length, dispatch, timezone.value],
|
||||
);
|
||||
return <Uplot data={transformedData} options={options} />;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ 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';
|
||||
|
||||
@@ -51,8 +52,9 @@ function TimelineFilters(): JSX.Element {
|
||||
);
|
||||
|
||||
const handleFilter = (value: TimelineFilter): void => {
|
||||
searchParams.set('timelineFilter', value);
|
||||
navigate({ search: searchParams.toString() });
|
||||
const params = getUnstableCurrentSearchParams();
|
||||
params.set('timelineFilter', value);
|
||||
navigate({ search: params.toString() });
|
||||
};
|
||||
|
||||
const tabs = [
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -20,8 +20,7 @@ export const SlackInitialConfig: Partial<AlertmanagertypesChannelSlackConfigDTO>
|
||||
|
||||
*Summary:* {{ .Annotations.summary }}
|
||||
*Description:* {{ .Annotations.description }}
|
||||
*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}}
|
||||
{{ template "signoz.relatedLinks.slack" . }}
|
||||
|
||||
*Details:*
|
||||
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
|
||||
@@ -141,11 +140,7 @@ export const JsmOpsInitialConfig: Partial<AlertmanagertypesChannelJSMOpsConfigDT
|
||||
|
||||
{{ end }}{{ if .GeneratorURL }}[View in SigNoz]({{ .GeneratorURL }})
|
||||
|
||||
{{ end }}{{ if .Annotations.related_logs }}[View related logs]({{ .Annotations.related_logs }})
|
||||
|
||||
{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})
|
||||
|
||||
{{ end }}{{ end }}`,
|
||||
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ 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',
|
||||
@@ -168,11 +163,7 @@ export const IncidentIOInitialConfig: Partial<AlertmanagertypesChannelIncidentIO
|
||||
|
||||
{{ end }}{{ if .GeneratorURL }}[View in SigNoz]({{ .GeneratorURL }})
|
||||
|
||||
{{ end }}{{ if .Annotations.related_logs }}[View related logs]({{ .Annotations.related_logs }})
|
||||
|
||||
{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})
|
||||
|
||||
{{ end }}{{ end }}`,
|
||||
{{ end }}{{ template "signoz.relatedLinks.markdown" . }}{{ end }}`,
|
||||
};
|
||||
|
||||
export const EmailInitialConfig: Partial<AlertmanagertypesChannelEmailConfigDTO> =
|
||||
|
||||
@@ -4,7 +4,7 @@ import { QueryKey } from 'react-query';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { Button, Select, Skeleton, Table } from 'antd';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
getQueryRangeRequestData,
|
||||
@@ -36,10 +36,12 @@ import { openInNewTab } from 'utils/navigation';
|
||||
import triangleRulerUrl from '@/assets/Icons/triangle-ruler.svg';
|
||||
|
||||
import { DOCS_LINKS } from '../constants';
|
||||
import { columns, TIME_PICKER_OPTIONS } from './constants';
|
||||
import { getColumns, TIME_PICKER_OPTIONS } from './constants';
|
||||
|
||||
const homeInterval = 30 * 60 * 1000;
|
||||
|
||||
const columns = getColumns(true);
|
||||
|
||||
// Extracted EmptyState component
|
||||
const EmptyState = memo(
|
||||
({
|
||||
@@ -69,7 +71,7 @@ const EmptyState = memo(
|
||||
type="default"
|
||||
className="periscope-btn secondary"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: Get Started clicked', {
|
||||
void logEvent('Homepage: Get Started clicked', {
|
||||
source: 'Service Metrics',
|
||||
});
|
||||
|
||||
@@ -90,7 +92,7 @@ const EmptyState = memo(
|
||||
type="link"
|
||||
className="learn-more-link"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: Learn more clicked', {
|
||||
void logEvent('Homepage: Learn more clicked', {
|
||||
source: 'Service Metrics',
|
||||
});
|
||||
window.open(
|
||||
@@ -118,7 +120,10 @@ const ServicesListTable = memo(
|
||||
services: ServicesList[];
|
||||
onRowClick: (record: ServicesList, event: React.MouseEvent) => void;
|
||||
}): JSX.Element => (
|
||||
<div className="services-list-container home-data-item-container metrics-services-list">
|
||||
<div
|
||||
className="services-list-container home-data-item-container metrics-services-list"
|
||||
data-testid="home-services-table"
|
||||
>
|
||||
<div className="services-list">
|
||||
<Table<ServicesList>
|
||||
columns={columns}
|
||||
@@ -197,7 +202,7 @@ function ServiceMetrics({
|
||||
(option) => option.value === value,
|
||||
);
|
||||
|
||||
logEvent('Homepage: Services time interval updated', {
|
||||
void logEvent('Homepage: Services time interval updated', {
|
||||
updatedTimeInterval: timeInterval?.label,
|
||||
});
|
||||
|
||||
@@ -222,7 +227,7 @@ function ServiceMetrics({
|
||||
|
||||
const dataQueries = useGetQueriesRange(
|
||||
queryRangeRequestData,
|
||||
ENTITY_VERSION_V4,
|
||||
ENTITY_VERSION_V5,
|
||||
{
|
||||
queryKey: useMemo(
|
||||
() => [
|
||||
@@ -258,12 +263,7 @@ function ServiceMetrics({
|
||||
);
|
||||
|
||||
const sortedServices = useMemo(
|
||||
() =>
|
||||
services?.sort((a, b) => {
|
||||
const aUpdateAt = new Date(a.p99).getTime();
|
||||
const bUpdateAt = new Date(b.p99).getTime();
|
||||
return bUpdateAt - aUpdateAt;
|
||||
}) || [],
|
||||
() => [...services].sort((a, b) => b.p99 - a.p99),
|
||||
[services],
|
||||
);
|
||||
|
||||
@@ -281,7 +281,7 @@ function ServiceMetrics({
|
||||
|
||||
const handleRowClick = useCallback(
|
||||
(record: ServicesList, event: React.MouseEvent) => {
|
||||
logEvent('Homepage: Service clicked', {
|
||||
void logEvent('Homepage: Service clicked', {
|
||||
serviceName: record.serviceName,
|
||||
});
|
||||
safeNavigate(`${ROUTES.APPLICATION}/${record.serviceName}`, {
|
||||
@@ -348,7 +348,7 @@ function ServiceMetrics({
|
||||
type="link"
|
||||
className="periscope-btn link learn-more-link"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: All Services clicked', {});
|
||||
void logEvent('Homepage: All Services clicked', {});
|
||||
}}
|
||||
>
|
||||
All Services <ArrowRight size={12} />
|
||||
|
||||
@@ -22,10 +22,12 @@ import { openInNewTab } from 'utils/navigation';
|
||||
import triangleRulerUrl from '@/assets/Icons/triangle-ruler.svg';
|
||||
|
||||
import { DOCS_LINKS } from '../constants';
|
||||
import { columns, TIME_PICKER_OPTIONS } from './constants';
|
||||
import { getColumns, TIME_PICKER_OPTIONS } from './constants';
|
||||
|
||||
const homeInterval = 30 * 60 * 1000;
|
||||
|
||||
const columns = getColumns(false);
|
||||
|
||||
export default function ServiceTraces({
|
||||
onUpdateChecklistDoneItem,
|
||||
loadingUserPreferences,
|
||||
@@ -91,7 +93,7 @@ export default function ServiceTraces({
|
||||
(option) => option.value === value,
|
||||
);
|
||||
|
||||
logEvent('Homepage: Services time interval updated', {
|
||||
void logEvent('Homepage: Services time interval updated', {
|
||||
updatedTimeInterval: timeInterval?.label,
|
||||
});
|
||||
|
||||
@@ -126,7 +128,7 @@ export default function ServiceTraces({
|
||||
type="default"
|
||||
className="periscope-btn secondary"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: Get Started clicked', {
|
||||
void logEvent('Homepage: Get Started clicked', {
|
||||
source: 'Service Traces',
|
||||
});
|
||||
|
||||
@@ -147,7 +149,7 @@ export default function ServiceTraces({
|
||||
type="link"
|
||||
className="learn-more-link"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: Learn more clicked', {
|
||||
void logEvent('Homepage: Learn more clicked', {
|
||||
source: 'Service Traces',
|
||||
});
|
||||
window.open(
|
||||
@@ -168,7 +170,10 @@ export default function ServiceTraces({
|
||||
|
||||
const renderDashboardsList = useCallback(
|
||||
() => (
|
||||
<div className="services-list-container home-data-item-container traces-services-list">
|
||||
<div
|
||||
className="services-list-container home-data-item-container traces-services-list"
|
||||
data-testid="home-services-table"
|
||||
>
|
||||
<div className="services-list">
|
||||
<Table<ServicesList>
|
||||
columns={columns}
|
||||
@@ -178,7 +183,7 @@ export default function ServiceTraces({
|
||||
className="services-table"
|
||||
onRow={(record: ServicesList): Record<string, unknown> => ({
|
||||
onClick: (event: React.MouseEvent): void => {
|
||||
logEvent('Homepage: Service clicked', {
|
||||
void logEvent('Homepage: Service clicked', {
|
||||
serviceName: record.serviceName,
|
||||
});
|
||||
|
||||
@@ -246,7 +251,7 @@ export default function ServiceTraces({
|
||||
type="link"
|
||||
className="periscope-btn link learn-more-link"
|
||||
onClick={(): void => {
|
||||
logEvent('Homepage: All Services clicked', {});
|
||||
void logEvent('Homepage: All Services clicked', {});
|
||||
}}
|
||||
>
|
||||
All Services <ArrowRight size={12} />
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
|
||||
import {
|
||||
Querybuildertypesv5ColumnTypeDTO,
|
||||
Querybuildertypesv5RequestTypeDTO,
|
||||
type QueryRangeV5200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import ServiceMetrics from '../ServiceMetrics';
|
||||
|
||||
const topLevelOperations: ServiceDataProps = { SampleApp: ['GET'] };
|
||||
|
||||
// A = p99 (ms), D = ops/s, F1 = error rate
|
||||
const scalarTable: QueryRangeV5200 = {
|
||||
status: 'success',
|
||||
data: {
|
||||
type: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
columns: ['A', 'D', 'F1'].map((queryName) => ({
|
||||
name: '__result_0',
|
||||
queryName,
|
||||
aggregationIndex: 0,
|
||||
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
|
||||
})),
|
||||
data: [[148.25, 12.4, 1.8]],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
describe('Home ServiceMetrics', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.post(
|
||||
'http://localhost/api/v1/service/top_level_operations',
|
||||
(_, res, ctx) => res(ctx.status(200), ctx.json(topLevelOperations)),
|
||||
),
|
||||
rest.post('http://localhost/api/v5/query_range', (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(scalarTable)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the span-metrics p99 in ms as sent', async () => {
|
||||
render(
|
||||
<ServiceMetrics
|
||||
onUpdateChecklistDoneItem={jest.fn()}
|
||||
loadingUserPreferences={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
Array.from(
|
||||
screen.getByTestId('home-services-table').querySelectorAll('tbody tr td'),
|
||||
).map((cell) => cell.textContent),
|
||||
).toStrictEqual(['SampleApp', '148.25', '1.80', '12.40']),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
import { ServicesList } from 'types/api/metrics/getService';
|
||||
|
||||
import ServiceTraces from '../ServiceTraces';
|
||||
|
||||
const services: ServicesList[] = [
|
||||
{
|
||||
serviceName: 'SampleApp',
|
||||
p99: 148_250_000,
|
||||
avgDuration: 0,
|
||||
numCalls: 100,
|
||||
callRate: 12.4,
|
||||
numErrors: 2,
|
||||
errorRate: 1.8,
|
||||
},
|
||||
];
|
||||
|
||||
describe('Home ServiceTraces', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.post('http://localhost/api/v2/services', (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: services })),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the traces p99 in ms from ns', async () => {
|
||||
render(
|
||||
<ServiceTraces
|
||||
onUpdateChecklistDoneItem={jest.fn()}
|
||||
loadingUserPreferences={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
Array.from(
|
||||
screen.getByTestId('home-services-table').querySelectorAll('tbody tr td'),
|
||||
).map((cell) => cell.textContent),
|
||||
).toStrictEqual(['SampleApp', '148.25', '1.80', '12.40']),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import { TableProps } from 'antd';
|
||||
import { ServicesList } from 'types/api/metrics/getService';
|
||||
|
||||
export const columns: TableProps<ServicesList>['columns'] = [
|
||||
export const getColumns = (
|
||||
isMetricData: boolean,
|
||||
): TableProps<ServicesList>['columns'] => [
|
||||
{
|
||||
title: 'APPLICATION',
|
||||
dataIndex: 'serviceName',
|
||||
@@ -11,7 +13,8 @@ export const columns: TableProps<ServicesList>['columns'] = [
|
||||
title: 'P99 LATENCY (in ms)',
|
||||
dataIndex: 'p99',
|
||||
key: 'p99',
|
||||
render: (value: number): string => (value / 1000000).toFixed(2),
|
||||
render: (value: number): string =>
|
||||
isMetricData ? value.toFixed(2) : (value / 1000000).toFixed(2),
|
||||
},
|
||||
{
|
||||
title: 'ERROR RATE (% of total)',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, 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,9 +28,6 @@ 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,
|
||||
@@ -60,10 +57,6 @@ 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(() => {
|
||||
@@ -75,28 +68,6 @@ 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);
|
||||
};
|
||||
@@ -226,6 +197,7 @@ function Hosts(): JSX.Element {
|
||||
|
||||
return (
|
||||
<>
|
||||
<DefaultQueryRedirect />
|
||||
<div className={styles.infraMonitoringContainer}>
|
||||
<div className={styles.infraContentRow}>
|
||||
{showFilters && (
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
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;
|
||||
}
|
||||
@@ -60,7 +60,6 @@ function K8sHeader({
|
||||
const currentExpression =
|
||||
currentQuery.builder.queryData[0]?.filter?.expression || '';
|
||||
const finalExpression = newExpression ?? currentExpression;
|
||||
void setCurrentPage(1);
|
||||
|
||||
const updatedQuery = {
|
||||
...currentQuery,
|
||||
@@ -87,6 +86,8 @@ 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()) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
@@ -9,14 +9,12 @@ 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 {
|
||||
@@ -66,9 +64,7 @@ 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);
|
||||
@@ -95,28 +91,6 @@ 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
|
||||
@@ -212,14 +186,7 @@ export default function InfraMonitoringK8s(): JSX.Element {
|
||||
|
||||
const handleCategorySelect = (key: string): void => {
|
||||
if (key !== selectedCategory) {
|
||||
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);
|
||||
// Navigate first: a navigation drops the nuqs writes still queued.
|
||||
redirectWithQueryBuilderData({
|
||||
...currentQuery,
|
||||
builder: {
|
||||
@@ -233,6 +200,14 @@ 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);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -262,6 +237,7 @@ export default function InfraMonitoringK8s(): JSX.Element {
|
||||
|
||||
return (
|
||||
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
|
||||
<DefaultQueryRedirect />
|
||||
<div className={styles.infraMonitoringContainer}>
|
||||
<div className={styles.infraContentRow}>
|
||||
{showFilters && (
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
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'),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -991,6 +991,15 @@ 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>,
|
||||
@@ -1157,8 +1166,15 @@ describe('Login Component', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: { href: 'http://localhost/' },
|
||||
value: {
|
||||
href: 'http://localhost/',
|
||||
origin: 'http://localhost',
|
||||
pathname: '/',
|
||||
search: '',
|
||||
hash: '',
|
||||
},
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
server.use(
|
||||
|
||||
@@ -47,6 +47,10 @@
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
&__search-trigger {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.members-filter-trigger__chevron {
|
||||
|
||||
@@ -6,15 +6,25 @@ 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;
|
||||
|
||||
@@ -23,6 +33,12 @@ 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);
|
||||
@@ -32,7 +48,18 @@ function MembersSettings(): JSX.Element {
|
||||
);
|
||||
const [selectedMember, setSelectedMember] = useState<MemberRow | null>(null);
|
||||
|
||||
const { data: usersData, isLoading, refetch: refetchUsers } = useListUsers();
|
||||
const canListUsers =
|
||||
!!authzError || (authzPermissions?.[UserListPermission]?.isGranted ?? false);
|
||||
|
||||
const {
|
||||
data: usersData,
|
||||
isLoading,
|
||||
refetch: refetchUsers,
|
||||
isError,
|
||||
error,
|
||||
} = useListUsers({ query: { enabled: canListUsers } });
|
||||
|
||||
const controlsDisabled = !canListUsers || isAuthZLoading;
|
||||
|
||||
const allMembers = useMemo(
|
||||
(): MemberRow[] =>
|
||||
@@ -176,57 +203,89 @@ function MembersSettings(): JSX.Element {
|
||||
</div>
|
||||
|
||||
<div className="members-settings__controls">
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<div className="members-settings__search">
|
||||
<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"
|
||||
/>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
<AuthZButton
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
checks={[UserCreatePermission]}
|
||||
onClick={(): void => void setIsInviteModalOpen(true)}
|
||||
prefix={<Plus size={12} />}
|
||||
testId="invite-member-btn"
|
||||
>
|
||||
Invite member
|
||||
</Button>
|
||||
</AuthZButton>
|
||||
</div>
|
||||
</div>
|
||||
<MembersTable
|
||||
data={filteredMembers}
|
||||
loading={isLoading}
|
||||
total={filteredMembers.length}
|
||||
currentPage={currentPage}
|
||||
pageSize={PAGE_SIZE}
|
||||
searchQuery={searchQuery}
|
||||
onPageChange={setPage}
|
||||
onRowClick={handleRowClick}
|
||||
/>
|
||||
<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>
|
||||
|
||||
<InviteMembersModal
|
||||
open={isInviteModalOpen}
|
||||
@@ -236,7 +295,6 @@ function MembersSettings(): JSX.Element {
|
||||
|
||||
<EditMemberDrawer
|
||||
member={selectedMember}
|
||||
open={selectedMember !== null}
|
||||
onClose={handleDrawerClose}
|
||||
onComplete={handleMemberEditComplete}
|
||||
/>
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { TypesUserDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
import {
|
||||
AUTHZ_CHECK_URL,
|
||||
setupAuthzAdmin,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
import { fireEvent, render, screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import MembersSettings from '../MembersSettings';
|
||||
|
||||
@@ -57,6 +61,7 @@ describe('MembersSettings (integration)', () => {
|
||||
rest.get(USERS_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: mockUsers })),
|
||||
),
|
||||
setupAuthzAdmin(),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -123,10 +128,22 @@ 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 />);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /invite member/i }));
|
||||
const inviteBtn = await screen.findByTestId('invite-member-btn');
|
||||
await waitFor(() =>
|
||||
expect(inviteBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
await userEvent.click(inviteBtn);
|
||||
|
||||
await expect(
|
||||
screen.findAllByPlaceholderText('e.g. john@signoz.io'),
|
||||
|
||||
@@ -4,6 +4,8 @@ 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';
|
||||
|
||||
@@ -58,18 +60,21 @@ function InviteMembersModal({
|
||||
Cancel
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
<AuthZButton
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={submit}
|
||||
disabled={!canSubmit}
|
||||
disabledTooltip="Add at least one team member to invite"
|
||||
disabledTooltip={
|
||||
canSubmit ? undefined : 'Add at least one team member to invite'
|
||||
}
|
||||
checks={[UserCreatePermission]}
|
||||
loading={isSubmitting}
|
||||
testId="invite-submit-btn"
|
||||
>
|
||||
{isSubmitting ? 'Inviting...' : 'Invite Team Members'}
|
||||
</Button>
|
||||
</AuthZButton>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
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 InviteMembersModal from '../InviteMembersModal';
|
||||
|
||||
@@ -55,6 +61,7 @@ describe('InviteMembersModal', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockInviteMembersProps = null;
|
||||
server.use(setupAuthzAdmin());
|
||||
});
|
||||
|
||||
describe('rendering', () => {
|
||||
@@ -134,7 +141,7 @@ describe('InviteMembersModal', () => {
|
||||
const { unmount } = renderComponent();
|
||||
unmount();
|
||||
|
||||
const { getByRole } = render(
|
||||
const { getByTestId } = render(
|
||||
mockInviteMembersProps?.renderFooter({
|
||||
submit: mockSubmit,
|
||||
canSubmit: true,
|
||||
@@ -142,10 +149,27 @@ describe('InviteMembersModal', () => {
|
||||
}) as JSX.Element,
|
||||
);
|
||||
|
||||
await user.click(getByRole('button', { name: /invite team members/i }));
|
||||
const submit = getByTestId('invite-submit-btn');
|
||||
await waitFor(() =>
|
||||
expect(submit).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
await user.click(submit);
|
||||
|
||||
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', () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
alphabet,
|
||||
initialFormulaBuilderFormValues,
|
||||
@@ -6,7 +7,9 @@ import {
|
||||
import getStep from 'lib/getStep';
|
||||
import store from 'store';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { SpaceAggregation, TimeAggregation } from 'types/api/v5/queryRange';
|
||||
import {
|
||||
DataSource,
|
||||
MetricAggregateOperator,
|
||||
QueryBuilderData,
|
||||
ReduceOperators,
|
||||
@@ -18,6 +21,38 @@ import {
|
||||
BuilderQuerieswithFormulaProps,
|
||||
} from '../Tabs/types';
|
||||
|
||||
// The query spreads in default `aggregations` (avg / sum, or count() for traces),
|
||||
// and v5 reads those before the top-level time / space fields, so set them here.
|
||||
const getAggregations = ({
|
||||
dataSource,
|
||||
key,
|
||||
aggregateOperator,
|
||||
timeAggregation,
|
||||
spaceAggregation,
|
||||
comparisonSpaceAggregationParam,
|
||||
}: {
|
||||
dataSource: DataSource;
|
||||
key: string;
|
||||
aggregateOperator: string;
|
||||
timeAggregation: MetricAggregateOperator;
|
||||
spaceAggregation: MetricAggregateOperator;
|
||||
comparisonSpaceAggregationParam?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
}): IBuilderQuery['aggregations'] =>
|
||||
dataSource === DataSource.TRACES
|
||||
? [{ expression: `${aggregateOperator}(${key})` }]
|
||||
: [
|
||||
{
|
||||
metricName: key,
|
||||
temporality: '',
|
||||
timeAggregation: timeAggregation as TimeAggregation,
|
||||
spaceAggregation: spaceAggregation as SpaceAggregation,
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
...(comparisonSpaceAggregationParam && {
|
||||
comparisonSpaceAggregationParam,
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
||||
export const getQueryBuilderQueries = ({
|
||||
autocompleteData,
|
||||
groupBy = [],
|
||||
@@ -31,23 +66,33 @@ export const getQueryBuilderQueries = ({
|
||||
}: BuilderQueriesProps): QueryBuilderData => ({
|
||||
queryFormulas: [],
|
||||
queryData: autocompleteData.map((item, index) => {
|
||||
const operator = aggregateOperator
|
||||
? aggregateOperator[index]
|
||||
: MetricAggregateOperator.SUM_RATE;
|
||||
const newQueryData: IBuilderQuery = {
|
||||
...initialQueryBuilderFormValuesMap.metrics,
|
||||
aggregateOperator: ((): string => {
|
||||
if (aggregateOperator) {
|
||||
return aggregateOperator[index];
|
||||
}
|
||||
return MetricAggregateOperator.SUM_RATE;
|
||||
})(),
|
||||
aggregateOperator: operator,
|
||||
aggregations: getAggregations({
|
||||
dataSource,
|
||||
key: item.key,
|
||||
aggregateOperator: operator,
|
||||
timeAggregation: timeAggregateOperators[index],
|
||||
spaceAggregation: spaceAggregateOperators[index],
|
||||
}),
|
||||
disabled: false,
|
||||
groupBy,
|
||||
aggregateAttribute: item,
|
||||
legend: legends[index],
|
||||
stepInterval: getStep({
|
||||
end: store.getState().globalTime.maxTime,
|
||||
inputFormat: 'ns',
|
||||
start: store.getState().globalTime.minTime,
|
||||
}),
|
||||
// v5 sets the metrics step (multiples of 300s from 1 day up); its traces
|
||||
// default is ~300 points, far denser than these cards
|
||||
stepInterval:
|
||||
dataSource === DataSource.METRICS
|
||||
? null
|
||||
: getStep({
|
||||
end: store.getState().globalTime.maxTime,
|
||||
inputFormat: 'ns',
|
||||
start: store.getState().globalTime.minTime,
|
||||
}),
|
||||
filters: {
|
||||
items: filterItems[index],
|
||||
op: 'AND',
|
||||
@@ -78,6 +123,8 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
legendFormulas,
|
||||
timeAggregateOperators,
|
||||
spaceAggregateOperators,
|
||||
comparisonSpaceAggregationParams = [],
|
||||
stepInterval,
|
||||
dataSource,
|
||||
}: BuilderQuerieswithFormulaProps): QueryBuilderData => ({
|
||||
queryFormulas: expressions.map((expression, index) => ({
|
||||
@@ -87,6 +134,14 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
})),
|
||||
queryData: autocompleteData.map((_, index) => ({
|
||||
...initialQueryBuilderFormValuesMap.metrics,
|
||||
aggregations: getAggregations({
|
||||
dataSource,
|
||||
key: autocompleteData[index].key,
|
||||
aggregateOperator: timeAggregateOperators[index],
|
||||
timeAggregation: timeAggregateOperators[index],
|
||||
spaceAggregation: spaceAggregateOperators[index],
|
||||
comparisonSpaceAggregationParam: comparisonSpaceAggregationParams[index],
|
||||
}),
|
||||
timeAggregation: timeAggregateOperators[index],
|
||||
spaceAggregation: spaceAggregateOperators[index],
|
||||
temporality: Temporality.Delta,
|
||||
@@ -101,11 +156,7 @@ export const getQueryBuilderQuerieswithFormula = ({
|
||||
items: additionalItems[index],
|
||||
op: 'AND',
|
||||
},
|
||||
stepInterval: getStep({
|
||||
end: store.getState().globalTime.maxTime,
|
||||
inputFormat: 'ns',
|
||||
start: store.getState().globalTime.minTime,
|
||||
}),
|
||||
stepInterval: stepInterval ?? null,
|
||||
dataSource,
|
||||
})),
|
||||
queryTraceOperator: [],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { OPERATORS } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
@@ -22,11 +23,10 @@ import {
|
||||
} from '../constant';
|
||||
import {
|
||||
ApDexMetricsQueryBuilderQueriesProps,
|
||||
ApDexProps,
|
||||
LatencyProps,
|
||||
OperationPerSecProps,
|
||||
} from '../Tabs/types';
|
||||
import { convertMilSecToNanoSec, getNearestHighestBucketValue } from '../utils';
|
||||
import { getNearestHighestBucketValue } from '../utils';
|
||||
import {
|
||||
getQueryBuilderQueries,
|
||||
getQueryBuilderQuerieswithFormula,
|
||||
@@ -40,11 +40,10 @@ export const latency = ({
|
||||
}: LatencyProps): QueryBuilderData => {
|
||||
const signozLatencyBucketMetrics = WidgetKeys.SignozLatencyBucket;
|
||||
|
||||
const signozMetricsServiceName = WidgetKeys.OTelServiceName;
|
||||
const newAutoCompleteData: BaseAutocompleteData = {
|
||||
key: isSpanMetricEnable
|
||||
? signozLatencyBucketMetrics
|
||||
: WidgetKeys.DurationNano,
|
||||
: WidgetKeys.SpanDurationNano,
|
||||
dataType: DataTypes.Float64,
|
||||
type: isSpanMetricEnable ? '' : MetricsType.Tag,
|
||||
};
|
||||
@@ -55,7 +54,7 @@ export const latency = ({
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: isSpanMetricEnable ? signozMetricsServiceName : WidgetKeys.ServiceName,
|
||||
key: WidgetKeys.OTelServiceName,
|
||||
dataType: DataTypes.String,
|
||||
type: isSpanMetricEnable ? MetricsType.Resource : MetricsType.Tag,
|
||||
},
|
||||
@@ -106,175 +105,6 @@ export const latency = ({
|
||||
});
|
||||
};
|
||||
|
||||
export const apDexTracesQueryBuilderQueries = ({
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
topLevelOperationsRoute,
|
||||
threashold,
|
||||
}: ApDexProps): QueryBuilderData => {
|
||||
const autoCompleteDataA: BaseAutocompleteData = {
|
||||
dataType: DataTypes.Float64,
|
||||
key: '',
|
||||
type: '',
|
||||
};
|
||||
|
||||
const autoCompleteDataB: BaseAutocompleteData = {
|
||||
dataType: DataTypes.Float64,
|
||||
key: '',
|
||||
type: '',
|
||||
};
|
||||
|
||||
const autoCompleteDataC: BaseAutocompleteData = {
|
||||
dataType: DataTypes.Float64,
|
||||
key: '',
|
||||
type: '',
|
||||
};
|
||||
|
||||
const filterItemA: TagFilterItem[] = [
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.ServiceName,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: servicename,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Name,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS.IN,
|
||||
value: [...topLevelOperationsRoute],
|
||||
},
|
||||
...tagFilterItems,
|
||||
];
|
||||
|
||||
const filterItemB: TagFilterItem[] = [
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.HasError,
|
||||
dataType: DataTypes.bool,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: false,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.DurationNano,
|
||||
dataType: DataTypes.Float64,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['<='],
|
||||
value: convertMilSecToNanoSec(threashold),
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.ServiceName,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: servicename,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Name,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS.IN,
|
||||
value: [...topLevelOperationsRoute],
|
||||
},
|
||||
];
|
||||
|
||||
const filterItemC: TagFilterItem[] = [
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.DurationNano,
|
||||
dataType: DataTypes.Float64,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['<='],
|
||||
value: convertMilSecToNanoSec(threashold * 4),
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.HasError,
|
||||
dataType: DataTypes.bool,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: false,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.ServiceName,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: servicename,
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Name,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS.IN,
|
||||
value: [...topLevelOperationsRoute],
|
||||
},
|
||||
];
|
||||
|
||||
const autocompleteData = [
|
||||
autoCompleteDataA,
|
||||
autoCompleteDataB,
|
||||
autoCompleteDataC,
|
||||
];
|
||||
const additionalItems = [filterItemA, filterItemB, filterItemC];
|
||||
const legends = [GraphTitle.APDEX];
|
||||
const disabled = Array(3).fill(true);
|
||||
const expressions = [FORMULA.APDEX_TRACES];
|
||||
const legendFormulas = [GraphTitle.APDEX];
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.COUNT,
|
||||
MetricAggregateOperator.COUNT,
|
||||
MetricAggregateOperator.COUNT,
|
||||
];
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
MetricAggregateOperator.EMPTY,
|
||||
];
|
||||
const dataSource = DataSource.TRACES;
|
||||
|
||||
return getQueryBuilderQuerieswithFormula({
|
||||
autocompleteData,
|
||||
additionalItems,
|
||||
legends,
|
||||
disabled,
|
||||
expressions,
|
||||
legendFormulas,
|
||||
timeAggregateOperators,
|
||||
spaceAggregateOperators,
|
||||
dataSource,
|
||||
});
|
||||
};
|
||||
|
||||
export const apDexMetricsQueryBuilderQueries = ({
|
||||
servicename,
|
||||
tagFilterItems,
|
||||
@@ -283,6 +113,30 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
delta,
|
||||
metricsBuckets,
|
||||
}: ApDexMetricsQueryBuilderQueriesProps): QueryBuilderData => {
|
||||
// the comparison count stops at the largest finite bucket, so a threshold past it
|
||||
// reads the count metric, which is the +Inf bucket
|
||||
const countAtOrBelow = (
|
||||
ms: number,
|
||||
): {
|
||||
key: string;
|
||||
spaceAggregation: MetricAggregateOperator;
|
||||
param?: MetrictypesComparisonSpaceAggregationParamDTO;
|
||||
} => {
|
||||
const bucket = getNearestHighestBucketValue(ms, metricsBuckets);
|
||||
return bucket === '+Inf'
|
||||
? {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
spaceAggregation: MetricAggregateOperator.SUM,
|
||||
}
|
||||
: {
|
||||
key: WidgetKeys.SignozLatencyBucket,
|
||||
spaceAggregation: MetricAggregateOperator.COUNT,
|
||||
param: { operator: '<=', threshold: Number(bucket) },
|
||||
};
|
||||
};
|
||||
const satisfied = countAtOrBelow(threashold * 1000);
|
||||
const tolerating = countAtOrBelow(threashold * 1000 * 4);
|
||||
|
||||
const autoCompleteDataA: BaseAutocompleteData = {
|
||||
key: WidgetKeys.SignozLatencyCount,
|
||||
dataType: DataTypes.Float64,
|
||||
@@ -290,13 +144,13 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
};
|
||||
|
||||
const autoCompleteDataB: BaseAutocompleteData = {
|
||||
key: WidgetKeys.SignozLatencyBucket,
|
||||
key: satisfied.key,
|
||||
dataType: DataTypes.Float64,
|
||||
type: '',
|
||||
};
|
||||
|
||||
const autoCompleteDataC: BaseAutocompleteData = {
|
||||
key: WidgetKeys.SignozLatencyBucket,
|
||||
key: tolerating.key,
|
||||
dataType: DataTypes.Float64,
|
||||
type: '',
|
||||
};
|
||||
@@ -336,16 +190,6 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
op: OPERATORS['!='],
|
||||
value: 'STATUS_CODE_ERROR',
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Le,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: getNearestHighestBucketValue(threashold * 1000, metricsBuckets),
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
@@ -370,16 +214,6 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
];
|
||||
|
||||
const filterItemC: TagFilterItem[] = [
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
key: WidgetKeys.Le,
|
||||
dataType: DataTypes.String,
|
||||
type: MetricsType.Tag,
|
||||
},
|
||||
op: OPERATORS['='],
|
||||
value: getNearestHighestBucketValue(threashold * 1000 * 4, metricsBuckets),
|
||||
},
|
||||
{
|
||||
id: '',
|
||||
key: {
|
||||
@@ -426,16 +260,23 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
? [FORMULA.APDEX_DELTA_SPAN_METRICS]
|
||||
: [FORMULA.APDEX_CUMULATIVE_SPAN_METRICS];
|
||||
const legendFormulas = [GraphTitle.APDEX];
|
||||
// v5 forces increase on histograms, so the total matches it
|
||||
const timeAggregateOperators = [
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.RATE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
MetricAggregateOperator.INCREASE,
|
||||
];
|
||||
|
||||
// a plain sum keeps the le label on B and C, and the formula then cannot join them
|
||||
const spaceAggregateOperators = [
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
MetricAggregateOperator.SUM,
|
||||
satisfied.spaceAggregation,
|
||||
tolerating.spaceAggregation,
|
||||
];
|
||||
const comparisonSpaceAggregationParams = [
|
||||
undefined,
|
||||
satisfied.param,
|
||||
tolerating.param,
|
||||
];
|
||||
const dataSource = DataSource.METRICS;
|
||||
|
||||
@@ -448,6 +289,7 @@ export const apDexMetricsQueryBuilderQueries = ({
|
||||
legendFormulas,
|
||||
timeAggregateOperators,
|
||||
spaceAggregateOperators,
|
||||
comparisonSpaceAggregationParams,
|
||||
dataSource,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import { prepareQueryRangePayloadV5 } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { QueryBuilderData } from 'types/common/queryBuilder';
|
||||
import { QueryEnvelope } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import {
|
||||
apDexMetricsQueryBuilderQueries,
|
||||
errorPercentage,
|
||||
latency,
|
||||
} from '../OverviewQueries';
|
||||
|
||||
const toV5Queries = (builder: QueryBuilderData): QueryEnvelope[] =>
|
||||
prepareQueryRangePayloadV5({
|
||||
query: {
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
promql: [],
|
||||
builder,
|
||||
clickhouse_sql: [],
|
||||
id: 'query',
|
||||
},
|
||||
graphType: PANEL_TYPES.TIME_SERIES,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
}).queryPayload.compositeQuery.queries;
|
||||
|
||||
const getAggregations = (queries: QueryEnvelope[]): unknown[] =>
|
||||
queries.map(
|
||||
(query) => (query.spec as { aggregations?: unknown[] }).aggregations,
|
||||
);
|
||||
|
||||
const getFilters = (queries: QueryEnvelope[]): unknown[] =>
|
||||
queries.map((query) => (query.spec as { filter?: unknown }).filter);
|
||||
|
||||
describe('service details queries on v5', () => {
|
||||
it('keeps the latency percentiles on the span metrics histogram', () => {
|
||||
const queries = toV5Queries(
|
||||
latency({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
isSpanMetricEnable: true,
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(getAggregations(queries)).toStrictEqual(
|
||||
['p50', 'p90', 'p99'].map((spaceAggregation) => [
|
||||
{
|
||||
metricName: 'signoz_latency.bucket',
|
||||
temporality: undefined,
|
||||
timeAggregation: '',
|
||||
spaceAggregation,
|
||||
reduceTo: undefined,
|
||||
},
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('builds the traces latency percentiles from span duration', () => {
|
||||
const queries = toV5Queries(
|
||||
latency({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(getAggregations(queries)).toStrictEqual([
|
||||
[{ expression: 'p50(duration_nano)' }],
|
||||
[{ expression: 'p90(duration_nano)' }],
|
||||
[{ expression: 'p99(duration_nano)' }],
|
||||
]);
|
||||
expect(getFilters(queries)[0]).toStrictEqual({
|
||||
expression: "service.name = 'frontend' AND name in ['GET /']",
|
||||
});
|
||||
});
|
||||
|
||||
it('rates the error and total calls behind the error percentage', () => {
|
||||
const queries = toV5Queries(
|
||||
errorPercentage({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperations: ['GET /'],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(getAggregations(queries).slice(0, 2)).toStrictEqual(
|
||||
Array(2).fill([
|
||||
{
|
||||
metricName: 'signoz_calls_total',
|
||||
temporality: undefined,
|
||||
timeAggregation: 'rate',
|
||||
spaceAggregation: 'sum',
|
||||
reduceTo: undefined,
|
||||
},
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('counts the apdex buckets at the threshold instead of filtering on le', () => {
|
||||
const queries = toV5Queries(
|
||||
apDexMetricsQueryBuilderQueries({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
threashold: 0.5,
|
||||
delta: true,
|
||||
metricsBuckets: [100, 250, 500, 1000, 2000, 5000],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(getAggregations(queries).slice(0, 3)).toStrictEqual([
|
||||
[
|
||||
{
|
||||
metricName: 'signoz_latency.count',
|
||||
temporality: undefined,
|
||||
timeAggregation: 'increase',
|
||||
spaceAggregation: 'sum',
|
||||
reduceTo: undefined,
|
||||
},
|
||||
],
|
||||
...[500, 2000].map((threshold) => [
|
||||
{
|
||||
metricName: 'signoz_latency.bucket',
|
||||
temporality: undefined,
|
||||
timeAggregation: 'increase',
|
||||
spaceAggregation: 'count',
|
||||
reduceTo: undefined,
|
||||
comparisonSpaceAggregationParam: { operator: '<=', threshold },
|
||||
},
|
||||
]),
|
||||
]);
|
||||
expect(getFilters(queries).slice(1, 3)).toStrictEqual([
|
||||
{
|
||||
expression:
|
||||
"status.code != 'STATUS_CODE_ERROR' AND service.name = 'frontend' AND operation in ['GET /']",
|
||||
},
|
||||
{
|
||||
expression:
|
||||
"status.code != 'STATUS_CODE_ERROR' AND service.name = 'frontend' AND operation in ['GET /']",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('reads the count metric when the apdex threshold is past the largest bucket', () => {
|
||||
const queries = toV5Queries(
|
||||
apDexMetricsQueryBuilderQueries({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
threashold: 0.5,
|
||||
delta: true,
|
||||
metricsBuckets: [100, 250, 500, 1000],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(getAggregations(queries)[2]).toStrictEqual([
|
||||
{
|
||||
metricName: 'signoz_latency.count',
|
||||
temporality: undefined,
|
||||
timeAggregation: 'increase',
|
||||
spaceAggregation: 'sum',
|
||||
reduceTo: undefined,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('leaves the metrics step to v5 on single and formula queries', () => {
|
||||
const queries = [
|
||||
...toV5Queries(
|
||||
latency({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
isSpanMetricEnable: true,
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
}),
|
||||
),
|
||||
...toV5Queries(
|
||||
errorPercentage({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperations: ['GET /'],
|
||||
}),
|
||||
),
|
||||
].filter((query) => query.type === 'builder_query');
|
||||
|
||||
expect(
|
||||
queries.map(
|
||||
(query) => (query.spec as { stepInterval?: unknown }).stepInterval,
|
||||
),
|
||||
).toStrictEqual(Array(queries.length).fill(null));
|
||||
});
|
||||
|
||||
it('keeps the card step on the traces latency', () => {
|
||||
const [p50] = toV5Queries(
|
||||
latency({
|
||||
servicename: 'frontend',
|
||||
tagFilterItems: [],
|
||||
topLevelOperationsRoute: ['GET /'],
|
||||
}),
|
||||
);
|
||||
|
||||
expect((p50.spec as { stepInterval?: unknown }).stepInterval).toBe(60);
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { Col } from 'antd';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
@@ -201,7 +201,7 @@ function DBCall(): JSX.Element {
|
||||
);
|
||||
}}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
@@ -240,7 +240,7 @@ function DBCall(): JSX.Element {
|
||||
);
|
||||
}}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { Col } from 'antd';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
@@ -273,7 +273,7 @@ function External(): JSX.Element {
|
||||
);
|
||||
}}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
@@ -317,7 +317,7 @@ function External(): JSX.Element {
|
||||
);
|
||||
}}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
@@ -362,7 +362,7 @@ function External(): JSX.Element {
|
||||
)
|
||||
}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
@@ -406,7 +406,7 @@ function External(): JSX.Element {
|
||||
);
|
||||
}}
|
||||
onDragSelect={onDragSelect}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
apDexToolTipUrl,
|
||||
apDexToolTipUrlText,
|
||||
} from 'constants/apDex';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
import DisplayThreshold from 'container/WidgetCard/Header/DisplayThreshold';
|
||||
@@ -95,7 +95,7 @@ function ApDexMetrics({
|
||||
onClickHandler={handleGraphClick('ApDex')}
|
||||
threshold={threshold}
|
||||
isQueryEnabled={isQueryEnabled}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { FeatureKeys } from 'constants/features';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
@@ -13,7 +13,10 @@ import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsAppli
|
||||
import { latency } from 'container/MetricsApplication/MetricsPageQueries/OverviewQueries';
|
||||
import { Card, GraphContainer } from 'container/MetricsApplication/styles';
|
||||
import useResourceAttribute from 'hooks/useResourceAttribute';
|
||||
import { resourceAttributesToTagFilterItems } from 'hooks/useResourceAttribute/utils';
|
||||
import {
|
||||
resourceAttributesToTagFilterItems,
|
||||
resourceAttributesToTracesFilterItems,
|
||||
} from 'hooks/useResourceAttribute/utils';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
@@ -49,9 +52,9 @@ function ServiceOverview({
|
||||
|
||||
const tagFilterItems = useMemo(
|
||||
() =>
|
||||
handleNonInQueryRange(
|
||||
resourceAttributesToTagFilterItems(queries, !isSpanMetricEnable),
|
||||
) || [],
|
||||
isSpanMetricEnable
|
||||
? handleNonInQueryRange(resourceAttributesToTagFilterItems(queries))
|
||||
: resourceAttributesToTracesFilterItems(queries),
|
||||
[isSpanMetricEnable, queries],
|
||||
);
|
||||
|
||||
@@ -72,7 +75,7 @@ function ServiceOverview({
|
||||
},
|
||||
title: GraphTitle.LATENCY,
|
||||
panelTypes: PANEL_TYPES.TIME_SERIES,
|
||||
yAxisUnit: 'ns',
|
||||
yAxisUnit: isSpanMetricEnable ? 'ms' : 'ns',
|
||||
id: SERVICE_CHART_ID.latency,
|
||||
}),
|
||||
[isSpanMetricEnable, servicename, tagFilterItems, topLevelOperationsRoute],
|
||||
@@ -116,7 +119,7 @@ function ServiceOverview({
|
||||
widget={latencyWidget}
|
||||
onClickHandler={handleGraphClick('Service')}
|
||||
isQueryEnabled={isQueryEnabled}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import axios from 'axios';
|
||||
import { SOMETHING_WENT_WRONG } from 'constants/api';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
import { SERVICE_DETAIL_DRILLDOWN_ENABLED } from 'container/MetricsApplication/constant';
|
||||
import { Card, GraphContainer } from 'container/MetricsApplication/styles';
|
||||
@@ -33,7 +33,7 @@ function TopLevelOperation({
|
||||
onClickHandler={handleGraphClick(opName)}
|
||||
onDragSelect={onDragSelect}
|
||||
isQueryEnabled={!topLevelOperationsIsLoading}
|
||||
version={ENTITY_VERSION_V4}
|
||||
version={ENTITY_VERSION_V5}
|
||||
enableDrillDown={SERVICE_DETAIL_DRILLDOWN_ENABLED}
|
||||
/>
|
||||
</GraphContainer>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ReactNode, useMemo } from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { useAppParams } from 'lib/router/useAppParams';
|
||||
import { ENTITY_VERSION_V4 } from 'constants/app';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { topOperationMetricsDownloadOptions } from 'container/MetricsApplication/constant';
|
||||
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
|
||||
@@ -15,6 +15,7 @@ import useResourceAttribute from 'hooks/useResourceAttribute';
|
||||
import { convertRawQueriesToTraceSelectedTags } from 'hooks/useResourceAttribute/utils';
|
||||
import { RowData } from 'lib/query/createTableColumnsFromQuery';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { QueryDataV3 } from 'types/api/widgets/getQuery';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
@@ -70,7 +71,7 @@ function TopOperationMetrics(): JSX.Element {
|
||||
globalSelectedInterval,
|
||||
variables: {},
|
||||
},
|
||||
ENTITY_VERSION_V4,
|
||||
ENTITY_VERSION_V5,
|
||||
{
|
||||
queryKey: [
|
||||
`GetMetricsQueryRange-${keyOperationWidget?.timePreferance}-${globalSelectedInterval}-${keyOperationWidget?.id}`,
|
||||
@@ -88,7 +89,9 @@ function TopOperationMetrics(): JSX.Element {
|
||||
},
|
||||
);
|
||||
|
||||
const queryTableData = data?.payload?.data?.newResult?.data?.result || [];
|
||||
const queryTableData = (data?.payload?.data?.newResult?.data?.result ||
|
||||
data?.payload?.data?.result ||
|
||||
[]) as QueryDataV3[];
|
||||
|
||||
const renderColumnCell = useMemo(
|
||||
() =>
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { prepareQueryRangePayloadV5 } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
|
||||
import { FeatureKeys } from 'constants/features';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import Graph from 'container/WidgetCard/Card';
|
||||
import { IResourceAttribute } from 'hooks/useResourceAttribute/types';
|
||||
import { encode } from 'js-base64';
|
||||
import { defaultFeatureFlags, render } from 'tests/test-utils';
|
||||
|
||||
import ServiceOverview from '../ServiceOverview';
|
||||
|
||||
jest.mock('container/WidgetCard/Card', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(() => null),
|
||||
}));
|
||||
|
||||
const resourceAttributes: IResourceAttribute[] = [
|
||||
{
|
||||
id: 'env',
|
||||
tagKey: 'resource_deployment.environment',
|
||||
operator: 'Not IN',
|
||||
tagValue: ['prod'],
|
||||
},
|
||||
];
|
||||
|
||||
describe('ServiceOverview', () => {
|
||||
it('filters the traces latency on the resource attribute with its operator', () => {
|
||||
render(
|
||||
<ServiceOverview
|
||||
stepInterval={60}
|
||||
selectedTimeStamp={0}
|
||||
selectedTraceTags="[]"
|
||||
onDragSelect={jest.fn()}
|
||||
handleGraphClick={jest.fn()}
|
||||
topLevelOperationsRoute={['GET /']}
|
||||
topLevelOperationsIsLoading={false}
|
||||
/>,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: `/services/frontend?${QueryParams.resourceAttributes}=${encodeURIComponent(
|
||||
encode(JSON.stringify(resourceAttributes)),
|
||||
)}`,
|
||||
routePath: ROUTES.SERVICE_METRICS,
|
||||
},
|
||||
);
|
||||
|
||||
const { widget } = jest.mocked(Graph).mock.calls[0][0];
|
||||
const [latencyQuery] = prepareQueryRangePayloadV5({
|
||||
query: widget.query,
|
||||
graphType: widget.panelTypes,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
}).queryPayload.compositeQuery.queries;
|
||||
|
||||
expect(latencyQuery.spec).toMatchObject({
|
||||
filter: {
|
||||
expression:
|
||||
"service.name = 'frontend' AND name in ['GET /'] AND deployment.environment NOT IN ['prod']",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ spanMetrics: false, unit: 'ns' },
|
||||
{ spanMetrics: true, unit: 'ms' },
|
||||
])(
|
||||
'reads the latency in $unit when span metrics is $spanMetrics',
|
||||
({ spanMetrics, unit }) => {
|
||||
render(
|
||||
<ServiceOverview
|
||||
stepInterval={60}
|
||||
selectedTimeStamp={0}
|
||||
selectedTraceTags="[]"
|
||||
onDragSelect={jest.fn()}
|
||||
handleGraphClick={jest.fn()}
|
||||
topLevelOperationsRoute={['GET /']}
|
||||
topLevelOperationsIsLoading={false}
|
||||
/>,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: '/services/frontend',
|
||||
routePath: ROUTES.SERVICE_METRICS,
|
||||
appContextOverrides: {
|
||||
featureFlags: defaultFeatureFlags.map((flag) =>
|
||||
flag.name === FeatureKeys.USE_SPAN_METRICS
|
||||
? { ...flag, active: spanMetrics }
|
||||
: flag,
|
||||
),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(jest.mocked(Graph).mock.calls[0][0].widget.yAxisUnit).toBe(unit);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { MetrictypesComparisonSpaceAggregationParamDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { RowData } from 'lib/query/createTableColumnsFromQuery';
|
||||
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
@@ -43,6 +44,12 @@ export interface BuilderQuerieswithFormulaProps {
|
||||
additionalItems: TagFilterItem[][];
|
||||
timeAggregateOperators: MetricAggregateOperator[];
|
||||
spaceAggregateOperators: MetricAggregateOperator[];
|
||||
comparisonSpaceAggregationParams?: (
|
||||
| MetrictypesComparisonSpaceAggregationParamDTO
|
||||
| undefined
|
||||
)[];
|
||||
// v5 picks its own step when none is sent; v4 needs one
|
||||
stepInterval?: number;
|
||||
dataSource: DataSource;
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,7 @@ export enum WidgetKeys {
|
||||
HasError = 'hasError',
|
||||
Address = 'address',
|
||||
DurationNano = 'durationNano',
|
||||
SpanDurationNano = 'duration_nano',
|
||||
StatusCode = 'status.code',
|
||||
Operation = 'operation',
|
||||
OperationName = 'operationName',
|
||||
|
||||
@@ -54,9 +54,6 @@ export const getNearestHighestBucketValue = (
|
||||
return nearestBucket?.toString() || '+Inf';
|
||||
};
|
||||
|
||||
export const convertMilSecToNanoSec = (value: number): number =>
|
||||
value * 1000000000;
|
||||
|
||||
export const convertedTracesToDownloadData = (
|
||||
originalData: TopOperationList[],
|
||||
): Record<string, string>[] =>
|
||||
|
||||
@@ -58,22 +58,6 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
useUpdateMyUserV2,
|
||||
} from 'api/generated/services/users';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { Check, FileTerminal, Mail, User } from '@signozhq/icons';
|
||||
import { Check, FileTerminal, Mail } from '@signozhq/icons';
|
||||
import { useAppContext } from 'providers/App/App';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import APIError from 'types/api/error';
|
||||
@@ -129,13 +129,9 @@ function UserInfo(): JSX.Element {
|
||||
</div>
|
||||
|
||||
<div className="user-info-subsection">
|
||||
<div className="user-email">
|
||||
<div className="user-email" data-testid="user-info-email">
|
||||
<Mail size={16} /> {user.email}
|
||||
</div>
|
||||
|
||||
<div className="user-role">
|
||||
<User size={16} /> {user.role.toLowerCase()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -168,6 +168,13 @@ 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);
|
||||
@@ -464,3 +471,34 @@ 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' }),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,8 @@ 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';
|
||||
@@ -118,20 +120,22 @@ function InviteTeamMembers({
|
||||
|
||||
return (
|
||||
<div className="onboarding-buttons-container">
|
||||
<Button
|
||||
<AuthZButton
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
width="100%"
|
||||
onClick={submit}
|
||||
loading={isButtonDisabled}
|
||||
disabled={!canSubmit}
|
||||
disabledTooltip="Add at least one team member to invite"
|
||||
disabledTooltip={
|
||||
canSubmit ? undefined : 'Add at least one team member to invite'
|
||||
}
|
||||
checks={[UserCreatePermission]}
|
||||
testId="send-invites-button"
|
||||
suffix={<ArrowRight size={12} />}
|
||||
>
|
||||
Send Invites
|
||||
</Button>
|
||||
</AuthZButton>
|
||||
<Button
|
||||
size="md"
|
||||
variant="ghost"
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
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',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,8 @@ 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';
|
||||
@@ -711,6 +713,7 @@ 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} />}
|
||||
>
|
||||
@@ -1185,7 +1188,7 @@ function OnboardingAddDataSource(): JSX.Element {
|
||||
>
|
||||
Cancel
|
||||
</SignozButton>
|
||||
<SignozButton
|
||||
<AuthZButton
|
||||
size="md"
|
||||
color="primary"
|
||||
variant="solid"
|
||||
@@ -1196,13 +1199,16 @@ function OnboardingAddDataSource(): JSX.Element {
|
||||
);
|
||||
void submit();
|
||||
}}
|
||||
disabled={!canSubmit}
|
||||
disabledTooltip="Add at least one team member to invite"
|
||||
disabledTooltip={
|
||||
canSubmit ? undefined : 'Add at least one team member to invite'
|
||||
}
|
||||
checks={[UserCreatePermission]}
|
||||
loading={isSubmitting}
|
||||
suffix={<ArrowRight size={14} />}
|
||||
testId="onboarding-send-invites-btn"
|
||||
>
|
||||
Send Invites
|
||||
</SignozButton>
|
||||
</AuthZButton>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user