Compare commits

..

2 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
109 changed files with 2673 additions and 1957 deletions

View File

@@ -11992,9 +11992,8 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
type: object
notificationSettings:
allOf:
@@ -12111,9 +12110,8 @@ components:
additionalProperties:
type: string
description: Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*;
values may use Go templates such as {{$labels.service_name}}. A label
named after one the engine writes, such as severity or threshold.name,
is ignored.
values may use Go templates such as {{$labels.service_name}}. severity
is the conventional routing label.
type: object
notificationSettings:
allOf:
@@ -24952,9 +24950,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- ADMIN
- organization:read
- tokenizer:
- ADMIN
- organization:read
summary: Get my organization
tags:
- orgs
@@ -25003,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

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

View File

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

@@ -64,7 +64,7 @@ const config: Config.InitialOptions = {
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

@@ -85,7 +85,6 @@
"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",
@@ -120,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",
@@ -178,7 +176,6 @@
"@types/d3-hierarchy": "1.1.11",
"@types/event-source-polyfill": "^1.0.0",
"@types/geojson": "7946.0.16",
"@types/history": "4.7.11",
"@types/jest": "30.0.0",
"@types/lodash-es": "^4.17.4",
"@types/node": "^22.20.5",
@@ -189,7 +186,6 @@
"@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",

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,

126
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)
@@ -166,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
@@ -204,7 +200,7 @@ 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
@@ -271,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)
@@ -404,9 +397,6 @@ importers:
'@types/geojson':
specifier: 7946.0.16
version: 7946.0.16
'@types/history':
specifier: 4.7.11
version: 4.7.11
'@types/jest':
specifier: 30.0.0
version: 30.0.0
@@ -437,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
@@ -3353,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}
@@ -4041,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==}
@@ -4128,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==}
@@ -5075,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'}
@@ -6172,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==}
@@ -7572,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':
@@ -7593,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':
@@ -8530,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:
@@ -8548,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==}
@@ -13025,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
@@ -13259,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
@@ -13283,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)
@@ -13739,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
@@ -13839,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
@@ -14905,6 +14861,8 @@ snapshots:
cookie@0.7.2: {}
cookie@1.1.1: {}
copy-anything@3.0.5:
dependencies:
is-what: 4.1.16
@@ -16111,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
@@ -16434,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: {}
@@ -17933,20 +17888,20 @@ snapshots:
dependencies:
fflate: 0.8.3
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):
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: {}
@@ -18331,6 +18286,7 @@ snapshots:
path-to-regexp@1.9.0:
dependencies:
isarray: 0.0.1
optional: true
path-to-regexp@6.3.0: {}
@@ -19110,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
@@ -19129,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
@@ -19142,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:

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

@@ -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,6 +8,9 @@ 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';
@@ -31,7 +33,7 @@ import { UserListPermission } from '@/lib/authz/hooks/useAuthZ/permissions/user.
// eslint-disable-next-line sonarjs/cognitive-complexity
function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
const location = useLocation();
const location = useAppLocation();
const { pathname } = location;
const {
org,
@@ -50,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],

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,6 +1,12 @@
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';
@@ -82,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>
</>
);
}
@@ -246,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>
@@ -514,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;
@@ -638,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)', () => {

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

