mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-18 06:10:41 +00:00
Compare commits
37 Commits
nv/exec-st
...
fix/jest-c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef3ce730f3 | ||
|
|
57f42a7262 | ||
|
|
fa404d24ba | ||
|
|
6707b06497 | ||
|
|
0d86eb7504 | ||
|
|
25b8aa4f4c | ||
|
|
a0052307a6 | ||
|
|
6856154ea0 | ||
|
|
03a0a510c6 | ||
|
|
6e5c15164c | ||
|
|
c2795dbbb2 | ||
|
|
ad4b77dc65 | ||
|
|
2b0c0323cb | ||
|
|
38b6c2f7f8 | ||
|
|
20db3a3406 | ||
|
|
fae2019971 | ||
|
|
eabbb49e31 | ||
|
|
6248d0f991 | ||
|
|
7026046e37 | ||
|
|
5aeeb21f42 | ||
|
|
62f567b482 | ||
|
|
987245495d | ||
|
|
dac45bc9a1 | ||
|
|
b8cb86afa6 | ||
|
|
d725bc8d8b | ||
|
|
6dde249b61 | ||
|
|
7a52290c0c | ||
|
|
d5a8c64f1f | ||
|
|
f0cde4f37d | ||
|
|
1efbbcfc5e | ||
|
|
7cef7e48ea | ||
|
|
7189736cea | ||
|
|
8e089a8bd8 | ||
|
|
5b2027ad81 | ||
|
|
ce78251920 | ||
|
|
879b6e4e69 | ||
|
|
f7e78384ed |
@@ -9,12 +9,14 @@ paths:
|
||||
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
|
||||
|
||||
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
|
||||
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query.
|
||||
- **Interact like a user.** `const user = userEvent.setup({ pointerEventsCheck: 0 })`, then an awaited `user.click`, `hover`, `keyboard` or `type`. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
|
||||
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check, which walks `getComputedStyle` up the tree on every action; never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
|
||||
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
|
||||
- **Router through the harness.** Pass `initialRoute`/`routePath` to `render` and assert with `getCurrentLocation()` from `lib/router/navigation`. Never mock `react-router`, `react-router-dom` or `lib/history`; when a test can't render at a route, use the `lib/router` spies in `tests/router-mocks`.
|
||||
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
|
||||
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides (`@floating-ui/dom`, `@testing-library/user-event` and antd's `collectScroller` in `jest.setup.ts`) or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
|
||||
- **Type mocks and fixtures.** `jest.mocked(fn)` for module mocks, `jest.fn() as jest.MockedFunction<T>` for a standalone mock you configure or assert on. Fixtures carry their real type, from `src/api/generated` where it exists. No `any`, no `as unknown as`. An inline `onX={jest.fn()}` on a typed prop that is never asserted needs no annotation.
|
||||
- **A test fails without its change.** Revert the change, or break the line under test, and run the test before you finish: it must fail. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
|
||||
- **One behaviour per test, at the smallest render.** Render the component that owns the behaviour, not the page around it, unless the page wiring is the behaviour. A flow of steps (a wizard, a multi-step form) becomes one test per step that starts at that step through props, store or route. A full click-through belongs in the e2e suite (`tests/e2e`).
|
||||
- **Each test under 500 ms.** `pnpm jest <file> --verbose` prints each test's time. CI runs about four times slower than a laptop, and the timeout is 5 s. Never raise a timeout (`jest.setTimeout`, a third argument to `it`) to make a slow test pass; slim the test instead.
|
||||
- **A test fails without its change.** At the gate in [`frontend/AGENTS.md`](../../frontend/AGENTS.md), revert the change, or break the line under test, and run the test: it must fail, and each test must stay under 500 ms. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
|
||||
- **No limit on tests per file.** Split a file when it mixes unrelated behaviour, not to hit a count.
|
||||
|
||||
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
|
||||
|
||||
27
.github/workflows/flakyci.yaml
vendored
Normal file
27
.github/workflows/flakyci.yaml
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
name: flakyci
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 4 * * 1"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
jest:
|
||||
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: report
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
POST_ISSUE: "true"
|
||||
run: node frontend/scripts/flaky-jest-report.mjs >> "$GITHUB_STEP_SUMMARY"
|
||||
2
.github/workflows/integrationci.yaml
vendored
2
.github/workflows/integrationci.yaml
vendored
@@ -40,7 +40,6 @@ jobs:
|
||||
suite:
|
||||
- alertmanager
|
||||
- alertmanagerrotation
|
||||
- auditquerier
|
||||
- basepath
|
||||
- callbackauthn
|
||||
- cloudintegrations
|
||||
@@ -58,6 +57,7 @@ jobs:
|
||||
- querierscalar
|
||||
- queriercommon
|
||||
- querierai
|
||||
- querieraudit
|
||||
- rawexportdata
|
||||
- promqlconformance
|
||||
- promapiconformance
|
||||
|
||||
75
.github/workflows/jsci.yaml
vendored
75
.github/workflows/jsci.yaml
vendored
@@ -23,17 +23,53 @@ jobs:
|
||||
PRIMUS_REF: main
|
||||
JS_SRC: frontend
|
||||
JS_PKG_MANAGER: pnpm
|
||||
test:
|
||||
test-shard:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
(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'))
|
||||
uses: signoz/primus.workflows/.github/workflows/js-test.yaml@main
|
||||
secrets: inherit
|
||||
with:
|
||||
PRIMUS_REF: main
|
||||
JS_SRC: frontend
|
||||
JS_PKG_MANAGER: pnpm
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3]
|
||||
steps:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: install-pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- name: node-install
|
||||
uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: pnpm
|
||||
cache-dependency-path: frontend/pnpm-lock.yaml
|
||||
- name: install-frontend
|
||||
run: cd frontend && pnpm install
|
||||
- name: jest-cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ runner.temp }}/jest-cache
|
||||
key: jest-${{ matrix.shard }}-${{ hashFiles('frontend/pnpm-lock.yaml', 'frontend/jest.config.ts', 'frontend/babel.config.cjs', 'frontend/tsconfig.json', 'frontend/tsconfig.jest.json') }}
|
||||
- name: test
|
||||
run: cd frontend && pnpm test --shard=${{ matrix.shard }}/${{ strategy.job-total }} --cacheDirectory=${{ runner.temp }}/jest-cache --reporters=default --reporters=./scripts/slow-test-reporter.js
|
||||
# Branch protection requires a check named "test / js"; this job keeps that name stable across shard changes.
|
||||
test:
|
||||
name: test / js
|
||||
needs: test-shard
|
||||
if: |
|
||||
always() && (
|
||||
github.event_name == 'merge_group' ||
|
||||
(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: shards-passed
|
||||
run: test "${{ needs.test-shard.result }}" = success
|
||||
fmt:
|
||||
if: |
|
||||
github.event_name == 'merge_group' ||
|
||||
@@ -85,7 +121,7 @@ jobs:
|
||||
(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
|
||||
timeout-minutes: 10
|
||||
timeout-minutes: 15
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.57.0-noble
|
||||
strategy:
|
||||
@@ -132,3 +168,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:
|
||||
@@ -24702,9 +24950,9 @@ paths:
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- ADMIN
|
||||
- organization:read
|
||||
- tokenizer:
|
||||
- ADMIN
|
||||
- organization:read
|
||||
summary: Get my organization
|
||||
tags:
|
||||
- orgs
|
||||
@@ -24753,9 +25001,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)
|
||||
```
|
||||
|
||||
@@ -99,7 +99,7 @@ is still by hand. The generator never adds a SideNav item; do that in
|
||||
CSS Modules (`docs/css-modules-guide.md`), React Query for server state (prefer
|
||||
`api/generated` hooks), nuqs for URL state, Zustand for client state, `data-testid` on
|
||||
every interactive element.
|
||||
5. **Verify** before reporting done:
|
||||
5. **Verify** at the gate in `AGENTS.md` (commit, push or PR), not after each edit; skip it while the user says `no checks`:
|
||||
```bash
|
||||
pnpm tsgo --noEmit
|
||||
pnpm oxlint src/pages/<Feature>
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -34,14 +34,18 @@ You are operating within a constrained context window and strict system prompts.
|
||||
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.
|
||||
- A payload saved under another kind or schema copies only the fields that schema accepts, and drops bindings to columns the user removed. The server rejects unknown or stale fields, so the preview works and the save fails.
|
||||
|
||||
3. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. Run these checks once all changes of a task are done, never after each edit. You are FORBIDDEN from reporting a task as complete until you have:
|
||||
3. CHECKS AT THE GATE: Your internal tools mark file writes as successful even if the code does not compile, so the checks below are required, but only at the gate. The gate is when the user says commit, push, raise or update the PR, mark it ready, or "run checks". Never run them after each edit or between the user's iterations.
|
||||
- Between gates, after an edit, run at most the one test file that covers it.
|
||||
- `no checks`: when the user says it (or "don't run tests", "just making changes"), run nothing: no tests, type check, lint, format or build. Make the change and stop. This holds until the user names a gate.
|
||||
|
||||
At the gate, you are FORBIDDEN from reporting a task as complete until you have:
|
||||
- Run `pnpm tsgo --noEmit`
|
||||
- Run `pnpm lint:js --quiet` to find critical errors
|
||||
- Run `pnpm oxlint <file1> <file2>` and fix all warnings
|
||||
- Run `pnpm build`
|
||||
- Find if the file has tests for it, or if there's `__test__` folder or the parent folder has tests, and run. Run them before coding the change or after all changes, never in between.
|
||||
- For e2e, run only the specs you added or changed: the stack is heavy. Leave the full jest and e2e suites to CI unless the user asks.
|
||||
- For every test you added or changed, revert the change it covers and confirm the test fails
|
||||
- For every test you added or changed, revert the change it covers and confirm the test fails, and that each test runs under 500 ms (`pnpm jest <file> --verbose`)
|
||||
- On a stacked branch (`gh stack`), run `pnpm tsgo --noEmit` on every branch above it before pushing: a renamed prop or moved export breaks them
|
||||
- Fixed ALL resulting errors
|
||||
|
||||
|
||||
@@ -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 ||
|
||||
@@ -134,6 +144,39 @@ window.getComputedStyle = function (
|
||||
}
|
||||
};
|
||||
|
||||
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
|
||||
// popover ancestor costs up to ~1 s per open.
|
||||
jest.mock('@floating-ui/dom', () => ({
|
||||
...jest.requireActual('@floating-ui/dom'),
|
||||
autoUpdate: (): (() => void) => (): void => {},
|
||||
computePosition: (
|
||||
_reference: unknown,
|
||||
_floating: unknown,
|
||||
{ placement = 'bottom', strategy = 'absolute' } = {},
|
||||
): Promise<unknown> =>
|
||||
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
|
||||
}));
|
||||
|
||||
jest.mock('@testing-library/user-event', () =>
|
||||
jest.requireActual('tests/userEventWithDefaults'),
|
||||
);
|
||||
|
||||
// antd popups walk getComputedStyle up every ancestor to find scroll
|
||||
// containers on each open. pnpm keeps the package under antd, not at the root.
|
||||
jest.mock(
|
||||
require.resolve('@rc-component/trigger/lib/util', {
|
||||
paths: [require.resolve('antd')],
|
||||
}),
|
||||
() => ({
|
||||
...jest.requireActual(
|
||||
require.resolve('@rc-component/trigger/lib/util', {
|
||||
paths: [require.resolve('antd')],
|
||||
}),
|
||||
),
|
||||
collectScroller: (): HTMLElement[] => [],
|
||||
}),
|
||||
);
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
|
||||
afterEach(() => server.resetHandlers());
|
||||
|
||||
@@ -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
|
||||
|
||||
57
frontend/scripts/__tests__/flaky-jest-report.test.mjs
Normal file
57
frontend/scripts/__tests__/flaky-jest-report.test.mjs
Normal file
@@ -0,0 +1,57 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import { findFlaky, parseFailures } from '../flaky-jest-report.mjs';
|
||||
|
||||
const LOG = [
|
||||
'2026-11-10T10:00:00.0000000Z \x1b[1mFAIL\x1b[22m src/a/A.test.tsx (12.1 s)',
|
||||
'2026-11-10T10:00:00.0000001Z \x1b[1m● A › saves the form\x1b[22m',
|
||||
'2026-11-10T10:00:00.0000002Z ',
|
||||
'2026-11-10T10:00:00.0000003Z thrown: "Exceeded timeout of 5000 ms for a test.',
|
||||
'2026-11-10T10:00:00.0000004Z FAIL src/b/B.test.tsx',
|
||||
'2026-11-10T10:00:00.0000005Z ● B › shows the error',
|
||||
'2026-11-10T10:00:00.0000006Z expect(received).toBe(expected)',
|
||||
'2026-11-10T10:00:00.0000007Z ● Test suite failed to run',
|
||||
'2026-11-10T10:00:00.0000008Z FAIL src/a/A.test.tsx (12.1 s)',
|
||||
'2026-11-10T10:00:00.0000009Z ● A › saves the form',
|
||||
].join('\n');
|
||||
|
||||
test('parseFailures reads each failing test once with its first error line', () => {
|
||||
assert.deepEqual(parseFailures(LOG), [
|
||||
{
|
||||
file: 'src/a/A.test.tsx',
|
||||
test: 'A › saves the form',
|
||||
error: 'thrown: "Exceeded timeout of 5000 ms for a test.',
|
||||
},
|
||||
{
|
||||
file: 'src/b/B.test.tsx',
|
||||
test: 'B › shows the error',
|
||||
error: 'expect(received).toBe(expected)',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('findFlaky keeps re-run, merge queue and multi-PR failures only', () => {
|
||||
const failure = (test, extra) => ({
|
||||
file: 'src/x.test.tsx',
|
||||
test,
|
||||
error: '',
|
||||
event: 'pull_request',
|
||||
pr: 1,
|
||||
passedOnRerun: false,
|
||||
...extra,
|
||||
});
|
||||
const flaky = findFlaky([
|
||||
failure('one PR only'),
|
||||
failure('one PR only'),
|
||||
failure('re-run', { passedOnRerun: true }),
|
||||
failure('queue', { event: 'merge_group', pr: null }),
|
||||
failure('spread', { pr: 1 }),
|
||||
failure('spread', { pr: 2 }),
|
||||
failure('spread', { pr: 3 }),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
flaky.map((entry) => entry.test),
|
||||
['spread', 're-run', 'queue'],
|
||||
);
|
||||
});
|
||||
262
frontend/scripts/flaky-jest-report.mjs
Normal file
262
frontend/scripts/flaky-jest-report.mjs
Normal file
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env node
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
const API = 'https://api.github.com';
|
||||
const ISSUE_TITLE = 'Flaky Jest tests: weekly report';
|
||||
const TEST_JOB = /^test-shard \(\d+\)$|^test \/ js$/;
|
||||
const MIN_PRS = 3;
|
||||
|
||||
export function parseFailures(log) {
|
||||
const lines = log.split('\n').map((line) =>
|
||||
line
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/\x1b\[[0-9;]*m/g, '')
|
||||
.replace(/^\d{4}-\d\d-\d\dT[\d:.]+Z /, ''),
|
||||
);
|
||||
const failures = new Map();
|
||||
let file = null;
|
||||
lines.forEach((line, index) => {
|
||||
const failedFile = line.match(/^\s*FAIL\s+(\S+)/);
|
||||
if (failedFile) {
|
||||
[, file] = failedFile;
|
||||
return;
|
||||
}
|
||||
const failedTest = line.match(/^\s*● (.+ › .+)$/);
|
||||
if (!failedTest || !file) {
|
||||
return;
|
||||
}
|
||||
const test = failedTest[1].trim();
|
||||
const key = `${file}\0${test}`;
|
||||
if (!failures.has(key)) {
|
||||
const error =
|
||||
lines
|
||||
.slice(index + 1, index + 8)
|
||||
.map((next) => next.trim())
|
||||
.find(Boolean) ?? '';
|
||||
failures.set(key, { file, test, error });
|
||||
}
|
||||
});
|
||||
return [...failures.values()];
|
||||
}
|
||||
|
||||
export function findFlaky(failures) {
|
||||
const byTest = new Map();
|
||||
failures.forEach((failure) => {
|
||||
const key = `${failure.file}\0${failure.test}`;
|
||||
const entry = byTest.get(key) ?? {
|
||||
file: failure.file,
|
||||
test: failure.test,
|
||||
error: failure.error,
|
||||
failures: 0,
|
||||
prs: new Set(),
|
||||
passedOnRerun: 0,
|
||||
mergeQueue: 0,
|
||||
};
|
||||
entry.failures += 1;
|
||||
if (failure.pr) {
|
||||
entry.prs.add(failure.pr);
|
||||
}
|
||||
entry.passedOnRerun += failure.passedOnRerun ? 1 : 0;
|
||||
entry.mergeQueue += failure.event === 'merge_group' ? 1 : 0;
|
||||
byTest.set(key, entry);
|
||||
});
|
||||
return [...byTest.values()]
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.passedOnRerun > 0 ||
|
||||
entry.mergeQueue > 0 ||
|
||||
entry.prs.size >= MIN_PRS,
|
||||
)
|
||||
.sort((a, b) => b.failures - a.failures);
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
async function gh(path, init = {}, attempt = 1) {
|
||||
const retry = !init.method && attempt < 4;
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(path.startsWith('http') ? path : API + path, {
|
||||
...init,
|
||||
headers: {
|
||||
accept: 'application/vnd.github+json',
|
||||
authorization: `Bearer ${process.env.GH_TOKEN}`,
|
||||
...init.headers,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (!retry) {
|
||||
throw error;
|
||||
}
|
||||
await sleep(attempt * 2000);
|
||||
return gh(path, init, attempt + 1);
|
||||
}
|
||||
if (retry && response.status >= 500) {
|
||||
await sleep(attempt * 2000);
|
||||
return gh(path, init, attempt + 1);
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(`${response.status} ${init.method ?? 'GET'} ${path}`);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
async function mapLimit(items, limit, fn) {
|
||||
const results = [];
|
||||
let next = 0;
|
||||
await Promise.all(
|
||||
Array.from({ length: limit }, async () => {
|
||||
while (next < items.length) {
|
||||
const index = next;
|
||||
next += 1;
|
||||
results[index] = await fn(items[index]);
|
||||
}
|
||||
}),
|
||||
);
|
||||
return results;
|
||||
}
|
||||
|
||||
async function paginate(path, key) {
|
||||
const items = [];
|
||||
let next = API + path;
|
||||
while (next) {
|
||||
const response = await gh(next);
|
||||
const body = await response.json();
|
||||
items.push(...(key ? body[key] : body));
|
||||
next = response.headers.get('link')?.match(/<([^>]+)>; rel="next"/)?.[1];
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
async function runFailures(repo, run) {
|
||||
const jobs = (
|
||||
await paginate(
|
||||
`/repos/${repo}/actions/runs/${run.id}/jobs?filter=all&per_page=100`,
|
||||
'jobs',
|
||||
)
|
||||
).filter((job) => TEST_JOB.test(job.name));
|
||||
const failures = [];
|
||||
for (const job of jobs.filter((j) => j.conclusion === 'failure')) {
|
||||
const passedOnRerun = jobs.some(
|
||||
(later) =>
|
||||
later.name === job.name &&
|
||||
later.run_attempt > job.run_attempt &&
|
||||
later.conclusion === 'success',
|
||||
);
|
||||
let log;
|
||||
try {
|
||||
log = await (await gh(`/repos/${repo}/actions/jobs/${job.id}/logs`)).text();
|
||||
} catch (error) {
|
||||
process.stderr.write(`skipped job ${job.id}: ${error.message}\n`);
|
||||
continue;
|
||||
}
|
||||
parseFailures(log).forEach((failure) =>
|
||||
failures.push({
|
||||
...failure,
|
||||
event: run.event,
|
||||
pr:
|
||||
run.event === 'merge_group'
|
||||
? null
|
||||
: (run.pull_requests[0]?.number ?? run.head_branch),
|
||||
passedOnRerun,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
|
||||
async function collectFailures(repo, since) {
|
||||
const runs = await paginate(
|
||||
`/repos/${repo}/actions/workflows/jsci.yaml/runs?created=>=${since}&per_page=100`,
|
||||
'workflow_runs',
|
||||
);
|
||||
const candidates = runs.filter(
|
||||
(run) => run.run_attempt > 1 || run.conclusion === 'failure',
|
||||
);
|
||||
return (await mapLimit(candidates, 8, (run) => runFailures(repo, run))).flat();
|
||||
}
|
||||
|
||||
async function lastChange(repo, file) {
|
||||
const [commit] = await (
|
||||
await gh(`/repos/${repo}/commits?path=frontend/${file}&per_page=1`)
|
||||
).json();
|
||||
if (!commit) {
|
||||
return 'unknown';
|
||||
}
|
||||
const who = commit.author?.login ?? commit.commit.author.name;
|
||||
const when = commit.commit.author.date.slice(0, 10);
|
||||
return `${who}, ${when}, [${commit.sha.slice(0, 7)}](${commit.html_url})`;
|
||||
}
|
||||
|
||||
function signal(entry) {
|
||||
return [
|
||||
entry.passedOnRerun && `passed on re-run (${entry.passedOnRerun})`,
|
||||
entry.mergeQueue && `merge queue (${entry.mergeQueue})`,
|
||||
entry.prs.size >= MIN_PRS && `${entry.prs.size} PRs`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
const cell = (text) => text.replace(/\|/g, '\\|');
|
||||
|
||||
async function report(repo, since, flaky) {
|
||||
const header = `## Flaky Jest tests since ${since}`;
|
||||
if (flaky.length === 0) {
|
||||
return `${header}\n\nNo flaky tests found.\n`;
|
||||
}
|
||||
const rows = await Promise.all(
|
||||
flaky.map(
|
||||
async (entry) =>
|
||||
`| ${cell(entry.test)} | \`${entry.file}\` | ${entry.failures} | ${signal(entry)} | ${cell(entry.error.slice(0, 80))} | ${await lastChange(repo, entry.file)} |`,
|
||||
),
|
||||
);
|
||||
return [
|
||||
header,
|
||||
'',
|
||||
'A test is listed when it failed and then passed on a re-run of the same commit, failed in the merge queue, or failed on 3 or more PRs.',
|
||||
'',
|
||||
'| Test | File | Failures | Signal | First error line | Last change |',
|
||||
'| --- | --- | --- | --- | --- | --- |',
|
||||
...rows,
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
async function postToIssue(repo, body) {
|
||||
const issues = await paginate(
|
||||
`/repos/${repo}/issues?state=open&creator=github-actions%5Bbot%5D&per_page=100`,
|
||||
);
|
||||
let issue = issues.find((candidate) => candidate.title === ISSUE_TITLE);
|
||||
if (!issue) {
|
||||
issue = await (
|
||||
await gh(`/repos/${repo}/issues`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
title: ISSUE_TITLE,
|
||||
body: 'A weekly comment lists the Jest tests that looked flaky in CI.',
|
||||
}),
|
||||
})
|
||||
).json();
|
||||
}
|
||||
await gh(`/repos/${repo}/issues/${issue.number}/comments`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ body }),
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const repo = process.env.GITHUB_REPOSITORY;
|
||||
const days = Number(process.env.DAYS ?? 7);
|
||||
const since = new Date(Date.now() - days * 864e5).toISOString().slice(0, 10);
|
||||
const flaky = findFlaky(await collectFailures(repo, since));
|
||||
const body = await report(repo, since, flaky);
|
||||
process.stdout.write(body);
|
||||
if (process.env.POST_ISSUE === 'true') {
|
||||
await postToIssue(repo, body);
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
await main();
|
||||
}
|
||||
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- ')}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
45
frontend/scripts/slow-test-reporter.js
Normal file
45
frontend/scripts/slow-test-reporter.js
Normal file
@@ -0,0 +1,45 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const budgetMs = Number(process.env.SLOW_TEST_MS ?? 2000);
|
||||
|
||||
class SlowTestReporter {
|
||||
constructor() {
|
||||
this.slow = [];
|
||||
}
|
||||
|
||||
onTestResult(_test, result) {
|
||||
const file = path.relative(process.cwd(), result.testFilePath);
|
||||
result.testResults.forEach((test) => {
|
||||
if ((test.duration ?? 0) > budgetMs) {
|
||||
this.slow.push({ file, name: test.fullName, ms: test.duration });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onRunComplete() {
|
||||
const summaryFile = process.env.GITHUB_STEP_SUMMARY;
|
||||
if (!summaryFile || this.slow.length === 0) {
|
||||
return;
|
||||
}
|
||||
const rows = this.slow
|
||||
.sort((a, b) => b.ms - a.ms)
|
||||
.map(
|
||||
(test) =>
|
||||
`| ${test.name.replace(/\|/g, '\\|')} | \`${test.file}\` | ${(test.ms / 1000).toFixed(1)} s |`,
|
||||
);
|
||||
fs.appendFileSync(
|
||||
summaryFile,
|
||||
[
|
||||
`### Jest tests over ${budgetMs / 1000} s`,
|
||||
'',
|
||||
'| Test | File | Time |',
|
||||
'| --- | --- | --- |',
|
||||
...rows,
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default SlowTestReporter;
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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,13 +36,13 @@ 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,
|
||||
isExpectedRequestFailure,
|
||||
@@ -45,12 +50,6 @@ import {
|
||||
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);
|
||||
});
|
||||
}, []);
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 [
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
createErrorHandler,
|
||||
createRolesHandler,
|
||||
createSuccessHandler,
|
||||
enterInviteEmail,
|
||||
pickInviteRole,
|
||||
VALID_EMAIL,
|
||||
} from './testUtils';
|
||||
|
||||
@@ -22,7 +24,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('reset behavior', () => {
|
||||
it('clears all rows when reset is called', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -35,13 +37,12 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
|
||||
await user.click(screen.getByTestId('reset-btn'));
|
||||
|
||||
const resetInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
const resetInputs = screen.getAllByTestId(/^invite-email-/);
|
||||
expect(resetInputs).toHaveLength(2);
|
||||
resetInputs.forEach((input) => {
|
||||
expect(input).toHaveValue('');
|
||||
@@ -49,7 +50,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
});
|
||||
|
||||
it('clears results on reset', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -66,10 +67,8 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
await expect(
|
||||
@@ -84,7 +83,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('results cleared on edit', () => {
|
||||
it('clears API error when email is edited', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -98,17 +97,15 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
await expect(
|
||||
screen.findByTestId('invite-api-error'),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
await user.type(emailInputs[0], 'x');
|
||||
await user.type(screen.getAllByTestId(/^invite-email-/)[0], 'x');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId('invite-api-error')).not.toBeInTheDocument();
|
||||
@@ -116,7 +113,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
});
|
||||
|
||||
it('clears API error when role is changed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -130,10 +127,8 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
await expect(
|
||||
@@ -153,7 +148,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('empty submission', () => {
|
||||
it('does not submit when no rows are touched', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onSuccess = jest.fn();
|
||||
|
||||
render(
|
||||
@@ -175,7 +170,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('submitting state', () => {
|
||||
it('disables submit while submitting', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -187,10 +182,8 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
const submitBtn = screen.getByTestId('submit-btn');
|
||||
await user.click(submitBtn);
|
||||
@@ -203,7 +196,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('whitespace handling', () => {
|
||||
it('trims email whitespace before submission', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const calls: { email: string }[] = [];
|
||||
|
||||
server.use(
|
||||
@@ -224,10 +217,8 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], ' alice@signoz.io ');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, ' alice@signoz.io ');
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
createRolesHandler,
|
||||
createSuccessHandler,
|
||||
createTrackingHandler,
|
||||
enterInviteEmail,
|
||||
pickInviteRole,
|
||||
VALID_EMAIL,
|
||||
} from './testUtils';
|
||||
|
||||
@@ -23,7 +25,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('API calls', () => {
|
||||
it('calls createUser API for each touched row', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const { handler, calls } = createTrackingHandler();
|
||||
server.use(handler);
|
||||
|
||||
@@ -38,10 +40,8 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -55,7 +55,7 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls createUser API for multiple touched rows', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const { handler, calls } = createTrackingHandler();
|
||||
server.use(handler);
|
||||
|
||||
@@ -70,21 +70,12 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
const editorOptions = await screen.findAllByTitle('Editor');
|
||||
await user.click(editorOptions[editorOptions.length - 1]);
|
||||
|
||||
await user.type(emailInputs[2], 'charlie@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
const adminOptions = await screen.findAllByTitle('Admin');
|
||||
await user.click(adminOptions[adminOptions.length - 1]);
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
await pickInviteRole(user, 'Editor');
|
||||
await enterInviteEmail(user, 2, 'charlie@signoz.io');
|
||||
await pickInviteRole(user, 'Admin');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -109,7 +100,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('callbacks', () => {
|
||||
it('calls onSuccess when all invites succeed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onSuccess = jest.fn();
|
||||
|
||||
render(
|
||||
@@ -123,10 +114,8 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -136,7 +125,7 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls onAllFailed when all invites fail', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onAllFailed = jest.fn();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
@@ -152,10 +141,8 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -173,7 +160,7 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls onPartialSuccess when some invites succeed and some fail', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onPartialSuccess = jest.fn();
|
||||
const onSuccess = jest.fn();
|
||||
const onAllFailed = jest.fn();
|
||||
@@ -215,16 +202,10 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
const editorOptions = await screen.findAllByTitle('Editor');
|
||||
await user.click(editorOptions[editorOptions.length - 1]);
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
await pickInviteRole(user, 'Editor');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -262,7 +243,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('result display', () => {
|
||||
it('shows success callout when all invites succeed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -274,10 +255,8 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -287,7 +266,7 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('shows error callout with failed emails when API fails', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -301,10 +280,8 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
await user.click(await screen.findByTitle('Viewer'));
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickInviteRole(user, 'Viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -317,7 +294,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('footer props', () => {
|
||||
it('provides correct canSubmit state', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -331,14 +308,13 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
expect(screen.getByTestId('submit-btn')).toBeDisabled();
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
|
||||
expect(screen.getByTestId('submit-btn')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('provides touchedCount', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -351,12 +327,11 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
expect(screen.getByTestId('touched-count')).toHaveTextContent('0');
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], 'a@b.com');
|
||||
await enterInviteEmail(user, 0, 'a@b.com');
|
||||
|
||||
expect(screen.getByTestId('touched-count')).toHaveTextContent('1');
|
||||
|
||||
await user.type(emailInputs[1], 'c@d.com');
|
||||
await enterInviteEmail(user, 1, 'c@d.com');
|
||||
|
||||
expect(screen.getByTestId('touched-count')).toHaveTextContent('2');
|
||||
});
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { RestHandler } from 'msw';
|
||||
import { rest } from 'mocks-server/server';
|
||||
import { screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
type User = ReturnType<typeof userEvent.setup>;
|
||||
|
||||
export const CREATE_USER_ENDPOINT = '*/api/v2/users';
|
||||
export const LIST_ROLES_ENDPOINT = '*/api/v1/roles';
|
||||
@@ -52,3 +55,18 @@ export function createTrackingHandler(): {
|
||||
});
|
||||
return { handler, calls };
|
||||
}
|
||||
|
||||
export async function enterInviteEmail(
|
||||
user: User,
|
||||
rowIndex: number,
|
||||
email: string,
|
||||
): Promise<void> {
|
||||
await user.click(screen.getAllByTestId(/^invite-email-/)[rowIndex]);
|
||||
await user.paste(email);
|
||||
}
|
||||
|
||||
export async function pickInviteRole(user: User, role: string): Promise<void> {
|
||||
await user.click(screen.getAllByText('Select roles')[0]);
|
||||
const options = await screen.findAllByTitle(role);
|
||||
await user.click(options[options.length - 1]);
|
||||
}
|
||||
|
||||
@@ -52,7 +52,10 @@ function MultiSelectFilter({
|
||||
disabled={disabled}
|
||||
onClear={onClear}
|
||||
optionRender={(option): JSX.Element => (
|
||||
<div className={styles.checkOption}>
|
||||
<div
|
||||
className={styles.checkOption}
|
||||
data-testid={`${testId}-option-${String(option.value)}`}
|
||||
>
|
||||
<div className={styles.checkOptionBox}>
|
||||
<Checkbox
|
||||
color="primary"
|
||||
|
||||
@@ -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 ?? [];
|
||||
|
||||
@@ -1,40 +1,32 @@
|
||||
import React, { ComponentType, Suspense } from 'react';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
waitForElementToBeRemoved,
|
||||
} from '@testing-library/react';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import Loadable from './index';
|
||||
|
||||
// Sample component to be loaded lazily
|
||||
function SampleComponent(): JSX.Element {
|
||||
return <div>Sample Component</div>;
|
||||
return <div data-testid="sample-component">Sample Component</div>;
|
||||
}
|
||||
|
||||
const loadSampleComponent = (): Promise<{
|
||||
default: ComponentType;
|
||||
}> =>
|
||||
new Promise<{ default: ComponentType }>((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({ default: SampleComponent });
|
||||
}, 500);
|
||||
});
|
||||
}> => Promise.resolve({ default: SampleComponent });
|
||||
|
||||
describe('Loadable', () => {
|
||||
it('should render the lazily loaded component', async () => {
|
||||
const LoadableSampleComponent = Loadable(loadSampleComponent);
|
||||
|
||||
const { container } = render(
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
render(
|
||||
<Suspense fallback={<div data-testid="loading">Loading...</div>}>
|
||||
<LoadableSampleComponent />
|
||||
</Suspense>,
|
||||
);
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
await waitForElementToBeRemoved(() => screen.queryByText('Loading...'));
|
||||
|
||||
expect(container.querySelector('div')).toHaveTextContent('Sample Component');
|
||||
expect(screen.getByTestId('loading')).toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByTestId('sample-component'),
|
||||
).resolves.toHaveTextContent('Sample Component');
|
||||
expect(screen.queryByTestId('loading')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call lazy with the provided import path', () => {
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
/* eslint-disable @typescript-eslint/explicit-function-return-type */
|
||||
import { jest } from '@jest/globals';
|
||||
import { fireEvent, waitFor } from '@testing-library/react';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
@@ -171,6 +170,25 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
const renderQueryV2 = (queriesCount: number): void => {
|
||||
const [queryA] = (baseQBContext.currentQuery as Query).builder.queryData;
|
||||
render(
|
||||
<QueryBuilderV2Provider>
|
||||
<QueryV2
|
||||
index={0}
|
||||
query={queryA}
|
||||
version="v4"
|
||||
isAvailableToDisable={false}
|
||||
isMultiQueryAllowed
|
||||
queriesCount={queriesCount}
|
||||
onSignalSourceChange={jest.fn()}
|
||||
signalSourceChangeEnabled={false}
|
||||
savePreviousQuery={false}
|
||||
/>
|
||||
</QueryBuilderV2Provider>,
|
||||
);
|
||||
};
|
||||
|
||||
it('renders limit input when dataSource is logs', () => {
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
@@ -184,43 +202,37 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
expect(limitInput).toHaveAttribute('data-testid', 'input-Limit');
|
||||
});
|
||||
|
||||
it('Cmd+Enter on an input triggers handleRunQuery via container handler', async () => {
|
||||
it('Cmd+Enter on the limit input triggers handleRunQuery via container handler', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
const limitInput = screen.getByPlaceholderText('Enter limit');
|
||||
fireEvent.keyDown(limitInput, {
|
||||
key: 'Enter',
|
||||
code: 'Enter',
|
||||
metaKey: true,
|
||||
});
|
||||
screen.getByTestId('input-Limit').focus();
|
||||
await user.keyboard('{Meta>}{Enter}{/Meta}');
|
||||
|
||||
expect(handleRunQueryMock).toHaveBeenCalled();
|
||||
expect(handleRunQueryMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
const legendInput = screen.getByPlaceholderText('Write legend format');
|
||||
fireEvent.keyDown(legendInput, {
|
||||
key: 'Enter',
|
||||
code: 'Enter',
|
||||
metaKey: true,
|
||||
});
|
||||
it('Cmd+Enter on the legend input triggers handleRunQuery via container handler', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
expect(handleRunQueryMock).toHaveBeenCalled();
|
||||
screen.getByPlaceholderText('Write legend format').focus();
|
||||
await user.keyboard('{Meta>}{Enter}{/Meta}');
|
||||
|
||||
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
expect(handleRunQueryMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
await userEvent.click(editor);
|
||||
fireEvent.keyDown(editor, {
|
||||
key: 'Enter',
|
||||
code: 'Enter',
|
||||
metaKey: true,
|
||||
});
|
||||
it('Cmd+Enter in the where clause editor triggers handleRunQuery via container handler', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
|
||||
expect(handleRunQueryMock).toHaveBeenCalled();
|
||||
const editor = (
|
||||
await screen.findByTestId('query-where-clause-editor')
|
||||
).querySelector('.cm-content') as HTMLElement;
|
||||
editor.focus();
|
||||
await user.keyboard('{Meta>}{Enter}{/Meta}');
|
||||
|
||||
expect(handleRunQueryMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not crash when builder.queryFormulas/queryTraceOperator are missing (partial/legacy query)', () => {
|
||||
@@ -250,15 +262,12 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
});
|
||||
|
||||
describe('query actions menu', () => {
|
||||
const openQueryActions = async (): Promise<void> => {
|
||||
await userEvent.click(screen.getAllByTestId('query-actions')[0]);
|
||||
};
|
||||
|
||||
it('Clone calls cloneQuery with the query', async () => {
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
const user = userEvent.setup();
|
||||
renderQueryV2(1);
|
||||
|
||||
await openQueryActions();
|
||||
await userEvent.click(
|
||||
await user.click(screen.getByTestId('query-actions'));
|
||||
await user.click(
|
||||
await screen.findByTestId('query-actions-item-clone-query'),
|
||||
);
|
||||
|
||||
@@ -270,9 +279,10 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
});
|
||||
|
||||
it('hides Delete when there is a single query', async () => {
|
||||
render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
|
||||
const user = userEvent.setup();
|
||||
renderQueryV2(1);
|
||||
|
||||
await openQueryActions();
|
||||
await user.click(screen.getByTestId('query-actions'));
|
||||
await screen.findByTestId('query-actions-item-clone-query');
|
||||
|
||||
expect(
|
||||
@@ -281,39 +291,26 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
});
|
||||
|
||||
it('shows Delete with more than one query and deletes on click', async () => {
|
||||
const [queryA] = (baseQBContext.currentQuery as Query).builder.queryData;
|
||||
const user = userEvent.setup();
|
||||
const handleDeleteQuery = jest.fn();
|
||||
mockedUseQueryOperations.mockReturnValue({
|
||||
...mockedUseQueryOperations({} as Parameters<UseQueryOperations>[0]),
|
||||
handleDeleteQuery,
|
||||
});
|
||||
|
||||
render(
|
||||
<QueryBuilderV2Provider>
|
||||
<QueryV2
|
||||
index={0}
|
||||
query={queryA}
|
||||
version="v4"
|
||||
isAvailableToDisable={false}
|
||||
isMultiQueryAllowed
|
||||
queriesCount={2}
|
||||
onSignalSourceChange={jest.fn()}
|
||||
signalSourceChangeEnabled={false}
|
||||
savePreviousQuery={false}
|
||||
/>
|
||||
</QueryBuilderV2Provider>,
|
||||
);
|
||||
renderQueryV2(2);
|
||||
|
||||
await openQueryActions();
|
||||
await userEvent.click(
|
||||
await user.click(screen.getByTestId('query-actions'));
|
||||
await user.click(
|
||||
await screen.findByTestId('query-actions-item-delete-query'),
|
||||
);
|
||||
|
||||
expect(handleDeleteQuery).toHaveBeenCalledTimes(1);
|
||||
}, 15000);
|
||||
});
|
||||
});
|
||||
|
||||
it('fx button is disabled when functions already exist', () => {
|
||||
it('fx button is disabled when functions already exist', async () => {
|
||||
const user = userEvent.setup();
|
||||
const currentQueryBase = baseQBContext.currentQuery as Query;
|
||||
const supersetQueryBase = baseQBContext.supersetQuery as Query;
|
||||
|
||||
@@ -359,9 +356,7 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
|
||||
'.query-function-delete-btn',
|
||||
) as HTMLButtonElement;
|
||||
expect(deleteButton).toBeInTheDocument();
|
||||
userEvent.click(deleteButton);
|
||||
waitFor(() => {
|
||||
expect(fxButton).not.toBeDisabled();
|
||||
});
|
||||
await user.click(deleteButton);
|
||||
expect(fxButton).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -193,6 +193,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
placeholder="Select a query"
|
||||
value={queryOptions.find((f) => f.value === validQueryIndex)?.label || ''}
|
||||
className="select-box"
|
||||
testId="quick-filters-query-select"
|
||||
/>
|
||||
{open && (
|
||||
<ComboboxContent>
|
||||
@@ -207,6 +208,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
setOpen(false);
|
||||
}}
|
||||
isSelected={validQueryIndex === option.value}
|
||||
testId={`quick-filters-query-option-${option.value}`}
|
||||
>
|
||||
{option.label}
|
||||
</ComboboxItem>
|
||||
@@ -300,6 +302,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
color="primary"
|
||||
textPlacement="right"
|
||||
value={showIP ?? true}
|
||||
testId="quick-filters-show-ip"
|
||||
onChange={(checked): void => {
|
||||
logEvent('API Monitoring: Show IP addresses clicked', {
|
||||
showIP: checked,
|
||||
|
||||
@@ -52,6 +52,7 @@ function SortableFilter({
|
||||
<Button
|
||||
className="remove-filter-btn periscope-btn"
|
||||
size="small"
|
||||
data-testid={`quick-filters-remove-${filter.key}`}
|
||||
onClick={(): void => {
|
||||
onRemove(filter);
|
||||
}}
|
||||
@@ -103,7 +104,7 @@ function AddedFilters({
|
||||
const allowRemove = addedFilters.length > 1;
|
||||
|
||||
return (
|
||||
<div className="qf-filters added-filters">
|
||||
<div className="qf-filters added-filters" data-testid="quick-filters-added">
|
||||
<div className="qf-filters-header">ADDED FILTERS</div>
|
||||
<div className="qf-added-filters-list">
|
||||
<OverlayScrollbar>
|
||||
|
||||
@@ -102,6 +102,7 @@ function OtherFilters({
|
||||
<Button
|
||||
className="add-filter-btn periscope-btn"
|
||||
size="small"
|
||||
data-testid={`quick-filters-add-${filter.key}`}
|
||||
onClick={(): void => handleAddFilter(filter)}
|
||||
>
|
||||
Add
|
||||
@@ -111,7 +112,7 @@ function OtherFilters({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="qf-filters other-filters">
|
||||
<div className="qf-filters other-filters" data-testid="quick-filters-other">
|
||||
<div className="qf-filters-header">OTHER FILTERS</div>
|
||||
<div className="qf-other-filters-list">
|
||||
<OverlayScrollbar>
|
||||
|
||||
@@ -83,6 +83,7 @@ function QuickFiltersSettings({
|
||||
<Button
|
||||
type="default"
|
||||
onClick={handleDiscardChanges}
|
||||
data-testid="quick-filters-settings-discard"
|
||||
icon={<X size={16} />}
|
||||
>
|
||||
Discard
|
||||
@@ -92,6 +93,7 @@ function QuickFiltersSettings({
|
||||
onClick={handleSaveChanges}
|
||||
icon={<Check size={16} />}
|
||||
loading={isUpdatingCustomFilters}
|
||||
data-testid="quick-filters-settings-save"
|
||||
>
|
||||
Save changes
|
||||
</Button>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
QuickfiltertypesSourceDTO,
|
||||
TelemetrytypesSignalDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import {
|
||||
ApiMonitoringParams,
|
||||
@@ -15,10 +18,12 @@ import {
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
|
||||
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
import QuickFilters from '../QuickFilters';
|
||||
import QuickFiltersSettings from '../QuickFiltersSettings/QuickFiltersSettings';
|
||||
import { IQuickFiltersConfig, QuickFiltersSource } from '../types';
|
||||
import { QuickFiltersConfig, QuickFiltersFieldApis } from './constants';
|
||||
|
||||
@@ -26,6 +31,17 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: jest.fn(),
|
||||
}));
|
||||
jest.mock('container/ApiMonitoring/queryParams');
|
||||
jest.mock(
|
||||
'components/OverlayScrollbar/OverlayScrollbar',
|
||||
() =>
|
||||
function MockOverlayScrollbar({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}): JSX.Element {
|
||||
return <div>{children}</div>;
|
||||
},
|
||||
);
|
||||
|
||||
const handleFilterVisibilityChange = jest.fn();
|
||||
const redirectWithQueryBuilderData = jest.fn();
|
||||
@@ -44,14 +60,27 @@ const fieldsValuesURL = `${BASE_URL}/api/v1/fields/values`;
|
||||
|
||||
const FILTER_OS_DESCRIPTION = 'os.description';
|
||||
const FILTER_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name';
|
||||
const ADDED_FILTERS_LABEL = /ADDED FILTERS/i;
|
||||
const OTHER_FILTERS_LABEL = /OTHER FILTERS/i;
|
||||
const SAVE_CHANGES_TEXT = 'Save changes';
|
||||
const DISCARD_TEXT = 'Discard';
|
||||
const ADDED_FILTERS_TEST_ID = 'quick-filters-added';
|
||||
const OTHER_FILTERS_TEST_ID = 'quick-filters-other';
|
||||
const SAVE_TEST_ID = 'quick-filters-settings-save';
|
||||
const SETTINGS_TEST_ID = 'settings-icon-container';
|
||||
const REMOVE_OS_DESCRIPTION_TEST_ID =
|
||||
'quick-filters-remove-resource:os.description:string';
|
||||
const ADD_K8S_DEPLOYMENT_NAME_TEST_ID =
|
||||
'quick-filters-add-resource:k8s.deployment.name:string';
|
||||
const FILTER_SERVICE_NAME = 'Service Name';
|
||||
const SETTINGS_ICON_TEST_ID = 'settings-icon';
|
||||
const QUERY_NAME = 'Test Query';
|
||||
|
||||
const savedFilters = quickFiltersListResponse.data
|
||||
.filters as TelemetryFieldKey[];
|
||||
const smallFiltersListResponse = {
|
||||
...quickFiltersListResponse,
|
||||
data: {
|
||||
...quickFiltersListResponse.data,
|
||||
filters: savedFilters.slice(0, 2),
|
||||
},
|
||||
};
|
||||
|
||||
const setupServer = (): void => {
|
||||
server.use(
|
||||
rest.get(quickFiltersListURL, (_, res, ctx) =>
|
||||
@@ -95,6 +124,24 @@ TestQuickFilters.defaultProps = {
|
||||
config: QuickFiltersConfig,
|
||||
};
|
||||
|
||||
function renderSettings(): void {
|
||||
render(
|
||||
<QuickFiltersSettings
|
||||
savedFiltersSource={QuickfiltertypesSourceDTO.logs}
|
||||
setIsSettingsOpen={jest.fn()}
|
||||
customFilters={savedFilters}
|
||||
refetchCustomFilters={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
async function openSettings(
|
||||
user: ReturnType<typeof userEvent.setup>,
|
||||
): Promise<void> {
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
await user.click(screen.getByTestId(SETTINGS_TEST_ID));
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
server.listen();
|
||||
});
|
||||
@@ -102,6 +149,7 @@ beforeAll(() => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
jest.clearAllMocks();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
@@ -139,7 +187,7 @@ describe('Quick Filters', () => {
|
||||
|
||||
it('should display and allow selection from query dropdown when multiple queries exist', async () => {
|
||||
const setLastUsedQuery = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useQueryBuilder as jest.Mock).mockReturnValue({
|
||||
currentQuery: {
|
||||
@@ -169,27 +217,28 @@ describe('Quick Filters', () => {
|
||||
render(<TestQuickFilters />);
|
||||
|
||||
// The dropdown trigger should show the first query name
|
||||
const trigger = screen.getByText('Query A');
|
||||
expect(trigger).toBeInTheDocument();
|
||||
const trigger = screen.getByTestId('quick-filters-query-select');
|
||||
expect(trigger).toHaveTextContent('Query A');
|
||||
|
||||
// Click to open the dropdown
|
||||
await user.click(trigger);
|
||||
|
||||
// All query options should be visible
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('option', { name: 'Query A' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('option', { name: 'Query B' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('option', { name: 'Query C' })).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('quick-filters-query-option-0'),
|
||||
).resolves.toHaveTextContent('Query A');
|
||||
expect(screen.getByTestId('quick-filters-query-option-1')).toHaveTextContent(
|
||||
'Query B',
|
||||
);
|
||||
expect(screen.getByTestId('quick-filters-query-option-2')).toHaveTextContent(
|
||||
'Query C',
|
||||
);
|
||||
|
||||
// Select Query B
|
||||
const queryBOption = screen.getByRole('option', { name: 'Query B' });
|
||||
await user.click(queryBOption);
|
||||
await user.click(screen.getByTestId('quick-filters-query-option-1'));
|
||||
|
||||
// Verify setLastUsedQuery was called with index 1
|
||||
await waitFor(() => {
|
||||
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
|
||||
});
|
||||
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should not display query dropdown in ListView', () => {
|
||||
@@ -235,7 +284,7 @@ describe('Quick Filters', () => {
|
||||
});
|
||||
|
||||
it('should add filter data to query when checkbox is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<TestQuickFilters />);
|
||||
|
||||
@@ -267,33 +316,27 @@ describe('Quick Filters', () => {
|
||||
});
|
||||
});
|
||||
it('toggles Show IP addresses and updates API Monitoring params', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.API_MONITORING} />,
|
||||
);
|
||||
|
||||
// Switch should be rendered and initially checked
|
||||
await expect(
|
||||
screen.findByText('Show IP addresses'),
|
||||
).resolves.toBeInTheDocument();
|
||||
const toggle = screen.getByRole('switch');
|
||||
const toggle = await screen.findByTestId('quick-filters-show-ip');
|
||||
expect(screen.getByText('Show IP addresses')).toBeInTheDocument();
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'true');
|
||||
|
||||
await user.click(toggle);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSetApiMonitoringParams).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ showIP: false }),
|
||||
);
|
||||
});
|
||||
expect(mockSetApiMonitoringParams).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ showIP: false }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Quick Filters with custom filters', () => {
|
||||
it('loads the custom filters correctly', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
@@ -304,28 +347,32 @@ describe('Quick Filters with custom filters', () => {
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
const allByText = await screen.findAllByText('otel-demo');
|
||||
expect(allByText).toHaveLength(2);
|
||||
});
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
await expect(
|
||||
screen.findByText('Edit quick filters'),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
|
||||
expect(addedSection).toContainElement(
|
||||
await screen.findByText(FILTER_OS_DESCRIPTION),
|
||||
it('opens the settings with the saved filters added and the rest under other filters', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
rest.get(quickFiltersListURL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(smallFiltersListResponse)),
|
||||
),
|
||||
);
|
||||
|
||||
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
|
||||
expect(otherSection).toContainElement(
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
await openSettings(user);
|
||||
|
||||
expect(screen.getByText('Edit quick filters')).toBeInTheDocument();
|
||||
expect(screen.getByTestId(ADDED_FILTERS_TEST_ID)).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
expect(screen.getByTestId(OTHER_FILTERS_TEST_ID)).toContainElement(
|
||||
await screen.findByText(FILTER_K8S_DEPLOYMENT_NAME),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps same-name fields with different context as distinct entries', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
server.use(
|
||||
rest.get(quickFiltersSuggestionsURL, (_req, res, ctx) =>
|
||||
res(
|
||||
@@ -356,153 +403,86 @@ describe('Quick Filters with custom filters', () => {
|
||||
),
|
||||
);
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
renderSettings();
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
|
||||
const otherSection = screen.getByTestId(OTHER_FILTERS_TEST_ID);
|
||||
// Both `level` variants are shown despite sharing a name.
|
||||
await waitFor(() =>
|
||||
expect(within(otherSection).getAllByText('level')).toHaveLength(2),
|
||||
const addButton = await screen.findByTestId(
|
||||
'quick-filters-add-attribute:level:string',
|
||||
);
|
||||
expect(within(otherSection).getAllByText('level')).toHaveLength(2);
|
||||
|
||||
// Adding one variant removes only that one; the other stays.
|
||||
const firstLevel = within(otherSection).getAllByText('level')[0];
|
||||
const addButton = firstLevel.parentElement?.querySelector('button');
|
||||
await user.click(addButton as HTMLButtonElement);
|
||||
await user.click(addButton);
|
||||
|
||||
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
|
||||
await waitFor(() => {
|
||||
expect(within(addedSection).getAllByText('level')).toHaveLength(1);
|
||||
expect(within(otherSection).getAllByText('level')).toHaveLength(1);
|
||||
});
|
||||
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
|
||||
expect(within(addedSection).getAllByText('level')).toHaveLength(1);
|
||||
expect(within(otherSection).getAllByText('level')).toHaveLength(1);
|
||||
expect(
|
||||
screen.getByTestId('quick-filters-add-span:level:string'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('adds a filter from OTHER FILTERS to ADDED FILTERS when clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
renderSettings();
|
||||
|
||||
await user.click(await screen.findByTestId(ADD_K8S_DEPLOYMENT_NAME_TEST_ID));
|
||||
|
||||
expect(screen.getByTestId(ADDED_FILTERS_TEST_ID)).toHaveTextContent(
|
||||
FILTER_K8S_DEPLOYMENT_NAME,
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
const otherFilterItem = await screen.findByText(FILTER_K8S_DEPLOYMENT_NAME);
|
||||
const addButton = otherFilterItem.parentElement?.querySelector('button');
|
||||
expect(addButton).not.toBeNull();
|
||||
await user.click(addButton as HTMLButtonElement);
|
||||
|
||||
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
|
||||
await waitFor(() => {
|
||||
expect(addedSection).toHaveTextContent(FILTER_K8S_DEPLOYMENT_NAME);
|
||||
});
|
||||
});
|
||||
|
||||
it('removes a filter from ADDED FILTERS and moves it to OTHER FILTERS', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
renderSettings();
|
||||
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
|
||||
const otherSection = screen.getByTestId(OTHER_FILTERS_TEST_ID);
|
||||
await screen.findByTestId(ADD_K8S_DEPLOYMENT_NAME_TEST_ID);
|
||||
|
||||
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
|
||||
|
||||
expect(addedSection).not.toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
|
||||
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
|
||||
const removeBtn = target.parentElement?.querySelector('button');
|
||||
expect(removeBtn).not.toBeNull();
|
||||
|
||||
await user.click(removeBtn as HTMLButtonElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(addedSection).not.toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
});
|
||||
|
||||
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
|
||||
expect(otherSection).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
});
|
||||
|
||||
it('restores original filter state on Discard', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
renderSettings();
|
||||
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
|
||||
const otherSection = screen.getByTestId(OTHER_FILTERS_TEST_ID);
|
||||
await screen.findByTestId(ADD_K8S_DEPLOYMENT_NAME_TEST_ID);
|
||||
|
||||
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
|
||||
expect(otherSection).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
await user.click(screen.getByTestId('quick-filters-settings-discard'));
|
||||
|
||||
const addedSection = screen.getByText(ADDED_FILTERS_LABEL).parentElement!;
|
||||
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
|
||||
const removeBtn = target.parentElement?.querySelector('button');
|
||||
expect(removeBtn).not.toBeNull();
|
||||
await user.click(removeBtn as HTMLButtonElement);
|
||||
|
||||
const otherSection = screen.getByText(OTHER_FILTERS_LABEL).parentElement!;
|
||||
await waitFor(() => {
|
||||
expect(addedSection).not.toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
expect(otherSection).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
});
|
||||
|
||||
const discardBtn = screen
|
||||
.getByText(DISCARD_TEXT)
|
||||
.closest('button') as HTMLButtonElement;
|
||||
expect(discardBtn).not.toBeNull();
|
||||
await user.click(discardBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(addedSection).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
expect(otherSection).not.toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
});
|
||||
expect(addedSection).toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
expect(otherSection).not.toContainElement(
|
||||
screen.getByText(FILTER_OS_DESCRIPTION),
|
||||
);
|
||||
});
|
||||
|
||||
it('saves the updated filters by calling PUT with correct payload', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
renderSettings();
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
|
||||
const removeBtn = target.parentElement?.querySelector('button');
|
||||
expect(removeBtn).not.toBeNull();
|
||||
await user.click(removeBtn as HTMLButtonElement);
|
||||
|
||||
const saveBtn = screen
|
||||
.getByText(SAVE_CHANGES_TEXT)
|
||||
.closest('button') as HTMLButtonElement;
|
||||
expect(saveBtn).not.toBeNull();
|
||||
await user.click(saveBtn);
|
||||
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
|
||||
await user.click(screen.getByTestId(SAVE_TEST_ID));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(putHandler).toHaveBeenCalled();
|
||||
@@ -516,24 +496,37 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('should render duration slider for duration_nono filter', async () => {
|
||||
server.use(
|
||||
rest.get(quickFiltersListURL, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
...quickFiltersListResponse,
|
||||
data: {
|
||||
...quickFiltersListResponse.data,
|
||||
filters: savedFilters.filter(({ name }) => name === 'duration_nano'),
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
// Use fake timers only in this test (for debounce), and wire them to userEvent
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
pointerEventsCheck: 0,
|
||||
});
|
||||
|
||||
const { getByTestId } = render(
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
await screen.findByTestId('collapse-duration');
|
||||
expect(screen.getByText('Duration')).toBeInTheDocument();
|
||||
|
||||
// Open the duration section (use role if it’s a button/collapse)
|
||||
await user.click(screen.getByText('Duration'));
|
||||
|
||||
const minDuration = getByTestId('min-input') as HTMLInputElement;
|
||||
const maxDuration = getByTestId('max-input') as HTMLInputElement;
|
||||
const minDuration = screen.getByTestId('min-input') as HTMLInputElement;
|
||||
const maxDuration = screen.getByTestId('max-input') as HTMLInputElement;
|
||||
|
||||
expect(minDuration).toHaveValue(null);
|
||||
expect(minDuration).toHaveProperty('placeholder', '0');
|
||||
@@ -635,7 +628,7 @@ describe('Quick Filters refetch behavior', () => {
|
||||
server.use(
|
||||
rest.get(quickFiltersListURL, (_req, res, ctx) => {
|
||||
getCalls += 1;
|
||||
return res(ctx.status(200), ctx.json(quickFiltersListResponse));
|
||||
return res(ctx.status(200), ctx.json(smallFiltersListResponse));
|
||||
}),
|
||||
rest.put(saveQuickFiltersURL, async (req, res, ctx) => {
|
||||
putHandler(await req.json());
|
||||
@@ -643,26 +636,14 @@ describe('Quick Filters refetch behavior', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByText(FILTER_SERVICE_NAME),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
|
||||
const removeBtn = target.parentElement?.querySelector(
|
||||
'button',
|
||||
) as HTMLButtonElement;
|
||||
await user.click(removeBtn);
|
||||
|
||||
await user.click(screen.getByText(SAVE_CHANGES_TEXT));
|
||||
await openSettings(user);
|
||||
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
|
||||
await user.click(screen.getByTestId(SAVE_TEST_ID));
|
||||
|
||||
await waitFor(() => expect(putHandler).toHaveBeenCalled());
|
||||
await waitFor(() => expect(getCalls).toBeGreaterThanOrEqual(2));
|
||||
@@ -670,11 +651,11 @@ describe('Quick Filters refetch behavior', () => {
|
||||
|
||||
it('renders updated filters after refetch post-save', async () => {
|
||||
const updatedResponse = {
|
||||
...quickFiltersListResponse,
|
||||
...smallFiltersListResponse,
|
||||
data: {
|
||||
...quickFiltersListResponse.data,
|
||||
...smallFiltersListResponse.data,
|
||||
filters: [
|
||||
...(quickFiltersListResponse.data.filters ?? []),
|
||||
...smallFiltersListResponse.data.filters,
|
||||
{
|
||||
name: 'new.custom.filter',
|
||||
fieldDataType: 'string',
|
||||
@@ -690,38 +671,26 @@ describe('Quick Filters refetch behavior', () => {
|
||||
getCount += 1;
|
||||
return getCount >= 2
|
||||
? res(ctx.status(200), ctx.json(updatedResponse))
|
||||
: res(ctx.status(200), ctx.json(quickFiltersListResponse));
|
||||
: res(ctx.status(200), ctx.json(smallFiltersListResponse));
|
||||
}),
|
||||
rest.put(saveQuickFiltersURL, async (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({})),
|
||||
),
|
||||
);
|
||||
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByText(FILTER_SERVICE_NAME),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
const icon = await screen.findByTestId(SETTINGS_ICON_TEST_ID);
|
||||
const settingsButton = icon.closest('button') ?? icon;
|
||||
await user.click(settingsButton);
|
||||
|
||||
await openSettings(user);
|
||||
// Make a minimal change so Save button appears
|
||||
const target = await screen.findByText(FILTER_OS_DESCRIPTION);
|
||||
const removeBtn = target.parentElement?.querySelector(
|
||||
'button',
|
||||
) as HTMLButtonElement;
|
||||
await user.click(removeBtn);
|
||||
await user.click(screen.getByTestId(REMOVE_OS_DESCRIPTION_TEST_ID));
|
||||
await user.click(screen.getByTestId(SAVE_TEST_ID));
|
||||
|
||||
await user.click(screen.getByText(SAVE_CHANGES_TEXT));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('New Custom Filter')).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByText('New Custom Filter'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows empty state when GET fails', async () => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -44,6 +44,7 @@ function SaveErrorItem({
|
||||
variant="link"
|
||||
color="secondary"
|
||||
aria-label="Retry"
|
||||
testId="sa-error-retry-btn"
|
||||
onClick={async (e): Promise<void> => {
|
||||
e.stopPropagation();
|
||||
setIsRetrying(true);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ServiceAccountRow } from 'container/ServiceAccountsSettings/utils';
|
||||
import {
|
||||
listRolesSuccessResponse,
|
||||
managedRoles,
|
||||
@@ -15,22 +16,25 @@ import {
|
||||
buildSADeletePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/service-account.permissions';
|
||||
|
||||
import KeysTab from '../KeysTab';
|
||||
import OverviewTab from '../OverviewTab';
|
||||
import ServiceAccountDrawer from '../ServiceAccountDrawer';
|
||||
|
||||
const ROLES_ENDPOINT = '*/api/v1/roles';
|
||||
const SA_KEYS_ENDPOINT = '*/api/v1/service_accounts/:id/keys';
|
||||
const SA_ENDPOINT = '*/api/v1/service_accounts/sa-1';
|
||||
const SA_DELETE_ENDPOINT = '*/api/v1/service_accounts/sa-1';
|
||||
const SA_ROLES_ENDPOINT = '*/api/v1/service_account_roles';
|
||||
const SA_ROLE_DELETE_ENDPOINT = '*/api/v1/service_account_roles/:id';
|
||||
|
||||
const activeAccountResponse = {
|
||||
const account: ServiceAccountRow = {
|
||||
id: 'sa-1',
|
||||
name: 'CI Bot',
|
||||
email: 'ci-bot@signoz.io',
|
||||
status: 'ACTIVE',
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-02T00:00:00Z',
|
||||
};
|
||||
|
||||
const activeAccountResponse = {
|
||||
...account,
|
||||
serviceAccountRoles: [
|
||||
{
|
||||
id: 'sar-admin-1',
|
||||
@@ -41,93 +45,88 @@ const activeAccountResponse = {
|
||||
],
|
||||
};
|
||||
|
||||
function renderDrawer(
|
||||
searchParams: Record<string, string> = { account: 'sa-1' },
|
||||
): ReturnType<typeof render> {
|
||||
function renderOverviewTab(): ReturnType<typeof render> {
|
||||
return render(
|
||||
<NuqsTestingAdapter searchParams={searchParams} hasMemory>
|
||||
<ServiceAccountDrawer onSuccess={jest.fn()} />
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
}
|
||||
|
||||
function setupBaseHandlers(): void {
|
||||
server.use(
|
||||
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
|
||||
),
|
||||
rest.get(SA_KEYS_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: [] })),
|
||||
),
|
||||
rest.get(SA_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: activeAccountResponse })),
|
||||
),
|
||||
rest.put(SA_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
|
||||
),
|
||||
rest.delete(SA_DELETE_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
|
||||
),
|
||||
rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(201),
|
||||
ctx.json({ status: 'success', data: { id: 'sar-new' } }),
|
||||
),
|
||||
),
|
||||
rest.delete(SA_ROLE_DELETE_ENDPOINT, (_, res, ctx) => res(ctx.status(204))),
|
||||
<OverviewTab
|
||||
account={account}
|
||||
localName="CI Bot"
|
||||
onNameChange={jest.fn()}
|
||||
localRoles={[]}
|
||||
onRolesChange={jest.fn()}
|
||||
isDisabled={false}
|
||||
availableRoles={[]}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ServiceAccountDrawer — permissions', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
setupBaseHandlers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('shows PermissionDeniedCallout inside drawer when read permission is denied', async () => {
|
||||
it('shows PermissionDeniedCallout in the Overview tab when read permission is denied', async () => {
|
||||
server.use(setupAuthzDenyAll());
|
||||
|
||||
renderDrawer();
|
||||
renderOverviewTab();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/read:serviceaccount/)).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('permission-denied-callout'),
|
||||
).resolves.toHaveTextContent('read:serviceaccount:sa-1');
|
||||
});
|
||||
|
||||
it('shows drawer content when read permission is granted', async () => {
|
||||
it('shows Overview tab content when read permission is granted', async () => {
|
||||
server.use(setupAuthzAdmin());
|
||||
|
||||
renderDrawer();
|
||||
renderOverviewTab();
|
||||
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
expect(screen.queryByText(/serviceaccount:read/)).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('permission-denied-callout'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows PermissionDeniedCallout in Keys tab when list-keys permission is denied', async () => {
|
||||
server.use(setupAuthzDeny(APIKeyListPermission));
|
||||
|
||||
renderDrawer({ account: 'sa-1', tab: 'keys' });
|
||||
render(
|
||||
<KeysTab
|
||||
keys={[]}
|
||||
isLoading={false}
|
||||
accountId="sa-1"
|
||||
currentPage={1}
|
||||
pageSize={15}
|
||||
onPageChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/list:factor-api-key/)).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('permission-denied-callout'),
|
||||
).resolves.toHaveTextContent('list:factor-api-key:*');
|
||||
});
|
||||
|
||||
it('disables Delete button when delete permission is denied', async () => {
|
||||
server.use(setupAuthzDeny(buildSADeletePermission('sa-1')));
|
||||
|
||||
renderDrawer();
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
|
||||
const deleteBtn = screen.getByRole('button', {
|
||||
name: /Delete Service Account/i,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(deleteBtn).toHaveAttribute('aria-disabled', 'true'),
|
||||
server.use(
|
||||
rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
|
||||
),
|
||||
rest.get(SA_KEYS_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: [] })),
|
||||
),
|
||||
rest.get(SA_ENDPOINT, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json({ data: activeAccountResponse })),
|
||||
),
|
||||
setupAuthzDeny(buildSADeletePermission('sa-1')),
|
||||
);
|
||||
|
||||
render(
|
||||
<NuqsTestingAdapter searchParams={{ account: 'sa-1' }} hasMemory>
|
||||
<ServiceAccountDrawer onSuccess={jest.fn()} />
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
|
||||
const deleteBtn = await screen.findByTestId('sa-delete-btn');
|
||||
await waitFor(() =>
|
||||
expect(deleteBtn).toHaveAttribute(
|
||||
'data-denied-permissions',
|
||||
buildSADeletePermission('sa-1'),
|
||||
),
|
||||
);
|
||||
expect(deleteBtn).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
} from 'mocks-server/__mockdata__/roles';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
|
||||
import ServiceAccountDrawer from '../ServiceAccountDrawer';
|
||||
@@ -93,7 +93,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
screen.findByDisplayValue('CI Bot'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText('ci-bot@signoz.io')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Save Changes/i })).toHaveAttribute(
|
||||
expect(screen.getByTestId('sa-save-btn')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
);
|
||||
@@ -102,7 +102,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
it('editing name enables Save; clicking Save sends correct payload and calls onSuccess', async () => {
|
||||
const onSuccess = jest.fn();
|
||||
const updateSpy = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.put(SA_ENDPOINT, async (req, res, ctx) => {
|
||||
@@ -121,7 +121,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'CI Bot Updated');
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -140,7 +140,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
it('adding a role fires POST for the new role and no DELETE for existing roles', async () => {
|
||||
const roleSpy = jest.fn();
|
||||
const deleteSpy = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(SA_ROLES_ENDPOINT, async (req, res, ctx) => {
|
||||
@@ -164,7 +164,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
await user.click(screen.getByLabelText('Roles'));
|
||||
await user.click(await screen.findByTitle('signoz-viewer'));
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -184,7 +184,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
it('removing a role fires DELETE for the removed role and no POST', async () => {
|
||||
const roleSpy = jest.fn();
|
||||
const deleteSpy = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(SA_ROLES_ENDPOINT, async (req, res, ctx) => {
|
||||
@@ -211,7 +211,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
) as Element;
|
||||
await user.click(removeBtn);
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -225,7 +225,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
|
||||
it('"Delete Service Account" opens confirm dialog; confirming sends delete request', async () => {
|
||||
const deleteSpy = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.delete(SA_DELETE_ENDPOINT, (_, res, ctx) => {
|
||||
@@ -238,9 +238,7 @@ describe('ServiceAccountDrawer', () => {
|
||||
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: /Delete Service Account/i }),
|
||||
);
|
||||
await user.click(screen.getByTestId('sa-delete-btn'));
|
||||
|
||||
await screen.findByTestId('delete-service-account-modal');
|
||||
expect(
|
||||
@@ -272,23 +270,19 @@ describe('ServiceAccountDrawer', () => {
|
||||
|
||||
await screen.findByText('CI Bot');
|
||||
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /Save Changes/i }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /Delete Service Account/i }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('sa-save-btn')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('sa-delete-btn')).not.toBeInTheDocument();
|
||||
expect(screen.queryByDisplayValue('CI Bot')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('switching to Keys tab shows "No keys" empty state', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Keys/i }));
|
||||
await user.click(screen.getByTestId('sa-tab-button-keys'));
|
||||
|
||||
await expect(screen.findByText(/No keys/i)).resolves.toBeInTheDocument();
|
||||
});
|
||||
@@ -341,11 +335,12 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('name update failure shows SaveErrorItem with "Name update" context', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.put(SA_ENDPOINT, (_, res, ctx) =>
|
||||
@@ -367,7 +362,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'New Name');
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -381,7 +376,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
});
|
||||
|
||||
it('role add failure shows SaveErrorItem with the role name context', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) =>
|
||||
@@ -405,7 +400,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
await user.click(screen.getByLabelText('Roles'));
|
||||
await user.click(await screen.findByTitle('signoz-viewer'));
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -419,7 +414,11 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
});
|
||||
|
||||
it('role add retries on 429 then succeeds without showing an error', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
const onSuccess = jest.fn();
|
||||
let roleAddCallCount = 0;
|
||||
|
||||
// First call → 429, second call → 201
|
||||
@@ -436,31 +435,35 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
renderDrawer();
|
||||
render(
|
||||
<NuqsTestingAdapter searchParams={{ account: 'sa-1' }} hasMemory>
|
||||
<ServiceAccountDrawer onSuccess={onSuccess} />
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
|
||||
await screen.findByDisplayValue('CI Bot');
|
||||
|
||||
await user.click(screen.getByLabelText('Roles'));
|
||||
await user.click(await screen.findByTitle('signoz-viewer'));
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
await user.click(saveBtn);
|
||||
|
||||
// Retried after 429 — at least 2 calls, no error shown
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(roleAddCallCount).toBeGreaterThanOrEqual(2);
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
await waitFor(() => expect(roleAddCallCount).toBe(1));
|
||||
await act(() => jest.advanceTimersByTimeAsync(1000));
|
||||
await waitFor(() =>
|
||||
expect(onSuccess).toHaveBeenCalledWith({ closeDrawer: false }),
|
||||
);
|
||||
expect(roleAddCallCount).toBe(2);
|
||||
expect(screen.queryByText(/role assign failed/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('sa-error-retry-btn')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking Retry on a name-update error re-triggers the request; on success the error item is removed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
// First: PUT always fails so the error appears
|
||||
server.use(
|
||||
@@ -483,7 +486,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, 'Retry Test');
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
|
||||
const saveBtn = screen.getByTestId('sa-save-btn');
|
||||
await waitFor(() =>
|
||||
expect(saveBtn).not.toHaveAttribute('aria-disabled', 'true'),
|
||||
);
|
||||
@@ -499,7 +502,7 @@ describe('ServiceAccountDrawer – save-error UX', () => {
|
||||
),
|
||||
);
|
||||
|
||||
const retryBtn = screen.getByRole('button', { name: /Retry/i });
|
||||
const retryBtn = screen.getByTestId('sa-error-retry-btn');
|
||||
await user.click(retryBtn);
|
||||
|
||||
// Error item should be removed after successful retry
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import TagKeyValueInput from './TagKeyValueInput';
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -66,6 +66,10 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('commits a manually-retryable error bubble with friendly copy and metadata', async () => {
|
||||
chat.createThread.mockResolvedValue('thread-1');
|
||||
chat.sendMessage.mockResolvedValue('exec-1');
|
||||
@@ -135,6 +139,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
});
|
||||
|
||||
it('silently retries auto-flagged errors, then downgrades to manual once spent', async () => {
|
||||
jest.useFakeTimers();
|
||||
chat.createThread.mockResolvedValue('thread-2');
|
||||
chat.sendMessage.mockResolvedValue('exec');
|
||||
// Always auto-retryable: 1 initial attempt + MAX_AUTO_RETRIES (2) = 3 sends.
|
||||
@@ -145,7 +150,9 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
);
|
||||
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
await useAIAssistantStore.getState().sendMessage('hi');
|
||||
const sending = useAIAssistantStore.getState().sendMessage('hi');
|
||||
await jest.runAllTimersAsync();
|
||||
await sending;
|
||||
|
||||
expect(chat.sendMessage).toHaveBeenCalledTimes(3);
|
||||
expect(lastMessage('thread-2')).toMatchObject({
|
||||
@@ -154,7 +161,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
// Auto budget exhausted → presented as manual so a Retry button shows.
|
||||
retryAction: RetryActionDTO.manual,
|
||||
});
|
||||
}, 10000);
|
||||
});
|
||||
|
||||
it('marks rate-limit errors and offers no retry', async () => {
|
||||
chat.createThread.mockResolvedValue('thread-3');
|
||||
@@ -184,6 +191,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
});
|
||||
|
||||
it('recovers silently when an auto-flagged error succeeds on retry', async () => {
|
||||
jest.useFakeTimers();
|
||||
chat.createThread.mockResolvedValue('thread-4');
|
||||
chat.sendMessage.mockResolvedValue('exec');
|
||||
chat.streamEvents
|
||||
@@ -205,7 +213,9 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
);
|
||||
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
await useAIAssistantStore.getState().sendMessage('hi');
|
||||
const sending = useAIAssistantStore.getState().sendMessage('hi');
|
||||
await jest.runAllTimersAsync();
|
||||
await sending;
|
||||
|
||||
// 1 initial attempt + 1 silent auto retry, then success — no error bubble.
|
||||
expect(chat.sendMessage).toHaveBeenCalledTimes(2);
|
||||
@@ -217,7 +227,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
content: 'Recovered',
|
||||
});
|
||||
expect(conv.messages.some((m) => m.isError)).toBe(false);
|
||||
}, 10000);
|
||||
});
|
||||
|
||||
it('replays the originating action on retry for a non-send error (approve)', async () => {
|
||||
chat.approveExecution.mockResolvedValue('exec-a');
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -26,8 +26,6 @@ window.ResizeObserver =
|
||||
}));
|
||||
|
||||
describe('BillingContainer', () => {
|
||||
jest.setTimeout(30000);
|
||||
|
||||
beforeEach(() => {
|
||||
server.use(setupAuthzAdmin());
|
||||
});
|
||||
@@ -39,40 +37,47 @@ describe('BillingContainer', () => {
|
||||
it('Component should render', async () => {
|
||||
render(<BillingContainer />);
|
||||
|
||||
const dataInjection = await screen.findByRole('columnheader', {
|
||||
name: /data ingested/i,
|
||||
});
|
||||
expect(dataInjection).toBeInTheDocument();
|
||||
const pricePerUnit = await screen.findByRole('columnheader', {
|
||||
name: /price per unit/i,
|
||||
});
|
||||
expect(pricePerUnit).toBeInTheDocument();
|
||||
const cost = await screen.findByRole('columnheader', {
|
||||
name: /cost/i,
|
||||
});
|
||||
expect(cost).toBeInTheDocument();
|
||||
|
||||
const dayRemainingInBillingPeriod = await screen.findByText(
|
||||
/Please upgrade plan now to retain your data./i,
|
||||
{},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
expect(dayRemainingInBillingPeriod).toBeInTheDocument();
|
||||
|
||||
expect(
|
||||
screen.getByText('Data Ingested', { selector: 'th' }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('Price per Unit', { selector: 'th' }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('Cost', { selector: 'th' })).toBeInTheDocument();
|
||||
|
||||
const upgradePlanButton = screen.getByTestId('upgrade-plan-button');
|
||||
expect(upgradePlanButton).toBeInTheDocument();
|
||||
|
||||
const dollar = await screen.findByText(/\$1,278.3/i, {}, { timeout: 5000 });
|
||||
expect(dollar).toBeInTheDocument();
|
||||
|
||||
const currentBill = await screen.findByText('billing');
|
||||
expect(currentBill).toBeInTheDocument();
|
||||
expect(screen.getByText(/\$1,278.3/i)).toBeInTheDocument();
|
||||
expect(screen.getByText('billing')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('Trial scenarios', () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
jest.setSystemTime(new Date('2023-10-20'));
|
||||
jest.useFakeTimers({
|
||||
now: new Date('2023-10-20'),
|
||||
doNotFake: [
|
||||
'hrtime',
|
||||
'nextTick',
|
||||
'performance',
|
||||
'queueMicrotask',
|
||||
'requestAnimationFrame',
|
||||
'cancelAnimationFrame',
|
||||
'requestIdleCallback',
|
||||
'cancelIdleCallback',
|
||||
'setImmediate',
|
||||
'clearImmediate',
|
||||
'setInterval',
|
||||
'clearInterval',
|
||||
'setTimeout',
|
||||
'clearTimeout',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -88,14 +93,9 @@ describe('BillingContainer', () => {
|
||||
{ appContextOverrides: { trialInfo: licensesSuccessResponse.data } },
|
||||
);
|
||||
|
||||
// If the component schedules any setTimeout on mount, flush them:
|
||||
jest.runOnlyPendingTimers();
|
||||
|
||||
await expect(screen.findByText('Free Trial')).resolves.toBeInTheDocument();
|
||||
await expect(screen.findByText('billing')).resolves.toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByText(/\$0/i, {}, { timeout: 5000 }),
|
||||
).resolves.toBeInTheDocument();
|
||||
await expect(screen.findByText(/\$0/i)).resolves.toBeInTheDocument();
|
||||
|
||||
await expect(
|
||||
screen.findByText(
|
||||
@@ -107,18 +107,20 @@ describe('BillingContainer', () => {
|
||||
screen.findByText(/1 days_remaining/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
const upgradeButtons = await screen.findAllByRole('button', {
|
||||
name: /upgrade_plan/i,
|
||||
});
|
||||
expect(upgradeButtons).toHaveLength(2);
|
||||
expect(upgradeButtons[1]).toBeInTheDocument();
|
||||
expect(screen.getByTestId('header-billing-button')).toHaveTextContent(
|
||||
'upgrade_plan',
|
||||
);
|
||||
expect(screen.getByTestId('upgrade-plan-button')).toHaveTextContent(
|
||||
'upgrade_plan',
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByText(/checkout_plans/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByRole('link', { name: /here/i }),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText('here', { selector: 'a' })).toHaveAttribute(
|
||||
'href',
|
||||
'https://signoz.io/pricing/',
|
||||
);
|
||||
|
||||
await expect(
|
||||
screen.findByText('Cancel your subscription', { selector: 'span' }),
|
||||
@@ -141,7 +143,7 @@ describe('BillingContainer', () => {
|
||||
const currentBill = await screen.findByText('billing');
|
||||
expect(currentBill).toBeInTheDocument();
|
||||
|
||||
const dollar0 = await screen.findByText(/\$0/i, {}, { timeout: 5000 });
|
||||
const dollar0 = await screen.findByText(/\$0/i);
|
||||
expect(dollar0).toBeInTheDocument();
|
||||
|
||||
const onTrail = await screen.findByText(
|
||||
@@ -154,10 +156,9 @@ describe('BillingContainer', () => {
|
||||
);
|
||||
expect(receivedCardDetails).toBeInTheDocument();
|
||||
|
||||
const manageBillingButton = await screen.findByRole('button', {
|
||||
name: /manage_billing/i,
|
||||
});
|
||||
expect(manageBillingButton).toBeInTheDocument();
|
||||
expect(screen.getByTestId('header-billing-button')).toHaveTextContent(
|
||||
'manage_billing',
|
||||
);
|
||||
|
||||
const dayRemainingInBillingPeriod =
|
||||
await screen.findByText(/1 days_remaining/i);
|
||||
@@ -259,27 +260,26 @@ describe('BillingContainer', () => {
|
||||
billingSuccessResponse.data.billingPeriodStart,
|
||||
)} to ${getFormattedDate(billingSuccessResponse.data.billingPeriodEnd)}`;
|
||||
|
||||
const billingPeriod = await findByText(
|
||||
billingPeriodText,
|
||||
{},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
const billingPeriod = await findByText(billingPeriodText);
|
||||
expect(billingPeriod).toBeInTheDocument();
|
||||
|
||||
const currentBill = await screen.findByText('billing');
|
||||
expect(currentBill).toBeInTheDocument();
|
||||
expect(screen.getByText('billing')).toBeInTheDocument();
|
||||
expect(screen.getByText(/\$1,278.3/i)).toBeInTheDocument();
|
||||
|
||||
const dollar0 = await screen.findByText(/\$1,278.3/i);
|
||||
expect(dollar0).toBeInTheDocument();
|
||||
const cellTexts = (rowName: string): string[] =>
|
||||
Array.from(
|
||||
screen
|
||||
.getByText(rowName, { selector: 'td > div' })
|
||||
.closest('tr')
|
||||
?.querySelectorAll('td') ?? [],
|
||||
).map((cell) => cell.textContent ?? '');
|
||||
|
||||
const metricsRow = await screen.findByRole('row', {
|
||||
name: /metrics 4012 Million 0.1 \$ 401.2/i,
|
||||
});
|
||||
expect(metricsRow).toBeInTheDocument();
|
||||
|
||||
const logRow = await screen.findByRole('row', {
|
||||
name: /Logs 497 GB 0.4 \$ 198.8/i,
|
||||
});
|
||||
expect(logRow).toBeInTheDocument();
|
||||
expect(cellTexts('Metrics')).toStrictEqual([
|
||||
'Metrics',
|
||||
'4012 Million',
|
||||
'0.1',
|
||||
'$ 401.2',
|
||||
]);
|
||||
expect(cellTexts('Logs')).toStrictEqual(['Logs', '497 GB', '0.4', '$ 198.8']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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> =
|
||||
|
||||
@@ -64,6 +64,31 @@ const multiOrgProps: ForgotPasswordRouteState = {
|
||||
orgs: mockMultipleOrgs,
|
||||
};
|
||||
|
||||
function mockForgot(): {
|
||||
forgotCalls: () => number;
|
||||
holdResponse: () => () => void;
|
||||
} {
|
||||
let calls = 0;
|
||||
let pending: Promise<void> = Promise.resolve();
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, async (_req, res, ctx) => {
|
||||
calls += 1;
|
||||
await pending;
|
||||
return res(ctx.status(200), ctx.json({ status: 'success' }));
|
||||
}),
|
||||
);
|
||||
return {
|
||||
forgotCalls: (): number => calls,
|
||||
holdResponse: (): (() => void) => {
|
||||
let release: () => void = () => {};
|
||||
pending = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
return release;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('ForgotPassword Component', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -136,7 +161,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('enables submit button after selecting an organization', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<ForgotPassword {...multiOrgProps} />);
|
||||
|
||||
@@ -144,7 +169,7 @@ describe('ForgotPassword Component', () => {
|
||||
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
// Click on the dropdown to reveal the options
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
await user.click(screen.getByText('Select your organization'));
|
||||
await user.click(screen.getByText('Organization One'));
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -168,7 +193,7 @@ describe('ForgotPassword Component', () => {
|
||||
|
||||
describe('Form Submission - Success', () => {
|
||||
it('successfully submits forgot password request and shows success screen', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
|
||||
@@ -190,7 +215,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('shows back to login button on success screen', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
|
||||
@@ -209,7 +234,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('redirects to login when clicking back to login on success screen', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
|
||||
@@ -235,7 +260,7 @@ describe('ForgotPassword Component', () => {
|
||||
|
||||
describe('Form Submission - Error Handling', () => {
|
||||
it('displays error message when forgot password API fails', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(
|
||||
@@ -255,7 +280,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('displays error message when API returns server error', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(rest.post(FORGOT_PASSWORD_ENDPOINT, handleInternalServerError));
|
||||
|
||||
@@ -270,7 +295,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('clears error message on new submission attempt', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
let requestCount = 0;
|
||||
|
||||
server.use(
|
||||
@@ -314,7 +339,7 @@ describe('ForgotPassword Component', () => {
|
||||
|
||||
describe('Navigation', () => {
|
||||
it('redirects to login when clicking back button on form', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -327,13 +352,9 @@ describe('ForgotPassword Component', () => {
|
||||
|
||||
describe('Loading States', () => {
|
||||
it('shows loading state during API call', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
|
||||
res(ctx.delay(100), ctx.status(200), ctx.json({ status: 'success' })),
|
||||
),
|
||||
);
|
||||
mockForgot().holdResponse();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -347,13 +368,9 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('disables submit button during loading', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) =>
|
||||
res(ctx.delay(100), ctx.status(200), ctx.json({ status: 'success' })),
|
||||
),
|
||||
);
|
||||
mockForgot().holdResponse();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -410,23 +427,8 @@ describe('ForgotPassword Component', () => {
|
||||
// The email input is disabled and Enter in the org Select opens it, so Enter
|
||||
// only reaches the form through the focused submit button.
|
||||
describe('Enter key submission', () => {
|
||||
function mockForgot(delayMs = 0): { forgotCalls: () => number } {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) => {
|
||||
calls += 1;
|
||||
return res(
|
||||
ctx.delay(delayMs),
|
||||
ctx.status(200),
|
||||
ctx.json({ status: 'success' }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
return { forgotCalls: (): number => calls };
|
||||
}
|
||||
|
||||
it('sends the reset link once on Enter on the submit button', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const { forgotCalls } = mockForgot();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
@@ -443,7 +445,7 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('does not send on Enter while no organization is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const { forgotCalls } = mockForgot();
|
||||
|
||||
render(<ForgotPassword {...multiOrgProps} />);
|
||||
@@ -459,8 +461,9 @@ describe('ForgotPassword Component', () => {
|
||||
});
|
||||
|
||||
it('does not send again on Enter while the first request is loading', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { forgotCalls } = mockForgot(1000);
|
||||
const user = userEvent.setup();
|
||||
const { forgotCalls, holdResponse } = mockForgot();
|
||||
const releaseResponse = holdResponse();
|
||||
|
||||
render(<ForgotPassword {...defaultProps} />);
|
||||
|
||||
@@ -472,8 +475,9 @@ describe('ForgotPassword Component', () => {
|
||||
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
|
||||
await user.keyboard('{enter}');
|
||||
|
||||
releaseResponse();
|
||||
await expect(
|
||||
screen.findByText(/check your email/i, undefined, { timeout: 2000 }),
|
||||
screen.findByText(/check your email/i),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(forgotCalls()).toBe(1);
|
||||
});
|
||||
|
||||
@@ -644,6 +644,7 @@ function GeneralSettings({
|
||||
onClick={category.save.modalOpen}
|
||||
disabled={category.save.isDisabled}
|
||||
loading={category.save.isLoading}
|
||||
testId={`${category.type}-retention-save-button`}
|
||||
>
|
||||
{category.save.saveButtonText}
|
||||
</Button>
|
||||
@@ -671,6 +672,9 @@ function GeneralSettings({
|
||||
centered
|
||||
open={category.save.modal}
|
||||
confirmLoading={category.save.apiLoading}
|
||||
okButtonProps={{
|
||||
'data-testid': `${category.type}-retention-confirm-button`,
|
||||
}}
|
||||
>
|
||||
<p className="retention-modal-description">
|
||||
{t('retention_confirmation_description', {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import setRetentionApiV2 from 'api/settings/setRetentionV2';
|
||||
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
|
||||
import { fireEvent, render, screen, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { IDiskType } from 'types/api/disks/getDisks';
|
||||
import {
|
||||
PayloadPropsLogs,
|
||||
@@ -108,7 +108,8 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
});
|
||||
|
||||
describe('Test 1: S3 Enabled - Only Days in Dropdown', () => {
|
||||
it('should show only Days option for S3 retention and send correct API payload', async () => {
|
||||
it('should show only Days option for S3 retention', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<GeneralSettings
|
||||
metricsTtlValuesPayload={mockMetricsRetention}
|
||||
@@ -138,7 +139,7 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
expect(s3Dropdown).toBeInTheDocument();
|
||||
|
||||
// Click the S3 dropdown to open it
|
||||
fireEvent.mouseDown(s3Dropdown);
|
||||
await user.click(s3Dropdown);
|
||||
|
||||
// Wait for dropdown options to appear and verify only "Days" is available
|
||||
await waitFor(() => {
|
||||
@@ -146,33 +147,34 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
expect(dropdownOptions).toHaveLength(1);
|
||||
expect(dropdownOptions[0]).toHaveTextContent('Days');
|
||||
});
|
||||
});
|
||||
|
||||
// Close dropdown
|
||||
fireEvent.click(document.body);
|
||||
it('should send correct API payload for S3 retention', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<GeneralSettings
|
||||
metricsTtlValuesPayload={mockMetricsRetention}
|
||||
tracesTtlValuesPayload={mockTracesRetention}
|
||||
logsTtlValuesPayload={mockLogsRetentionWithS3}
|
||||
getAvailableDiskPayload={mockDisksWithS3}
|
||||
metricsTtlValuesRefetch={jest.fn()}
|
||||
tracesTtlValuesRefetch={jest.fn()}
|
||||
logsTtlValuesRefetch={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const s3Input = getLogsRow().querySelectorAll('input[type="number"]')[1];
|
||||
|
||||
// Change S3 retention value to 5 days
|
||||
fireEvent.change(s3Input, { target: { value: '5' } });
|
||||
await user.clear(s3Input);
|
||||
await user.type(s3Input, '5');
|
||||
|
||||
// Find the save button in the Logs row
|
||||
const saveButton = logsRow.querySelector(
|
||||
'button:not([disabled])',
|
||||
) as HTMLButtonElement;
|
||||
expect(saveButton).toBeInTheDocument();
|
||||
const saveButton = screen.getByTestId('logs-retention-save-button');
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(saveButton);
|
||||
|
||||
// Wait for button to be enabled
|
||||
await waitFor(() => {
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
// Wait for modal to appear
|
||||
const modal = await screen.findByRole('dialog');
|
||||
expect(modal).toBeInTheDocument();
|
||||
|
||||
// Click OK button
|
||||
const okButton = await screen.findByRole('button', { name: /ok/i });
|
||||
fireEvent.click(okButton);
|
||||
// Wait for modal to appear and click OK
|
||||
await user.click(await screen.findByTestId('logs-retention-confirm-button'));
|
||||
|
||||
// Verify API was called with correct payload
|
||||
await waitFor(() => {
|
||||
@@ -208,6 +210,7 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
|
||||
describe('Test 2: S3 Disabled - Field Hidden', () => {
|
||||
it('should hide S3 retention field and send empty S3 values to API', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<GeneralSettings
|
||||
metricsTtlValuesPayload={mockMetricsRetention}
|
||||
@@ -234,45 +237,28 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
const totalDropdown = logsRow.querySelector(
|
||||
'.ant-select-selector',
|
||||
) as HTMLElement;
|
||||
fireEvent.mouseDown(totalDropdown);
|
||||
|
||||
// Wait for dropdown options to appear
|
||||
await waitFor(() => {
|
||||
const options = document.querySelectorAll('.ant-select-item');
|
||||
expect(options.length).toBeGreaterThan(0);
|
||||
});
|
||||
await user.click(totalDropdown);
|
||||
|
||||
// Find and click the Days option
|
||||
const options = document.querySelectorAll('.ant-select-item');
|
||||
const daysOption = Array.from(options).find((opt) =>
|
||||
opt.textContent?.includes('Days'),
|
||||
);
|
||||
expect(daysOption).toBeInTheDocument();
|
||||
fireEvent.click(daysOption as HTMLElement);
|
||||
const daysOption = await waitFor(() => {
|
||||
const option = Array.from(
|
||||
document.querySelectorAll('.ant-select-item'),
|
||||
).find((opt) => opt.textContent?.includes('Days'));
|
||||
expect(option).toBeInTheDocument();
|
||||
return option as HTMLElement;
|
||||
});
|
||||
await user.click(daysOption);
|
||||
|
||||
// Now change the value
|
||||
fireEvent.change(totalInput, { target: { value: '60' } });
|
||||
await user.clear(totalInput);
|
||||
await user.type(totalInput, '60');
|
||||
|
||||
// Find the save button
|
||||
const saveButton = logsRow.querySelector(
|
||||
'button:not([disabled])',
|
||||
) as HTMLButtonElement;
|
||||
expect(saveButton).toBeInTheDocument();
|
||||
const saveButton = screen.getByTestId('logs-retention-save-button');
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await user.click(saveButton);
|
||||
|
||||
// Wait for button to be enabled
|
||||
await waitFor(() => {
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
|
||||
// Click save button
|
||||
fireEvent.click(saveButton);
|
||||
|
||||
// Wait for modal to appear
|
||||
const okButton = await screen.findByRole('button', { name: /ok/i });
|
||||
expect(okButton).toBeInTheDocument();
|
||||
|
||||
// Click OK button
|
||||
fireEvent.click(okButton);
|
||||
// Wait for modal to appear and click OK
|
||||
await user.click(await screen.findByTestId('logs-retention-confirm-button'));
|
||||
|
||||
// Verify API was called with empty S3 values (60 days)
|
||||
await waitFor(() => {
|
||||
@@ -321,6 +307,7 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
|
||||
describe('Test 4: Save Button State with S3 Disabled', () => {
|
||||
it('should disable save button when cold_storage_ttl_days is -1 and no changes made', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<GeneralSettings
|
||||
metricsTtlValuesPayload={mockMetricsRetention}
|
||||
@@ -336,12 +323,8 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
const logsRow = getLogsRow();
|
||||
expect(logsRow).toBeInTheDocument();
|
||||
|
||||
// Find the save button by accessible name within the Logs row
|
||||
const allSaveButtons = screen.getAllByRole('button', { name: /save/i });
|
||||
const saveButton = allSaveButtons.find((btn) =>
|
||||
logsRow.contains(btn),
|
||||
) as HTMLButtonElement;
|
||||
expect(saveButton).toBeInTheDocument();
|
||||
const saveButton = screen.getByTestId('logs-retention-save-button');
|
||||
expect(logsRow).toContainElement(saveButton);
|
||||
|
||||
// Verify save button is disabled on initial load
|
||||
expect(saveButton).toHaveAttribute('aria-disabled', 'true');
|
||||
@@ -351,20 +334,18 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
const totalInput = inputs[0] as HTMLInputElement;
|
||||
|
||||
// Change total retention value to trigger button enable
|
||||
fireEvent.change(totalInput, { target: { value: '60' } });
|
||||
await user.clear(totalInput);
|
||||
await user.type(totalInput, '60');
|
||||
|
||||
// Button should now be enabled after change
|
||||
await waitFor(() => {
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
expect(saveButton).not.toHaveAttribute('aria-disabled', 'true');
|
||||
|
||||
// Revert to original value (30 days displays as 1 Month)
|
||||
fireEvent.change(totalInput, { target: { value: '1' } });
|
||||
await user.clear(totalInput);
|
||||
await user.type(totalInput, '1');
|
||||
|
||||
// Button should be disabled again (back to original state)
|
||||
await waitFor(() => {
|
||||
expect(saveButton).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
expect(saveButton).toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -421,8 +402,11 @@ describe('GeneralSettings - S3 Logs Retention', () => {
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// Save buttons should be visible for non-cloud users (these are from retentions)
|
||||
const saveButtons = screen.getAllByRole('button', { name: /save/i });
|
||||
expect(saveButtons.length).toBeGreaterThan(0);
|
||||
['metrics', 'traces', 'logs'].forEach((type) => {
|
||||
expect(
|
||||
screen.getByTestId(`${type}-retention-save-button`),
|
||||
).toHaveTextContent('retention_save_button.success');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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()) {
|
||||
|
||||
@@ -426,7 +426,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// Find pagination navigation and page 2 button
|
||||
const nav = screen.getByRole('navigation');
|
||||
const nav = document.querySelector('nav') as HTMLElement;
|
||||
const page2Button = Array.from(nav.querySelectorAll('button')).find(
|
||||
(btn) => btn.textContent?.trim() === '2',
|
||||
);
|
||||
@@ -446,13 +446,16 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
it('should open row in new tab when ctrl+click on row', async () => {
|
||||
const user = userEvent.setup();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText(`PodId:${itemId}`);
|
||||
// Ctrl+click to open in new tab
|
||||
fireEvent.click(firstRow, { ctrlKey: true });
|
||||
await user.keyboard('{Control>}');
|
||||
await user.click(firstRow);
|
||||
await user.keyboard('{/Control}');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
|
||||
@@ -463,13 +466,16 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
it('should open row in new tab when meta+click (cmd on Mac) on row', async () => {
|
||||
const user = userEvent.setup();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(`PodId:${itemId}`)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const firstRow = screen.getByText(`PodId:${itemId}`);
|
||||
// Meta+click (cmd on Mac) to open in new tab
|
||||
fireEvent.click(firstRow, { metaKey: true });
|
||||
await user.keyboard('{Meta>}');
|
||||
await user.click(firstRow);
|
||||
await user.keyboard('{/Meta}');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
|
||||
@@ -536,7 +542,7 @@ describe('K8sBaseList', () => {
|
||||
expect(screen.getByText('namespace-default')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const expandButtons = screen.getAllByRole('button');
|
||||
const expandButtons = document.querySelectorAll('button');
|
||||
expect(expandButtons.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
@@ -604,7 +610,7 @@ describe('K8sBaseList', () => {
|
||||
expect(screen.getByText('namespace-default')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const expandButtons = screen.getAllByRole('button');
|
||||
const expandButtons = document.querySelectorAll('button');
|
||||
expect(expandButtons.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
@@ -940,12 +946,8 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// All columns should be visible
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /id/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /name/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Id').closest('th')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Name').closest('th')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -988,9 +990,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// Columns should be visible
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /id/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Id').closest('th')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show columns when grouped', async () => {
|
||||
@@ -1014,9 +1014,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// Id should be visible
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /id/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Id').closest('th')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1096,12 +1094,8 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
// All columns should be visible
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /id/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('columnheader', { name: /^name$/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Id').closest('th')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Name').closest('th')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render data in cells correctly', async () => {
|
||||
@@ -1211,6 +1205,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
it('should include cluster and namespace params in new tab URL on ctrl+click', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderComponent<TestItemWithTitle, SelectedItemParams>({
|
||||
onUrlUpdate: onUrlUpdateMock,
|
||||
entity: InfraMonitoringEntity.PODS,
|
||||
@@ -1225,7 +1220,9 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
const firstRow = await screen.findByText(`PodId:${itemId}`);
|
||||
fireEvent.click(firstRow, { ctrlKey: true });
|
||||
await user.keyboard('{Control>}');
|
||||
await user.click(firstRow);
|
||||
await user.keyboard('{/Control}');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
|
||||
@@ -1237,6 +1234,7 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
it('should omit null cluster/namespace params in new tab URL', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderComponent<TestItemWithTitle, SelectedItemParams>({
|
||||
onUrlUpdate: onUrlUpdateMock,
|
||||
entity: InfraMonitoringEntity.PODS,
|
||||
@@ -1251,7 +1249,9 @@ describe('K8sBaseList', () => {
|
||||
});
|
||||
|
||||
const firstRow = await screen.findByText(`PodId:${itemId}`);
|
||||
fireEvent.click(firstRow, { ctrlKey: true });
|
||||
await user.keyboard('{Control>}');
|
||||
await user.click(firstRow);
|
||||
await user.keyboard('{/Control}');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(openInNewTabMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { InfraMonitoringEntity } from 'container/InfraMonitoringK8sV2/constants';
|
||||
import { act, screen, userEvent, within } from 'tests/test-utils';
|
||||
import { act, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import { renderEntityTraces } from './testUtils';
|
||||
import { mockQueryRangeV5WithTracesResponse } from '__tests__/query_range_v5.util';
|
||||
@@ -31,15 +31,13 @@ describe('EntityTraces - Table Rendering', () => {
|
||||
it('should render table with all column headers', async () => {
|
||||
mockQueryRangeV5WithTracesResponse({ pageSize: 3 });
|
||||
|
||||
act(() => {
|
||||
renderEntityTraces();
|
||||
});
|
||||
const { container } = renderEntityTraces();
|
||||
|
||||
await expect(screen.findByText('Service Name')).resolves.toBeInTheDocument();
|
||||
|
||||
const headerTexts = within(screen.getByRole('table'))
|
||||
.getAllByRole('columnheader')
|
||||
.map((header) => header.textContent);
|
||||
const headerTexts = Array.from(
|
||||
container.querySelectorAll('table thead th'),
|
||||
).map((header) => header.textContent);
|
||||
|
||||
expect(headerTexts).toStrictEqual(
|
||||
expect.arrayContaining([
|
||||
@@ -152,13 +150,11 @@ describe('EntityTraces - Table Rendering', () => {
|
||||
customTraces: [{ serviceName: 'frontend' }],
|
||||
});
|
||||
|
||||
act(() => {
|
||||
renderEntityTraces();
|
||||
});
|
||||
const { container } = renderEntityTraces();
|
||||
|
||||
await expect(screen.findByTestId('serviceName')).resolves.toBeInTheDocument();
|
||||
|
||||
const links = within(screen.getByRole('table')).getAllByRole('link');
|
||||
const links = container.querySelectorAll('table a[href]');
|
||||
|
||||
expect(links.length).toBeGreaterThan(0);
|
||||
links.forEach((link) => {
|
||||
|
||||
@@ -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'),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1141,6 +1141,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
icon
|
||||
color="secondary"
|
||||
aria-label={`Edit ${signalName} limit`}
|
||||
testId={`edit-limit-btn-${signalName}`}
|
||||
disabled={
|
||||
!!(activeAPIKey?.id === APIKey?.id && activeSignal)
|
||||
}
|
||||
@@ -1637,6 +1638,7 @@ function MultiIngestionSettings(): JSX.Element {
|
||||
target="_blank"
|
||||
className="learn-more"
|
||||
rel="noreferrer"
|
||||
data-testid="ingestion-keys-learn-more"
|
||||
>
|
||||
Learn more <ArrowUpRight size={14} />
|
||||
</a>
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { GatewaytypesGettableIngestionKeysDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import MultiIngestionSettings from '../MultiIngestionSettings';
|
||||
|
||||
@@ -48,6 +42,7 @@ describe('MultiIngestionSettings Page', () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
@@ -62,7 +57,8 @@ describe('MultiIngestionSettings Page', () => {
|
||||
screen.getByText('Create and manage ingestion keys for the SigNoz Cloud'),
|
||||
).toBeInTheDocument();
|
||||
|
||||
const aboutKeyslink = screen.getByRole('link', { name: /Learn more/i });
|
||||
const aboutKeyslink = screen.getByTestId('ingestion-keys-learn-more');
|
||||
expect(aboutKeyslink).toHaveTextContent('Learn more');
|
||||
expect(aboutKeyslink).toHaveAttribute(
|
||||
'href',
|
||||
'https://signoz.io/docs/ingestion/signoz-cloud/keys/',
|
||||
@@ -73,6 +69,7 @@ describe('MultiIngestionSettings Page', () => {
|
||||
});
|
||||
|
||||
it('navigates to create alert with metrics count threshold', async () => {
|
||||
const user = userEvent.setup();
|
||||
const response: TestGatewayIngestionKeysResponse = {
|
||||
status: 'success',
|
||||
data: {
|
||||
@@ -111,13 +108,10 @@ describe('MultiIngestionSettings Page', () => {
|
||||
render(<MultiIngestionSettings />, undefined, {
|
||||
initialRoute: INGESTION_SETTINGS_ROUTE,
|
||||
});
|
||||
await screen.findByText('Key One');
|
||||
fireEvent.click(screen.getByRole('button', { name: /right Key One/i }));
|
||||
await user.click(await screen.findByText('Key One'));
|
||||
|
||||
await screen.findByText('LIMITS');
|
||||
fireEvent.click(
|
||||
(await screen.findByTestId('set-alert-btn-metrics')) as HTMLButtonElement,
|
||||
);
|
||||
await user.click(await screen.findByTestId('set-alert-btn-metrics'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledTimes(1);
|
||||
@@ -151,6 +145,7 @@ describe('MultiIngestionSettings Page', () => {
|
||||
});
|
||||
|
||||
it('navigates to create alert for logs with GiB threshold and bytes yAxisUnit', async () => {
|
||||
const user = userEvent.setup();
|
||||
const GIB = 1073741824;
|
||||
const sizeInBytes = 400 * GIB;
|
||||
|
||||
@@ -192,13 +187,10 @@ describe('MultiIngestionSettings Page', () => {
|
||||
render(<MultiIngestionSettings />, undefined, {
|
||||
initialRoute: INGESTION_SETTINGS_ROUTE,
|
||||
});
|
||||
await screen.findByText('Key Logs');
|
||||
fireEvent.click(screen.getByRole('button', { name: /right Key Logs/i }));
|
||||
await user.click(await screen.findByText('Key Logs'));
|
||||
|
||||
await screen.findByText('LIMITS');
|
||||
fireEvent.click(
|
||||
(await screen.findByTestId('set-alert-btn-logs')) as HTMLButtonElement,
|
||||
);
|
||||
await user.click(await screen.findByTestId('set-alert-btn-logs'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledTimes(1);
|
||||
@@ -231,6 +223,7 @@ describe('MultiIngestionSettings Page', () => {
|
||||
});
|
||||
|
||||
it('shows alert CTAs in view mode and helper text in edit mode for configured limits', async () => {
|
||||
const user = userEvent.setup();
|
||||
const KEY_NAME = 'Key With Limits';
|
||||
const response: TestGatewayIngestionKeysResponse = {
|
||||
status: 'success',
|
||||
@@ -276,22 +269,22 @@ describe('MultiIngestionSettings Page', () => {
|
||||
initialRoute: INGESTION_SETTINGS_ROUTE,
|
||||
});
|
||||
|
||||
await screen.findByText(KEY_NAME);
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: new RegExp(`right ${KEY_NAME}`, 'i') }),
|
||||
);
|
||||
await user.click(await screen.findByText(KEY_NAME));
|
||||
await screen.findByText('LIMITS');
|
||||
|
||||
expect(screen.getAllByText('Set alert').length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Edit logs limit' }));
|
||||
await user.click(screen.getByTestId('edit-limit-btn-logs'));
|
||||
expect(
|
||||
screen.getByText('You can set up an alert after saving'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('switches to search API when search text is entered', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
|
||||
const getResponse: TestGatewayIngestionKeysResponse = {
|
||||
status: 'success',
|
||||
|
||||
@@ -101,7 +101,7 @@ function S3BucketsSelector({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="s3-buckets-selector">
|
||||
<div className="s3-buckets-selector" data-testid="s3-buckets-selector">
|
||||
<div className="s3-buckets-selector-title">Select S3 Buckets by Region</div>
|
||||
<div className="s3-buckets-selector-content">
|
||||
{allRegions.map((region) => {
|
||||
@@ -120,6 +120,7 @@ function S3BucketsSelector({
|
||||
</div>
|
||||
<div className="s3-buckets-selector-region-select">
|
||||
<Select
|
||||
data-testid={`s3-buckets-select-${region}`}
|
||||
mode="tags"
|
||||
placeholder={`Enter S3 bucket names for ${region}`}
|
||||
value={bucketsByRegion[region] || []}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { RestRequest } from 'msw';
|
||||
import type logEvent from '../../../../../api/common/logEvent';
|
||||
@@ -14,9 +14,6 @@ jest.mock('../../../../../api/common/logEvent', () => ({
|
||||
default: jest.fn() as jest.MockedFunction<typeof logEvent>,
|
||||
}));
|
||||
|
||||
// The form flow drives antd selects and typing, which outruns the 5s default on CI.
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
type OnClose = ComponentProps<typeof CloudAccountSetupModal>['onClose'];
|
||||
|
||||
const mockOnClose = (): jest.MockedFunction<OnClose> =>
|
||||
@@ -84,26 +81,28 @@ const mockApi = ({ failFirstPoll = false } = {}): {
|
||||
return api;
|
||||
};
|
||||
|
||||
type User = ReturnType<typeof userEvent.setup>;
|
||||
|
||||
const generateCommand = async (user: User): Promise<void> => {
|
||||
const select = await screen.findByTestId('aws-deployment-region-select');
|
||||
await user.click(within(select).getByRole('combobox', { hidden: true }));
|
||||
await user.click(await screen.findByText('US East (N. Virginia)'));
|
||||
await user.click(screen.getByTestId('aws-region-us-east-1'));
|
||||
await user.click(screen.getByTestId('aws-generate-command-btn'));
|
||||
await screen.findByTestId('aws-agent-command');
|
||||
};
|
||||
|
||||
describe('AWS CloudAccountSetupModal', () => {
|
||||
it('creates the account and shows its setup command', async () => {
|
||||
const api = mockApi();
|
||||
const openSpy = jest.spyOn(window, 'open').mockImplementation(() => null);
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
|
||||
|
||||
await user.click(await screen.findByRole('combobox'));
|
||||
await user.click(await screen.findByText('US East (N. Virginia)'));
|
||||
await user.click(await screen.findByRole('checkbox', { name: /us-east-1/i }));
|
||||
await user.click(screen.getByTestId('aws-generate-command-btn'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('aws-agent-command')).toHaveTextContent(
|
||||
cliCommand,
|
||||
);
|
||||
});
|
||||
await generateCommand(user);
|
||||
|
||||
expect(screen.getByTestId('aws-agent-command')).toHaveTextContent(cliCommand);
|
||||
expect(api.createAccountPayload).toStrictEqual({
|
||||
config: { aws: { deploymentRegion: 'us-east-1', regions: ['us-east-1'] } },
|
||||
credentials,
|
||||
@@ -111,11 +110,25 @@ describe('AWS CloudAccountSetupModal', () => {
|
||||
expect(
|
||||
screen.queryByTestId('aws-generate-command-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryAllByRole('combobox')).toHaveLength(0);
|
||||
expect(screen.getByText(/waiting for connection/i)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('aws-deployment-region-select'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('cloud-connect-waiting')).toHaveTextContent(
|
||||
/waiting for connection/i,
|
||||
);
|
||||
expect(openSpy).not.toHaveBeenCalled();
|
||||
|
||||
openSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('asks before closing once a setup command exists', async () => {
|
||||
mockApi();
|
||||
const user = userEvent.setup();
|
||||
const onClose = mockOnClose();
|
||||
|
||||
render(<CloudAccountSetupModal onClose={onClose} />);
|
||||
|
||||
await generateCommand(user);
|
||||
|
||||
await user.click(screen.getByTestId('aws-cancel-btn'));
|
||||
await user.click(await screen.findByTestId('aws-continue-setup-btn'));
|
||||
@@ -150,16 +163,15 @@ describe('AWS CloudAccountSetupModal', () => {
|
||||
|
||||
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
|
||||
|
||||
await user.click(await screen.findByRole('combobox'));
|
||||
await user.click(await screen.findByText('US East (N. Virginia)'));
|
||||
await user.click(await screen.findByRole('checkbox', { name: /us-east-1/i }));
|
||||
await user.click(screen.getByTestId('aws-generate-command-btn'));
|
||||
await generateCommand(user);
|
||||
|
||||
await user.click(await screen.findByTestId('aws-check-connection-btn'));
|
||||
|
||||
await waitFor(() => expect(api.pollCount()).toBe(2));
|
||||
|
||||
await screen.findByText(/waiting for connection/i);
|
||||
await expect(
|
||||
screen.findByTestId('cloud-connect-waiting'),
|
||||
).resolves.toHaveTextContent(/waiting for connection/i);
|
||||
expect(
|
||||
screen.queryByTestId('aws-check-connection-btn'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user