Compare commits

..

10 Commits

Author SHA1 Message Date
Vinicius Lourenço
d5a8c64f1f feat(router): upgrade to react-router v7 on a data router (#13335)
Some checks are pending
build-staging / prepare (push) Waiting to run
build-staging / js-build (push) Blocked by required conditions
build-staging / go-build (push) Blocked by required conditions
build-staging / staging (push) Blocked by required conditions
cacheci / tests (push) Waiting to run
Release Drafter / update_release_draft (push) Waiting to run
#### Description

> TLDR: You can take a look at
https://claude.ai/artifact/LbFG6NcXyeRCm5MSnCKANc

- Upgrades react-router v5 (plus `react-router-dom-v5-compat` 6.30 and
`history@4`) to `react-router` 7.18.4. Follows #13173: pages and
components keep calling `src/lib/router`, so outside the router code the
only changes are render-order and nuqs write-order fixes.
- The app mounts a data router (`createBrowserRouter`) under a pathless
root route that renders `AppProviders`. The base path becomes the
router's `basename`. `lib/history`, `history`, `@types/history` and
`@types/react-router-dom` are removed.
- nuqs moves to its `react-router/v7` adapter, and the `react-router <7`
override goes, which held nuqs's copy below the fix for
GHSA-wrjc-x8rr-h8h6.
- The route table is static. A `RouteGate` renders `NotFound` for routes
the plan, license or flags turn off, which is what the old dynamic
`<Switch>` fell through to. `exact` is dropped (v7 matches exactly) and
the 4 prefix routes become `nested` (`pattern/*`).
- `useNavigationBlocker` moves to v7 `useBlocker` through a new
`useAppBlocker`, which deletes the history@4 replay code from #13173.

What replaced what:

| Before | After |
| --- | --- |
| `<Router history>` + `<CompatRouter>` in `AppShell` |
`createAppRouter` + `RouterProvider` in `index.tsx` |
| `<Switch>` over the enabled routes | static table in
`AppRoutes/routeTable.tsx`, `<Outlet context={enabledRouteKeys}>` |
| `lib/history` singleton behind `navigate()` | `attachRouter`:
`navigate()` drives the data router attached last |
| `blockNavigation` + `retryTransition` | `useAppBlocker` (`proceed` /
`reset`) |
| `nuqs/adapters/react` | `nuqs/adapters/react-router/v7` |
| `MemoryRouter` / history-backed `TestRouter` | browser data router
over jsdom's history, `HostRouter` |
| `lib/history` alias in Storybook | memory data router per story with a
guarded `navigate` |

#### Issues closed by this PR

Closes https://github.com/SigNoz/uforge-pod/issues/2544

#### Additional Information

Reviewing: read by commit. Only the tip builds, since the package swap
cannot land halfway.

- Read closely: `feat(router): back the facade with react-router v7`
(`navigation.ts`, `matchRoute`, `buildRoutePath`, `AppLink` /
`Redirect`), `feat(router): mount the app on a data router`
(`app/AppRouter.tsx`, `AppRoutes/routeTable.tsx`, `Private.tsx`), the
blocker commit and the test router commit (`tests/router.tsx`,
`router-utils.ts`, `lib/router/HostRouter.tsx`).
- Read closely: the 8 `fix(router)` commits. `useShareBuilderUrl` and
`QuerySearchV2Provider` published their query onto the next route while
a route-driven tab was leaving, and the provider then wiped an
expression a child runs on mount (the K8s drawer's Overview tab); two
lazy routes of one module (logs explorer, pipelines) reused the previous
page until the gate was keyed by route entry; `stripBasePath` now
matches case-insensitively, as the router does.
- Three fix nuqs writes that a navigation dropped or overwrote.
`nuqs/adapters/react-router/v7` patches `history.pushState` and
`replaceState`, and any write it did not make clears the writes it still
has queued. On K8s a row needed two clicks to open its drawer (a no-op
`replace` from `useSafeNavigate`), a category switch with a filter kept
the old category, run query kept the old page, and a stored page size
was lost on mount. Alert history rebuilt URLs from the router's stale
location, and the adapter adopted them, dropping the search expression.
Fixed at the call sites; the tests run the real adapter, and
`routing/url-state.spec.ts` TC-05 to TC-08 cover K8s. #13336 has the 2
K8s commits, not the alert history one. The FAQ below has the full nuqs
picture.
- Skim: deps, jest environment, Storybook and lint commits.

Behavior to know:

- Route transitions run with `useTransitions={false}`. Under a
transition React keeps the old screen, so a route whose chunk is not
cached would show no loader.
- The post-login hop to the stashed route still pushes
(`replace={false}`). Back from it now ends on `/home` instead of the
stashed route, because the stash is already cleared; TC-15 asserts it.
- `navigate()` and `getCurrentLocation()` throw when no router is
attached. Tests render first or call `attachTestRouter`.

Testing:

- The 2 K8s nuqs commits came after those runs: `tsgo`, lint and `pnpm
build` clean on the tip, and the 46 related jest suites pass. With the
fixed files reverted, 5 of their 7 new tests fail.
- E2E chromium, run before the rebase onto main, routing specs from
#13078 included: 415 passed, 4 failed. The 4 (alert history expression
filter TC-10 to TC-12, token highlight dark theme) are load flakes:
repeated 3 times at 6 workers, those specs fail 15 of 50 runs on the
#13173 build and 12 of 50 here.
- Bundle, against the #13173 build: the entry chunk grows by 20 KB gzip
(+0.78%). Router libraries in it go from 33 KB minified (v5, v6 compat,
history) to 95 KB (`react-router` 7). CSS unchanged, one lazy chunk
fewer.

FAQ:

<details>
<summary>Why a data router and not declarative mode
(<code>&lt;BrowserRouter&gt;</code> +
<code>&lt;Routes&gt;</code>)?</summary>

`<BrowserRouter>` creates its history inside the component and gives
nothing outside React a handle on it. 88 files navigate through
`lib/router/navigation`, some from plain modules (`api/utils.ts`,
`utils/app.ts`). In declarative mode the only way to reach them is
`unstable_HistoryRouter` over a `history@5` object we own, which is what
#13336 does. A data router is an object created before the first render,
so `navigation.ts` calls `router.navigate` on it directly. `useBlocker`
needs one too: in 7.18.4 it throws under `<Routes>` or
`unstable_HistoryRouter`.

</details>

<details>
<summary>Why remove <code>history</code> and
<code>lib/history</code>?</summary>

A data router creates and owns its history; v7 has no prop that accepts
one. Keeping the `lib/history` singleton would leave a second writer to
`window.history` that the router never hears: the router only listens to
`popstate`, so a `history.push` from the singleton moves the address bar
and renders nothing. What the singleton did (navigate from anywhere,
`listen`, `hasInAppHistory`) now lives in `navigation.ts` on top of the
attached router.

</details>

<details>
<summary>Why a new React context in <code>HostRouter</code>?</summary>

It is for tests and stories only; the app does not use it. A data
router's routes, elements included, are fixed when the router is
created. `TestRouter` creates its router once per mount, so a `rerender`
with new children would keep showing the first ones. `HostRouter` puts
the children in a context and the route element (`HostedTreeOutlet`)
reads it, so a re-render shows the new tree.

</details>

<details>
<summary>Why do routes read the enabled set from outlet
context?</summary>

The route table is built once, at module load, before any hook runs, so
it cannot ask the plan, license or flags which routes are on. `App`
still computes that set the way it did and passes it down as `<Outlet
context>`. `RouteGate` reads it and renders the page or `NotFound`,
where the old dynamic `<Switch>` fell through. Flags loading later never
recreates the router.

</details>

<details>
<summary>Why do the providers render inside the router now?</summary>

A data router renders everything under `RouterProvider`, and the only
place for a layout above the pages is the root route's element. The nuqs
adapter calls `useNavigate` and `useSearchParams`, so it has to be
inside a router. `AppProviders` and `App` became that root element.

</details>

<details>
<summary>Why does <code>navigate()</code> keep a stack of routers, and
throw without one?</summary>

Tests and stories mount their own data router. `attachRouter` pushes it
and its detach pops it, so `navigate()` moves whichever router is on
screen and hands back to the one below. With nothing attached there is
no router to hear the navigation, so it throws instead of silently
writing the URL.

</details>

<details>
<summary>Why is <code>RouteGate</code> keyed by route entry?</summary>

`<Outlet>` renders the matched element without a key. The logs explorer
and pipelines routes lazy-load the same module, so React reused the old
instance and showed the previous page. The key remounts the page when
the route entry changes.

</details>

<details>
<summary>Does any page load data through a loader now?</summary>

No. No route has a `loader` or `lazy`, so every page fetches through
react-query as before and navigations commit synchronously. The first
`loader` makes navigations through that route asynchronous:
`getCurrentLocation()` right after `navigate()` would then return the
old location.

</details>

<details>
<summary>Why did query builder files change if pages only call the
facade?</summary>

A route-driven tab keeps the leaving pane mounted until its animation
ends. On v7 that pane saw the new location and published onto it:
`useShareBuilderUrl` wrote the old tab's `compositeQuery`, and
`QuerySearchV2Provider` restored a dropped `expression`. Both now
publish only for their own page, and the URL owns the expression. That
last change wiped an expression a child runs on mount (the K8s drawer's
Overview tab starts from the list filter), so the provider skips its
first run when the URL has none.

</details>

<details>
<summary>Is the nuqs de-sync fixed?</summary>

It is two problems, and only one is fixed.

The router still lags nuqs, as on main. A nuqs write is shallow: it
calls `history.replaceState` or `pushState` itself and does not tell the
router, so `useLocation().search` stays behind the address bar until the
next router navigation. Event handlers read the real URL through
`getUnstableCurrentSearchParams()`. Removing that lag means `shallow:
false` writes, a separate change with known regressions (the role editor
blocker, AI assistant chips, Back behavior, a re-render per write).

The adapter swap is new. `nuqs/adapters/react-router/v7` patches
`pushState` and `replaceState`. A write it did not make, which means
every router navigation, does two things: it aborts the nuqs writes
still queued (they wait up to 50 ms), and it becomes nuqs's state.
Main's `nuqs/adapters/react` does neither, so router writes to a nuqs
param do not reach its hooks there. That gave two kinds of bug:

| Kind | Example | Status |
| --- | --- | --- |
| A navigation drops a queued write | K8s: two clicks to open a drawer,
category switch keeps the old category, run query keeps the old page,
stored page size lost | fixed: navigate before the nuqs setters,
`useSafeNavigate` skips a no-op target, the default query redirect
renders before the list |
| A URL rebuilt from the stale router location is adopted back | alert
history: a state tab, the top contributors drawer or a graph zoom
dropped the search expression | fixed: build from
`getUnstableCurrentSearchParams()` |
| Same, not confirmed | members `?invite=true`, dashboard `variables`
(`useViewPanel`, `usePanelInteractions`), planned downtime, routing
policies | open: needs a contrast test against main's adapter |

Jest tests run the real adapter, and `routing/url-state.spec.ts` TC-05
to TC-08 check the K8s first clicks. For new code: navigate first and
call nuqs setters after, and build a URL from
`getUnstableCurrentSearchParams()`, not from the router location.

</details>
2026-11-16 20:41:05 +00:00
Swapnil Nakade
f0cde4f37d feat(authz): enable FGA for org routes (#13586)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- Adds resource defs to `GET`/`PUT /api/v2/orgs/me` so org updates emit
audit events.
- Moves both routes from `AdminAccess` to `CheckResources`, scoped to
`organization:read` and `organization:update`. Admin gets both; editor
and viewer stay blocked.
- Migration 149 backfills the admin grants and refreshes managed roles
for existing orgs.
- The org ID comes from the caller's claims, since the update handler
ignores the body `id`.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
contributes to https://github.com/SigNoz/keystone-pod/issues/10
contributes to https://github.com/SigNoz/keystone-pod/issues/43

<!--Anything reviewers should keep in mind while reviewing -->
#### Additional Information
- The organization object has no org prefix, so the managed `*` grant
(`organization:organization/*`) covers every org. Safe here because both
routes take the org from claims. A route that takes an org ID from the
request needs an org-scoped grant first.
2026-11-16 18:03:21 +00:00
Swapnil Nakade
1efbbcfc5e feat: adding integration tests for audit querier (#13550)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- adding integration tests for audit querier
- adds tests for querying ingested audit logs

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
contributes to https://github.com/SigNoz/keystone-pod/issues/13
2026-11-16 14:21:04 +00:00
Aditya Singh
7cef7e48ea feat(pipelines): move the filter preview to query_range v5 (#13608)
#### Description
- The pipeline filter preview read its sample logs and its match count
from the v3 `query_range` API. The backend plans to remove the v3 APIs.
- The sample logs and the match count now come from v5 `query_range`.
The preview sends the filter as a v5 filter expression.
- On `use_json_body` tenants, v5 returns the log body as an object. The
pipelines preview API accepts only a string body, so "Simulate
Processing" failed with a 400. The preview now sends an object body as a
JSON string, as v3 did.

#### Issues closed by this PR

Closes https://github.com/SigNoz/events-pod/issues/274

#### Screen recording


https://github.com/user-attachments/assets/229ded0a-fc40-4f79-b593-d9387a43f3c7

#### Additional Information
- Part of https://github.com/SigNoz/events-pod/issues/156. This is the
`query_range` follow-up that https://github.com/SigNoz/signoz/pull/13207
mentioned.
- The preview calls v5 through the existing `useGetQueryRange` wrapper,
like the other v5 migrations.
- reproduced the 400 on a staging tenant with `use_json_body`. With the
fix, the simulation returns the processed logs.
- Stories: the Pipelines story serves v5 `query_range` for the sample
logs and the count. The story no longer serves the v3 suggestion APIs,
because the filter uses the v5 fields APIs since #13207. The simulation
fix renders nothing new, so the story is unchanged for it.
2026-11-16 13:32:18 +00:00
hardik-signoz
7189736cea feat(authz): add users fine-grained access control (#13506)
#### Description

- Add `user` and `factor-password` to the role permission schema and
panels, and teach the `generate authz` command to emit both.
- Gate the Members page on `user:list` (list, filter, search) and Invite
member, including the modal's submit, on `user:create`. Attach failures
show as the inline API error after click.
- Gate the member drawer: details on `user:read`, name and save on
`user:update`, delete/revoke on `user:delete`, and the password reset
link on `factor-password:create` + `user:attach`.
- Show the Members settings entry to every user; permissions decide what
it renders.
- Update unit tests, Members stories (new `Authz` folder, one story per
permission) and the e2e settings smoke spec for the new gating.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#202

#### Screenshots
[Before/after diff, dark and
light](https://claude.ai/artifact/XXY1xvkAMZoR6GS2cMmDdZ?sk=Yz4QIeLw8gEJ2ia5Ti5nbA):
110 pairs, 48 identical, 18 new, 44 changed (30 Roles permission cards,
6 settings nav, 8 sub-0.1% Members noise).

---------

Co-authored-by: vikrantgupta25 <vikrant@signoz.io>
2026-11-16 13:08:12 +00:00
Nikhil Mantri
8e089a8bd8 refactor(alert-notification-templates): render related links from Go instead of stored channel templates. (#13174)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Add a `relatedLinks` template func and `signoz.relatedLinks.slack` /
`signoz.relatedLinks.markdown` / `signoz.relatedLinks.html` blocks so
link selection, labels and formatting live in Go, not in stored channel
templates.
- Go-rendered notifiers (email, Google Chat, Jira, Slack buttons) build
their buttons from the shared `BuildRelatedLinks`.
- FE and Go defaults for Slack/MS Teams text, incident.io/JSM Ops
description and the Telegram message call the blocks instead of inlining
`.Annotations.related_logs/related_traces`.
- Migration 148 rewrites the shipped link snippet in
`alertmanager_config` receivers and `notification_channel` data/spec to
the block call. Sections that differ from the shipped defaults are left
as is and logged.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/587

#### Additional Information

- Labels change to "View Related Logs" / "View Related Traces" on
incident.io, JSM Ops and Telegram; Slack text now renders `<url|View
Related Logs> · <url|View Related Traces>` with no header lines when
links are absent.
- Telegram's FE default intentionally carries no `message` (the backend
fills `DefaultTelegramMessageTemplate`), so only the Go constant changes
for it. If #13119 ever ships a literal `message` default, that string
needs the html block call too.
- incident.io tests switch to `alertmanagernotifytest.CreateTmpl`
because upstream's helper lacks the SigNoz template blocks.
2026-11-16 11:58:00 +00:00
Abhi kumar
5b2027ad81 feat(dashboards): add plugin schema for geo map panel (#13349)
#### Description

- Adds `signoz/GeoMapPanel`: query results on a map as shaded
countries/states, bubbles or lat/lon points, in Mercator, Equal Earth or
Natural Earth.
- `location` names the group-by columns that place a row (country,
region, lat/lon); `map.colorBy` / `map.sizeBy` pick value columns. Both
are checked against the query, and all queries must share a group by,
since rows join by location (as for Scatter).
- Reuses Table formatting (`columnUnits`), Legend and the Heatmap
palette/scale enums. Thresholds are the Number panel's minus `format`: a
match always sets the color.
- Nested objects reject unknown fields; bubble radius bounds are checked
against the layer's defaults when only one is set.
- Allowed query kinds: builder, composite, formula and ClickHouse SQL.
No PromQL, and no trace operators: their input queries have no group by,
which breaks the shared group-by rule (same as Scatter).
- Public dashboards join GeoMap results into one table, as for Table and
Scatter.

#### Additional Information

- Stacked on #13030. Chart layer is #13350; the panel (#13351) carries
the regenerated Orval types.
- Replaces #13138, closed when the stack was reordered to put Geo Map
below Top List.


Closes https://github.com/SigNoz/pulse-pod/issues/694

---------

Co-authored-by: Naman Verma <naman.verma@signoz.io>
2026-11-16 10:18:22 +00:00
hardik-signoz
ce78251920 fix(onboarding): skip onboarding flow for admin@signoz.cloud (#13600)
#### Description

- Stop redirecting `admin@signoz.cloud` to `/onboarding`. The first-user
check excluded that email from the user count but not from the redirect,
so support was locked out of every page on a new deployment until the
customer finished the questionnaire.
- Move the email to a `SIGNOZ_ADMIN_EMAIL` constant, shared by the user
filter and the redirect check.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#217
2026-11-16 09:33:49 +00:00
Ashwin Bhatkal
879b6e4e69 ci(e2e): start e2e on the safe-to-e2e label and run it in the merge queue (#13595)
#### Description

- Adding the `safe-to-e2e` label now starts e2e right away. Before,
`e2eci` ignored label events, so the label only took effect on the next
push or reopen.
- Other labels get their own concurrency group and report as
`ignored-label`, so they never cancel a running e2e or hide its `e2e`
result. They still add a short run of skipped jobs to the checks list.
- The merge queue now runs the full test suite and reports a real `e2e`
result, instead of passing without running anything. Full runs take 17
to 27 minutes, inside the 60-minute queue timeout.
- `fmtlint` is skipped in the merge queue. It only checks `tests/e2e/`,
which each PR's own run already covers.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/736
2026-11-16 08:25:19 +00:00
Aditya Singh
f7e78384ed feat(query-builder): move QueryBuilderSearchV2 off the v3 autocomplete APIs (#13207)
#### Description
- The funnel step filters fetched keys and values from the v3
autocomplete APIs. The backend plans to remove those APIs.
- `QueryBuilderSearchV2` now fetches keys and values from the v5 fields
APIs. The pills and the saved filter shape stay the same, so saved
funnels and pipelines load as before.
- The funnel step Service and Span name dropdowns fetch values from v5
too, scoped to the `resource` and `span` contexts. They share a hook
with the Celery filters, so those move to v5 as well.
- Celery "Worker Online" counts workers from a v5 `query_range` over the
selected time range. It used to count the worker dropdown options, which
had no time range and a cap of 50.
- Pills carry the v5 context as the key type. The pipelines filter
converts it back to the legacy type when the filter changes (`attribute`
→ `tag`, log fields → top-level), so the filter preview, the save and
the stored pipelines match main.
- Span and log fields are marked as columns, so a funnel `EXISTS` on a
field like `name` reads the column.

#### Issues closed by this PR

Closes https://github.com/SigNoz/events-pod/issues/146
Closes https://github.com/SigNoz/events-pod/issues/145

#### Screen recordings
Funnels, Exceptions and pipelines on v5.


https://github.com/user-attachments/assets/217a0a85-984b-4f94-bf9e-a5f21696c3a6


https://github.com/user-attachments/assets/19ba4648-7466-447e-9cf2-e50700022cf9


https://github.com/user-attachments/assets/6dd6e984-d2e6-4a03-b639-a82181618d40

#### Additional Information

- Part of https://github.com/SigNoz/events-pod/issues/156. The same
changes move these filters off v3:
- the exceptions filter, https://github.com/SigNoz/events-pod/issues/145
  - the pipelines filter, https://github.com/SigNoz/events-pod/issues/25
- the Celery dropdowns, https://github.com/SigNoz/events-pod/issues/157
- UI change: the key dropdown badge shows the v5 context, `attribute`
instead of `tag` and `span` for span fields. Neither has a badge colour.
Visible on the funnel step Where filter, the exceptions filter and the
pipelines filter.
- The pipelines filter no longer shows example queries. The v5 fields
API has no equivalent.
- These filters stay on `QueryBuilderSearchV2` with v5 lookups. The move
to `QuerySearch` is left to the page revamps.
- Stories: the Funnels, Celery and Exceptions page stories serve the v5
fields APIs, and the Celery story serves the Worker Online query.
- another PR will be raised to move query range to v5 for logs pipeline
2026-11-16 07:59:24 +00:00
678 changed files with 24057 additions and 5403 deletions

View File

@@ -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

View File

@@ -40,7 +40,6 @@ jobs:
suite:
- alertmanager
- alertmanagerrotation
- auditquerier
- basepath
- callbackauthn
- cloudintegrations
@@ -58,6 +57,7 @@ jobs:
- querierscalar
- queriercommon
- querierai
- querieraudit
- rawexportdata
- promqlconformance
- promapiconformance

View File

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

View File

@@ -16,14 +16,6 @@ packages:
filename: "maintenance.go"
structname: 'Mock{{.InterfaceName}}'
pkgname: '{{.SrcPackageName}}test'
github.com/SigNoz/signoz/pkg/types/condensedmetertypes:
interfaces:
Store:
config:
dir: '{{.InterfaceDir}}/condensedmetertypestest'
filename: "store.go"
structname: 'Mock{{.InterfaceName}}'
pkgname: '{{.SrcPackageName}}test'
github.com/SigNoz/signoz/pkg/types/telemetrytypes:
interfaces:
SchemaMetadataStore:

View File

@@ -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),
})
}

View File

@@ -16,7 +16,6 @@ import (
"github.com/SigNoz/signoz/pkg/authz/openfgaschema"
"github.com/SigNoz/signoz/pkg/authz/openfgaserver"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/condensedmeter"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/flagger"
@@ -122,9 +121,6 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
func(_ context.Context, _ factory.ProviderSettings, _ flagger.Flagger, _ licensing.Licensing, _ telemetrystore.TelemetryStore, _ retention.Getter, _ organization.Getter, _ zeus.Zeus) (factory.NamedMap[factory.ProviderFactory[meterreporter.Reporter, meterreporter.Config]], string) {
return signoz.NewMeterReporterProviderFactories(), "noop"
},
func(_ flagger.Flagger, _ licensing.Licensing, _ organization.Getter, _ telemetrystore.TelemetryStore, _ sqlstore.SQLStore) factory.NamedMap[factory.ProviderFactory[condensedmeter.Reporter, condensedmeter.Config]] {
return signoz.NewCondensedMeterProviderFactories()
},
func(ps factory.ProviderSettings, q querier.Querier, a analytics.Analytics) querier.Handler {
return querier.NewHandler(ps, q, a)
},

View File

@@ -16,7 +16,6 @@ import (
"github.com/SigNoz/signoz/ee/authz/openfgaauthz"
"github.com/SigNoz/signoz/ee/authz/openfgaschema"
"github.com/SigNoz/signoz/ee/authz/openfgaserver"
"github.com/SigNoz/signoz/ee/condensedmeter/kafkacondensedmeter"
"github.com/SigNoz/signoz/ee/gateway/httpgateway"
enterpriselicensing "github.com/SigNoz/signoz/ee/licensing"
"github.com/SigNoz/signoz/ee/licensing/httplicensing"
@@ -39,7 +38,6 @@ import (
"github.com/SigNoz/signoz/pkg/authn"
"github.com/SigNoz/signoz/pkg/authz"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/condensedmeter"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
pkgflagger "github.com/SigNoz/signoz/pkg/flagger"
@@ -178,13 +176,6 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
return factories, "http"
},
func(flagger pkgflagger.Flagger, licensing licensing.Licensing, orgGetter organization.Getter, telemetryStore telemetrystore.TelemetryStore, sqlstore sqlstore.SQLStore) factory.NamedMap[factory.ProviderFactory[condensedmeter.Reporter, condensedmeter.Config]] {
factories := signoz.NewCondensedMeterProviderFactories()
if err := factories.Add(kafkacondensedmeter.NewFactory(flagger, licensing, orgGetter, telemetryStore, sqlstore, version.Info)); err != nil {
panic(err)
}
return factories
},
func(ps factory.ProviderSettings, q querier.Querier, a analytics.Analytics) querier.Handler {
communityHandler := querier.NewHandler(ps, q, a)
return eequerier.NewHandler(ps, q, communityHandler)

View File

@@ -522,30 +522,3 @@ meterreporter:
# interval - random(0, jitter). Must be between 10m and interval. Defaults to
# min(interval, 2h) when unset.
jitter: 2h
##################### Condensed Meter #####################
condensedmeter:
# Specifies the condensed meter provider to use.
# noop: reports nothing (community default).
# kafka: sends the hourly count of condensed metric rows to a Kafka topic as OTLP protobuf (enterprise).
provider: noop
# How often closed hours are looked for. Minimum 10m, maximum 1h.
interval: 1h
# The meter connector's dimensions. Condensed rows are split by them like every other meter row.
dimensions:
- service.name
- deployment.environment
- host.name
- signoz.workspace.key.id
# The maximum number of data points per Kafka record.
batch_size: 100
kafka:
# The seed broker addresses (host:port) used to discover the cluster.
brokers:
- localhost:9092
# The topic condensed rows are written to. It must already exist.
topic: ""
# The client id the producer reports to the brokers.
client_id: signoz
# The compression codec for produced batches: none, gzip, snappy, lz4 or zstd.
compression: lz4

View File

@@ -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

View File

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

View File

@@ -1,97 +0,0 @@
package kafkacondensedmeter
import (
"context"
"fmt"
"strings"
"time"
"github.com/SigNoz/signoz/pkg/clickhousesql"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/telemetryschema/metertelemetryschema"
"github.com/SigNoz/signoz/pkg/telemetryschema/metricstelemetryschema"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/types/condensedmetertypes"
)
const metricNameMetricsDataPointsIngestedCount = "signoz.meter.metric.datapoint.ingested.count"
type clickhouseStore struct {
telemetryStore telemetrystore.TelemetryStore
}
func newClickhouseStore(telemetryStore telemetrystore.TelemetryStore) *clickhouseStore {
return &clickhouseStore{telemetryStore: telemetryStore}
}
// FirstIngested is the time of the first ingested meter row, zero when there is none yet.
func (store *clickhouseStore) FirstIngested(ctx context.Context) (time.Time, error) {
query := fmt.Sprintf("SELECT toInt64(ifNull(min(unix_milli), 0)) FROM %s.%s WHERE metric_name = ?", metertelemetryschema.DBName, metertelemetryschema.SamplesTableName)
var unixMilli int64
if err := store.telemetryStore.ClickhouseDB().QueryRow(ctx, query, metricNameMetricsDataPointsIngestedCount).Scan(&unixMilli); err != nil {
return time.Time{}, errors.WrapInternalf(err, errors.CodeInternal, "failed to query first ingested meter row")
}
if unixMilli == 0 {
return time.Time{}, nil
}
return time.UnixMilli(unixMilli), nil
}
// CondensedRows counts distinct (reduced_fingerprint, minute) in both reduced tables, since the condensing views append each minute several times.
// A minute never appears in both tables: gauges go to one and counters to the other.
// Dimensions come from the reduced series; a condensed row without its series is still counted, without dimensions.
func (store *clickhouseStore) CondensedRows(ctx context.Context, dimensions []string, hour time.Time) ([]condensedmetertypes.Row, error) {
aliases := make([]string, len(dimensions))
selects := make([]string, len(dimensions))
for i, dimension := range dimensions {
aliases[i] = clickhousesql.Identifier(fmt.Sprintf("dimension_%d", i))
selects[i] = fmt.Sprintf("any(resource_attrs[%s]) AS %s", clickhousesql.StringLiteral(dimension), aliases[i])
}
condensed := func(table string) string {
return fmt.Sprintf("SELECT reduced_fingerprint, unix_milli FROM %s.%s WHERE unix_milli >= ? AND unix_milli < ? AND NOT match(metric_name, '^(signoz|otelcol)') GROUP BY reduced_fingerprint, unix_milli", metricstelemetryschema.DBName, table)
}
query := fmt.Sprintf(
"SELECT %s FROM (%s UNION ALL %s) AS condensed LEFT JOIN (SELECT %s FROM %s.%s WHERE unix_milli >= ? AND unix_milli < ? GROUP BY fingerprint) AS series ON condensed.reduced_fingerprint = series.fingerprint",
strings.Join(append(aliases, "toUInt64(count())"), ", "),
condensed(metricstelemetryschema.SamplesV4ReducedLastTableName),
condensed(metricstelemetryschema.SamplesV4ReducedSumTableName),
strings.Join(append([]string{"fingerprint"}, selects...), ", "),
metricstelemetryschema.DBName,
metricstelemetryschema.TimeseriesV4ReducedTableName,
)
if len(aliases) > 0 {
query += " GROUP BY " + strings.Join(aliases, ", ")
}
start, end := hour.UnixMilli(), hour.Add(time.Hour).UnixMilli()
rows, err := store.telemetryStore.ClickhouseDB().Query(ctx, query, start, end, start, end, start, end)
if err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to query condensed rows")
}
defer rows.Close()
condensedRows := []condensedmetertypes.Row{}
for rows.Next() {
row := condensedmetertypes.Row{Values: make([]string, len(dimensions))}
dest := make([]any, 0, len(dimensions)+1)
for i := range row.Values {
dest = append(dest, &row.Values[i])
}
dest = append(dest, &row.Count)
if err := rows.Scan(dest...); err != nil {
return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to scan condensed rows")
}
if row.Count > 0 {
condensedRows = append(condensedRows, row)
}
}
return condensedRows, rows.Err()
}

View File

@@ -1,215 +0,0 @@
package kafkacondensedmeter
import (
"context"
"log/slog"
"time"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/twmb/franz-go/plugin/kslog"
"go.opentelemetry.io/collector/pdata/pmetric"
"github.com/SigNoz/signoz/pkg/condensedmeter"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/flagger"
"github.com/SigNoz/signoz/pkg/licensing"
"github.com/SigNoz/signoz/pkg/modules/organization"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/types/condensedmetertypes"
"github.com/SigNoz/signoz/pkg/types/featuretypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/SigNoz/signoz/pkg/version"
)
var _ condensedmeter.Reporter = (*provider)(nil)
type provider struct {
settings factory.ScopedProviderSettings
config condensedmeter.Config
flagger flagger.Flagger
licensing licensing.Licensing
orgGetter organization.Getter
clickhouseStore *clickhouseStore
store condensedmetertypes.Store
build version.Build
marshaler pmetric.ProtoMarshaler
client *kgo.Client
healthyC chan struct{}
stopC chan struct{}
}
func NewFactory(flagger flagger.Flagger, licensing licensing.Licensing, orgGetter organization.Getter, telemetryStore telemetrystore.TelemetryStore, sqlstore sqlstore.SQLStore, build version.Build) factory.ProviderFactory[condensedmeter.Reporter, condensedmeter.Config] {
return factory.NewProviderFactory(factory.MustNewName("kafka"), func(ctx context.Context, providerSettings factory.ProviderSettings, config condensedmeter.Config) (condensedmeter.Reporter, error) {
return newProvider(ctx, providerSettings, config, flagger, licensing, orgGetter, telemetryStore, newStore(sqlstore), build)
})
}
func newProvider(_ context.Context, providerSettings factory.ProviderSettings, config condensedmeter.Config, flagger flagger.Flagger, licensing licensing.Licensing, orgGetter organization.Getter, telemetryStore telemetrystore.TelemetryStore, store condensedmetertypes.Store, build version.Build) (*provider, error) {
settings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/ee/condensedmeter/kafkacondensedmeter")
// Acks from all in-sync replicas, idempotent writes and unbounded record retries are franz-go defaults and are kept as is.
// A delivery timeout or retry limit lets franz-go < v1.22.2 ack a record that was never written (twmb/franz-go#1484).
client, err := kgo.NewClient(
kgo.SeedBrokers(config.Kafka.Brokers...),
kgo.ClientID(config.Kafka.ClientID),
kgo.ProducerBatchCompression(compressionCodec(config.Kafka.Compression)),
kgo.ProducerLinger(0),
kgo.WithLogger(kslog.New(settings.Logger())),
)
if err != nil {
return nil, err
}
return &provider{
settings: settings,
config: config,
flagger: flagger,
licensing: licensing,
orgGetter: orgGetter,
clickhouseStore: newClickhouseStore(telemetryStore),
store: store,
build: build,
marshaler: pmetric.ProtoMarshaler{},
client: client,
healthyC: make(chan struct{}),
stopC: make(chan struct{}),
}, nil
}
func (provider *provider) Start(ctx context.Context) error {
close(provider.healthyC)
ticker := time.NewTicker(provider.config.Interval)
defer ticker.Stop()
provider.report(ctx)
for {
select {
case <-provider.stopC:
return nil
case <-ticker.C:
provider.report(ctx)
}
}
}
func (provider *provider) Stop(_ context.Context) error {
close(provider.stopC)
provider.client.Close()
return nil
}
func (provider *provider) Healthy() <-chan struct{} {
return provider.healthyC
}
func (provider *provider) report(ctx context.Context) {
orgs, err := provider.orgGetter.ListByOwnedKeyRange(ctx)
if err != nil {
provider.settings.Logger().ErrorContext(ctx, "failed to get orgs data", errors.Attr(err))
return
}
for _, org := range orgs {
if !provider.flagger.BooleanOrEmpty(ctx, flagger.FeatureEnableMetricsReduction, featuretypes.NewFlaggerEvaluationContext(org.ID)) {
continue
}
if _, err := provider.licensing.GetActive(ctx, org.ID); err != nil {
if errors.Ast(err, errors.TypeNotFound) {
continue
}
provider.settings.Logger().ErrorContext(ctx, "failed to fetch active license for org", errors.Attr(err), slog.String("org_id", org.ID.StringValue()))
return
}
if err := provider.reportOrg(ctx, org.ID, time.Now()); err != nil {
provider.settings.Logger().ErrorContext(ctx, "failed to report condensed rows", errors.Attr(err), slog.String("org_id", org.ID.StringValue()))
}
}
}
func (provider *provider) reportOrg(ctx context.Context, orgID valuer.UUID, now time.Time) error {
next, err := provider.nextHour(ctx, orgID)
if err != nil || next.IsZero() {
return err
}
for _, hour := range condensedmetertypes.ClosedHours(next, now) {
rows, err := provider.clickhouseStore.CondensedRows(ctx, provider.config.Dimensions, hour)
if err != nil {
return err
}
if len(rows) > 0 {
if err := provider.send(ctx, rows, now); err != nil {
return err
}
}
if err := provider.store.Upsert(ctx, condensedmetertypes.NewCheckpoint(orgID, hour)); err != nil {
return err
}
}
return nil
}
// nextHour is the hour after the checkpoint, or the first hour after the first ingested meter row; zero when there is none yet.
func (provider *provider) nextHour(ctx context.Context, orgID valuer.UUID) (time.Time, error) {
checkpoint, err := provider.store.Get(ctx, orgID)
if err == nil {
return checkpoint.LastReportedHour.UTC().Add(time.Hour), nil
}
if !errors.Ast(err, errors.TypeNotFound) {
return time.Time{}, err
}
firstIngested, err := provider.clickhouseStore.FirstIngested(ctx)
if err != nil || firstIngested.IsZero() {
return time.Time{}, err
}
return condensedmetertypes.FirstHour(firstIngested), nil
}
// send stamps the points with the send time, not the hour they count, so an hour reported after its day is sealed lands in the next day instead of being missed.
func (provider *provider) send(ctx context.Context, rows []condensedmetertypes.Row, timestamp time.Time) error {
batchSize := provider.config.BatchSize
records := make([]*kgo.Record, 0, (len(rows)+batchSize-1)/batchSize)
for start := 0; start < len(rows); start += batchSize {
metrics := condensedmetertypes.NewPMetrics(rows[start:min(start+batchSize, len(rows))], provider.config.Dimensions, timestamp, "signoz", provider.build.Version())
value, err := provider.marshaler.MarshalMetrics(metrics)
if err != nil {
return errors.WrapInternalf(err, errors.CodeInternal, "failed to marshal condensed rows")
}
records = append(records, &kgo.Record{Topic: provider.config.Kafka.Topic, Value: value})
}
if err := provider.client.ProduceSync(ctx, records...).FirstErr(); err != nil {
return errors.WrapInternalf(err, errors.CodeInternal, "failed to send condensed rows")
}
return nil
}
func compressionCodec(name string) kgo.CompressionCodec {
switch name {
case "gzip":
return kgo.GzipCompression()
case "snappy":
return kgo.SnappyCompression()
case "lz4":
return kgo.Lz4Compression()
case "zstd":
return kgo.ZstdCompression()
default:
return kgo.NoCompression()
}
}

View File

@@ -1,176 +0,0 @@
package kafkacondensedmeter
import (
"context"
"regexp"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
cmock "github.com/SigNoz/clickhouse-go-mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/twmb/franz-go/pkg/kfake"
"github.com/twmb/franz-go/pkg/kgo"
"go.opentelemetry.io/collector/pdata/pmetric"
"github.com/SigNoz/signoz/pkg/condensedmeter"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/telemetrystore/telemetrystoretest"
"github.com/SigNoz/signoz/pkg/types/condensedmetertypes"
"github.com/SigNoz/signoz/pkg/types/condensedmetertypes/condensedmetertypestest"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/SigNoz/signoz/pkg/version"
)
// Polls the topic until it has wantRecords records or the timeout passes.
func consumeMetrics(t *testing.T, brokers []string, topic string, wantRecords int, timeout time.Duration) []pmetric.Metrics {
t.Helper()
client, err := kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.ConsumeTopics(topic),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
)
require.NoError(t, err)
defer client.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
metrics := []pmetric.Metrics{}
for len(metrics) < wantRecords && ctx.Err() == nil {
for _, record := range client.PollFetches(ctx).Records() {
recordMetrics, err := (&pmetric.ProtoUnmarshaler{}).UnmarshalMetrics(record.Value)
require.NoError(t, err)
metrics = append(metrics, recordMetrics)
}
}
return metrics
}
func TestReportOrg(t *testing.T) {
orgID := valuer.GenerateUUID()
now := time.Date(2026, 11, 12, 13, 30, 0, 0, time.UTC)
checkpointHour := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)
// 11:00 is closed at 13:30 (11:00 + 2h = 13:00); 12:00 is not (14:00)
reportedHour := time.Date(2026, 11, 12, 11, 0, 0, 0, time.UTC)
notFound := errors.New(errors.TypeNotFound, condensedmetertypes.ErrCodeCheckpointNotFound, "no checkpoint")
condensedColumns := []cmock.ColumnType{{Name: "dimension_0", Type: "String"}, {Name: "dimension_1", Type: "String"}, {Name: "count", Type: "UInt64"}}
testCases := []struct {
name string
checkpoint *condensedmetertypes.Checkpoint
firstIngestedMs int64
condensedRows [][]any
condensedErr error
expectedUpsert *time.Time
expectedRecords int
expectedDataPoint []int64
expectedErr bool
}{
{
name: "NoCheckpointNoIngestedRows_NothingReported",
firstIngestedMs: 0,
},
{
name: "Checkpoint_ClosedHourSentAndCheckpointAdvanced",
checkpoint: condensedmetertypes.NewCheckpoint(orgID, checkpointHour),
condensedRows: [][]any{{"frontend", "host-1", uint64(31)}, {"checkout", "", uint64(4)}},
expectedUpsert: &reportedHour,
expectedRecords: 1,
expectedDataPoint: []int64{31, 4},
},
{
name: "Checkpoint_LargeHourSplitAcrossRecords",
checkpoint: condensedmetertypes.NewCheckpoint(orgID, checkpointHour),
condensedRows: [][]any{{"frontend", "host-1", uint64(31)}, {"checkout", "", uint64(4)}, {"cart", "host-2", uint64(9)}},
expectedUpsert: &reportedHour,
expectedRecords: 2,
expectedDataPoint: []int64{31, 4, 9},
},
{
name: "Checkpoint_EmptyHourNotSentCheckpointAdvanced",
checkpoint: condensedmetertypes.NewCheckpoint(orgID, checkpointHour),
condensedRows: [][]any{},
expectedUpsert: &reportedHour,
},
{
name: "Checkpoint_QueryFails_CheckpointNotAdvanced",
checkpoint: condensedmetertypes.NewCheckpoint(orgID, checkpointHour),
condensedErr: errors.New(errors.TypeInternal, errors.CodeInternal, "clickhouse down"),
expectedErr: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
cluster, err := kfake.NewCluster(kfake.NumBrokers(1), kfake.SeedTopics(1, "tenant_meter"))
require.NoError(t, err)
defer cluster.Close()
telemetryStore := telemetrystoretest.New(telemetrystore.Config{}, sqlmock.QueryMatcherRegexp)
store := condensedmetertypestest.NewMockStore(t)
if testCase.checkpoint != nil {
store.EXPECT().Get(mock.Anything, orgID).Return(testCase.checkpoint, nil)
} else {
store.EXPECT().Get(mock.Anything, orgID).Return(nil, notFound)
telemetryStore.Mock().ExpectQueryRow(regexp.QuoteMeta("min(unix_milli)")).
WillReturnRow(cmock.NewRow([]cmock.ColumnType{{Name: "min", Type: "Int64"}}, []any{testCase.firstIngestedMs}))
}
if testCase.condensedRows != nil || testCase.condensedErr != nil {
query := telemetryStore.Mock().ExpectQuery(regexp.QuoteMeta("distributed_time_series_v4_reduced")).
WithArgs(reportedHour.UnixMilli(), reportedHour.Add(time.Hour).UnixMilli(), reportedHour.UnixMilli(), reportedHour.Add(time.Hour).UnixMilli(), reportedHour.UnixMilli(), reportedHour.Add(time.Hour).UnixMilli())
if testCase.condensedErr != nil {
query.WillReturnError(testCase.condensedErr)
} else {
query.WillReturnRows(cmock.NewRows(condensedColumns, testCase.condensedRows))
}
}
if testCase.expectedUpsert != nil {
store.EXPECT().Upsert(mock.Anything, mock.MatchedBy(func(checkpoint *condensedmetertypes.Checkpoint) bool {
return checkpoint.OrgID == orgID && checkpoint.LastReportedHour.Equal(*testCase.expectedUpsert)
})).Return(nil)
}
config := condensedmeter.Config{
Provider: "kafka",
Interval: time.Hour,
Dimensions: []string{"service.name", "host.name"},
BatchSize: 2,
Kafka: condensedmeter.KafkaConfig{Brokers: cluster.ListenAddrs(), Topic: "tenant_meter", ClientID: "signoz-test", Compression: "none"},
}
provider, err := newProvider(context.Background(), instrumentationtest.New().ToProviderSettings(), config, nil, nil, nil, telemetryStore, store, version.Info)
require.NoError(t, err)
defer provider.client.Close()
err = provider.reportOrg(context.Background(), orgID, now)
if testCase.expectedErr {
assert.Error(t, err)
} else {
require.NoError(t, err)
}
assert.NoError(t, telemetryStore.Mock().ExpectationsWereMet())
metrics := consumeMetrics(t, cluster.ListenAddrs(), "tenant_meter", testCase.expectedRecords+1, 500*time.Millisecond)
require.Len(t, metrics, testCase.expectedRecords)
dataPoints := []int64{}
for _, recordMetrics := range metrics {
points := recordMetrics.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Sum().DataPoints()
for i := 0; i < points.Len(); i++ {
dataPoints = append(dataPoints, points.At(i).IntValue())
assert.Equal(t, now, points.At(i).Timestamp().AsTime())
}
}
assert.ElementsMatch(t, testCase.expectedDataPoint, dataPoints)
})
}
}

View File

@@ -1,43 +0,0 @@
package kafkacondensedmeter
import (
"context"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/types/condensedmetertypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
type store struct {
sqlstore sqlstore.SQLStore
}
func newStore(sqlstore sqlstore.SQLStore) condensedmetertypes.Store {
return &store{sqlstore: sqlstore}
}
func (store *store) Get(ctx context.Context, orgID valuer.UUID) (*condensedmetertypes.Checkpoint, error) {
checkpoint := new(condensedmetertypes.Checkpoint)
err := store.sqlstore.
BunDBCtx(ctx).
NewSelect().
Model(checkpoint).
Where("org_id = ?", orgID).
Scan(ctx)
if err != nil {
return nil, store.sqlstore.WrapNotFoundErrf(err, condensedmetertypes.ErrCodeCheckpointNotFound, "no condensed meter checkpoint found for org %q", orgID.StringValue())
}
return checkpoint, nil
}
func (store *store) Upsert(ctx context.Context, checkpoint *condensedmetertypes.Checkpoint) error {
_, err := store.sqlstore.
BunDBCtx(ctx).
NewInsert().
Model(checkpoint).
On("CONFLICT (org_id) DO UPDATE").
Set("last_reported_hour = EXCLUDED.last_reported_hour").
Set("updated_at = EXCLUDED.updated_at").
Exec(ctx)
return err
}

View File

@@ -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": {

View File

@@ -8,8 +8,8 @@ const srcPath = resolve(dirname(fileURLToPath(import.meta.url)), '../src');
/**
* Modules replaced for every story. Same idea as `moduleNameMapper` in
* `jest.config.ts`: the app keeps importing its own paths, Storybook resolves
* them to a mock. Regexes so only exact specifiers match: `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$/,

View File

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

View File

@@ -56,15 +56,15 @@ const config: Config.InitialOptions = {
transformIgnorePatterns: [
// @chenglou/pretext is ESM-only; @signozhq/ui pulls it in via text-ellipsis.
// Pattern 1: allow .pnpm virtual store through (handled by pattern 2), plus root-level ESM packages.
'node_modules/(?!(\\.pnpm|react-json-tree|react-base16-styling|lodash-es|react-dnd|core-dnd|@react-dnd|dnd-core|react-dnd-html5-backend|axios|@chenglou/pretext|@signozhq/design-tokens|@signozhq|date-fns|d3-interpolate|d3-color|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,

View 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;

View File

@@ -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 ||

View File

@@ -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",
@@ -78,12 +79,12 @@
"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",
@@ -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,6 +131,7 @@
"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",
@@ -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",

View File

@@ -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 },
],
},
],

View File

@@ -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,

327
frontend/pnpm-lock.yaml generated
View File

@@ -22,7 +22,6 @@ overrides:
js-yaml@>=4.0.0 <4.3.2: '>=4.3.2 <5'
prismjs@<1.30.0: '>=1.30.0 <2'
postcss-selector-parser@>=7.1.0 <7.1.3: '>=7.1.3 <8'
react-router@>=6.7.0 <6.30.6: '>=6.30.6 <7'
tmp@<0.2.6: '>=0.2.6 <0.3.0'
yaml@>=1.0.0 <1.10.3: '>=1.10.3 <2'
'@types/node': ^22.20.5
@@ -81,7 +80,7 @@ importers:
version: 0.4.0
'@signozhq/ui':
specifier: 0.2.0
version: 0.2.0(@date-fns/tz@1.4.1)(@emotion/is-prop-valid@1.2.0)(@signozhq/icons@0.4.0)(@types/react-dom@18.0.10)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0)
version: 0.2.0(@date-fns/tz@1.4.1)(@emotion/is-prop-valid@1.2.0)(@signozhq/icons@0.4.0)(@types/react-dom@18.0.10)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
'@tanstack/react-table':
specifier: 8.21.3
version: 8.21.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -148,6 +147,9 @@ importers:
crypto-js:
specifier: 4.2.0
version: 4.2.0
d3-geo:
specifier: 3.1.1
version: 3.1.1
d3-hierarchy:
specifier: 3.1.2
version: 3.1.2
@@ -163,9 +165,6 @@ importers:
eventemitter3:
specifier: 5.0.1
version: 5.0.1
history:
specifier: 4.10.1
version: 4.10.1
html-to-image:
specifier: 1.11.13
version: 1.11.13
@@ -201,7 +200,10 @@ importers:
version: 12.4.13(@emotion/is-prop-valid@1.2.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
nuqs:
specifier: 2.8.8
version: 2.8.8(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0)
version: 2.8.8(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
ol:
specifier: 10.11.0
version: 10.11.0
overlayscrollbars:
specifier: ^2.16.0
version: 2.16.0
@@ -265,12 +267,9 @@ importers:
react-rnd:
specifier: ^10.5.3
version: 10.5.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
react-router-dom:
specifier: ^5.2.0
version: 5.3.4(react@18.2.0)
react-router-dom-v5-compat:
specifier: 6.30.6
version: 6.30.6(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react@18.2.0)
react-router:
specifier: 7.18.4
version: 7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
react-syntax-highlighter:
specifier: 15.5.0
version: 15.5.0(react@18.2.0)
@@ -304,6 +303,9 @@ importers:
timestamp-nano:
specifier: ^1.0.0
version: 1.0.1
topojson-client:
specifier: 3.1.0
version: 3.1.0
translation-resilience:
specifier: ^0.2.0
version: 0.2.0
@@ -383,15 +385,18 @@ importers:
'@types/crypto-js':
specifier: 4.2.2
version: 4.2.2
'@types/d3-geo':
specifier: 3.1.1
version: 3.1.1
'@types/d3-hierarchy':
specifier: 1.1.11
version: 1.1.11
'@types/event-source-polyfill':
specifier: ^1.0.0
version: 1.0.1
'@types/history':
specifier: 4.7.11
version: 4.7.11
'@types/geojson':
specifier: 7946.0.16
version: 7946.0.16
'@types/jest':
specifier: 30.0.0
version: 30.0.0
@@ -422,9 +427,6 @@ importers:
'@types/react-resizable':
specifier: 3.0.3
version: 3.0.3
'@types/react-router-dom':
specifier: ^5.1.6
version: 5.3.3
'@types/react-syntax-highlighter':
specifier: 15.5.13
version: 15.5.13
@@ -437,6 +439,12 @@ importers:
'@types/testing-library__jest-dom':
specifier: ^5.14.5
version: 5.14.5
'@types/topojson-client':
specifier: 3.1.5
version: 3.1.5
'@types/topojson-specification':
specifier: 1.0.5
version: 1.0.5
'@typescript/native-preview':
specifier: 7.0.0-dev.20260430.1
version: 7.0.0-dev.20260430.1
@@ -500,6 +508,12 @@ importers:
svgo:
specifier: 4.1.0
version: 4.1.0
topojson-server:
specifier: 3.0.1
version: 3.0.1
topojson-simplify:
specifier: 3.0.3
version: 3.0.3
ts-jest:
specifier: 29.4.15
version: 29.4.15(@babel/core@7.29.7)(@jest/transform@30.4.1)(@jest/types@30.2.0)(babel-jest@29.6.4(@babel/core@7.29.7))(esbuild@0.28.1)(jest-util@30.4.1)(jest@30.2.0(@types/node@22.20.5)(babel-plugin-macros@3.1.0)(ts-node@10.9.1(@swc/core@1.16.2)(@types/node@22.20.5)(typescript@5.9.3)))(typescript@5.9.3)
@@ -2898,6 +2912,9 @@ packages:
'@petamoriken/float16@3.8.0':
resolution: {integrity: sha512-AhVAm6SQ+zgxIiOzwVdUcDmKlu/qU39FiYD2UD6kQQaVenrn0dGZewIghWAENGQsvC+1avLCuT+T2/3Gsp/W3w==}
'@petamoriken/float16@3.9.3':
resolution: {integrity: sha512-8awtpHXCx/bNpFt4mt2xdkgtgVvKqty8VbjHI/WWWQuEw+KLzFot3f4+LkQY9YmOtq7A5GdOnqoIC8Pdygjk2g==}
'@pkgjs/parseargs@0.11.0':
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
@@ -3323,10 +3340,6 @@ packages:
'@react-dnd/shallowequal@4.0.2':
resolution: {integrity: sha512-/RVXdLvJxLg4QKvMoM5WlwNR9ViO9z8B/qPcc+C0Sa/teJY7QG7kJ441DwzOjMYEY7GmU4dj5EcGHIkKZiQZCA==}
'@remix-run/router@1.23.4':
resolution: {integrity: sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q==}
engines: {node: '>=14.0.0'}
'@rolldown/binding-android-arm64@1.0.0-beta.53':
resolution: {integrity: sha512-Ok9V8o7o6YfSdTTYA/uHH30r3YtOxLD6G3wih/U9DO0ucBBFq8WPt/DslU53OgfteLRHITZny9N/qCUxMf9kjQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -3951,6 +3964,9 @@ packages:
'@types/d3-geo@3.1.0':
resolution: {integrity: sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==}
'@types/d3-geo@3.1.1':
resolution: {integrity: sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w==}
'@types/d3-hierarchy@1.1.11':
resolution: {integrity: sha512-lnQiU7jV+Gyk9oQYk0GGYccuexmQPTp08E0+4BidgFdiJivjEvf+esPSdZqCZ2C7UwTWejWpqetVaU8A+eX3FA==}
@@ -3996,8 +4012,8 @@ packages:
'@types/file-saver@2.0.5':
resolution: {integrity: sha512-zv9kNf3keYegP5oThGLaPk8E081DFDuwfqjtiTzm6PoxChdJ1raSuADf2YGCVIyrSynLrgc8JWv296s7Q7pQSQ==}
'@types/geojson@7946.0.14':
resolution: {integrity: sha512-WCfD5Ht3ZesJUsONdhvm84dmzWOiOzOAqOncN0++w0lBw1o8OuDNJF2McvvCef/yBqb/HYRahp1BYtODFQ8bRg==}
'@types/geojson@7946.0.16':
resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}
'@types/graceful-fs@4.1.6':
resolution: {integrity: sha512-Sig0SNORX9fdW+bQuTEovKj3uHcUL6LQKbCrrqb1X7J6/ReAbhCXRAhc+SMejhLELFj2QcyuxmUooZ4bt5ReSw==}
@@ -4008,9 +4024,6 @@ packages:
'@types/hast@3.0.4':
resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}
'@types/history@4.7.11':
resolution: {integrity: sha512-qjDJRrmvBMiTx+jyLxvLfJU7UznFuokDv4f3WRuriHKERccVpFU+8XMQUAbDzoiJCsmexxRExQeMwwCdamSKDA==}
'@types/hoist-non-react-statics@3.3.1':
resolution: {integrity: sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==}
@@ -4077,6 +4090,9 @@ packages:
'@types/prop-types@15.7.5':
resolution: {integrity: sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==}
'@types/rbush@4.0.0':
resolution: {integrity: sha512-+N+2H39P8X+Hy1I5mC6awlTX54k3FhiUmvt7HWzGJZvF+syUAAxP/stwppS8JE84YHqFgRMv6fCy31202CMFxQ==}
'@types/react-addons-update@0.14.21':
resolution: {integrity: sha512-HOxr0Hd8C1L4uw8DHyv2etqMVIj78oLEpe567/HgjoE+1Lc+PUsTGXTrkr1BDvFqsu5r49mSlgI5evwrk9eutA==}
@@ -4092,12 +4108,6 @@ packages:
'@types/react-resizable@3.0.3':
resolution: {integrity: sha512-W/QsUOZoXBAIBQNhNm95A5ohoaiUA874lWQytO2UP9dOjp5JHO9+a0cwYNabea7sA12ZDJnGVUFZxcNaNksAWA==}
'@types/react-router-dom@5.3.3':
resolution: {integrity: sha512-kpqnYK4wcdm5UaWI3fLcELopqLrHgLqNsdpHauzlQktfkHL3npOSwtj1Uz9oKBAzs7lFtVkV8j83voAz2D8fhw==}
'@types/react-router@5.1.20':
resolution: {integrity: sha512-jGjmu/ZqS7FjSH6owMcD5qpq19+1RS9DeVRqfl1FeBMxTDQAGwlMWOcs52NDoXaNKyG3d1cYQFMs9rCrb88o9Q==}
'@types/react-syntax-highlighter@15.5.13':
resolution: {integrity: sha512-uLGJ87j6Sz8UaBAooU0T6lWJ0dBmjZgN1PZTrj05TNql2/XpC6+4HhMT5syIdFUUt+FASfCeLLv4kBygNU+8qA==}
@@ -4128,6 +4138,12 @@ packages:
'@types/testing-library__jest-dom@5.14.5':
resolution: {integrity: sha512-SBwbxYoyPIvxHbeHxTZX2Pe/74F/tX2/D3mMvzabdeJ25bBojfW0TyB8BHrbq/9zaaKICJZjLP+8r6AeZMFCuQ==}
'@types/topojson-client@3.1.5':
resolution: {integrity: sha512-C79rySTyPxnQNNguTZNI1Ct4D7IXgvyAs3p9HPecnl6mNrJ5+UhvGNYcZfpROYV2lMHI48kJPxwR+F9C6c7nmw==}
'@types/topojson-specification@1.0.5':
resolution: {integrity: sha512-C7KvcQh+C2nr6Y2Ub4YfgvWvWCgP2nOQMtfhlnwsRL4pYmmwzBS7HclGiS87eQfDOU/DLQpX6GEscviaz4yLIQ==}
'@types/tough-cookie@4.0.5':
resolution: {integrity: sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==}
@@ -4413,6 +4429,9 @@ packages:
'@xobotyi/scrollbar-width@1.9.5':
resolution: {integrity: sha512-N8tkAACJx2ww8vFMneJmaAgmjAG1tnVBZJRLRcx061tmsLRZHSEZSLuGWnwPtunsSLvSqXQ2wfp7Mgqg1I+2dQ==}
'@zarrita/storage@0.2.0':
resolution: {integrity: sha512-855ZXqtnds7spnT8vNvD+MXa3QExP1m2GqShe8yt7uZXHnQLgJHgkpVwFjE1B0KDDRO0ki09hmk6OboTaIfPsQ==}
'@zxing/text-encoding@0.9.0':
resolution: {integrity: sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==}
@@ -5030,6 +5049,10 @@ packages:
resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}
engines: {node: '>= 0.6'}
cookie@1.1.1:
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'}
copy-anything@3.0.5:
resolution: {integrity: sha512-yCEafptTtb4bk7GLEQoM8KVJpxAfdBJYaXyzQEgQQQgYrZiDp8SJmGKlYza6CYjEDNstAdNdKA3UuoULlEbS6w==}
engines: {node: '>=12.13'}
@@ -5212,6 +5235,10 @@ packages:
resolution: {integrity: sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA==}
engines: {node: '>=12'}
d3-geo@3.1.1:
resolution: {integrity: sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==}
engines: {node: '>=12'}
d3-hierarchy@1.1.9:
resolution: {integrity: sha512-j8tPxlqh1srJHAtxfvOUwKNYJkQuBFdM1+JAUfq6xqH5eAqf93L7oG1NVqDa4CpFZNvnNKtCYEUC8KY9yEn9lQ==}
@@ -5487,6 +5514,9 @@ packages:
earcut@2.2.4:
resolution: {integrity: sha512-/pjZsA1b4RPHbeWZQn66SWS8nZZWLQQ23oE3Eam7aroEFGEvwKAsJfZ9ytiEMycfzXWpca4FA9QIOehf7PocBQ==}
earcut@3.2.4:
resolution: {integrity: sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==}
eastasianwidth@0.2.0:
resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
@@ -5754,6 +5784,9 @@ packages:
fflate@0.4.9:
resolution: {integrity: sha512-zdxgIEddhfsyCaWpJ2SdXEP8ZMrKJ6+5jl4OupODcywU0IhRk6gdXuVGcPICyfx2H97hVK7xmJtRLPjkxAX8Vw==}
fflate@0.8.3:
resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
figures@3.2.0:
resolution: {integrity: sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==}
engines: {node: '>=8'}
@@ -5931,6 +5964,10 @@ packages:
resolution: {integrity: sha512-PT6uoF5a1+kbC3tHmZSUsLHBp2QJlHasxxxxPW47QIY1VBKpFB+FcDvX+MxER6UzgLQZ0xDzJ9s48B9JbOCTqA==}
engines: {node: '>=10.19'}
geotiff@3.1.0-beta.0:
resolution: {integrity: sha512-wbVwOaQYuN+ywly5NoMXn37nHslwkQg5EFHqMeUTtjDACrSag0EEVlFsc+2DK3Pzmmp6XzJW2RTZOamPsBM6ng==}
engines: {node: '>=10.19'}
get-caller-file@2.0.5:
resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}
engines: {node: 6.* || 8.* || >= 10.*}
@@ -6113,9 +6150,6 @@ packages:
history@4.10.1:
resolution: {integrity: sha512-36nwAD620w12kuzPAsyINPWJqlNbij+hpK1k9XRloDtym8mxzGYl2c17LnV6IAGB2Dmg4tEa7G7DlawS0+qjew==}
history@5.3.0:
resolution: {integrity: sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ==}
hoist-non-react-statics@3.3.2:
resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==}
@@ -7503,6 +7537,9 @@ packages:
nth-check@2.1.1:
resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
numcodecs@0.3.2:
resolution: {integrity: sha512-6YSPnmZgg0P87jnNhi3s+FVLOcIn3y+1CTIgUulA3IdASzK9fJM87sUFkpyA+be9GibGRaST2wCgkD+6U+fWKw==}
nuqs@2.8.8:
resolution: {integrity: sha512-LF5sw9nWpHyPWzMMu9oho3r9C5DvkpmBIg4LQN78sexIzGaeRx8DWr0uy3YiFx5i2QGZN1Qqcb+OAtEVRa2bnA==}
peerDependencies:
@@ -7510,7 +7547,7 @@ packages:
'@tanstack/react-router': ^1
next: '>=14.2.0'
react: '>=18.2.0 || ^19.0.0-0'
react-router: '>=6.30.6 <7'
react-router: ^5 || ^6 || ^7
react-router-dom: ^5 || ^6 || ^7
peerDependenciesMeta:
'@remix-run/react':
@@ -7531,7 +7568,7 @@ packages:
'@tanstack/react-router': ^1
next: '>=14.2.0'
react: '>=18.2.0 || ^19.0.0-0'
react-router: '>=6.30.6 <7'
react-router: ^5 || ^6 || ^7 || ^8
react-router-dom: ^5 || ^6 || ^7
peerDependenciesMeta:
'@remix-run/react':
@@ -7579,6 +7616,9 @@ packages:
ol-mapbox-style@10.7.0:
resolution: {integrity: sha512-S/UdYBuOjrotcR95Iq9AejGYbifKeZE85D9VtH11ryJLQPTZXZSW1J5bIXcr4AlAH6tyjPPHTK34AdkwB32Myw==}
ol@10.11.0:
resolution: {integrity: sha512-OJ+lrx7kx/1O7Xx18Ff9QkVnwZIEL0OuhJQSy2sYgzzDvyZ2qHvuZEGAajbSstUyBwaS1OtQ4RWnY84tRMDdqg==}
ol@7.4.0:
resolution: {integrity: sha512-bgBbiah694HhC0jt8ptEFNRXwgO8d6xWH3G97PCg4bmn9Li5nLLbi59oSrvqUI6VPVwonPQF1YcqJymxxyMC6A==}
@@ -7803,6 +7843,10 @@ packages:
resolution: {integrity: sha512-ClrV7pNOn7rtmoQVF4TS1vyU0WhYRnP92fzbfF75jAIwpnzdJXf8iTd4CMEqO4yUenH6NDqLiwjqlh6QgZzgLQ==}
hasBin: true
pbf@5.1.2:
resolution: {integrity: sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==}
hasBin: true
picocolors@1.1.1:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -8008,9 +8052,15 @@ packages:
quickselect@2.0.0:
resolution: {integrity: sha512-RKJ22hX8mHe3Y6wH/N3wCM6BWtjaxIyyUIkpHOvfFnxdI4yD4tBXEBKSbriGujF6jnSVkJrffuo6vxACiSSxIw==}
quickselect@3.0.0:
resolution: {integrity: sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==}
rbush@3.0.1:
resolution: {integrity: sha512-XRaVO0YecOpEuIvbhbpTrZgoiI6xBlz6hnlr6EHhd+0x9ase6EmeN+hdwwUaJvLcsFFQ8iWVF1GAK1yB0BWi0w==}
rbush@4.0.1:
resolution: {integrity: sha512-IP0UpfeWQujYC8Jg162rMNc01Rf0gWMMAb2Uxus/Q0qOFw4lCcq6ZnQEZwUoJqWyUGJ9th7JjwI4yIWo+uvoAQ==}
rc-cascader@3.20.0:
resolution: {integrity: sha512-lkT9EEwOcYdjZ/jvhLoXGzprK1sijT3/Tp4BLxQQcHDZkkOzzwYQC9HgmKoJz0K7CukMfgvO9KqHeBdgE+pELw==}
peerDependencies:
@@ -8455,14 +8505,6 @@ packages:
react: '>=16.3.0'
react-dom: '>=16.3.0'
react-router-dom-v5-compat@6.30.6:
resolution: {integrity: sha512-I54amXpivD3V0r1BYUIj1qLOljXx+UpbLG63Bqbm3BdKH62z4H3znC0L7SyMTYAMEDZuUjDSlqtkBRG/OEDXBg==}
engines: {node: '>=14.0.0'}
peerDependencies:
react: '>=16.8'
react-dom: '>=16.8'
react-router-dom: 4 || 5
react-router-dom@5.3.4:
resolution: {integrity: sha512-m4EqFMHv/Ih4kpcBCONHbkT68KoAeHN4p3lAGoNryfHi0dMy0kCzEZakiKRsvg5wHZ/JLrLW8o8KomWiz/qbYQ==}
peerDependencies:
@@ -8473,11 +8515,15 @@ packages:
peerDependencies:
react: '>=15'
react-router@6.30.6:
resolution: {integrity: sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg==}
engines: {node: '>=14.0.0'}
react-router@7.18.4:
resolution: {integrity: sha512-PUPQcMhMGRAslLcvtlPz/kmzBEWPhLdgLFrL7pLNepBL6dX0lWj4WD2cUYVgYCuT3jxvghYFg81cDTj44DhetQ==}
engines: {node: '>=20.0.0'}
peerDependencies:
react: '>=16.8'
react: '>=18'
react-dom: '>=18'
peerDependenciesMeta:
react-dom:
optional: true
react-style-singleton@2.2.3:
resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==}
@@ -8571,6 +8617,9 @@ packages:
resolution: {integrity: sha512-J8rn6v4DBb2nnFqkqwy6/NnTYMcgLA+sLr0iIO41qpv0n+ngb7ksag2tMRl0inb1bbO/esUwzW1vbJi7K0sI0g==}
engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0}
reference-spec-reader@0.2.0:
resolution: {integrity: sha512-q0mfCi5yZSSHXpCyxjgQeaORq3tvDsxDyzaadA/5+AbAUwRyRuuTh0aRQuE/vAOt/qzzxidJ5iDeu1cLHaNBlQ==}
refractor@3.6.0:
resolution: {integrity: sha512-MY9W41IOWxxk31o+YvFCNyNzdkc9M20NoZK5vq6jkv4I/uh2zkWcfudj0Q1fovjUQJrNewS9NMzeTtqPf+n5EA==}
@@ -9258,6 +9307,18 @@ packages:
toggle-selection@1.0.6:
resolution: {integrity: sha512-BiZS+C1OS8g/q2RRbJmy59xpyghNBqrr6k5L/uKBGRsTfxmu3ffiRnd8mlGPUVayg8pvfi5urfnu8TU7DVOkLQ==}
topojson-client@3.1.0:
resolution: {integrity: sha512-605uxS6bcYxGXw9qi62XyrV6Q3xwbndjachmNxu8HWTtVPxZfEJN9fd/SZS1Q54Sn2y0TMyMxFj/cJINqGHrKw==}
hasBin: true
topojson-server@3.0.1:
resolution: {integrity: sha512-/VS9j/ffKr2XAOjlZ9CgyyeLmgJ9dMwq6Y0YEON8O7p/tGGk+dCWnrE03zEdu7i4L7YsFZLEPZPzCvcB7lEEXw==}
hasBin: true
topojson-simplify@3.0.3:
resolution: {integrity: sha512-V+pBjLVzSQ3+hSOxBiV01OVXgFiCmMO8ia3huxKEyIMTC1ApQHBcdXdOqcQ6U2JJJD31TZduwY6KyF15R8sUgg==}
hasBin: true
tough-cookie@4.1.4:
resolution: {integrity: sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==}
engines: {node: '>=6'}
@@ -9507,6 +9568,10 @@ packages:
unrs-resolver@1.11.1:
resolution: {integrity: sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==}
unzipit@2.0.0:
resolution: {integrity: sha512-DVeVIWUZCAQPNzm5sB0hpsG1GygTTdBnzNtYYEpInkttx5evkyqRgZi6rTczoySqp8hO5jHVKzrH0f23X8FZLg==}
engines: {node: '>=18'}
update-browserslist-db@1.3.3:
resolution: {integrity: sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==}
hasBin: true
@@ -9825,6 +9890,9 @@ packages:
resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==}
engines: {node: '>=12'}
xml-utils@1.10.2:
resolution: {integrity: sha512-RqM+2o1RYs6T8+3DzDSoTRAUfrvaejbVHcp3+thnAtDKo8LskR+HomLajEy5UjTz24rpka7AxVBRR3g2wTUkJA==}
xml-utils@1.7.0:
resolution: {integrity: sha512-bWB489+RQQclC7A9OW8e5BzbT8Tu//jtAOvkYwewFr+Q9T9KDGvfzC1lp0pYPEQPEoPQLDkmxkepSC/2gIAZGw==}
@@ -9907,12 +9975,18 @@ packages:
resolution: {integrity: sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==}
engines: {node: '>=18'}
zarrita@0.7.5:
resolution: {integrity: sha512-ZriOSEne+Wf2iuM0yjDZvUKpHNlug3dO7qJ6mAxXoOgsYV18DPOkAkwB9e0rf21bHcKcOffFuwoZwn5g6pvUeA==}
zod@4.3.6:
resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}
zstddec@0.1.0:
resolution: {integrity: sha512-w2NTI8+3l3eeltKAdK8QpiLo/flRAr2p8AGeakfMZOXBxOg9HIu4LVDxBi81sYgVhFhdJjv1OrB5ssI8uFPoLg==}
zstddec@0.2.0:
resolution: {integrity: sha512-oyPnDa1X5c13+Y7mA/FDMNJrn4S8UNBe0KCqtDmor40Re7ALrPN6npFwyYVRRh+PqozZQdeg23QtbcamZnG5rA==}
zustand@5.0.11:
resolution: {integrity: sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg==}
engines: {node: '>=12.20.0'}
@@ -12489,6 +12563,8 @@ snapshots:
'@petamoriken/float16@3.8.0': {}
'@petamoriken/float16@3.9.3': {}
'@pkgjs/parseargs@0.11.0':
optional: true
@@ -12920,8 +12996,6 @@ snapshots:
'@react-dnd/shallowequal@4.0.2': {}
'@remix-run/router@1.23.4': {}
'@rolldown/binding-android-arm64@1.0.0-beta.53':
optional: true
@@ -13154,7 +13228,7 @@ snapshots:
'@signozhq/icons@0.4.0': {}
'@signozhq/ui@0.2.0(@date-fns/tz@1.4.1)(@emotion/is-prop-valid@1.2.0)(@signozhq/icons@0.4.0)(@types/react-dom@18.0.10)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0)':
'@signozhq/ui@0.2.0(@date-fns/tz@1.4.1)(@emotion/is-prop-valid@1.2.0)(@signozhq/icons@0.4.0)(@types/react-dom@18.0.10)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)':
dependencies:
'@base-ui/react': 1.7.0(@date-fns/tz@1.4.1)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@chenglou/pretext': 0.0.8
@@ -13178,7 +13252,7 @@ snapshots:
lodash-es: 4.18.1
motion: 11.18.2(@emotion/is-prop-valid@1.2.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
next-themes: 0.4.6(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
nuqs: 2.9.6(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0)
nuqs: 2.9.6(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
react: 18.2.0
react-compiler-runtime: 1.0.0(react@18.2.0)
react-day-picker: 9.9.0(react@18.2.0)
@@ -13576,7 +13650,11 @@ snapshots:
'@types/d3-geo@3.1.0':
dependencies:
'@types/geojson': 7946.0.14
'@types/geojson': 7946.0.16
'@types/d3-geo@3.1.1':
dependencies:
'@types/geojson': 7946.0.16
'@types/d3-hierarchy@1.1.11': {}
@@ -13616,7 +13694,7 @@ snapshots:
'@types/file-saver@2.0.5': {}
'@types/geojson@7946.0.14': {}
'@types/geojson@7946.0.16': {}
'@types/graceful-fs@4.1.6':
dependencies:
@@ -13630,8 +13708,6 @@ snapshots:
dependencies:
'@types/unist': 3.0.2
'@types/history@4.7.11': {}
'@types/hoist-non-react-statics@3.3.1':
dependencies:
'@types/react': 18.0.26
@@ -13705,6 +13781,8 @@ snapshots:
'@types/prop-types@15.7.5': {}
'@types/rbush@4.0.0': {}
'@types/react-addons-update@0.14.21':
dependencies:
'@types/react': 18.0.26
@@ -13728,17 +13806,6 @@ snapshots:
dependencies:
'@types/react': 18.0.26
'@types/react-router-dom@5.3.3':
dependencies:
'@types/history': 4.7.11
'@types/react': 18.0.26
'@types/react-router': 5.1.20
'@types/react-router@5.1.20':
dependencies:
'@types/history': 4.7.11
'@types/react': 18.0.26
'@types/react-syntax-highlighter@15.5.13':
dependencies:
'@types/react': 18.0.26
@@ -13775,6 +13842,15 @@ snapshots:
dependencies:
'@types/jest': 30.0.0
'@types/topojson-client@3.1.5':
dependencies:
'@types/geojson': 7946.0.16
'@types/topojson-specification': 1.0.5
'@types/topojson-specification@1.0.5':
dependencies:
'@types/geojson': 7946.0.16
'@types/tough-cookie@4.0.5': {}
'@types/trusted-types@2.0.7':
@@ -14070,6 +14146,11 @@ snapshots:
'@xobotyi/scrollbar-width@1.9.5': {}
'@zarrita/storage@0.2.0':
dependencies:
reference-spec-reader: 0.2.0
unzipit: 2.0.0
'@zxing/text-encoding@0.9.0':
optional: true
@@ -14780,6 +14861,8 @@ snapshots:
cookie@0.7.2: {}
cookie@1.1.1: {}
copy-anything@3.0.5:
dependencies:
is-what: 4.1.16
@@ -14958,6 +15041,10 @@ snapshots:
dependencies:
d3-array: 3.2.4
d3-geo@3.1.1:
dependencies:
d3-array: 3.2.4
d3-hierarchy@1.1.9: {}
d3-hierarchy@3.1.2: {}
@@ -15224,6 +15311,8 @@ snapshots:
earcut@2.2.4: {}
earcut@3.2.4: {}
eastasianwidth@0.2.0: {}
electron-to-chromium@1.5.427: {}
@@ -15540,6 +15629,8 @@ snapshots:
fflate@0.4.9: {}
fflate@0.8.3: {}
figures@3.2.0:
dependencies:
escape-string-regexp: 1.0.5
@@ -15728,6 +15819,17 @@ snapshots:
xml-utils: 1.7.0
zstddec: 0.1.0
geotiff@3.1.0-beta.0:
dependencies:
'@petamoriken/float16': 3.9.3
lerc: 3.0.0
pako: 2.1.0
parse-headers: 2.0.5
quick-lru: 6.1.1
web-worker: 1.5.0
xml-utils: 1.10.2
zstddec: 0.2.0
get-caller-file@2.0.5: {}
get-east-asian-width@1.5.0: {}
@@ -15967,10 +16069,6 @@ snapshots:
tiny-warning: 1.0.3
value-equal: 1.0.1
history@5.3.0:
dependencies:
'@babel/runtime': 7.29.2
hoist-non-react-statics@3.3.2:
dependencies:
react-is: 16.13.1
@@ -16290,7 +16388,8 @@ snapshots:
dependencies:
is-inside-container: 1.0.0
isarray@0.0.1: {}
isarray@0.0.1:
optional: true
isarray@1.0.0: {}
@@ -17785,20 +17884,24 @@ snapshots:
dependencies:
boolbase: 1.0.0
nuqs@2.8.8(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0):
numcodecs@0.3.2:
dependencies:
fflate: 0.8.3
nuqs@2.8.8(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0):
dependencies:
'@standard-schema/spec': 1.0.0
react: 18.2.0
optionalDependencies:
react-router: 6.30.6(react@18.2.0)
react-router: 7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
react-router-dom: 5.3.4(react@18.2.0)
nuqs@2.9.6(react-router-dom@5.3.4(react@18.2.0))(react-router@6.30.6(react@18.2.0))(react@18.2.0):
nuqs@2.9.6(react-router-dom@5.3.4(react@18.2.0))(react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0):
dependencies:
'@standard-schema/spec': 1.1.0
react: 18.2.0
optionalDependencies:
react-router: 6.30.6(react@18.2.0)
react-router: 7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
react-router-dom: 5.3.4(react@18.2.0)
nwsapi@2.2.23: {}
@@ -17863,6 +17966,15 @@ snapshots:
mapbox-to-css-font: 2.4.5
ol: 7.4.0
ol@10.11.0:
dependencies:
'@types/rbush': 4.0.0
earcut: 3.2.4
geotiff: 3.1.0-beta.0
pbf: 5.1.2
rbush: 4.0.1
zarrita: 0.7.5
ol@7.4.0:
dependencies:
earcut: 2.2.4
@@ -18174,6 +18286,7 @@ snapshots:
path-to-regexp@1.9.0:
dependencies:
isarray: 0.0.1
optional: true
path-to-regexp@6.3.0: {}
@@ -18189,6 +18302,10 @@ snapshots:
ieee754: 1.2.1
resolve-protobuf-schema: 2.1.0
pbf@5.1.2:
dependencies:
resolve-protobuf-schema: 2.1.0
picocolors@1.1.1: {}
picomatch@2.3.2: {}
@@ -18372,10 +18489,16 @@ snapshots:
quickselect@2.0.0: {}
quickselect@3.0.0: {}
rbush@3.0.1:
dependencies:
quickselect: 2.0.0
rbush@4.0.1:
dependencies:
quickselect: 3.0.0
rc-cascader@3.20.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
dependencies:
'@babel/runtime': 7.28.2
@@ -18943,18 +19066,9 @@ snapshots:
react-draggable: 4.5.0(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
tslib: 2.6.2
react-router-dom-v5-compat@6.30.6(react-dom@18.2.0(react@18.2.0))(react-router-dom@5.3.4(react@18.2.0))(react@18.2.0):
dependencies:
'@remix-run/router': 1.23.4
history: 5.3.0
react: 18.2.0
react-dom: 18.2.0(react@18.2.0)
react-router: 6.30.6(react@18.2.0)
react-router-dom: 5.3.4(react@18.2.0)
react-router-dom@5.3.4(react@18.2.0):
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.29.2
history: 4.10.1
loose-envify: 1.4.0
prop-types: 15.8.1
@@ -18962,10 +19076,11 @@ snapshots:
react-router: 5.3.4(react@18.2.0)
tiny-invariant: 1.3.3
tiny-warning: 1.0.3
optional: true
react-router@5.3.4(react@18.2.0):
dependencies:
'@babel/runtime': 7.28.2
'@babel/runtime': 7.29.2
history: 4.10.1
hoist-non-react-statics: 3.3.2
loose-envify: 1.4.0
@@ -18975,11 +19090,15 @@ snapshots:
react-is: 16.13.1
tiny-invariant: 1.3.3
tiny-warning: 1.0.3
optional: true
react-router@6.30.6(react@18.2.0):
react-router@7.18.4(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
dependencies:
'@remix-run/router': 1.23.4
cookie: 1.1.1
react: 18.2.0
set-cookie-parser: 2.6.0
optionalDependencies:
react-dom: 18.2.0(react@18.2.0)
react-style-singleton@2.2.3(@types/react@18.0.26)(react@18.2.0):
dependencies:
@@ -19109,6 +19228,8 @@ snapshots:
dependencies:
'@eslint-community/regexpp': 4.12.2
reference-spec-reader@0.2.0: {}
refractor@3.6.0:
dependencies:
hastscript: 6.0.0
@@ -19884,6 +20005,19 @@ snapshots:
toggle-selection@1.0.6: {}
topojson-client@3.1.0:
dependencies:
commander: 2.20.3
topojson-server@3.0.1:
dependencies:
commander: 2.20.3
topojson-simplify@3.0.3:
dependencies:
commander: 2.20.3
topojson-client: 3.1.0
tough-cookie@4.1.4:
dependencies:
psl: 1.15.0
@@ -20152,6 +20286,8 @@ snapshots:
'@unrs/resolver-binding-win32-ia32-msvc': 1.11.1
'@unrs/resolver-binding-win32-x64-msvc': 1.11.1
unzipit@2.0.0: {}
update-browserslist-db@1.3.3(browserslist@4.28.9):
dependencies:
browserslist: 4.28.9
@@ -20473,6 +20609,8 @@ snapshots:
xml-name-validator@4.0.0: {}
xml-utils@1.10.2: {}
xml-utils@1.7.0: {}
xml@1.0.1: {}
@@ -20549,10 +20687,17 @@ snapshots:
yoctocolors@2.1.2: {}
zarrita@0.7.5:
dependencies:
'@zarrita/storage': 0.2.0
numcodecs: 0.3.2
zod@4.3.6: {}
zstddec@0.1.0: {}
zstddec@0.2.0: {}
zustand@5.0.11(@types/react@18.0.26)(immer@11.1.3)(react@18.2.0)(use-sync-external-store@1.6.0(react@18.2.0)):
optionalDependencies:
'@types/react': 18.0.26

View File

@@ -67,11 +67,6 @@ 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'

View 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;
});

View 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',
]);

View 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),
},
};
}

View 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 };
}

View 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 };
}

View 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- ')}`,
);
}
}

View File

@@ -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

View 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 />;
}

View File

@@ -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,

View 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');
});
});

View File

@@ -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>

View 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 /> },
],
},
];
}

View File

@@ -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;
}

View File

@@ -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.

View File

@@ -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 [

View File

@@ -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,

View 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} />;
}

View File

@@ -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>
);
}

View 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;
}

View File

@@ -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>

View File

@@ -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,
});
});
});

View File

@@ -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 };

View File

@@ -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>

View File

@@ -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' }],
},
},
],
},
});

View File

@@ -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' }],
},
},
],
},
},
]);
});
});

View File

@@ -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,
});
}

View File

@@ -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);

View File

@@ -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

View File

@@ -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,

View File

@@ -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)' },
]);
});
});

View File

@@ -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 ?? [];

View File

@@ -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"
>

View File

@@ -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) {

View File

@@ -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());

View File

@@ -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 {

View File

@@ -1,5 +1,5 @@
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
import { fieldContextToAttributeType } from 'utils/fieldContext';
import { fieldDataTypeToDataType } from 'utils/fieldDataType';
import { FiltersType, IQuickFiltersConfig } from './types';
@@ -14,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,

View File

@@ -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';

View File

@@ -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,

View File

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

View File

@@ -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;

View File

@@ -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 (

View File

@@ -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} />;
}

View File

@@ -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 = [

View File

@@ -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();
});
});

View File

@@ -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> =

View File

@@ -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 && (

View File

@@ -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;
}

View File

@@ -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()) {

View File

@@ -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 && (

View File

@@ -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'),
);
});
});

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,5 @@
import { useMemo } from 'react';
import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import {
initialFilters,
initialQueriesMap,
@@ -50,7 +50,7 @@ const useSampleLogs = ({
selectedTime: 'GLOBAL_TIME',
globalSelectedInterval: timeInterval,
},
DEFAULT_ENTITY_VERSION,
ENTITY_VERSION_V5,
);
const { isFetching: isLoading, data } = response;

View File

@@ -10,7 +10,6 @@ import {
userEvent,
waitFor,
} from 'tests/test-utils';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { pipelineApiResponseMockData } from '../mocks/pipeline';
import PipelineListsView from '../PipelineListsView';
@@ -85,7 +84,7 @@ jest.mock('providers/preferences/sync/usePreferenceSync', () => ({
}));
const BASE_URL = ENVIRONMENT.baseURL;
const attributeKeysURL = `${BASE_URL}/api/v3/filter_suggestions`;
const fieldKeysURL = `${BASE_URL}/api/v1/fields/keys`;
describe('PipelinePage container test', () => {
beforeAll(() => {
@@ -339,42 +338,41 @@ describe('PipelinePage container test', () => {
expect(screen.queryAllByText('source = nginx')).toHaveLength(2);
server.use(
rest.get(attributeKeysURL, (_req, res, ctx) =>
rest.get(fieldKeysURL, (_req, res, ctx) =>
res(
ctx.status(200),
ctx.json({
status: 'success',
data: {
attributes: [
{
key: 'otelServiceName',
dataType: DataTypes.String,
type: 'tag',
isColumn: false,
isJSON: false,
},
{
key: 'service.name',
dataType: DataTypes.String,
type: 'resource',
isColumn: false,
isJSON: false,
},
{
key: 'service.instance.id',
dataType: DataTypes.String,
type: 'resource',
isColumn: false,
isJSON: false,
},
{
key: 'service.name',
dataType: DataTypes.String,
type: 'tag',
isColumn: false,
isJSON: false,
},
],
complete: true,
keys: {
otelServiceName: [
{
name: 'otelServiceName',
fieldContext: 'attribute',
fieldDataType: 'string',
},
],
'service.name': [
{
name: 'service.name',
fieldContext: 'resource',
fieldDataType: 'string',
},
{
name: 'service.name',
fieldContext: 'attribute',
fieldDataType: 'string',
},
],
'service.instance.id': [
{
name: 'service.instance.id',
fieldContext: 'resource',
fieldDataType: 'string',
},
],
},
},
}),
),

View File

@@ -10,9 +10,9 @@ import {
} from 'react';
import { type RefSelectProps, Select, Spin } from 'antd';
import { Pill } from '@signozhq/ui/pill';
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import cx from 'classnames';
import {
DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY,
OperatorConfigKeys,
OPERATORS,
QUERY_BUILDER_OPERATORS_BY_TYPES,
@@ -22,23 +22,14 @@ import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
import { LogsExplorerShortcuts } from 'constants/shortcuts/logsExplorerShortcuts';
import { useDynamicVariableSuggestions } from 'hooks/dashboard/useDynamicVariableSuggestions';
import { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
import { useGetAggregateKeys } from 'hooks/queryBuilder/useGetAggregateKeys';
import { useGetAggregateValues } from 'hooks/queryBuilder/useGetAggregateValues';
import { useGetAttributeSuggestions } from 'hooks/queryBuilder/useGetAttributeSuggestions';
import { validationMapper } from 'hooks/queryBuilder/useIsValidTag';
import { operatorTypeMapper } from 'hooks/queryBuilder/useOperatorType';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useRunQueryWithFilterItems } from 'hooks/queryBuilder/useRunQueryWithFilterItems';
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
import { useFieldValuesSuggestion } from 'hooks/querySuggestions/useFieldValuesSuggestion';
import useDebounceValue from 'hooks/useDebounce';
import {
cloneDeep,
isArray,
isEmpty,
isEqual,
isObject,
isUndefined,
unset,
} from 'lodash-es';
import { isArray, isEmpty, isEqual, isObject, isUndefined } from 'lodash-es';
import { ChevronDown, ChevronUp } from '@signozhq/icons';
import {
BaseAutocompleteData,
@@ -48,7 +39,13 @@ import {
IBuilderQuery,
TagFilter,
} from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import {
DATA_SOURCE_TO_SIGNAL,
DataSource,
QUERY_SOURCE_TO_FIELD_SOURCE,
} from 'types/common/queryBuilder';
import { attributeTypeToFieldContext } from 'utils/fieldContext';
import { getValuesForDataType } from 'utils/fieldValues';
import { useSelectPopupContainer } from 'utils/selectPopupContainer';
import { v4 as uuid } from 'uuid';
@@ -61,7 +58,8 @@ import {
getTagToken,
isInNInOperator,
} from './utils';
import { filterByOperatorConfig } from '../utils';
import { toAttributeKey } from '../GroupByFilter/utils';
import { filterByOperatorConfig, getMetricNameForQuery } from '../utils';
import QueryBuilderSearchDropdown from './QueryBuilderSearchDropdown';
import SpanScopeSelector from './SpanScopeSelector';
import Suggestions from './Suggestions';
@@ -75,6 +73,8 @@ export interface ITag {
value: (string | number | boolean)[] | string | number | boolean;
}
const SPAN_SEARCH_SCOPE_KEYS = ['isRoot', 'isEntryPoint'];
interface CustomTagProps {
label: React.ReactNode;
value: string;
@@ -186,70 +186,15 @@ function QueryBuilderSearchV2(
[query.dataSource],
);
const memoizedSearchParams = useMemo(
() => [
searchValue,
query.dataSource,
query.aggregateOperator,
query.aggregateAttribute?.key,
],
[
searchValue,
query.dataSource,
query.aggregateOperator,
query.aggregateAttribute?.key,
],
);
const queryFiltersWithoutId = useMemo(
() => ({
...query.filters,
items: query.filters?.items.map((item) => {
const filterWithoutId = cloneDeep(item);
unset(filterWithoutId, 'id');
return filterWithoutId;
}),
}),
[query.filters],
);
const memoizedSuggestionsParams = useMemo(
() => [searchValue, query.dataSource, queryFiltersWithoutId],
[query.dataSource, queryFiltersWithoutId, searchValue],
);
const memoizedValueParams = useMemo(
() => [
query.aggregateOperator,
query.dataSource,
query.aggregateAttribute?.key,
currentFilterItem?.key?.key || '',
currentFilterItem?.key?.dataType,
currentFilterItem?.key?.type ?? '',
isArray(currentFilterItem?.value)
? currentFilterItem?.value?.[currentFilterItem.value.length - 1]
: currentFilterItem?.value,
],
[
query.aggregateOperator,
query.dataSource,
query.aggregateAttribute?.key,
currentFilterItem?.key?.key,
currentFilterItem?.key?.dataType,
currentFilterItem?.key?.type,
currentFilterItem?.value,
],
);
const searchParams = useDebounceValue(memoizedSearchParams, DEBOUNCE_DELAY);
const valueParams = useDebounceValue(memoizedValueParams, DEBOUNCE_DELAY);
const suggestionsParams = useDebounceValue(
memoizedSuggestionsParams,
const debouncedKeySearchText = useDebounceValue(
searchValue?.split(' ')[0] ?? '',
DEBOUNCE_DELAY,
);
const valueSearchText = isArray(currentFilterItem?.value)
? String(currentFilterItem?.value?.[currentFilterItem.value.length - 1] ?? '')
: currentFilterItem?.value?.toString() || '';
const isQueryEnabled = useMemo(() => {
if (currentState === DropdownState.ATTRIBUTE_KEY) {
return query.dataSource === DataSource.METRICS
@@ -262,53 +207,76 @@ function QueryBuilderSearchV2(
const dashboardDynamicVariables = useDynamicVariableSuggestions();
const { data, isFetching } = useGetAggregateKeys(
const signal = DATA_SOURCE_TO_SIGNAL[query.dataSource];
const source = QUERY_SOURCE_TO_FIELD_SOURCE[query.source ?? ''];
const metricName = getMetricNameForQuery(query);
const { data: fieldKeys, isFetching } = useFieldKeysSuggestion(
{
searchText: searchValue?.split(' ')[0],
dataSource: query.dataSource,
aggregateOperator: query.aggregateOperator || '',
aggregateAttribute: query.aggregateAttribute?.key || '',
tagType: query.aggregateAttribute?.type ?? null,
signal,
source,
metricName,
fieldContext: attributeTypeToFieldContext(query.aggregateAttribute?.type),
searchText: debouncedKeySearchText,
},
query.builderQueryType,
{
queryKey: [searchParams],
enabled: isQueryEnabled && !isLogsDataSource && !hardcodedAttributeKeys,
enabled: isQueryEnabled && !hardcodedAttributeKeys,
keepPreviousData: true,
},
);
const { data: suggestionsData, isFetching: isFetchingSuggestions } =
useGetAttributeSuggestions(
{
searchText: searchValue?.split(' ')[0],
dataSource: query.dataSource,
filters: query.filters || { items: [], op: 'AND' },
},
{
queryKey: [suggestionsParams],
enabled: isQueryEnabled && isLogsDataSource,
},
);
// The legacy traces builder checks `exists` on the column only for keys marked as columns.
// Body JSON keys come back as bare paths, which the legacy builders read as top-level fields,
// and the span search scope selectors are not columns the legacy filter builder can read.
const attributeKeys = useMemo(
() =>
(fieldKeys ?? [])
.filter(
(fieldKey) =>
fieldKey.fieldContext !== TelemetrytypesFieldContextDTO.body &&
!(
fieldKey.fieldContext === TelemetrytypesFieldContextDTO.span &&
SPAN_SEARCH_SCOPE_KEYS.includes(fieldKey.name)
),
)
.map((fieldKey) => ({
...toAttributeKey(fieldKey),
isColumn:
fieldKey.fieldContext === TelemetrytypesFieldContextDTO.span ||
fieldKey.fieldContext === TelemetrytypesFieldContextDTO.log,
})),
[fieldKeys],
);
const { data: attributeValues, isFetching: isFetchingAttributeValues } =
useGetAggregateValues(
{
aggregateOperator: query.aggregateOperator || '',
dataSource: query.dataSource,
aggregateAttribute: query.aggregateAttribute?.key || '',
attributeKey: currentFilterItem?.key?.key || '',
filterAttributeKeyDataType:
currentFilterItem?.key?.dataType ?? DataTypes.EMPTY,
tagType: currentFilterItem?.key?.type ?? '',
searchText: isArray(currentFilterItem?.value)
? String(currentFilterItem?.value?.[currentFilterItem.value.length - 1]) ||
''
: currentFilterItem?.value?.toString() || '',
},
{
enabled: currentState === DropdownState.ATTRIBUTE_VALUE,
queryKey: [valueParams],
},
);
const fieldValuesConfig = useMemo(
() => ({
signal,
source,
metricName,
name: currentFilterItem?.key?.key || '',
fieldContext: attributeTypeToFieldContext(currentFilterItem?.key?.type),
searchText: valueSearchText,
}),
[
signal,
source,
metricName,
currentFilterItem?.key?.key,
currentFilterItem?.key?.type,
valueSearchText,
],
);
const debouncedFieldValuesConfig = useDebounceValue(
fieldValuesConfig,
DEBOUNCE_DELAY,
);
const { data: fieldValues, isFetching: isFetchingAttributeValues } =
useFieldValuesSuggestion(debouncedFieldValuesConfig, query.builderQueryType, {
enabled: currentState === DropdownState.ATTRIBUTE_VALUE,
});
const handleDropdownSelect = useCallback(
(value: string) => {
@@ -533,15 +501,13 @@ function QueryBuilderSearchV2(
if (tagKey && isUndefined(currentFilterItem?.key)) {
let currentRunningAttributeKey;
const isSuggestedKeyInAutocomplete =
suggestionsData?.payload?.attributes?.some(
(value) => value.key === tagKey.split(' ')[0],
);
isLogsDataSource &&
attributeKeys.some((value) => value.key === tagKey.split(' ')[0]);
if (isSuggestedKeyInAutocomplete) {
const allAttributesMatchingTheKey =
suggestionsData?.payload?.attributes?.filter(
(value) => value.key === tagKey.split(' ')[0],
) || [];
const allAttributesMatchingTheKey = attributeKeys.filter(
(value) => value.key === tagKey.split(' ')[0],
);
if (allAttributesMatchingTheKey?.length === 1) {
[currentRunningAttributeKey] = allAttributesMatchingTheKey;
@@ -648,9 +614,10 @@ function QueryBuilderSearchV2(
currentFilterItem,
currentFilterItem?.key,
currentFilterItem?.op,
suggestionsData?.payload?.attributes,
attributeKeys,
isLogsDataSource,
searchValue,
isFetchingSuggestions,
isFetching,
currentState,
]);
@@ -662,9 +629,7 @@ function QueryBuilderSearchV2(
// add the user typed option in the dropdown to select that and move ahead irrespective of the matches and all
setDropdownOptions([
...(!isEmpty(tagKey) &&
!suggestionsData?.payload?.attributes?.some((val) =>
isEqual(val.key, tagKey),
)
!attributeKeys.some((val) => isEqual(val.key, tagKey))
? [
{
label: tagKey,
@@ -676,10 +641,10 @@ function QueryBuilderSearchV2(
},
]
: []),
...(suggestionsData?.payload?.attributes?.map((key) => ({
...attributeKeys.map((key) => ({
label: key.key,
value: key,
})) || []),
})),
]);
} else if (hardcodedAttributeKeys) {
const filteredKeys = hardcodedAttributeKeys.filter((key) =>
@@ -697,7 +662,7 @@ function QueryBuilderSearchV2(
setDropdownOptions([
// Add user typed option if it doesn't exist in the payload
...(tagKey.trim().length > 0 &&
!data?.payload?.attributeKeys?.some((val) => val.key === tagKey)
!attributeKeys.some((val) => val.key === tagKey)
? [
{
label: tagKey,
@@ -710,10 +675,10 @@ function QueryBuilderSearchV2(
]
: []),
// Map existing attribute keys from payload
...(data?.payload?.attributeKeys?.map((key) => ({
...attributeKeys.map((key) => ({
label: key.key,
value: key,
})) || []),
})),
]);
}
}
@@ -778,10 +743,10 @@ function QueryBuilderSearchV2(
values.push(tagValue);
}
if (attributeValues?.payload) {
const dataType = currentFilterItem?.key?.dataType || DataTypes.String;
const key = DATA_TYPE_VS_ATTRIBUTE_VALUES_KEY[dataType];
values.push(...(attributeValues?.payload?.[key] || []));
if (fieldValues) {
values.push(
...getValuesForDataType(fieldValues, currentFilterItem?.key?.dataType),
);
// here we want to suggest the variable name matching with the key here, we will go over the dynamic variables for the keys
const variableName = dashboardDynamicVariables.find(
@@ -805,13 +770,12 @@ function QueryBuilderSearchV2(
}
}, [
hardcodedAttributeKeys,
attributeValues?.payload,
fieldValues,
currentFilterItem?.key?.dataType,
currentState,
data?.payload?.attributeKeys,
attributeKeys,
isLogsDataSource,
searchValue,
suggestionsData?.payload?.attributes,
operatorConfigKey,
currentFilterItem?.key?.key,
dashboardDynamicVariables,
@@ -880,8 +844,8 @@ function QueryBuilderSearchV2(
}, [deregisterShortcut, isLastQuery, registerShortcut]);
const loading = useMemo(
() => isFetching || isFetchingAttributeValues || isFetchingSuggestions,
[isFetching, isFetchingAttributeValues, isFetchingSuggestions],
() => isFetching || isFetchingAttributeValues,
[isFetching, isFetchingAttributeValues],
);
const isMetricsDataSource = useMemo(
@@ -991,7 +955,7 @@ function QueryBuilderSearchV2(
setTags((prev) => [...prev, ...(val.items as ITag[])]);
}}
searchValue={searchValue}
exampleQueries={suggestionsData?.payload?.example_queries || []}
exampleQueries={[]}
tags={tags}
currentFilterItem={currentFilterItem}
isLogsDataSource={isLogsDataSource}

View File

@@ -1,13 +1,23 @@
import { QueryClient, QueryClientProvider } from 'react-query';
import { render, RenderResult, screen, within } from '@testing-library/react';
import {
render,
RenderResult,
screen,
waitFor,
within,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {
initialQueriesMap,
initialQueryBuilderFormValues,
} from 'constants/queryBuilder';
import { TelemetrytypesTelemetryFieldValuesDTO } from 'api/generated/services/sigNoz.schemas';
import { DynamicVariableSuggestion } from 'providers/Dashboard/store/dynamicVariableSuggestions';
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
import { useFieldValuesSuggestion } from 'hooks/querySuggestions/useFieldValuesSuggestion';
import { QueryBuilderContext } from 'providers/QueryBuilder';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { FieldDataType, TelemetryFieldKey } from 'types/api/v5/queryRange';
import { DataSource } from 'types/common/queryBuilder';
import QueryBuilderSearchV2 from '../QueryBuilderSearchV2';
@@ -88,57 +98,34 @@ const renderWithContext = (props = {}): RenderResult => {
const getSearchCombobox = (): HTMLElement =>
within(screen.getByTestId('qb-search-select')).getByRole('combobox');
// Constants to fix linter errors
const TYPE_TAG = 'tag';
const IS_COLUMN_FALSE = false;
const IS_JSON_FALSE = false;
const mockAggregateKeysData = {
payload: {
attributeKeys: [
{
key: 'http.status',
dataType: DataTypes.String,
type: TYPE_TAG,
id: 'http.status--string--tag--false',
},
{
key: 'service.name',
dataType: DataTypes.String,
type: TYPE_TAG,
isColumn: IS_COLUMN_FALSE,
isJSON: IS_JSON_FALSE,
id: 'service.name--string--tag--false',
},
{
key: 'unmapped.attribute',
dataType: 'not-a-real-data-type' as unknown as DataTypes,
type: TYPE_TAG,
isColumn: IS_COLUMN_FALSE,
isJSON: IS_JSON_FALSE,
id: 'unmapped.attribute--String--tag--false',
},
],
const mockFieldKeys: TelemetryFieldKey[] = [
{ name: 'http.status', fieldContext: 'attribute', fieldDataType: 'string' },
{ name: 'service.name', fieldContext: 'attribute', fieldDataType: 'string' },
{ name: 'name', fieldContext: 'span', fieldDataType: 'string' },
{ name: 'user.id', fieldContext: 'body', fieldDataType: 'string' },
{ name: 'isRoot', fieldContext: 'span', fieldDataType: 'bool' },
{
name: 'unmapped.attribute',
fieldContext: 'attribute',
fieldDataType: 'not-a-real-data-type' as FieldDataType,
},
};
];
jest.mock('hooks/queryBuilder/useGetAggregateKeys', () => ({
useGetAggregateKeys: jest.fn(() => ({
data: mockAggregateKeysData,
jest.mock('hooks/querySuggestions/useFieldKeysSuggestion', () => ({
useFieldKeysSuggestion: jest.fn(() => ({
data: mockFieldKeys,
isFetching: false,
})),
}));
const mockAggregateValuesData = {
payload: {
stringAttributeValues: ['200', '404', '500'],
numberAttributeValues: [200, 404, 500],
},
const mockFieldValues: TelemetrytypesTelemetryFieldValuesDTO = {
stringValues: ['200', '404', '500'],
numberValues: [200, 404, 500],
};
jest.mock('hooks/queryBuilder/useGetAggregateValues', () => ({
useGetAggregateValues: jest.fn(() => ({
data: mockAggregateValuesData,
jest.mock('hooks/querySuggestions/useFieldValuesSuggestion', () => ({
useFieldValuesSuggestion: jest.fn(() => ({
data: mockFieldValues,
isFetching: false,
})),
}));
@@ -196,7 +183,11 @@ describe('Suggestion Key -> Operator -> Value Flow', () => {
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({
key: expect.objectContaining({ key: 'http.status' }),
key: expect.objectContaining({
key: 'http.status',
type: 'attribute',
dataType: 'string',
}),
op: '=',
value: '200',
}),
@@ -292,7 +283,7 @@ describe('Filter chips', () => {
key: {
key: 'http.status',
dataType: DataTypes.String,
type: TYPE_TAG,
type: 'tag',
id: 'http.status--string--tag--false',
},
op: '=',
@@ -332,3 +323,87 @@ describe('Filter chips', () => {
expect(getSearchCombobox()).toHaveDisplayValue(CHIP_LABEL);
});
});
describe('Key fetch context', () => {
it('limits keys to the aggregate attribute context, as the resource filter needs', () => {
renderWithContext({
query: {
...defaultProps.query,
aggregateAttribute: {
...defaultProps.query.aggregateAttribute,
type: 'resource',
},
},
});
expect(useFieldKeysSuggestion).toHaveBeenLastCalledWith(
expect.objectContaining({ fieldContext: 'resource' }),
undefined,
expect.anything(),
);
});
it('fetches keys from every context when the aggregate attribute has no type', () => {
renderWithContext();
expect(useFieldKeysSuggestion).toHaveBeenLastCalledWith(
expect.objectContaining({ fieldContext: undefined }),
undefined,
expect.anything(),
);
});
});
describe('Keys the legacy filter builders cannot read', () => {
it('does not suggest body JSON keys or span search scope selectors', async () => {
const user = userEvent.setup({ delay: null });
renderWithContext();
const combobox = getSearchCombobox();
await user.click(combobox);
await user.type(combobox, 'user');
await screen.findByRole('listbox');
await expect(screen.findByText('http.status')).resolves.toBeInTheDocument();
expect(screen.queryByText('user.id')).not.toBeInTheDocument();
expect(screen.queryByText('isRoot')).not.toBeInTheDocument();
});
});
describe('Span field keys', () => {
it('marks span fields as columns and looks up their values in the span context', async () => {
const user = userEvent.setup({ delay: null });
renderWithContext();
const combobox = getSearchCombobox();
await user.click(combobox);
await user.type(combobox, 'nam');
await screen.findByRole('listbox');
await user.click(await screen.findByText('name'));
await user.click(screen.getByText('='));
await waitFor(() =>
expect(jest.mocked(useFieldValuesSuggestion)).toHaveBeenLastCalledWith(
expect.objectContaining({ name: 'name', fieldContext: 'span' }),
undefined,
expect.anything(),
),
);
await user.click(screen.getByText('200'));
expect(mockOnChange).toHaveBeenLastCalledWith(
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({
key: expect.objectContaining({
key: 'name',
type: 'span',
isColumn: true,
}),
}),
]),
}),
);
});
});

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