@@ -13156,7 +13156,7 @@ export interface RuletypesNotificationSettingsDTO {
export type RuletypesPostableRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
@@ -13273,7 +13273,7 @@ export interface RuletypesPostableRuleDTO {
evaluation: RuletypesEvaluationEnvelopeDTO;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
labels?: RuletypesPostableRuleDTOLabels;
/**
@@ -13306,7 +13306,7 @@ export interface RuletypesPostableRuleViewDTO {
export type RuletypesRuleDTOAnnotations = { [key: string]: string };
/**
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
export type RuletypesRuleDTOLabels = { [key: string]: string };
@@ -13365,7 +13365,7 @@ export interface RuletypesRuleDTO {
id: string;
/**
* @type object
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored.
* @description Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label.
*/
labels?: RuletypesRuleDTOLabels;
/**

View File

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

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

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

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

@@ -1,28 +1,46 @@
import { act, renderHook } from '@testing-library/react';
import type { ReactNode } from 'react';
import { act, renderHook, type RenderHookResult } from '@testing-library/react';
import { getCurrentLocation, navigate } from 'lib/router/navigation';
import { TestRouter } from 'tests/router';
import { useNavigationBlocker } from '../useNavigationBlocker';
function settle(): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, 60);
type BlockerHook = RenderHookResult<
ReturnType<typeof useNavigationBlocker>,
{ shouldBlock: boolean }
>;
function wrapper({ children }: { children: ReactNode }): JSX.Element {
return <TestRouter initialRoute="/start">{children}</TestRouter>;
}
/** Lets router updates, and the `popstate` a POP arrives on, reach React. */
async function settle(): Promise<void> {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 60));
});
}
describe('useNavigationBlocker against the real history', () => {
beforeEach(async () => {
navigate('/start');
navigate('/a');
navigate('/b');
navigate('/c');
await settle();
});
/** Mounts the blocker, disarmed, at /c with /start, /a and /b behind it. */
async function renderAtC(): Promise<BlockerHook> {
const hook = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ wrapper, initialProps: { shouldBlock: false } },
);
navigate('/a');
navigate('/b');
navigate('/c');
await settle();
return hook;
}
describe('useNavigationBlocker against the real history', () => {
it('lets a bypassed browser Back through without showing the modal', async () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const { result, rerender } = await renderAtC();
rerender({ shouldBlock: true });
act(() => result.current.allowNextNavigation());
act(() => window.history.back());
window.history.back();
await settle();
expect(getCurrentLocation().pathname).toBe('/b');
@@ -30,23 +48,26 @@ describe('useNavigationBlocker against the real history', () => {
});
it('keeps blocking after a bypassed navigation', async () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const { result, rerender } = await renderAtC();
rerender({ shouldBlock: true });
act(() => result.current.allowNextNavigation());
act(() => window.history.back());
window.history.back();
await settle();
navigate('/elsewhere');
await settle();
act(() => navigate('/elsewhere'));
expect(getCurrentLocation().pathname).toBe('/b');
expect(result.current.isBlocked).toBe(true);
});
it('replays a blocked Forward on confirm', async () => {
act(() => window.history.go(-2));
const { result, rerender } = await renderAtC();
window.history.go(-2);
await settle();
const { result } = renderHook(() => useNavigationBlocker(true));
rerender({ shouldBlock: true });
act(() => window.history.forward());
window.history.forward();
await settle();
expect(result.current.isBlocked).toBe(true);
@@ -59,12 +80,16 @@ describe('useNavigationBlocker against the real history', () => {
});
it('replays a blocked multi-entry jump on confirm', async () => {
act(() => window.history.go(-2));
const { result, rerender } = await renderAtC();
window.history.go(-2);
await settle();
const { result } = renderHook(() => useNavigationBlocker(true));
rerender({ shouldBlock: true });
act(() => window.history.go(2));
window.history.go(2);
await settle();
expect(result.current.isBlocked).toBe(true);
act(() => result.current.confirmNavigation());
await settle();

View File

@@ -1,383 +0,0 @@
import { act, renderHook } from '@testing-library/react';
import { useNavigationBlocker } from '../useNavigationBlocker';
const mockUnblock = jest.fn();
const mockBlock = jest.fn().mockReturnValue(mockUnblock);
const mockRetry = jest.fn();
jest.mock('lib/router/navigation', () => ({
blockNavigation: (blocker: unknown): unknown => mockBlock(blocker),
}));
describe('useNavigationBlocker', () => {
const mockLocation = {
pathname: '/new-route',
search: '',
hash: '',
state: null,
key: 'test-key',
};
/**
* `blockNavigation` hands the blocker one transition object and cancels the
* navigation on its own; `retry()` is the only way through, which is why
* these cases assert on `retry` rather than on a returned `false`.
*/
function transition(action: string): {
location: typeof mockLocation;
action: string;
retry: jest.Mock;
} {
return { location: mockLocation, action, retry: mockRetry };
}
beforeEach(() => {
jest.clearAllMocks();
mockBlock.mockReturnValue(mockUnblock);
});
describe('initial state', () => {
it('returns isBlocked false when shouldBlock is false', () => {
const { result } = renderHook(() => useNavigationBlocker(false));
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
it('returns isBlocked false when shouldBlock is true but no navigation attempted', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
});
describe('blockNavigation behavior', () => {
it('registers a blocker when shouldBlock is true', () => {
renderHook(() => useNavigationBlocker(true));
expect(mockBlock).toHaveBeenCalledTimes(1);
expect(mockBlock).toHaveBeenCalledWith(expect.any(Function));
});
it('does not register a blocker when shouldBlock is false', () => {
renderHook(() => useNavigationBlocker(false));
expect(mockBlock).not.toHaveBeenCalled();
});
it('unblocks when shouldBlock changes from true to false', () => {
const { rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ initialProps: { shouldBlock: true } },
);
expect(mockBlock).toHaveBeenCalledTimes(1);
rerender({ shouldBlock: false });
expect(mockUnblock).toHaveBeenCalledTimes(1);
});
it('unblocks on unmount when blocking', () => {
const { unmount } = renderHook(() => useNavigationBlocker(true));
unmount();
expect(mockUnblock).toHaveBeenCalledTimes(1);
});
it('does not call unblock on unmount when not blocking', () => {
const { unmount } = renderHook(() => useNavigationBlocker(false));
unmount();
expect(mockUnblock).not.toHaveBeenCalled();
});
});
describe('navigation blocking', () => {
it('blocks PUSH navigation and sets blockedNavigationDetails', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('PUSH'));
});
expect(mockRetry).not.toHaveBeenCalled();
expect(result.current.isBlocked).toBe(true);
expect(result.current.blockedNavigationDetails).toStrictEqual({
location: mockLocation,
action: 'PUSH',
});
});
it('blocks REPLACE navigation and sets blockedNavigationDetails', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('REPLACE'));
});
expect(result.current.isBlocked).toBe(true);
expect(result.current.blockedNavigationDetails?.action).toBe('REPLACE');
});
it('blocks POP navigation and sets blockedNavigationDetails', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('POP'));
});
expect(result.current.isBlocked).toBe(true);
expect(result.current.blockedNavigationDetails?.action).toBe('POP');
});
});
describe('confirmNavigation', () => {
it('does nothing when no blockedNavigationDetails', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
act(() => {
result.current.confirmNavigation();
});
expect(mockRetry).not.toHaveBeenCalled();
});
it('unblocks before retrying, or the blocker would catch the retry too', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('PUSH'));
});
act(() => {
result.current.confirmNavigation();
});
expect(mockUnblock).toHaveBeenCalled();
expect(mockUnblock.mock.invocationCallOrder[0]).toBeLessThan(
mockRetry.mock.invocationCallOrder[0],
);
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
it.each(['PUSH', 'REPLACE', 'POP'])(
'retries the blocked %s, which replays it with its own action',
(action) => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition(action));
});
act(() => {
result.current.confirmNavigation();
});
expect(mockRetry).toHaveBeenCalledTimes(1);
},
);
});
describe('cancelNavigation', () => {
it('clears blockedNavigationDetails without performing navigation', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('PUSH'));
});
expect(result.current.isBlocked).toBe(true);
act(() => {
result.current.cancelNavigation();
});
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
expect(mockRetry).not.toHaveBeenCalled();
});
});
describe('allowNextNavigation', () => {
it('bypasses blocking for next navigation only', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
act(() => {
result.current.allowNextNavigation();
});
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
blockCallback(transition('PUSH'));
});
expect(mockRetry).toHaveBeenCalledTimes(1);
expect(result.current.isBlocked).toBe(false);
expect(mockBlock).toHaveBeenCalledTimes(1);
expect(mockUnblock).not.toHaveBeenCalled();
});
it('drops a pending prompt when a bypassed navigation goes through', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
const stale = jest.fn();
act(() => {
blockCallback({ ...transition('PUSH'), retry: stale });
});
expect(result.current.isBlocked).toBe(true);
act(() => {
result.current.allowNextNavigation();
});
act(() => {
blockCallback(transition('PUSH'));
});
act(() => {
result.current.confirmNavigation();
});
expect(result.current.isBlocked).toBe(false);
expect(stale).not.toHaveBeenCalled();
});
it('resumes blocking after bypassed navigation', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
result.current.allowNextNavigation();
});
act(() => {
blockCallback(transition('PUSH'));
});
mockRetry.mockClear();
act(() => {
blockCallback(transition('PUSH'));
});
expect(mockRetry).not.toHaveBeenCalled();
expect(result.current.isBlocked).toBe(true);
});
it('resets bypass flag when shouldBlock changes to false before navigation', () => {
const { result, rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ initialProps: { shouldBlock: true } },
);
act(() => {
result.current.allowNextNavigation();
});
rerender({ shouldBlock: false });
rerender({ shouldBlock: true });
const blockCallback = mockBlock.mock.calls[1][0];
act(() => {
blockCallback(transition('PUSH'));
});
expect(mockRetry).not.toHaveBeenCalled();
expect(result.current.isBlocked).toBe(true);
});
});
describe('beforeunload event', () => {
let addEventListenerSpy: jest.SpyInstance;
let removeEventListenerSpy: jest.SpyInstance;
beforeEach(() => {
addEventListenerSpy = jest.spyOn(window, 'addEventListener');
removeEventListenerSpy = jest.spyOn(window, 'removeEventListener');
});
afterEach(() => {
addEventListenerSpy.mockRestore();
removeEventListenerSpy.mockRestore();
});
it('adds beforeunload listener when shouldBlock is true', () => {
renderHook(() => useNavigationBlocker(true));
expect(addEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('does not add beforeunload listener when shouldBlock is false', () => {
renderHook(() => useNavigationBlocker(false));
expect(addEventListenerSpy).not.toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('removes beforeunload listener on unmount', () => {
const { unmount } = renderHook(() => useNavigationBlocker(true));
unmount();
expect(removeEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('removes beforeunload listener when shouldBlock changes to false', () => {
const { rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ initialProps: { shouldBlock: true } },
);
rerender({ shouldBlock: false });
expect(removeEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('beforeunload handler calls preventDefault', () => {
renderHook(() => useNavigationBlocker(true));
const beforeUnloadHandler = addEventListenerSpy.mock.calls.find(
(call) => call[0] === 'beforeunload',
)?.[1];
const mockEvent = {
preventDefault: jest.fn(),
};
const result = beforeUnloadHandler(mockEvent);
expect(mockEvent.preventDefault).toHaveBeenCalled();
expect(result).toBeUndefined();
});
});
});

View File

@@ -0,0 +1,317 @@
import type { ReactNode } from 'react';
import { act, renderHook, waitFor } from '@testing-library/react';
import { back, getCurrentLocation, navigate } from 'lib/router/navigation';
import { TestRouter } from 'tests/router';
import { useNavigationBlocker } from '../useNavigationBlocker';
function wrapper({ children }: { children: ReactNode }): JSX.Element {
return <TestRouter initialRoute="/start">{children}</TestRouter>;
}
/** Lets router updates, and the `popstate` a POP arrives on, reach React. */
async function settle(): Promise<void> {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
}
describe('useNavigationBlocker', () => {
describe('initial state', () => {
it('returns isBlocked false when shouldBlock is false', () => {
const { result } = renderHook(() => useNavigationBlocker(false), {
wrapper,
});
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
it('returns isBlocked false when shouldBlock is true but no navigation attempted', () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
});
describe('navigation blocking', () => {
it('lets navigation through when shouldBlock is false', async () => {
renderHook(() => useNavigationBlocker(false), { wrapper });
navigate('/next');
await settle();
expect(getCurrentLocation().pathname).toBe('/next');
});
it('blocks PUSH navigation and sets blockedNavigationDetails', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next');
await settle();
expect(result.current.isBlocked).toBe(true);
expect(result.current.blockedNavigationDetails).toMatchObject({
location: { pathname: '/next' },
action: 'PUSH',
});
expect(getCurrentLocation().pathname).toBe('/start');
});
it('blocks REPLACE navigation and sets blockedNavigationDetails', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next', { replace: true });
await settle();
expect(result.current.blockedNavigationDetails?.action).toBe('REPLACE');
});
it('blocks POP navigation and sets blockedNavigationDetails', async () => {
const { result, rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ wrapper, initialProps: { shouldBlock: false } },
);
navigate('/next');
await settle();
rerender({ shouldBlock: true });
await settle();
back();
await waitFor(() => expect(result.current.isBlocked).toBe(true));
expect(result.current.blockedNavigationDetails).toMatchObject({
location: { pathname: '/start' },
action: 'POP',
});
await waitFor(() => expect(getCurrentLocation().pathname).toBe('/next'));
});
it('stops blocking when shouldBlock changes from true to false', async () => {
const { rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ wrapper, initialProps: { shouldBlock: true } },
);
rerender({ shouldBlock: false });
navigate('/next');
await settle();
expect(getCurrentLocation().pathname).toBe('/next');
});
});
describe('confirmNavigation', () => {
it('does nothing when nothing is blocked', () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
act(() => result.current.confirmNavigation());
expect(getCurrentLocation().pathname).toBe('/start');
});
it('completes the blocked navigation', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next', { state: { from: 'test' } });
await settle();
act(() => result.current.confirmNavigation());
await settle();
expect(getCurrentLocation()).toMatchObject({
pathname: '/next',
state: { from: 'test' },
});
expect(result.current.isBlocked).toBe(false);
});
it('keeps a blocked REPLACE a replace', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
const before = window.history.length;
navigate('/next', { replace: true });
await settle();
act(() => result.current.confirmNavigation());
await settle();
expect(getCurrentLocation().pathname).toBe('/next');
expect(window.history).toHaveLength(before);
});
});
describe('cancelNavigation', () => {
it('clears blockedNavigationDetails without performing navigation', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next');
await settle();
act(() => result.current.cancelNavigation());
await settle();
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
expect(getCurrentLocation().pathname).toBe('/start');
});
it('keeps blocking after a cancel', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next');
await settle();
act(() => result.current.cancelNavigation());
await settle();
navigate('/next');
await settle();
expect(result.current.isBlocked).toBe(true);
});
});
describe('allowNextNavigation', () => {
it('bypasses blocking for next navigation only', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
act(() => result.current.allowNextNavigation());
navigate('/next');
await settle();
expect(getCurrentLocation().pathname).toBe('/next');
expect(result.current.isBlocked).toBe(false);
navigate('/after');
await settle();
expect(result.current.isBlocked).toBe(true);
expect(getCurrentLocation().pathname).toBe('/next');
});
it('drops a pending prompt when a bypassed navigation goes through', async () => {
const { result } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
navigate('/next');
await settle();
expect(result.current.isBlocked).toBe(true);
act(() => result.current.allowNextNavigation());
navigate('/other');
await settle();
expect(getCurrentLocation().pathname).toBe('/other');
expect(result.current.isBlocked).toBe(false);
});
it('resets bypass flag when shouldBlock changes to false before navigation', async () => {
const { result, rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ wrapper, initialProps: { shouldBlock: true } },
);
act(() => result.current.allowNextNavigation());
rerender({ shouldBlock: false });
rerender({ shouldBlock: true });
navigate('/next');
await settle();
expect(result.current.isBlocked).toBe(true);
});
});
describe('beforeunload event', () => {
let addEventListenerSpy: jest.SpyInstance;
let removeEventListenerSpy: jest.SpyInstance;
beforeEach(() => {
addEventListenerSpy = jest.spyOn(window, 'addEventListener');
removeEventListenerSpy = jest.spyOn(window, 'removeEventListener');
});
afterEach(() => {
addEventListenerSpy.mockRestore();
removeEventListenerSpy.mockRestore();
});
it('adds beforeunload listener when shouldBlock is true', () => {
renderHook(() => useNavigationBlocker(true), { wrapper });
expect(addEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('does not add beforeunload listener when shouldBlock is false', () => {
renderHook(() => useNavigationBlocker(false), { wrapper });
expect(addEventListenerSpy).not.toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('removes beforeunload listener on unmount', () => {
const { unmount } = renderHook(() => useNavigationBlocker(true), {
wrapper,
});
unmount();
expect(removeEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('removes beforeunload listener when shouldBlock changes to false', () => {
const { rerender } = renderHook(
({ shouldBlock }) => useNavigationBlocker(shouldBlock),
{ wrapper, initialProps: { shouldBlock: true } },
);
rerender({ shouldBlock: false });
expect(removeEventListenerSpy).toHaveBeenCalledWith(
'beforeunload',
expect.any(Function),
);
});
it('beforeunload handler calls preventDefault', () => {
renderHook(() => useNavigationBlocker(true), { wrapper });
const beforeUnloadHandler = addEventListenerSpy.mock.calls.find(
(call) => call[0] === 'beforeunload',
)?.[1];
const mockEvent = {
preventDefault: jest.fn(),
};
const result = beforeUnloadHandler(mockEvent);
expect(mockEvent.preventDefault).toHaveBeenCalled();
expect(result).toBeUndefined();
});
});
});

View File

@@ -0,0 +1,64 @@
import { ReactNode } from 'react';
import { renderHook } from 'tests/test-utils';
import { TestRouter } from 'tests/router';
// jest.config.ts maps every `useSafeNavigate` import to a mock; the extension
// slips past that mapping.
const { useSafeNavigate } = jest.requireActual<
typeof import('hooks/useSafeNavigate')
>('../useSafeNavigate.ts');
function wrapper({ children }: { children: ReactNode }): JSX.Element {
return <TestRouter initialRoute="/page?a=1">{children}</TestRouter>;
}
describe('useSafeNavigate same-URL check', () => {
let pushState: jest.SpyInstance;
let replaceState: jest.SpyInstance;
beforeEach(() => {
pushState = jest.spyOn(window.history, 'pushState');
replaceState = jest.spyOn(window.history, 'replaceState');
});
afterEach(() => {
jest.restoreAllMocks();
});
function render(): ReturnType<typeof useSafeNavigate>['safeNavigate'] {
const { result } = renderHook(() => useSafeNavigate(), { wrapper });
pushState.mockClear();
replaceState.mockClear();
return result.current.safeNavigate;
}
it('navigates to a different URL', () => {
const safeNavigate = render();
safeNavigate('/page?a=2');
expect(pushState).toHaveBeenCalledTimes(1);
expect(window.location.search).toBe('?a=2');
});
it('skips the URL the router is on', () => {
const safeNavigate = render();
safeNavigate('/page?a=1');
expect(pushState).not.toHaveBeenCalled();
expect(replaceState).not.toHaveBeenCalled();
});
it('skips the URL a shallow write published ahead of the router', () => {
const safeNavigate = render();
// A nuqs write: it reaches the address bar but not the router.
window.history.replaceState(window.history.state, '', '/page?a=1&b=1');
replaceState.mockClear();
safeNavigate('/page?a=1&b=1');
expect(pushState).not.toHaveBeenCalled();
expect(replaceState).not.toHaveBeenCalled();
});
});

View File

@@ -1,5 +1,6 @@
import { useEffect } from 'react';
import { useEffect, useRef } from 'react';
import useUrlQuery from 'hooks/useUrlQuery';
import { useAppLocation } from 'lib/router/useAppLocation';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { useGetCompositeQueryParam } from './useGetCompositeQueryParam';
@@ -17,10 +18,19 @@ export const useShareBuilderUrl = ({
}: UseShareBuilderUrlParams): void => {
const { resetQuery, redirectWithQueryBuilderData } = useQueryBuilder();
const urlQuery = useUrlQuery();
const { pathname } = useAppLocation();
// The page that owns this query. A caller can keep rendering for a beat after
// a sibling pushes the next route (tab switches do this), and publishing then
// writes this page's query onto the URL of the page being entered.
const ownerPathname = useRef(pathname);
const compositeQuery = useGetCompositeQueryParam();
useEffect(() => {
if (pathname !== ownerPathname.current) {
return;
}
if (!compositeQuery || forceReset) {
resetQuery(defaultValue);
redirectWithQueryBuilderData(defaultValue);
@@ -32,5 +42,6 @@ export const useShareBuilderUrl = ({
compositeQuery,
resetQuery,
forceReset,
pathname,
]);
};

View File

@@ -1,10 +1,10 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { blockNavigation } from 'lib/router/navigation';
import { useCallback, useEffect, useRef } from 'react';
import type {
AppLocation,
BlockedTransition,
BlockerFunction,
NavigationAction,
} from 'lib/router/types';
import { useAppBlocker } from 'lib/router/useAppBlocker';
interface BlockedNavigationDetails {
location: AppLocation;
@@ -48,45 +48,31 @@ interface UseNavigationBlockerResult {
export function useNavigationBlocker(
shouldBlock: boolean,
): UseNavigationBlockerResult {
const [blockedNavigation, setBlockedNavigation] =
useState<BlockedNavigationDetails | null>(null);
const unblockRef = useRef<(() => void) | null>(null);
const retryRef = useRef<(() => void) | null>(null);
const bypassNextRef = useRef(false);
const blockedActionRef = useRef<NavigationAction>('PUSH');
useEffect(() => {
if (!shouldBlock) {
if (unblockRef.current) {
unblockRef.current();
unblockRef.current = null;
}
bypassNextRef.current = false;
return;
}
}, [shouldBlock]);
unblockRef.current = blockNavigation((transition: BlockedTransition) => {
const blockerFunction = useCallback<BlockerFunction>(
({ action }) => {
if (!shouldBlock) {
return false;
}
if (bypassNextRef.current) {
bypassNextRef.current = false;
retryRef.current = null;
setBlockedNavigation(null);
transition.retry();
return;
return false;
}
retryRef.current = transition.retry;
setBlockedNavigation({
location: transition.location,
action: transition.action,
});
});
blockedActionRef.current = action;
return true;
},
[shouldBlock],
);
return (): void => {
if (unblockRef.current) {
unblockRef.current();
unblockRef.current = null;
}
bypassNextRef.current = false;
};
}, [shouldBlock]);
const blocker = useAppBlocker(blockerFunction);
useEffect(() => {
if (!shouldBlock) {
@@ -104,37 +90,30 @@ export function useNavigationBlocker(
};
}, [shouldBlock]);
// The router replays a proceeded navigation itself, so a blocked REPLACE
// stays a REPLACE and a blocked POP still walks the history stack.
const confirmNavigation = useCallback((): void => {
if (!blockedNavigation) {
return;
if (blocker.state === 'blocked') {
blocker.proceed();
}
if (unblockRef.current) {
unblockRef.current();
unblockRef.current = null;
}
setBlockedNavigation(null);
// The transition replays itself, so a blocked REPLACE stays a REPLACE and
// a blocked POP still walks the history stack.
const retry = retryRef.current;
retryRef.current = null;
retry?.();
}, [blockedNavigation]);
}, [blocker]);
const cancelNavigation = useCallback((): void => {
retryRef.current = null;
setBlockedNavigation(null);
}, []);
if (blocker.state === 'blocked') {
blocker.reset();
}
}, [blocker]);
const allowNextNavigation = useCallback((): void => {
bypassNextRef.current = true;
}, []);
return {
isBlocked: blockedNavigation !== null,
blockedNavigationDetails: blockedNavigation,
isBlocked: blocker.state === 'blocked',
blockedNavigationDetails:
blocker.state === 'blocked'
? { location: blocker.location, action: blockedActionRef.current }
: null,
confirmNavigation,
cancelNavigation,
allowNextNavigation,

View File

@@ -553,8 +553,9 @@ describe('ResourceProvider', () => {
];
const encoded = encode(JSON.stringify(seeded));
// The effect that re-hydrates reads the URL through lib/history, the same
// history the router runs on, so one navigation drives both.
// The effect that re-hydrates reads the URL through lib/router/navigation,
// which drives the same router the tree renders in, so one navigation
// drives both.
act(() => {
navigate(`/?resourceAttribute=${encoded}`);
});

View File

@@ -1,11 +1,12 @@
import { useCallback } from 'react';
import { useLocation, useNavigate } from 'react-router-dom-v5-compat';
import { useLocation, useNavigate } from 'react-router';
import { cloneDeep, isEqual } from 'lodash-es';
import { withBasePath } from 'utils/basePath';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
interface NavigateOptions {
replace?: boolean;
state?: any;
state?: unknown;
newTab?: boolean;
}
@@ -108,6 +109,12 @@ export const useSafeNavigate = (
// oxlint-disable-next-line signoz/no-raw-absolute-path
const base = window.location.origin;
const currentUrl = new URL(`${location.pathname}${location.search}`, base);
// nuqs writes shallowly, so the address bar can be ahead of the router.
// Navigating to it anyway makes nuqs drop its queued writes.
const publishedUrl = new URL(
`${location.pathname}?${getUnstableCurrentSearchParams().toString()}`,
base,
);
let targetUrl: URL;
@@ -131,7 +138,9 @@ export const useSafeNavigate = (
return;
}
const urlsAreSame = areUrlsEffectivelySame(currentUrl, targetUrl);
const urlsAreSame =
areUrlsEffectivelySame(currentUrl, targetUrl) ||
areUrlsEffectivelySame(publishedUrl, targetUrl);
const isDefaultParamsNavigation = isDefaultNavigation(currentUrl, targetUrl);
if (preventSameUrlNavigation && urlsAreSame) {
@@ -144,9 +153,9 @@ export const useSafeNavigate = (
};
if (typeof to === 'string') {
navigate(to, navigationOptions);
void navigate(to, navigationOptions);
} else {
navigate(
void navigate(
{
pathname: to.pathname || location.pathname,
search: to.search,

View File

@@ -2,10 +2,12 @@ import { ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient } from 'react-query';
import AppProviders from 'app/AppProviders';
import { AppRouterProvider } from 'app/AppRouterProvider';
import { createAppRouter } from 'app/createAppRouter';
import AppRoutes from 'AppRoutes';
import { AxiosError } from 'axios';
import { configureOverlayScrollbars } from 'lib/configureOverlayScrollbars';
import { NuqsAdapter } from 'nuqs/adapters/react';
import { NuqsAdapter } from 'nuqs/adapters/react-router/v7';
import { AppProvider } from 'providers/App/App';
import store from 'store';
import APIError from 'types/api/error';
@@ -55,8 +57,7 @@ const container = document.getElementById('root');
if (container) {
const root = createRoot(container);
root.render(
const router = createAppRouter(
<AppProviders
store={store}
queryClient={queryClient}
@@ -66,4 +67,6 @@ if (container) {
<AppRoutes />
</AppProviders>,
);
root.render(<AppRouterProvider router={router} />);
}

View File

@@ -1,15 +0,0 @@
import { createBrowserHistory } from 'history';
import { getBasePath } from 'utils/basePath';
const history = createBrowserHistory({ basename: getBasePath() });
let inAppPushCount = 0;
history.listen((_, action) => {
if (action === 'PUSH') {
inAppPushCount += 1;
}
});
export const hasInAppHistory = (): boolean => inAppPushCount > 0;
export default history;

View File

@@ -1,10 +1,8 @@
import { forwardRef } from 'react';
import type { AnchorHTMLAttributes, ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { Link } from 'react-router';
import type { To } from './types';
import { useAppLocation } from './useAppLocation';
import { withState } from './utils';
export interface AppLinkProps extends Omit<
AnchorHTMLAttributes<HTMLAnchorElement>,
@@ -18,15 +16,8 @@ export interface AppLinkProps extends Omit<
export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
function AppLink({ to, replace, state, children, ...rest }, ref) {
const location = useAppLocation();
return (
<Link
ref={ref}
to={withState(to, state, location)}
replace={replace}
{...rest}
>
<Link ref={ref} to={to} replace={replace} state={state} {...rest}>
{children}
</Link>
);

View File

@@ -0,0 +1,22 @@
import type { ReactNode } from 'react';
import { type DataRouter, RouterProvider } from 'react-router';
import { HostedTreeContext } from './HostedTreeContext';
interface HostRouterProps {
router: DataRouter;
children: ReactNode;
}
/**
* A data router's routes are fixed when it is created, so the tree reaches the
* route element through context instead, and a re-render with new children
* shows them.
*/
export function HostRouter({ router, children }: HostRouterProps): JSX.Element {
return (
<HostedTreeContext.Provider value={children}>
<RouterProvider router={router} useTransitions={false} />
</HostedTreeContext.Provider>
);
}

View File

@@ -0,0 +1,5 @@
// eslint-disable-next-line no-restricted-imports
import { createContext, type ReactNode } from 'react';
/** The tree `HostRouter` was last rendered with. */
export const HostedTreeContext = createContext<ReactNode>(null);

View File

@@ -0,0 +1,8 @@
// eslint-disable-next-line no-restricted-imports
import { useContext } from 'react';
import { HostedTreeContext } from './HostedTreeContext';
export function HostedTreeOutlet(): JSX.Element {
return <>{useContext(HostedTreeContext)}</>;
}

View File

@@ -1,12 +1,11 @@
import { Redirect as RouterRedirect } from 'react-router-dom';
import { Navigate } from 'react-router';
import type { To } from './types';
import { withState } from './utils';
export interface RedirectProps {
to: To;
/**
* Defaults to `true`, matching v5's `<Redirect>`. v6's `<Navigate>` pushes
* Defaults to `true`, matching v5's `<Redirect>`. v7's `<Navigate>` pushes
* unless told otherwise, which is invisible until someone presses Back.
*/
replace?: boolean;
@@ -18,7 +17,7 @@ export function Redirect({
replace = true,
state,
}: RedirectProps): JSX.Element {
return <RouterRedirect to={withState(to, state)} push={!replace} />;
return <Navigate to={to} replace={replace} state={state} />;
}
Redirect.defaultProps = {

View File

@@ -0,0 +1,10 @@
import { useRouteError } from 'react-router';
/**
* Rethrows past the router, so a render error reaches the next error boundary
* outside it (or fails a test) instead of rendering the router's default error
* page.
*/
export function RethrowRouteError(): never {
throw useRouteError();
}

View File

@@ -1,14 +1,14 @@
import { createRef } from 'react';
import type { ReactNode } from 'react';
import { useHistory } from 'react-router-dom';
import { cleanup, fireEvent, render, screen } from 'tests/test-utils';
import { AppLink, type AppLinkProps } from '../AppLink';
import { useAppLocation } from '../useAppLocation';
import { useAppNavigationType } from '../useAppNavigationType';
function LocationProbe(): JSX.Element {
const location = useAppLocation();
const history = useHistory();
const navigationType = useAppNavigationType();
return (
<div>
@@ -16,7 +16,7 @@ function LocationProbe(): JSX.Element {
<span data-testid="search">{location.search}</span>
<span data-testid="hash">{location.hash}</span>
<span data-testid="state">{JSON.stringify(location.state ?? null)}</span>
<span data-testid="length">{history.length}</span>
<span data-testid="action">{navigationType}</span>
</div>
);
}
@@ -146,17 +146,23 @@ describe('AppLink', () => {
expect(screen.getByTestId('state')).toHaveTextContent('{"from":"test"}');
});
it('pushes by default', () => {
renderLink({ to: '/logs', 'data-testid': 'link' } as AppLinkProps);
fireEvent.click(screen.getByTestId('link'));
expect(screen.getByTestId('action')).toHaveTextContent('PUSH');
});
it('replaces the entry when replace is set', () => {
renderLink({
to: '/logs',
replace: true,
'data-testid': 'link',
} as AppLinkProps);
const before = screen.getByTestId('length').textContent;
fireEvent.click(screen.getByTestId('link'));
expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
expect(screen.getByTestId('length').textContent).toBe(before);
expect(screen.getByTestId('action')).toHaveTextContent('REPLACE');
});
it('forwards a ref to the anchor', () => {

View File

@@ -1,19 +1,19 @@
import { useHistory } from 'react-router-dom';
import { render, screen } from 'tests/test-utils';
import { Redirect, type RedirectProps } from '../Redirect';
import { useAppLocation } from '../useAppLocation';
import { useAppNavigationType } from '../useAppNavigationType';
function LocationProbe(): JSX.Element {
const location = useAppLocation();
const history = useHistory();
const navigationType = useAppNavigationType();
return (
<div>
<span data-testid="pathname">{location.pathname}</span>
<span data-testid="search">{location.search}</span>
<span data-testid="state">{JSON.stringify(location.state ?? null)}</span>
<span data-testid="action">{history.action}</span>
<span data-testid="action">{navigationType}</span>
</div>
);
}

View File

@@ -3,8 +3,9 @@ import ROUTES from 'constants/routes';
import { buildRoutePath } from '../buildRoutePath';
/**
* These assertions pin every URL `buildRoutePath` produces, so a router
* upgrade cannot change one unnoticed.
* The encoding contract. v7's `generatePath` percent-encodes every param with
* `encodeURIComponent`, so `buildRoutePath` no longer encodes anything itself
* and these assertions are what pins the library's behaviour.
*/
describe('buildRoutePath', () => {
it('fills a single param', () => {
@@ -45,9 +46,15 @@ describe('buildRoutePath', () => {
expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: value })).toBe(expected);
});
it('leaves a colon alone', () => {
it('percent-encodes a colon', () => {
expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: 'a:b' })).toBe(
'/trace/a:b',
'/trace/a%3Ab',
);
});
it('encodes a raw value rather than passing an encoded one through', () => {
expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: 'a%2Fb' })).toBe(
'/trace/a%252Fb',
);
});
});

View File

@@ -1,10 +1,11 @@
import type { BlockedTransition } from '../types';
/**
* `lib/history` is a module-level singleton that reads the base path at import
* time, so every case loads it in isolation with a fresh DOM.
* `utils/basePath` reads the base path at import time, so every case loads the
* module, and the test router it drives, in isolation with a fresh DOM.
*/
type NavigationModule = typeof import('../navigation');
type TestRouterModule = typeof import('tests/router-utils');
let release: (() => void) | undefined;
function loadNavigation(baseHref?: string): NavigationModule {
if (baseHref !== undefined) {
@@ -14,16 +15,25 @@ function loadNavigation(baseHref?: string): NavigationModule {
}
let mod!: NavigationModule;
let testRouter!: TestRouterModule;
jest.isolateModules(() => {
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
mod = require('../navigation');
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
testRouter = require('tests/router-utils');
});
({ release } = testRouter.attachTestRouter());
return mod;
}
function settle(): Promise<void> {
function nextUpdate(
nav: NavigationModule,
): Promise<{ location: { pathname: string }; action: string }> {
return new Promise((resolve) => {
setTimeout(resolve, 60);
const unsubscribe = nav.subscribe((update) => {
unsubscribe();
resolve(update);
});
});
}
@@ -32,6 +42,8 @@ beforeEach(() => {
});
afterEach(() => {
release?.();
release = undefined;
for (const element of document.head.querySelectorAll('base')) {
element.remove();
}
@@ -44,6 +56,13 @@ describe('navigate', () => {
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
it('throws when no router is attached', () => {
const nav = loadNavigation();
release?.();
release = undefined;
expect(() => nav.navigate('/logs')).toThrow('no router is attached');
});
it('carries search and hash from a string target', () => {
const nav = loadNavigation();
nav.navigate('/logs?a=1#top');
@@ -112,23 +131,79 @@ describe('basename ownership', () => {
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
it('does not double-prefix a path that already carries the base path', () => {
it('round-trips getCurrentLocation through navigate', () => {
const nav = loadNavigation('/signoz/');
nav.navigate('/logs');
nav.navigate(nav.getCurrentLocation().pathname);
expect(window.location.pathname).toBe('/signoz/logs');
});
it('prefixes a path whose first segment equals the base path', () => {
const nav = loadNavigation('/logs/');
nav.navigate('/logs/logs-explorer');
expect(window.location.pathname).toBe('/logs/logs/logs-explorer');
expect(nav.getCurrentLocation().pathname).toBe('/logs/logs-explorer');
});
it('prefixes the pathname of an object target', () => {
const nav = loadNavigation('/signoz/');
nav.navigate({ pathname: '/logs', search: '?a=1' });
expect(window.location.pathname).toBe('/signoz/logs');
expect(window.location.search).toBe('?a=1');
});
});
describe('subscribe', () => {
it('reports a single update object, not two arguments', async () => {
const nav = loadNavigation();
const listener = jest.fn();
const unsubscribe = nav.subscribe(listener);
nav.navigate('/logs');
expect(listener).toHaveBeenCalledTimes(1);
expect(listener.mock.calls[0]).toHaveLength(1);
expect(listener.mock.calls[0][0]).toMatchObject({
location: { pathname: '/logs' },
action: 'PUSH',
});
unsubscribe();
});
it('reports REPLACE', () => {
const nav = loadNavigation();
const listener = jest.fn();
const unsubscribe = nav.subscribe(listener);
nav.navigate('/logs', { replace: true });
expect(listener.mock.calls[0][0].action).toBe('REPLACE');
unsubscribe();
});
it('stops reporting after unsubscribe', () => {
const nav = loadNavigation();
const listener = jest.fn();
nav.subscribe(listener)();
nav.navigate('/logs');
expect(listener).not.toHaveBeenCalled();
});
});
describe('back', () => {
it('restores the previous location', async () => {
it('reports POP and restores the previous location', async () => {
const nav = loadNavigation();
nav.navigate('/logs');
nav.navigate('/traces');
const popped = nextUpdate(nav);
nav.back();
await settle();
const update = await popped;
expect(update.action).toBe('POP');
expect(update.location.pathname).toBe('/logs');
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
});
@@ -151,261 +226,3 @@ describe('hasInAppHistory', () => {
expect(nav.hasInAppHistory()).toBe(true);
});
});
describe('blockNavigation', () => {
it('hands the blocker a transition and cancels the navigation', () => {
const nav = loadNavigation();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
nav.navigate('/logs');
expect(seen).toHaveLength(1);
expect(seen[0].action).toBe('PUSH');
expect(seen[0].location.pathname).toBe('/logs');
expect(typeof seen[0].retry).toBe('function');
expect(nav.getCurrentLocation().pathname).toBe('/');
unblock();
});
it('completes the navigation when retry runs after unblocking', () => {
const nav = loadNavigation();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
nav.navigate('/logs');
unblock();
seen[0].retry();
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
it('blocks again when retry runs while still blocked, as history@5 does', () => {
const nav = loadNavigation();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
nav.navigate('/logs');
seen[0].retry();
expect(seen).toHaveLength(2);
expect(nav.getCurrentLocation().pathname).toBe('/');
unblock();
});
it('lets a POP through when retry runs inside the blocker', async () => {
const nav = loadNavigation();
nav.navigate('/logs');
nav.navigate('/traces');
const seen: BlockedTransition[] = [];
let unblock = (): void => {};
unblock = nav.blockNavigation((tx) => {
seen.push(tx);
unblock();
tx.retry();
});
nav.back();
await settle();
expect(seen).toHaveLength(1);
expect(seen[0].action).toBe('POP');
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
it('replays a blocked Forward by one entry', async () => {
const nav = loadNavigation();
nav.navigate('/logs');
nav.navigate('/traces');
nav.back();
await settle();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.forward();
await settle();
unblock();
seen[0].retry();
await settle();
expect(seen[0].action).toBe('POP');
expect(nav.getCurrentLocation().pathname).toBe('/traces');
});
it('replays a blocked multi-entry jump by its full distance', async () => {
const nav = loadNavigation();
nav.navigate('/a');
nav.navigate('/b');
nav.navigate('/c');
window.history.go(-2);
await settle();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.go(2);
await settle();
unblock();
seen[0].retry();
await settle();
expect(nav.getCurrentLocation().pathname).toBe('/c');
});
it('replays a blocked Back to an entry from before a reload', async () => {
const earlier = loadNavigation();
earlier.navigate('/a');
earlier.navigate('/b');
earlier.navigate('/c');
const nav = loadNavigation();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.back();
await settle();
unblock();
seen[0].retry();
await settle();
expect(seen[0].action).toBe('POP');
expect(nav.getCurrentLocation().pathname).toBe('/b');
expect(window.location.pathname).toBe('/b');
});
it('replays a blocked Forward after leaving through an entry from before a reload', async () => {
const earlier = loadNavigation();
earlier.navigate('/a');
earlier.navigate('/b');
const nav = loadNavigation();
nav.navigate('/c');
window.history.go(-2);
await settle();
expect(nav.getCurrentLocation().pathname).toBe('/a');
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.forward();
await settle();
unblock();
seen[0].retry();
await settle();
expect(seen[0].action).toBe('POP');
expect(nav.getCurrentLocation().pathname).toBe('/b');
expect(window.location.pathname).toBe('/b');
});
it('replays a blocked Forward that skips from an entry from before a reload past the first known one', async () => {
const earlier = loadNavigation();
earlier.navigate('/a');
earlier.navigate('/b');
const nav = loadNavigation();
nav.navigate('/c');
window.history.go(-2);
await settle();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.go(2);
await settle();
unblock();
seen[0].retry();
await settle();
expect(nav.getCurrentLocation().pathname).toBe('/c');
expect(window.location.pathname).toBe('/c');
window.history.back();
await settle();
expect(window.location.pathname).toBe('/b');
});
it('replays a blocked Back that skips from a known entry to one from before a reload', async () => {
const earlier = loadNavigation();
earlier.navigate('/a');
earlier.navigate('/b');
const nav = loadNavigation();
nav.navigate('/c');
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.go(-2);
await settle();
unblock();
seen[0].retry();
await settle();
expect(nav.getCurrentLocation().pathname).toBe('/a');
expect(window.location.pathname).toBe('/a');
window.history.forward();
await settle();
expect(window.location.pathname).toBe('/b');
});
it('catches the router up when history@4 does not revert a blocked POP', async () => {
const nav = loadNavigation();
nav.navigate('/p');
// nuqs pushes like this, so both entries carry the same history@4 key.
window.history.pushState(window.history.state, '', '/p?x=1');
window.history.back();
await settle();
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
window.history.forward();
await settle();
unblock();
seen[0].retry();
expect(nav.getCurrentLocation().search).toBe('?x=1');
expect(window.location.search).toBe('?x=1');
});
it('keeps the blocker armed when retry runs inside it', () => {
const nav = loadNavigation();
let allowNext = true;
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => {
seen.push(tx);
if (allowNext) {
allowNext = false;
tx.retry();
}
});
nav.navigate('/logs');
nav.navigate('/traces');
expect(nav.getCurrentLocation().pathname).toBe('/logs');
expect(seen).toHaveLength(2);
unblock();
});
it('preserves the replace action through retry', () => {
const nav = loadNavigation();
nav.navigate('/logs');
const before = window.history.length;
const seen: BlockedTransition[] = [];
const unblock = nav.blockNavigation((tx) => seen.push(tx));
nav.navigate('/traces', { replace: true });
unblock();
seen[0].retry();
expect(seen[0].action).toBe('REPLACE');
expect(nav.getCurrentLocation().pathname).toBe('/traces');
expect(window.history).toHaveLength(before);
});
it('stops blocking after unblock', () => {
const nav = loadNavigation();
const listener = jest.fn();
nav.blockNavigation(listener)();
nav.navigate('/logs');
expect(listener).not.toHaveBeenCalled();
expect(nav.getCurrentLocation().pathname).toBe('/logs');
});
});

View File

@@ -1,6 +1,6 @@
import type { ReactNode } from 'react';
import { TestRouter } from 'tests/router';
import { renderHook } from 'tests/test-utils';
import { act, renderHook } from 'tests/test-utils';
import { navigate } from '../navigation';
import { useAppLocation } from '../useAppLocation';
@@ -25,10 +25,10 @@ describe('useAppLocation', () => {
});
it('returns the entry state', () => {
navigate('/logs', { replace: true, state: { from: 'test' } });
const { result } = renderHook(() => useAppLocation<{ from: string }>(), {
wrapper: TestRouter,
});
act(() => navigate('/logs', { replace: true, state: { from: 'test' } }));
expect(result.current.state.from).toBe('test');
});

View File

@@ -1,9 +1,9 @@
import { useHistory } from 'react-router-dom';
import { fireEvent, render, screen } from 'tests/test-utils';
import type { NavigateOptions, To } from '../types';
import { useAppLocation } from '../useAppLocation';
import { useAppNavigate } from '../useAppNavigate';
import { useAppNavigationType } from '../useAppNavigationType';
function Probe({
to,
@@ -14,7 +14,7 @@ function Probe({
}): JSX.Element {
const navigate = useAppNavigate();
const location = useAppLocation();
const history = useHistory();
const navigationType = useAppNavigationType();
return (
<div>
@@ -27,7 +27,7 @@ function Probe({
<span data-testid="pathname">{location.pathname}</span>
<span data-testid="search">{location.search}</span>
<span data-testid="state">{JSON.stringify(location.state ?? null)}</span>
<span data-testid="length">{history.length}</span>
<span data-testid="action">{navigationType}</span>
</div>
);
}
@@ -62,20 +62,16 @@ describe('useAppNavigate', () => {
it('adds a history entry by default', () => {
renderProbe('/logs');
const before = screen.getByTestId('length').textContent;
fireEvent.click(screen.getByTestId('navigate'));
expect(Number(screen.getByTestId('length').textContent)).toBe(
Number(before) + 1,
);
expect(screen.getByTestId('action')).toHaveTextContent('PUSH');
});
it('does not add a history entry when replacing', () => {
renderProbe('/logs', { replace: true });
const before = screen.getByTestId('length').textContent;
fireEvent.click(screen.getByTestId('navigate'));
expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
expect(screen.getByTestId('length').textContent).toBe(before);
expect(screen.getByTestId('action')).toHaveTextContent('REPLACE');
});
});

View File

@@ -45,6 +45,18 @@ describe('useAppParams', () => {
expect(result.current).toMatchObject({ dashboardId: 'd1', panelId: 'p2' });
});
it.each([
['/', '/services/api%2Fworker', 'api/worker'],
['?', '/services/a%3Fb', 'a?b'],
['a space', '/services/my%20svc', 'my svc'],
])('decodes %s in a param value', (_, route, expected) => {
const { result } = renderHook(() => useAppParams<'servicename'>(), {
wrapper: wrapperAt(route, '/services/:servicename'),
});
expect(result.current.servicename).toBe(expected);
});
it('returns an empty object on a route without params', () => {
const { result } = renderHook(() => useAppParams(), {
wrapper: wrapperAt('/logs', '/logs'),

View File

@@ -1,146 +0,0 @@
import type { History } from 'history';
import { applyNavigate, retryTransition, withState } from '../utils';
function fakeHistory(): {
history: History;
push: jest.Mock;
replace: jest.Mock;
go: jest.Mock;
} {
const push = jest.fn();
const replace = jest.fn();
const go = jest.fn();
return {
history: { push, replace, go } as unknown as History,
push,
replace,
go,
};
}
describe('applyNavigate', () => {
it('pushes a string target with no second argument', () => {
const { history, push } = fakeHistory();
applyNavigate(history, '/logs');
expect(push).toHaveBeenCalledWith('/logs');
});
it('pushes an object target with no state key', () => {
const { history, push } = fakeHistory();
applyNavigate(history, { pathname: '/logs', search: '?a=1' });
expect(push).toHaveBeenCalledWith({ pathname: '/logs', search: '?a=1' });
});
it('forwards state when there is state to forward', () => {
const { history, push } = fakeHistory();
applyNavigate(history, '/logs', { state: { from: '/home' } });
expect(push).toHaveBeenCalledWith('/logs', { from: '/home' });
});
it('attaches state to an object target', () => {
const { history, push } = fakeHistory();
applyNavigate(history, { pathname: '/logs' }, { state: { from: '/home' } });
expect(push).toHaveBeenCalledWith({ pathname: '/logs' }, { from: '/home' });
});
it('replaces instead of pushing', () => {
const { history, push, replace } = fakeHistory();
applyNavigate(history, '/logs', { replace: true });
expect(replace).toHaveBeenCalledWith('/logs');
expect(push).not.toHaveBeenCalled();
});
it('replaces with state', () => {
const { history, replace } = fakeHistory();
applyNavigate(history, '/logs', { replace: true, state: { a: 1 } });
expect(replace).toHaveBeenCalledWith('/logs', { a: 1 });
});
});
describe('retryTransition', () => {
const location = { pathname: '/logs', search: '', hash: '', state: undefined };
it('walks a blocked POP by its distance', () => {
const { history, go } = fakeHistory();
retryTransition(history, location, 'POP', 2);
expect(go).toHaveBeenCalledWith(2);
});
it('does not reload when a blocked POP has no distance', () => {
const { history, go } = fakeHistory();
retryTransition(history, location, 'POP', 0);
expect(go).not.toHaveBeenCalled();
});
it('settles on the carried location when a blocked POP has an unknown distance', () => {
const { history, go, replace } = fakeHistory();
retryTransition(history, location, 'POP', null);
expect(go).not.toHaveBeenCalled();
expect(replace).toHaveBeenCalledWith(location);
});
it('replays PUSH and REPLACE from the carried location', () => {
const { history, push, replace } = fakeHistory();
retryTransition(history, location, 'PUSH', 0);
retryTransition(history, location, 'REPLACE', 0);
expect(push).toHaveBeenCalledWith(location);
expect(replace).toHaveBeenCalledWith(location);
});
});
describe('withState', () => {
it('returns the target untouched when there is no state', () => {
expect(withState('/logs?a=1', undefined)).toBe('/logs?a=1');
});
it('splits a string target before attaching state', () => {
expect(withState('/logs?a=1#top', { from: '/home' })).toStrictEqual({
pathname: '/logs',
search: '?a=1',
hash: '#top',
state: { from: '/home' },
});
});
it('resolves a search-only string against the current location', () => {
expect(
withState(
'?tab=2',
{ from: '/home' },
{ pathname: '/x/y', search: '?q=1', hash: '', state: null },
),
).toMatchObject({
pathname: '/x/y',
search: '?tab=2',
state: { from: '/home' },
});
});
it('attaches state to an object target', () => {
expect(withState({ pathname: '/logs' }, { from: '/home' })).toStrictEqual({
pathname: '/logs',
state: { from: '/home' },
});
});
});

View File

@@ -1,16 +1,31 @@
import { generatePath } from 'react-router-dom';
import { generatePath } from 'react-router';
/**
* Fills `:param` segments in a route pattern.
*
* Param values are URI-encoded. `/`, `?` and `#` come back percent-encoded, so
* a value can never introduce extra path segments or a query string. v5's
* `generatePath` does this via path-to-regexp; v7's runs `encodeURIComponent`,
* which also encodes `:`.
* Param values are passed raw and come back percent-encoded. `generatePath`
* runs each one through `encodeURIComponent`, so a value can never introduce
* extra path segments or a query string. A value that is already encoded gets
* encoded twice. `useAppParams` values are already decoded; `matchRoute` ones
* un-escape only `%2F`, so decode those before passing one here.
*
* v7's `generatePath` types params as `string | null`, so non-strings are
* stringified here. `undefined` values are dropped, which leaves an optional
* segment out and makes a required one throw.
*/
export function buildRoutePath(
pattern: string,
params?: Record<string, string | number | boolean | undefined>,
): string {
return generatePath(pattern, params);
if (params === undefined) {
return generatePath(pattern);
}
const stringified = Object.fromEntries(
Object.entries(params)
.filter(([, value]) => value !== undefined)
.map(([key, value]) => [key, String(value)]),
);
return generatePath(pattern, stringified);
}

View File

@@ -0,0 +1,22 @@
import type { RouteObject } from 'react-router';
import { HostedTreeOutlet } from './HostedTreeOutlet';
import { RethrowRouteError } from './RethrowRouteError';
/**
* The route table for the test and story mounts: the tree `HostRouter` was last
* rendered with, at any URL, or only at `patterns` so it can read their params
* the way a page does. Render errors propagate out of the router.
*/
export function createHostRoutes(patterns?: string[]): RouteObject[] {
const children: RouteObject[] = patterns
? [
...patterns.map((path) => ({ path, element: <HostedTreeOutlet /> })),
{ path: '*', element: null },
]
: [{ path: '*', element: <HostedTreeOutlet /> }];
return [{ errorElement: <RethrowRouteError />, children }];
}
export const hostRoutes: RouteObject[] = createHostRoutes();

View File

@@ -1,10 +1,10 @@
import { matchPath } from 'react-router-dom';
import { matchPath } from 'react-router';
import type { AppParams, RouteMatch } from './types';
interface MatchRouteOptions {
/**
* Defaults to `false`, matching v5's string form. v6's `end` defaults to
* Defaults to `false`, matching v5's string form. v7's `end` defaults to
* `true`, so callers that pass no options rely on this default and would
* silently flip to exact matching without it.
*/
@@ -18,29 +18,22 @@ export function matchRoute<Key extends string = string>(
): RouteMatch<Key> | null {
const end = options.exact ?? false;
const match = matchPath<Record<string, string | undefined>>(pathname, {
path: pattern,
exact: end,
});
// v7 un-escapes `%2F` in param values itself (and nothing else), which is
// what keeps `buildRoutePath` -> `matchRoute` a round trip for a value
// containing a slash.
const match = matchPath(
{ path: pattern, end, caseSensitive: false },
pathname,
);
if (match === null) {
return null;
}
// v6.30 un-escapes `%2F` in param values (and nothing else); v5 hands them
// back raw. Doing it here keeps `buildRoutePath` -> `matchRoute` a round trip
// for values containing a slash, on both versions.
const params = Object.fromEntries(
Object.entries(match.params).map(([key, value]) => [
key,
value?.replace(/%2F/g, '/'),
]),
);
return {
params: params as AppParams<Key>,
pathname: match.url,
pathnameBase: match.url,
params: match.params as AppParams<Key>,
pathname: match.pathname,
pathnameBase: match.pathnameBase,
pattern: { path: pattern, caseSensitive: false, end },
};
}

View File

@@ -1,85 +1,114 @@
import history from 'lib/history';
import type { DataRouter } from 'react-router';
import { stripBasePath } from 'utils/basePath';
import type {
AppLocation,
NavigateOptions,
NavigationAction,
NavigationBlocker,
To,
} from './types';
import { applyNavigate, retryTransition, toAppLocation } from './utils';
import { toAppLocation } from './utils';
let entryKeys: Array<string | undefined> = [history.location.key];
let currentKey = history.location.key;
/**
* Imperative navigation, usable from any code. `useAppNavigate` navigates on
* the nearest router instead. Unlike `useSafeNavigate` it does not suppress
* same-URL navigation and has no new-tab branch, because it cannot see the
* current render.
*
* It drives the data router attached last: the app's, or the one a test or a
* story mounts. Callers pass and receive basename-free app paths. The router
* prepends the base path on write, and its `state.location` is the full browser
* path, so reads strip it here.
*
* A navigation commits synchronously only while no matched route has a loader;
* once one does, `router.navigate` settles after the loader.
*/
type Listener = (update: {
location: AppLocation;
action: NavigationAction;
}) => void;
// history@4 reports a blocked POP's target but not how far away it is, and the
// POP is already reverted by the time `retry` runs. Mirroring its entry keys
// gives the distance back. Like history@4, an entry it never saw (one from
// before a reload) counts as the first one, so a POP whose ends both land on
// index 0 is not reverted.
history.listen((location, action) => {
const index = entryKeys.indexOf(currentKey);
currentKey = location.key;
if (action === 'PUSH') {
entryKeys = [...entryKeys.slice(0, index + 1), location.key];
} else if (action === 'REPLACE' && index !== -1) {
entryKeys[index] = location.key;
const attached: DataRouter[] = [];
const listeners = new Set<Listener>();
let inAppPushCount = 0;
function activeRouter(): DataRouter {
const router = attached[attached.length - 1];
if (!router) {
throw new Error(
'lib/router/navigation: no router is attached. Mount the app router, a TestRouter or a story first.',
);
}
});
return router;
}
function entryIndex(key: string | undefined): number {
return Math.max(0, entryKeys.indexOf(key));
function toAppPath<S>(location: AppLocation<S>): AppLocation<S> {
return { ...location, pathname: stripBasePath(location.pathname) };
}
/**
* Imperative navigation on the app's history singleton, usable from any code.
* `useAppNavigate` navigates on the nearest router instead. Unlike
* `useSafeNavigate` it does not suppress same-URL navigation and has no new-tab
* branch, because it cannot see the current render.
*
* Callers pass and receive basename-free app paths.
* Makes `router` the one this module drives until the returned detach runs.
* Attachments stack, so detaching a router a test mounted hands control back
* to the one below it.
*/
export function attachRouter(router: DataRouter): () => void {
attached.push(router);
let { location } = router.state;
const unsubscribe = router.subscribe((state) => {
// The router also publishes navigation, fetcher and blocker state; only a
// committed location is a navigation.
if (state.location === location) {
return;
}
location = state.location;
if (attached[attached.length - 1] !== router) {
return;
}
if (state.historyAction === 'PUSH') {
inAppPushCount += 1;
}
const update = {
location: toAppPath(toAppLocation(state.location)),
action: state.historyAction as NavigationAction,
};
listeners.forEach((listener) => listener(update));
});
return (): void => {
unsubscribe();
const index = attached.lastIndexOf(router);
if (index !== -1) {
attached.splice(index, 1);
}
};
}
export function navigate(to: To, options?: NavigateOptions): void {
applyNavigate(history, to, options);
}
export function back(): void {
history.goBack();
}
export function getCurrentLocation(): AppLocation {
return toAppLocation(history.location);
}
export function blockNavigation(blocker: NavigationBlocker): () => void {
return history.block((location, action) => {
const appLocation = toAppLocation(location);
const navigationAction = action as NavigationAction;
const delta = entryIndex(location.key) - entryIndex(currentKey);
const popDelta = delta === 0 ? null : delta;
let deciding = true;
let allowed = false;
blocker({
location: appLocation,
action: navigationAction,
retry: () => {
if (deciding) {
allowed = true;
return;
}
retryTransition(history, appLocation, navigationAction, popDelta);
},
});
deciding = false;
// history@4 cancels the transition when the prompt returns `false`;
// history@5 cancels whenever a blocker is registered and hands control to
// `retry()`. A `retry()` inside the blocker means "let it through", and
// history@4 does that by not cancelling: re-issuing a POP would walk the
// stack twice.
return allowed ? undefined : false;
void activeRouter().navigate(to, {
replace: options?.replace,
state: options?.state,
});
}
export { hasInAppHistory } from 'lib/history';
export function back(): void {
void activeRouter().navigate(-1);
}
export function getCurrentLocation(): AppLocation {
return toAppPath(toAppLocation(activeRouter().state.location));
}
export function subscribe(listener: Listener): () => void {
// Wrapped so that subscribing the same function twice yields two
// subscriptions, as `history.listen` did.
const entry: Listener = (update) => listener(update);
listeners.add(entry);
return (): void => {
listeners.delete(entry);
};
}
export const hasInAppHistory = (): boolean => inAppPushCount > 0;

View File

@@ -1,7 +1,6 @@
/**
* Facade contracts for the router. Every shape here is defined the way
* react-router v6+ / history@5 behaves; the v5-backed implementations adapt up
* to it.
* react-router v7 behaves.
*/
export type NavigationAction = 'PUSH' | 'REPLACE' | 'POP';
@@ -11,7 +10,7 @@ export interface AppLocation<S = unknown> {
search: string;
hash: string;
state: S;
/** history@4 leaves this undefined on the initial entry; v6 always sets it. */
/** Always set by v7; optional for callers that build a location by hand. */
key?: string;
}
@@ -24,7 +23,7 @@ export type AppParams<Key extends string = string> = {
};
/**
* Mirrors v6's `useParams` return type so both call shapes keep working:
* Mirrors v7's `useParams` return type so both call shapes keep working:
* a union of param names (`useAppParams<'dashboardId'>()`) or a record
* (`useAppParams<{ dashboardId: string }>()`).
*/
@@ -58,15 +57,25 @@ export interface NavigateOptions {
export type NavigateFn = (to: To, options?: NavigateOptions) => void;
export interface BlockedTransition {
location: AppLocation;
/** The navigation a blocker function is asked about. */
export interface BlockerArgs {
currentLocation: AppLocation;
nextLocation: AppLocation;
action: NavigationAction;
/**
* Called inside the blocker, lets this navigation through and leaves the
* blocker registered. Called later, replays the navigation, so unblock first
* or the blocker catches the replay too.
*/
retry: () => void;
}
export type NavigationBlocker = (transition: BlockedTransition) => void;
export type BlockerFunction = (args: BlockerArgs) => boolean;
/**
* A blocked navigation waits on `proceed` or `reset`. Locations are
* basename-free, like every other location the facade hands out.
*/
export type AppBlocker =
| { state: 'unblocked'; location: undefined }
| {
state: 'blocked';
location: AppLocation;
proceed: () => void;
reset: () => void;
}
| { state: 'proceeding'; location: AppLocation };

View File

@@ -0,0 +1,58 @@
import { useCallback } from 'react';
import {
type BlockerFunction as RouterBlockerFunction,
useBlocker,
} from 'react-router';
import { stripBasePath } from 'utils/basePath';
import type {
AppBlocker,
AppLocation,
BlockerFunction,
NavigationAction,
} from './types';
import { toAppLocation } from './utils';
function toAppPath(location: AppLocation): AppLocation {
return {
...toAppLocation(location),
pathname: stripBasePath(location.pathname),
};
}
/**
* Holds in-app navigations while `shouldBlock` returns true: links, `navigate`
* calls and the browser's back and forward buttons. A page unload is not an
* in-app navigation and needs its own `beforeunload` handler.
*
* The blocker registers in an effect, so it does not cover a navigation made
* during the render that mounts it. A router honours one blocker at a time.
*/
export function useAppBlocker(shouldBlock: BlockerFunction): AppBlocker {
// The router strips the base path from these before calling in.
const blockerFunction = useCallback<RouterBlockerFunction>(
({ currentLocation, nextLocation, historyAction }) =>
shouldBlock({
currentLocation: toAppLocation(currentLocation),
nextLocation: toAppLocation(nextLocation),
action: historyAction as NavigationAction,
}),
[shouldBlock],
);
const blocker = useBlocker(blockerFunction);
switch (blocker.state) {
case 'blocked':
return {
state: 'blocked',
location: toAppPath(blocker.location),
proceed: blocker.proceed,
reset: blocker.reset,
};
case 'proceeding':
return { state: 'proceeding', location: toAppPath(blocker.location) };
default:
return { state: 'unblocked', location: undefined };
}
}

View File

@@ -1,7 +1,7 @@
import { useLocation } from 'react-router-dom';
import { useLocation } from 'react-router';
import type { AppLocation } from './types';
export function useAppLocation<S = unknown>(): AppLocation<S> {
return useLocation<S>();
return useLocation() as AppLocation<S>;
}

View File

@@ -1,21 +1,20 @@
import { useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import { useNavigate } from 'react-router';
import type { NavigateFn, NavigateOptions, To } from './types';
import { applyNavigate } from './utils';
/**
* Hook-context imperative navigation, for `useHistory()` call sites that only
* push or replace. Prefer `useSafeNavigate` when the call site wants same-URL
* Hook-context imperative navigation, for the call sites that only push or
* replace. Prefer `useSafeNavigate` when the call site wants same-URL
* suppression or new-tab handling.
*/
export function useAppNavigate(): NavigateFn {
const history = useHistory();
const navigate = useNavigate();
return useCallback(
(to: To, options?: NavigateOptions): void => {
applyNavigate(history, to, options);
navigate(to, { replace: options?.replace, state: options?.state });
},
[history],
[navigate],
);
}

View File

@@ -1,10 +1,10 @@
import { useNavigationType } from 'react-router-dom-v5-compat';
import { useNavigationType } from 'react-router';
import type { NavigationAction } from './types';
/**
* The action that produced the current location (`POP` for browser back and
* forward). v6 only; v5 exposes this as `history.action`.
* forward).
*/
export function useAppNavigationType(): NavigationAction {
return useNavigationType();

View File

@@ -1,10 +1,11 @@
import { useParams } from 'react-router-dom';
import { useParams } from 'react-router';
import type { AppParamsResult } from './types';
/**
* Types every param `string | undefined`, as v6 does. v5 types them as required
* strings.
* Params are typed `string | undefined`, which is what v7 returns. Values are
* fully percent-decoded, `/` and `?` included, so put one back in a URL with
* `buildRoutePath`, never a template string.
*/
export function useAppParams<
ParamsOrKey extends string | Record<string, string | undefined> = string,

View File

@@ -1,8 +1,7 @@
import { useSearchParams } from 'react-router-dom-v5-compat';
import { useSearchParams } from 'react-router';
/**
* v6's `useSearchParams`, which has no v5 equivalent. Its setter navigates
* through the router.
* Its setter navigates through the router.
*/
export function useAppSearchParams(): ReturnType<typeof useSearchParams> {
return useSearchParams();

View File

@@ -1,98 +1,13 @@
import type { History, Location, LocationDescriptor } from 'history';
import { parsePath } from 'history';
import type {
AppLocation,
NavigateOptions,
NavigationAction,
To,
} from './types';
import type { AppLocation } from './types';
export function toAppLocation<S = unknown>(
location: Location<S>,
location: AppLocation<unknown>,
): AppLocation<S> {
return {
pathname: location.pathname,
search: location.search,
hash: location.hash,
state: location.state,
state: location.state as S,
key: location.key,
};
}
/**
* v5 carries state inside `to`. The string form is parsed first, or search and
* hash would land in `pathname`. Pass `currentLocation` where the target
* renders an href, so a search-only or hash-only string keeps the current
* pathname as it does without state; `history.push` resolves it on its own.
* Not `createLocation`: its `decodeURI` runs again when the link is followed.
*/
export function withState(
to: To,
state: unknown,
currentLocation?: AppLocation,
): LocationDescriptor {
if (state === undefined) {
return to;
}
if (typeof to === 'string') {
const parsed = parsePath(to);
return {
...parsed,
pathname: parsed.pathname || currentLocation?.pathname || '',
state,
};
}
return { ...to, state };
}
/**
* `state` always travels as the second argument, which history@4 and history@5
* both honour for string and object targets. It is omitted rather than passed
* as `undefined`, so a stateless `navigate(path)` reaches the history as the
* bare `push(path)` the call sites used before the facade.
*/
export function applyNavigate(
history: History,
to: To,
options?: NavigateOptions,
): void {
const { replace = false, state } = options ?? {};
const args: Parameters<History['push']> =
state === undefined ? [to] : [to, state];
if (replace) {
history.replace(...args);
} else {
history.push(...args);
}
}
/**
* Replays a transition that a blocker cancelled. history@4 discards the
* transition on cancel, so it has to be re-issued from the location it carried.
* `popDelta` walks the browser from where history@4 reverted the blocked POP
* back to its target. It is `null` when history@4 did not revert, so the
* browser is already on the target and only the router has to catch up.
*/
export function retryTransition(
history: History,
location: AppLocation,
action: NavigationAction,
popDelta: number | null,
): void {
if (action === 'POP') {
if (popDelta === null) {
history.replace(location);
} else if (popDelta !== 0) {
history.go(popDelta);
}
return;
}
if (action === 'REPLACE') {
history.replace(location);
return;
}
history.push(location);
}

View File

@@ -1,6 +1,8 @@
import { Tabs, TabsProps } from 'antd';
import { buildRoutePath } from 'lib/router/buildRoutePath';
import { useAppParams } from 'lib/router/useAppParams';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import DBCall from 'container/MetricsApplication/Tabs/DBCall';
import External from 'container/MetricsApplication/Tabs/External';
import Overview from 'container/MetricsApplication/Tabs/Overview';
@@ -15,9 +17,7 @@ import useMetricsApplicationTabKey from './useMetricsApplicationTabKey';
import './MetricsApplication.styles.scss';
function MetricsApplication(): JSX.Element {
const { servicename: encodedServiceName } = useAppParams<{
servicename: string;
}>();
const { servicename } = useAppParams<'servicename'>();
const activeKey = useMetricsApplicationTabKey();
@@ -44,7 +44,9 @@ function MetricsApplication(): JSX.Element {
const onTabChange = (tab: string): void => {
urlQuery.set(QueryParams.tab, tab);
safeNavigate(`/services/${encodedServiceName}?${urlQuery.toString()}`);
safeNavigate(
`${buildRoutePath(ROUTES.SERVICE_METRICS, { servicename })}?${urlQuery.toString()}`,
);
};
return (

View File

@@ -0,0 +1,49 @@
import ROUTES from 'constants/routes';
import { getCurrentLocation } from 'lib/router/navigation';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import MetricsApplication from '../MetricsApplication';
// The `.ts` extension slips past jest.config.ts's useSafeNavigate mock, so the
// tab click moves the real router.
jest.mock('hooks/useSafeNavigate', () =>
jest.requireActual('../../../hooks/useSafeNavigate.ts'),
);
jest.mock('container/MetricsApplication/Tabs/Overview', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('container/MetricsApplication/Tabs/DBCall', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('container/MetricsApplication/Tabs/External', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('container/ResourceAttributesFilter', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('../ApDex/ApDexApplication', () => ({
__esModule: true,
default: (): null => null,
}));
describe('MetricsApplication', () => {
it('keeps an encoded slash in the service name when switching tabs', async () => {
const user = userEvent.setup();
render(<MetricsApplication />, undefined, {
initialRoute: '/services/api%2Fworker',
routePath: ROUTES.SERVICE_METRICS,
});
await user.click(screen.getByRole('tab', { name: 'DB Call Metrics' }));
await waitFor(() => {
const { pathname, search } = getCurrentLocation();
expect(pathname).toBe('/services/api%2Fworker');
expect(new URLSearchParams(search).get('tab')).toBe('DB_CALL_METRICS');
});
});
});

View File

@@ -531,7 +531,7 @@ describe('PreferencesProvider integration', () => {
});
expect(screen.getByTestId('ai-columns-len')).toHaveTextContent(
AI_DEFAULT_COUNT,
String(URL_COLUMNS.length),
);
});

View File

@@ -352,7 +352,6 @@ rather than a story that fails at render:
| Module | Replacement | Why |
| --------------------- | ---------------------------------- | ------------------------------------------ |
| `lib/history` | `navigation/history.alias.ts` | keeps a story on its page, see below |
| `store` | `mocks/store.mock.ts` | the singleton answers from the story's store |
| `api/common/logEvent` | `mocks/logEvent.mock.ts` | analytics never leave the iframe |
| `constants/env` | `mocks/env.mock.ts` | pins the API origin the handlers answer on |
@@ -415,17 +414,17 @@ story turns the control that lengthens it rather than a story-only prop.
## Navigation
A story renders one page, so leaving that page would unmount it.
`navigation/pageScope.ts` holds the rule, `navigation/containment.ts` is what the
app sees in place of `lib/history`, and the two tell a navigation apart by
pathname:
`navigation/pageScope.ts` holds the rule, `navigation/containment.ts` creates the
story's memory data router and guards its `navigate`, which every navigation in
the app reaches, and the two tell a navigation apart by pathname:
- **Same page**: a query-param or hash change, which is how tabs, filters,
pagination and time ranges are driven. It is applied, and the page re-renders
the way it does in the app. Anchors are covered too: an in-page `<a href="?tab=x">`
or `<Link to="/home?tab=x">` is intercepted and pushed onto the story's history
or `<Link to="/home?tab=x">` is intercepted and pushed onto the story's router
rather than followed, which would navigate the iframe out of the story.
- **Another page**: a different pathname, an off-site href, `window.open` (what
`useSafeNavigate({ newTab })` calls) or a relative `go`/`goBack`, which carries
`useSafeNavigate({ newTab })` calls) or a relative `navigate(-1)`, which carries
no target to compare against. It is swallowed and reported to
`NavigationBlockedOverlay`, which lists what was attempted. Nothing is silently
dropped.

View File

@@ -1,65 +1,46 @@
import {
History,
LocationDescriptor,
LocationDescriptorObject,
parsePath,
} from 'history';
import { fn, type Mock } from 'storybook/test';
import { createMemoryRouter, type DataRouter, parsePath } from 'react-router';
import { hostRoutes } from 'lib/router/createHostRoutes';
import { fn } from 'storybook/test';
import { recordBlockedNavigation } from './blockedNavigationStore';
import { navigateWithinPage, storyHistory, toHref } from './pageScope';
import { navigateWithinPage, setStoryRouter, toHref } from './pageScope';
const guardedNavigate = (
via: 'push' | 'replace',
): Mock<(to: LocationDescriptor, state?: unknown) => void> =>
fn((to: LocationDescriptor, state?: unknown): void => {
const target: LocationDescriptorObject =
typeof to === 'string' ? { ...parsePath(to), state } : { state, ...to };
if (navigateWithinPage(target, { replace: via === 'replace' })) {
return;
}
recordBlockedNavigation(via, toHref(to));
}).mockName(`history.${via}`);
const blockedRelativeNavigate = (via: string): Mock<(delta?: number) => void> =>
fn((delta?: number): void => {
recordBlockedNavigation(via, delta === undefined ? via : `${via}(${delta})`);
}).mockName(`history.${via}`);
const overriddenMethods = {
push: guardedNavigate('push'),
replace: guardedNavigate('replace'),
go: blockedRelativeNavigate('go'),
goBack: blockedRelativeNavigate('goBack'),
goForward: blockedRelativeNavigate('goForward'),
} as const;
type OverriddenMethod = keyof typeof overriddenMethods;
const isOverriddenMethod = (prop: string | symbol): prop is OverriddenMethod =>
typeof prop === 'string' && prop in overriddenMethods;
type Navigate = DataRouter['navigate'];
/**
* What the app sees in place of `lib/history`. Reads (`location`, `action`,
* `listen`) are proxied to the story's memory history so react-router renders
* normally; navigation goes through `pageScope`, and whatever would leave the
* page is swallowed and reported to `blockedNavigationStore`.
* `react-router-dom-v5-compat` drives its `useNavigate` through this same
* object, so `useSafeNavigate` is covered too.
* Every navigation the app makes reaches `router.navigate`: `useNavigate`,
* `<Link>`, `useSearchParams` and `lib/router/navigation` all call it. One that
* stays on the page goes through `pageScope`; whatever would leave the page is
* swallowed and reported to `blockedNavigationStore`.
*/
export const containedHistory: History = new Proxy(storyHistory, {
get(target, prop, receiver) {
if (isOverriddenMethod(prop)) {
return overriddenMethods[prop];
}
return Reflect.get(target, prop, receiver);
},
});
const guardedNavigate = fn(((to, options) => {
if (typeof to === 'number') {
recordBlockedNavigation('go', `go(${to})`);
return Promise.resolve();
}
export const hasInAppHistory = (): boolean => false;
const target = typeof to === 'string' ? parsePath(to) : (to ?? {});
const replace = options?.replace ?? false;
if (!navigateWithinPage(target, { replace, state: options?.state })) {
recordBlockedNavigation(replace ? 'replace' : 'push', toHref(target));
}
return Promise.resolve();
}) as Navigate).mockName('router.navigate');
/** A router for one story, placed at its route before anything renders. */
export const createStoryRouter = (
route: string,
routeState?: unknown,
): DataRouter => {
const router = createMemoryRouter(hostRoutes, {
initialEntries: [{ ...parsePath(route), state: routeState }],
});
setStoryRouter(router);
router.navigate = guardedNavigate as Navigate;
return router;
};
export const resetStoryHistory = (): void => {
Object.values(overriddenMethods).forEach((method) => method.mockClear());
guardedNavigate.mockClear();
};

View File

@@ -1,20 +0,0 @@
import {
containedHistory,
hasInAppHistory as containedHasInAppHistory,
} from './containment';
/**
* Replaces `lib/history` in Storybook (aliased in `.storybook/main.ts`). The
* containment rule lives in `containment.ts`; this file only has to keep the
* module's shape, and the annotation is what checks it against the real one.
* An export added to `lib/history` fails to compile here instead of failing at
* render in whichever component imports it.
*/
const libHistory: typeof import('lib/history') = {
default: containedHistory,
hasInAppHistory: containedHasInAppHistory,
};
export default libHistory.default;
export const { hasInAppHistory } = libHistory;

View File

@@ -1,9 +1,5 @@
import {
createMemoryHistory,
LocationDescriptor,
MemoryHistory,
parsePath,
} from 'history';
import { createPath, type DataRouter, parsePath } from 'react-router';
import type { To } from 'lib/router/types';
/**
* Query keys the Storybook preview owns. They live in the iframe's URL, which
@@ -19,16 +15,18 @@ const PREVIEW_PARAMS = [
];
/**
* The story's own history. A story renders one page, so this never leaves it:
* `pageScope` decides what counts as staying, and `containment.ts` is what the
* app sees in place of `lib/history`.
* The story's own router. A story renders one page, so this never leaves it:
* `pageScope` decides what counts as staying, and `containment.ts` creates the
* router and guards its `navigate`. `navigateStoryRouter` is the unguarded one.
*/
export const storyHistory: MemoryHistory = createMemoryHistory({
initialEntries: ['/'],
});
let storyRouter: DataRouter | undefined;
let navigateStoryRouter: DataRouter['navigate'] | undefined;
export const toHref = (to: LocationDescriptor): string =>
typeof to === 'string' ? to : storyHistory.createHref(to);
const currentPathname = (): string =>
storyRouter?.state.location.pathname ?? '/';
export const toHref = (to: To): string =>
typeof to === 'string' ? to : createPath(to);
const withoutPreviewParams = (search: string): URLSearchParams => {
const params = new URLSearchParams(search);
@@ -56,9 +54,11 @@ const mirrorSearchToBrowser = (): void => {
}
});
withoutPreviewParams(storyHistory.location.search).forEach((value, key) => {
mirrored.set(key, value);
});
withoutPreviewParams(storyRouter?.state.location.search ?? '').forEach(
(value, key) => {
mirrored.set(key, value);
},
);
window.history.replaceState(
window.history.state,
@@ -67,7 +67,23 @@ const mirrorSearchToBrowser = (): void => {
);
};
storyHistory.listen(mirrorSearchToBrowser);
/**
* Makes `router` the story's router. `navigate` is captured before
* `containment.ts` replaces it, so in-page moves skip the guard.
*/
export const setStoryRouter = (router: DataRouter): void => {
storyRouter = router;
navigateStoryRouter = router.navigate;
let { location } = router.state;
router.subscribe((state) => {
if (state.location !== location) {
({ location } = state);
mirrorSearchToBrowser();
}
});
mirrorSearchToBrowser();
};
/** `/home/` and `/home` are the same page as far as a story is concerned. */
const normalizePathname = (pathname: string): string =>
@@ -77,8 +93,7 @@ const normalizePathname = (pathname: string): string =>
export const isSamePagePathname = (pathname: string | undefined): boolean =>
!pathname ||
normalizePathname(pathname) ===
normalizePathname(storyHistory.location.pathname);
normalizePathname(pathname) === normalizePathname(currentPathname());
/**
* Applies a navigation that stays on the story's page: a query-param or hash
@@ -86,8 +101,8 @@ export const isSamePagePathname = (pathname: string | undefined): boolean =>
* when the target is another page, leaving the caller to report it as blocked.
*/
export const navigateWithinPage = (
to: LocationDescriptor,
{ replace = false }: { replace?: boolean } = {},
to: To,
{ replace = false, state }: { replace?: boolean; state?: unknown } = {},
): boolean => {
const target = typeof to === 'string' ? parsePath(to) : to;
@@ -98,19 +113,21 @@ export const navigateWithinPage = (
// The preview's params ride along in whatever the app read out of
// `window.location.search`, so they are dropped on the way back in and the
// story's history stays the page's own URL.
storyHistory[replace ? 'replace' : 'push']({
...target,
search: `?${withoutPreviewParams(target.search ?? '')}`,
pathname: storyHistory.location.pathname,
});
void navigateStoryRouter?.(
{
...target,
search: `?${withoutPreviewParams(target.search ?? '')}`,
pathname: currentPathname(),
},
{ replace, state },
);
return true;
};
/** Places the story at a route without going through the block. */
export const setStoryLocation = (to: LocationDescriptor): void => {
storyHistory.replace(to);
mirrorSearchToBrowser();
/** Moves the story to another route without going through the block. */
export const setStoryLocation = (route: string, state?: unknown): void => {
void navigateStoryRouter?.(route, { replace: true, state });
};
/**
@@ -121,7 +138,7 @@ export const isBlockableHref = (href: string): boolean =>
href.length > 0 && !href.startsWith('#') && !href.startsWith('javascript:');
/**
* An anchor href as a location the story's history understands, or `undefined`
* An anchor href as a location the story's router understands, or `undefined`
* when it leads off the page. Relative hrefs (`?tab=logs`) carry no pathname and
* stay on the page; app links do, and are resolved against the iframe so an
* off-site href fails the host check before its path is compared.

View File

@@ -1,6 +1,4 @@
import { ReactNode, useEffect, useMemo } from 'react';
import { Router } from 'react-router-dom';
import { CompatRouter } from 'react-router-dom-v5-compat';
import AppPageProviders from '@/app/AppPageProviders';
import AppProviders from '@/app/AppProviders';
import AppShell from '@/app/AppShell';
@@ -8,7 +6,7 @@ import type { AppLayer } from '@/app/types';
import { CmdKPalette } from 'components/cmdKPalette/cmdKPalette';
import { Toaster } from '@signozhq/ui/sonner';
import AppLayout from 'container/AppLayout';
import history from 'lib/history';
import { HostRouter } from 'lib/router/HostRouter';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { AppContext, useAppContext } from 'providers/App/App';
@@ -41,12 +39,6 @@ function StoryContextProbe(): null {
return null;
}
const storyRouter: AppLayer = (children) => (
<Router history={history}>
<CompatRouter>{children}</CompatRouter>
</Router>
);
const appLayout: AppLayer = (children) => <AppLayout>{children}</AppLayout>;
const bareLayout: AppLayer = (children) => (
@@ -66,7 +58,7 @@ function StorybookProviders({
routeState,
reduxState,
}: StorybookProvidersProps): JSX.Element {
const searchParams = useStoryRoute(route, routeState);
const { router, searchParams } = useStoryRoute(route, routeState);
const queryClient = useMemo(createStorybookQueryClient, []);
const store = useMemo(() => {
const created = createStorybookStore(reduxState);
@@ -83,36 +75,37 @@ function StorybookProviders({
useEffect(interceptExternalNavigation, []);
return (
<AppProviders
store={store}
queryClient={queryClient}
appContext={(scoped): ReactNode => (
<AppContext.Provider value={appContextValue}>{scoped}</AppContext.Provider>
)}
searchParams={(scoped): ReactNode => (
<NuqsTestingAdapter searchParams={searchParams} hasMemory>
{scoped}
</NuqsTestingAdapter>
)}
>
<AppShell
router={storyRouter}
overlays={
<>
<StoryContextProbe />
<CmdKPalette userRole={role} />
<NavigationBlockedOverlay />
</>
}
<HostRouter router={router}>
<AppProviders
store={store}
queryClient={queryClient}
appContext={(scoped): ReactNode => (
<AppContext.Provider value={appContextValue}>{scoped}</AppContext.Provider>
)}
searchParams={(scoped): ReactNode => (
<NuqsTestingAdapter searchParams={searchParams} hasMemory>
{scoped}
</NuqsTestingAdapter>
)}
>
<AppPageProviders
layout={layout === 'app' ? appLayout : bareLayout}
queryBuilder={queryBuilder}
<AppShell
overlays={
<>
<StoryContextProbe />
<CmdKPalette userRole={role} />
<NavigationBlockedOverlay />
</>
}
>
{children}
</AppPageProviders>
</AppShell>
</AppProviders>
<AppPageProviders
layout={layout === 'app' ? appLayout : bareLayout}
queryBuilder={queryBuilder}
>
{children}
</AppPageProviders>
</AppShell>
</AppProviders>
</HostRouter>
);
}

View File

@@ -1,18 +1,51 @@
import { useMemo } from 'react';
import { parsePath } from 'history';
import { useEffect, useMemo, useRef, useState } from 'react';
import { attachRouter } from 'lib/router/navigation';
import { createStoryRouter } from '../navigation/containment';
import { setStoryLocation } from '../navigation/pageScope';
type StoryRouter = ReturnType<typeof createStoryRouter>;
/**
* Places the story's history at its route before the router mounts and hands
* back the search params for the nuqs testing adapter.
* Creates the story's router at its route, so the page's first render already
* reads it, and attaches it to `lib/router/navigation`. A later route (a control
* that changes it) moves the same router. Also hands back the search params for
* the nuqs testing adapter.
*/
export const useStoryRoute = (
route: string,
routeState?: unknown,
): URLSearchParams =>
useMemo(() => {
setStoryLocation({ ...parsePath(route), state: routeState });
): { router: StoryRouter; searchParams: URLSearchParams } => {
// Attached while rendering: children run their effects first, and one that
// navigates must reach this router.
const [mounted] = useState(() => {
const router = createStoryRouter(route, routeState);
return { router, detach: attachRouter(router) };
});
useEffect(
() => (): void => {
mounted.detach();
mounted.router.dispose();
},
[mounted],
);
const placed = useRef({ route, routeState });
useEffect(() => {
if (
placed.current.route !== route ||
placed.current.routeState !== routeState
) {
placed.current = { route, routeState };
setStoryLocation(route, routeState);
}
}, [route, routeState]);
const searchParams = useMemo(() => {
const [, search = ''] = route.split('?');
return new URLSearchParams(search);
}, [route, routeState]);
}, [route]);
return { router: mounted.router, searchParams };
};

View File

@@ -1,17 +1,23 @@
import type { ComponentType } from 'react';
import { Route } from 'react-router-dom';
import { Route, Routes } from 'react-router';
/**
* A page that reads its params out of the pathname renders under its own route
* rather than being mounted bare. Stories declare the pattern here instead of
* mounting a router `<Route>` themselves.
* rather than being mounted bare. `<Route>` only resolves inside `<Routes>`, so
* the pattern a story declares is mounted here instead of in each meta.
*/
export const renderAtRoute = (
path: string | string[],
Component: ComponentType,
): (() => JSX.Element) => {
function StoryAtRoute(): JSX.Element {
return <Route exact path={path} component={Component} />;
return (
<Routes>
{(Array.isArray(path) ? path : [path]).map((pattern) => (
<Route key={pattern} path={pattern} element={<Component />} />
))}
</Routes>
);
}
return StoryAtRoute;

View File

@@ -99,7 +99,10 @@ render(<Page />, undefined, {
expect(getCurrentLocation().pathname).toBe(ROUTES.HOME);
```
Never mock the router packages (`react-router`, `react-router-dom`) or `lib/history`;
Module-level `navigate()` and `getCurrentLocation()` drive the mounted router and throw
when none is. Render first, or attach one with `attachTestRouter` from `tests/router-utils`.
Never mock the router packages (`react-router`, `react-router-dom`);
`signoz/no-direct-react-router-import` rejects it. When a test cannot render at a route,
or asserts the call itself, spy on the `lib/router` facade with `tests/router-mocks`:
```ts

View File

@@ -1,6 +1,6 @@
// Spies on the `lib/router` facade, for tests that cannot render at a route or
// assert the navigation call itself. Tests never mock the router packages or
// `lib/history`: those change at a router upgrade, the facade does not.
// assert the navigation call itself. Tests never mock the router packages: they
// change at a router upgrade, the facade does not.
// Spies last for the rest of the file unless restored.
import * as navigation from 'lib/router/navigation';

View File

@@ -1,6 +1,41 @@
import { navigate } from 'lib/router/navigation';
import { createBrowserRouter, type DataRouter } from 'react-router';
import { createHostRoutes } from 'lib/router/createHostRoutes';
import { attachRouter } from 'lib/router/navigation';
import { getBasePath, withBasePath } from 'utils/basePath';
/** Returns the history singleton to the state a suite should start each test in. */
export function resetTestRoute(): void {
navigate('/', { replace: true });
interface AttachedTestRouter {
router: DataRouter;
/** Detaches the router and disposes it. */
release: () => void;
}
/**
* A browser data router over jsdom's `window.history`, attached to
* `lib/router/navigation`. `TestRouter` mounts one; a test of code that
* navigates without rendering can use one directly. With `routePatterns` the
* tree renders only at those patterns and reads their params.
*/
export function attachTestRouter(
initialRoute?: string,
routePatterns?: string[],
): AttachedTestRouter {
if (initialRoute) {
window.history.replaceState(null, '', withBasePath(initialRoute));
}
const router = createBrowserRouter(createHostRoutes(routePatterns), {
basename: getBasePath(),
});
const detach = attachRouter(router);
return {
router,
release: (): void => {
detach();
router.dispose();
},
};
}
/** Returns the browser URL to the state a suite should start each test in. */
export function resetTestRoute(): void {
window.history.replaceState(null, '', withBasePath('/'));
}

View File

@@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import { TestRouter } from './router';
@@ -26,7 +25,7 @@ describe('TestRouter', () => {
});
it('keeps the existing URL when initialRoute is omitted', () => {
navigate('/existing');
window.history.replaceState(null, '', '/existing');
render(
<TestRouter>

View File

@@ -1,27 +1,26 @@
import { ReactElement, ReactNode, useRef } from 'react';
import { Route, Router } from 'react-router-dom';
import { CompatRouter, useInRouterContext } from 'react-router-dom-v5-compat';
import history from 'lib/history';
import { ReactElement, ReactNode, useEffect, useState } from 'react';
import { Route, Routes, useInRouterContext } from 'react-router';
import { HostRouter } from 'lib/router/HostRouter';
import { resetTestRoute } from './router-utils';
import { attachTestRouter, resetTestRoute } from './router-utils';
// Mounts on the `lib/history` singleton like `src/AppRoutes/index.tsx`, so
// imperative `navigate()` calls move the router. `CompatRouter` is always
// present for the v6-only facade hooks. A `TestRouter` inside another renders
// its children on the outer router and cannot take an `initialRoute`: the outer
// `CompatRouter` has already read the location, so v6-backed hooks would keep
// the outer route.
// Each mount creates a browser data router over jsdom's `window.history`, the
// way `src/AppRoutes/index.tsx` mounts one, and attaches it to
// `lib/router/navigation`, so imperative `navigate()` calls move it and
// `useAppBlocker` works. The base path is applied as the real mount applies it.
// A `TestRouter` inside another renders its children on the outer router and
// cannot take an `initialRoute`: the outer router has already read the URL.
interface TestRouterProps {
children: ReactNode;
/**
* Seeded onto the history singleton before the router reads it. Omit to mount
* at whatever URL the test has already set up. `render()` defaults it to `/`.
* Seeded onto `window.history` before the router reads it. Omit to mount at
* whatever URL the test has already set up. `render()` defaults it to `/`.
*/
initialRoute?: string;
/**
* Route pattern(s) to mount the children under, for a component that reads
* `useParams`. Matching is exact.
* `useParams`. Matching is exact, which is `<Routes>`'s default.
*/
routePath?: string | string[];
}
@@ -37,34 +36,29 @@ export function TestRouter({
'A nested TestRouter cannot take initialRoute. Pass it to the outermost TestRouter or to render().',
);
}
// The seed has to land before `<Router>` reads `history.location`, hence the
// render body rather than an effect. The ref keeps it to the first render, so
// a navigation made by the component under test is not undone.
const seeded = useRef(false);
if (!seeded.current) {
seeded.current = true;
if (initialRoute) {
history.replace(initialRoute);
}
}
const tree = routePath ? (
<Route exact path={routePath}>
{children}
</Route>
) : (
children
const patterns = routePath === undefined ? undefined : [routePath].flat();
// Attached while rendering rather than in an effect: children run their
// effects first, and one that subscribes or navigates must reach this router.
const [mounted] = useState(() =>
nested ? undefined : attachTestRouter(initialRoute, patterns),
);
if (nested) {
return <>{tree}</>;
useEffect(() => (): void => mounted?.release(), [mounted]);
if (mounted) {
return <HostRouter router={mounted.router}>{children}</HostRouter>;
}
if (!patterns) {
return <>{children}</>;
}
return (
<Router history={history}>
<CompatRouter>{tree}</CompatRouter>
</Router>
<Routes>
{patterns.map((pattern) => (
<Route key={pattern} path={pattern} element={children} />
))}
</Routes>
);
}

View File

@@ -4,7 +4,7 @@ import { QueryClient, QueryClientProvider } from 'react-query';
import { Provider } from 'react-redux';
import { render, RenderOptions, RenderResult } from '@testing-library/react';
import { ResourceProvider } from 'hooks/useResourceAttribute';
import { NuqsAdapter } from 'nuqs/adapters/react';
import { NuqsAdapter } from 'nuqs/adapters/react-router/v7';
import { AppContext } from 'providers/App/App';
import { IAppContext } from 'providers/App/types';
import { ErrorModalProvider } from 'providers/ErrorModalProvider';

View File

@@ -51,6 +51,12 @@ describe('at basePath="/"', () => {
expect(m.getAbsoluteUrl('/logs')).toBe(`${window.location.origin}/logs`);
});
it('stripBasePath is a no-op for any internal path', () => {
expect(m.stripBasePath('/logs')).toBe('/logs');
expect(m.stripBasePath('/logs/explorer')).toBe('/logs/explorer');
expect(m.stripBasePath('/')).toBe('/');
});
it('getBaseUrl returns bare origin', () => {
expect(m.getBaseUrl()).toBe(window.location.origin);
});
@@ -85,6 +91,39 @@ describe('at basePath="/signoz/"', () => {
);
});
it('stripBasePath removes the prefix', () => {
expect(m.stripBasePath('/signoz/logs')).toBe('/logs');
expect(m.stripBasePath('/signoz/logs/explorer')).toBe('/logs/explorer');
});
it('stripBasePath maps the prefix itself to "/"', () => {
expect(m.stripBasePath('/signoz/')).toBe('/');
expect(m.stripBasePath('/signoz')).toBe('/');
});
it('stripBasePath is idempotent, so safe to call twice', () => {
expect(m.stripBasePath(m.stripBasePath('/signoz/logs'))).toBe('/logs');
});
it('stripBasePath leaves a path that only looks like the prefix alone', () => {
expect(m.stripBasePath('/signozzz/logs')).toBe('/signozzz/logs');
});
it('stripBasePath matches the prefix case-insensitively, as the router does', () => {
expect(m.stripBasePath('/SigNoz/logs')).toBe('/logs');
expect(m.stripBasePath('/SIGNOZ')).toBe('/');
});
it('stripBasePath passes through external URLs', () => {
expect(m.stripBasePath('https://example.com/signoz/foo')).toBe(
'https://example.com/signoz/foo',
);
});
it('stripBasePath round-trips withBasePath', () => {
expect(m.stripBasePath(m.withBasePath('/logs?a=1'))).toBe('/logs?a=1');
});
it('getAbsoluteUrl returns origin + prefixed path', () => {
expect(m.getAbsoluteUrl('/logs')).toBe(
`${window.location.origin}/signoz/logs`,

View File

@@ -30,6 +30,32 @@ export function withBasePath(path: string): string {
return _basePath + path.slice(1);
}
/**
* Inverse of withBasePath: turns a real browser pathname into an app path.
* Idempotent and safe to call on any value.
*
* stripBasePath('/signoz/logs') → '/logs'
* stripBasePath('/logs') → '/logs' (already stripped)
* stripBasePath('/signoz') → '/' (the base path itself)
*/
export function stripBasePath(path: string): string {
if (!path.startsWith('/')) {
return path;
}
if (_basePath === '/') {
return path;
}
const lowerPath = path.toLowerCase();
const lowerBase = _basePath.toLowerCase();
if (lowerPath === lowerBase || lowerPath === lowerBase.slice(0, -1)) {
return '/';
}
if (lowerPath.startsWith(lowerBase)) {
return path.slice(_basePath.length - 1);
}
return path;
}
/**
* Full absolute URL — for copy-to-clipboard and window.open calls.
* getAbsoluteUrl(ROUTES.LOGS_EXPLORER) → 'https://host/signoz/logs/logs-explorer'

View File

@@ -1,20 +1,22 @@
/**
* This was introduced to fix a sync bug between Nuqs and react-router-dom
* Reads the params nuqs has actually published, which `useLocation().search`
* (and `useUrlQuery()`) can lag behind.
*
* We are using the wrong adapter for nuqs because the correct one only supports v6/v7,
* and we are at version v5. Nuqs writes params straight to the History API, which
* react-router v5 never observes, so `useLocation().search` (and `useUrlQuery()`) can
* be several nuqs updates behind the real URL.
* A nuqs write defaults to `shallow: true`, which means it calls
* `history.replaceState` and stops there. `nuqs/adapters/react-router/v7` only
* calls the router's `navigate()` when a write opts into `shallow: false`, and
* nothing here does. A `replaceState` made behind the router's back fires no
* `popstate`, so the router's location does not move. That is nuqs working as
* designed, not a version problem: the v5 -> v6 -> v7 migrations did not change
* it and the adapter swap does not either.
*
* Use this whenever you need to build a navigation target on top of the current
* params, otherwise stale values get republished and nuqs adopts them back on its
* next flush (it snapshots `window.location.search`).
*
* We can revert this once we migrate react-router-dom to v6.
*/
/**
* This was created to help testing the regression introduced between nuqs/react-router-dom
* Test seam for the nuqs/router sync this module papers over.
*/
type SearchParamsGetter = () => URLSearchParams;
let getter: SearchParamsGetter = (): URLSearchParams =>

View File

@@ -5,11 +5,13 @@ import (
"github.com/SigNoz/signoz/pkg/http/handler"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/coretypes"
"github.com/gorilla/mux"
)
func (provider *provider) addOrgRoutes(router *mux.Router) error {
if err := router.Handle("/api/v2/orgs/me", handler.New(provider.authzMiddleware.AdminAccess(provider.orgHandler.Get), handler.OpenAPIDef{
if err := router.Handle("/api/v2/orgs/me", handler.New(provider.authzMiddleware.CheckResources(provider.orgHandler.Get, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
ID: "GetMyOrganization",
Tags: []string{"orgs"},
Summary: "Get my organization",
@@ -21,12 +23,18 @@ func (provider *provider) addOrgRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
})).Methods(http.MethodGet).GetError(); err != nil {
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceOrganization.Scope(coretypes.VerbRead)}),
}, handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceOrganization,
Verb: coretypes.VerbRead,
Category: coretypes.ActionCategoryDataAccess,
ID: provider.orgIDExtractor(),
Selector: coretypes.IDSelector,
}))).Methods(http.MethodGet).GetError(); err != nil {
return err
}
if err := router.Handle("/api/v2/orgs/me", handler.New(provider.authzMiddleware.AdminAccess(provider.orgHandler.Update), handler.OpenAPIDef{
if err := router.Handle("/api/v2/orgs/me", handler.New(provider.authzMiddleware.CheckResources(provider.orgHandler.Update, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
ID: "UpdateMyOrganization",
Tags: []string{"orgs"},
Summary: "Update my organization",
@@ -38,10 +46,31 @@ func (provider *provider) addOrgRoutes(router *mux.Router) error {
SuccessStatusCode: http.StatusNoContent,
ErrorStatusCodes: []int{http.StatusConflict, http.StatusBadRequest},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
})).Methods(http.MethodPut).GetError(); err != nil {
SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceOrganization.Scope(coretypes.VerbUpdate)}),
}, handler.WithResourceDefs(handler.BasicResourceDef{
Resource: coretypes.ResourceOrganization,
Verb: coretypes.VerbUpdate,
Category: coretypes.ActionCategoryConfigurationChange,
ID: provider.orgIDExtractor(),
Selector: coretypes.IDSelector,
}))).Methods(http.MethodPut).GetError(); err != nil {
return err
}
return nil
}
func (provider *provider) orgIDExtractor() coretypes.ResourceIDExtractor {
return coretypes.NewResourceIDExtractor(coretypes.PhaseRequest, func(ec coretypes.ExtractorContext) (string, error) {
if ec.Request == nil {
return "", nil
}
claims, err := authtypes.ClaimsFromContext(ec.Request.Context())
if err != nil {
return "", err
}
return claims.OrgID, nil
})
}

View File

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

View File

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

View File

@@ -276,6 +276,7 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewAddLLMPricingRuleTuplesFactory(sqlstore),
sqlmigration.NewRemoveUnsupportedQuickFiltersFactory(),
sqlmigration.NewMigrateRelatedLinksTemplateFactory(),
sqlmigration.NewAddOrganizationTuplesFactory(sqlstore),
)
}

View File

@@ -0,0 +1,158 @@
package sqlmigration
import (
"context"
"database/sql"
"encoding/json"
"time"
"github.com/oklog/ulid/v2"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect"
"github.com/uptrace/bun/migrate"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/coretypes"
)
type addOrganizationTuples struct {
sqlstore sqlstore.SQLStore
}
func NewAddOrganizationTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
return factory.NewProviderFactory(factory.MustNewName("add_organization_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
return &addOrganizationTuples{sqlstore: sqlstore}, nil
})
}
func (migration *addOrganizationTuples) Register(migrations *migrate.Migrations) error {
return migrations.Register(migration.Up, migration.Down)
}
func (migration *addOrganizationTuples) Up(ctx context.Context, db *bun.DB) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
var storeID string
err = tx.QueryRowContext(ctx, `SELECT id FROM store WHERE name = ? LIMIT 1`, "signoz").Scan(&storeID)
if err != nil {
return err
}
var orgIDs []string
err = tx.NewSelect().
Table("organizations").
Column("id").
Scan(ctx, &orgIDs)
if err != nil && err != sql.ErrNoRows {
return err
}
isPG := migration.sqlstore.BunDB().Dialect().Name() == dialect.PG
tuples := []migrationTuple{
{authtypes.SigNozAdminRoleName, "organization", "organization", "read"},
{authtypes.SigNozAdminRoleName, "organization", "organization", "update"},
}
for _, orgID := range orgIDs {
for _, tuple := range tuples {
entropy := ulid.DefaultEntropy()
now := time.Now().UTC()
tupleID := ulid.MustNew(ulid.Timestamp(now), entropy).String()
// The organization object has no org prefix: organization:organization/<selector>.
objectID := tuple.objectName + "/*"
roleSubject := "organization/" + orgID + "/role/" + tuple.roleName
if isPG {
user := "role:" + roleSubject + "#assignee"
result, err := tx.ExecContext(ctx, `
INSERT INTO tuple (store, object_type, object_id, relation, _user, user_type, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, object_type, object_id, relation, _user) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, user, "userset", tupleID, now,
)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
continue
}
_, err = tx.ExecContext(ctx, `
INSERT INTO changelog (store, object_type, object_id, relation, _user, operation, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, ulid, object_type) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, user, 0, tupleID, now,
)
if err != nil {
return err
}
} else {
result, err := tx.ExecContext(ctx, `
INSERT INTO tuple (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, user_type, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", "userset", tupleID, now,
)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
continue
}
_, err = tx.ExecContext(ctx, `
INSERT INTO changelog (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, operation, ulid, inserted_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (store, ulid, object_type) DO NOTHING`,
storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", 0, tupleID, now,
)
if err != nil {
return err
}
}
}
}
managedRoleGroups := make(map[string]string, len(coretypes.ManagedRoleToTransactions))
for roleName, transactions := range coretypes.ManagedRoleToTransactions {
data, err := json.Marshal(authtypes.NewTransactionGroupsFromTransactions(transactions))
if err != nil {
return err
}
managedRoleGroups[roleName] = string(data)
}
for _, orgID := range orgIDs {
for roleName, data := range managedRoleGroups {
if _, err := tx.NewUpdate().
Model(new(roles)).
Set("transaction_groups = ?", data).
Where("org_id = ?", orgID).
Where("type = ?", authtypes.RoleTypeManaged.StringValue()).
Where("name = ?", roleName).
Exec(ctx); err != nil {
return err
}
}
}
return tx.Commit()
}
func (migration *addOrganizationTuples) Down(context.Context, *bun.DB) error {
return nil
}

View File

@@ -88,6 +88,9 @@ var ManagedRoleToTransactions = map[string][]Transaction{
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindOrgPreference}, WildCardSelectorString)},
{Verb: VerbCreate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindOrgPreference}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindOrgPreference}, WildCardSelectorString)},
// organization: admin only
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeOrganization, Kind: KindOrganization}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeOrganization, Kind: KindOrganization}, WildCardSelectorString)},
// public-dashboard — admin manages, anonymous reads
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindPublicDashboard}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindPublicDashboard}, WildCardSelectorString)},

View File

@@ -71,7 +71,7 @@ type PostableRule struct {
RuleType RuleType `json:"ruleType" required:"true" description:"The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries."`
RuleCondition *RuleCondition `json:"condition" required:"true" description:"The query to evaluate and the thresholds applied to its result."`
Labels map[string]string `json:"labels,omitempty" description:"Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. A label named after one the engine writes, such as severity or threshold.name, is ignored."`
Labels map[string]string `json:"labels,omitempty" description:"Labels attached to every alert the rule fires. Keys match [a-zA-Z_.][a-zA-Z0-9_.]*; values may use Go templates such as {{$labels.service_name}}. severity is the conventional routing label."`
Annotations map[string]string `json:"annotations,omitempty" description:"Free text attached to every alert, conventionally summary and description. Values may use Go templates with $value, $threshold and $labels."`
Disabled bool `json:"disabled" description:"Whether the rule is paused. A disabled rule is neither evaluated nor notifies. Defaults to false."`

View File

@@ -31,23 +31,6 @@ const (
AlertDescriptionLabel = "description"
)
// reservedLabelNames are written by the rule engine; a rule label with one of
// these names never reaches the alert.
var reservedLabelNames = map[string]struct{}{
MetricNameLabel: {},
TemporalityLabel: {},
AlertNameLabel: {},
AlertRuleIDLabel: {},
RuleSourceLabel: {},
NoDataLabel: {},
LabelThresholdName: {},
LabelSeverityName: {},
LabelLastSeen: {},
// TODO: the template layer reads is_recovering but nothing writes it;
// set it from Alert.IsRecovering.
LabelIsRecovering: {},
}
// Label is a key/value pair of strings.
// TODO(srikanthccv): https://github.com/SigNoz/signoz/issues/9232?
type Label struct {
@@ -302,20 +285,6 @@ func (b *Builder) Set(n, v string) *Builder {
return b
}
// SetRuleLabels adds the rule's labels, each expanded, skipping the names the
// engine writes.
// TODO: a rule label still overwrites a query result label of the same name;
// decide whether those are locked too.
func (b *Builder) SetRuleLabels(ruleLabels map[string]string, expand func(string) string) *Builder {
for name, value := range ruleLabels {
if _, reserved := reservedLabelNames[name]; reserved {
continue
}
b.Set(name, expand(value))
}
return b
}
// Labels returns the labels from the builder. If no modifications
// were made, the original labels are returned.
func (b *Builder) Labels() Labels {

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